from pygments import highlight, styles
from pygments.lexers import get_lexer_by_name
from pygments.formatters import ImageFormatter, HtmlFormatter
from PIL import Image, ImageDraw, ImageFont, ImageOps, ImageColor
import re
import os
from customtkinter import *

class App(CTk):
    def __init__(self, root):
        set_appearance_mode("System")  # Modes: "System" (standard), "Dark", "Light"
        set_default_color_theme("green")  # Themes: "blue" (standard), "green", "dark-blue"

        self.root = root
        self.root.title("Code to Image Renderer")

        # Initialize the language input
        self.lang_label = CTkLabel(root, text="Programming Language:")
        self.lang_label.pack()

        self.lang_entry = CTkTextbox(root, height=10, width=300)
        self.lang_entry.pack()

        # Initialize the code input
        self.code_label = CTkLabel(root, text="Code:")
        self.code_label.pack()

        self.code_input = CTkTextbox(root, height=200, width=1000)
        self.code_input.pack()

        # Initialize the theme selection
        self.theme_label = CTkLabel(root, text="Theme:")
        self.theme_label.pack()

        self.theme_names = list(styles.get_all_styles())
        self.theme_combobox = CTkOptionMenu(root, values=self.theme_names)
        self.theme_combobox.pack()

        # Initialize the submit button
        self.submit_button = CTkButton(root, text="Submit", command=self.submit)
        self.submit_button.pack(pady=20)

    def submit(self):
        lang = self.lang_entry.get("1.0", END).strip()  # get language
        code = self.code_input.get("1.0", END)  # get code
        theme = self.theme_combobox.get()  # get theme

        if not lang or not code or not theme:
            messagebox.showerror("Error", "Please provide language, code, and theme!")
        else:
            self.code_to_image(lang, code, theme)

class ChromaScript(App):
    def __init__(self, root):
        super().__init__(root)
        self.extension_mapping = {"Python": "py", "JavaScript": "js", "Java": "java", "C": "c", "C++": "cpp"}

    def get_theme_colors(self, theme):
        style = styles.get_style_by_name(theme)
        formatter = HtmlFormatter(style=style)
        css = formatter.get_style_defs('.highlight')

        # Extract background color
        background_match = re.search(r'background:(.*?);', css)
        if background_match:
            background_color = background_match.group(1).strip()
            return background_color, background_color

        return None, None

    def draw_macos_buttons(self, draw, button_colors):
        y = 10
        x = 10
        for color in button_colors:
            draw.ellipse([x, y, x+12, y+12], fill=color)
            x += 20  # space between buttons
        return x  # return final x position

    def code_to_image(self, lang, code, theme):
        # Syntax highlighting
        try:
            lexer = get_lexer_by_name(lang)
            style = styles.get_style_by_name(theme)
        except ValueError:
            messagebox.showerror("Error", f"No such language or theme: {lang}, {theme}")
            return

        formatter = ImageFormatter(font_name="DejaVu Sans Mono", line_numbers=False, style=style)
        code_bytes = highlight(code, lexer, formatter)

        # Save the highlighted code as an image
        with open("temp.png", "wb") as temp_file:
            temp_file.write(code_bytes)

        # Open the saved image as a PIL Image object
        code_image = Image.open("temp.png")

        # Create a new image with padding for the MacOS buttons
        width, height = code_image.size

        # Extract the theme colors
        background_color, text_color = self.get_theme_colors(theme)
        new_image = Image.new("RGBA", (width, height + 30), background_color)  # Increased height for padding

        # Draw MacOS buttons on the new image
        draw = ImageDraw.Draw(new_image)
        button_colors = ["#ff5e56", "#febd2c", "#26c83f"]
        final_x = self.draw_macos_buttons(draw, button_colors)

        # Draw window title
        title_font = ImageFont.truetype("font/appleFont.ttf", 15)  # Use SF Pro font for title
        file_extension = self.extension_mapping.get(lang, lang)  # Use the mapping to get the correct file extension
        draw.text((final_x + 10, 10), f"main.{file_extension}", fill=text_color, font=title_font)  # Adjusted position

        # Paste the code image onto the new image, shifted by the padding size
        new_image.paste(code_image, (0, 30))  # Shifted down by 30 pixels

        # Save the final image with higher resolution and quality
        dpi = 1000  # Set the desired DPI value
        output_image_path = "output.png"
        new_image.save(output_image_path, dpi=(dpi, dpi), quality="maximum", subsampling=0)
        #Rounnd the image's corners by 2px

        corner_radius = 10
        rounded_image = Image.new("RGBA", new_image.size)
        mask = Image.new("L", rounded_image.size, 0)
        mask_draw = ImageDraw.Draw(mask)
        mask_draw.rounded_rectangle([(0, 0), rounded_image.size], corner_radius, fill=255)
        rounded_image.paste(new_image, (0, 0), mask=mask)

        # Save the rounded image
        output_image_path = "output.png"
        rounded_image.save(output_image_path, dpi=(dpi, dpi), quality="maximum", subsampling=0)
        os.remove('temp.png')
        rounded_image.show()

if __name__ == "__main__":
    root = CTk()
    app = ChromaScript(root)
    root.mainloop()


from __future__ import print_function, division

import os
import numpy as np

from gensim.models import KeyedVectors

d = "../data"
w2v = KeyedVectors.load_word2vec_format(os.path.join(d, "wikipedia-pubmed-and-PMC-w2v.bin"), binary=True)
print("word2vec parameters loaded.")

def avg_sent_emb(s):
    words = s.split()
    l = len(words)

    for w in words:
        if w not in w2v:
            l -= 1

    return np.sum([w2v[w] for w in s.split() if w in w2v], axis=0) / l

def convert_sents_to_emb(sents):
    emb = []
    for p in sents:
        emb.append(np.array([avg_sent_emb(p[0]), avg_sent_emb(p[1])]))

    return np.array(emb)


#!/usr/bin/env python
"""
    Created by howie.hu at 2021-04-08.
    Description：样本处理脚本
    Changelog: all notable changes to this file will be documented
"""

import os

import pandas as pd

from src.classifier import ads2txt, text2py
from src.collector import extract_keyword_list
from src.config import Config
from src.databases import MongodbManager
from src.utils import load_text_to_list

def gen_final_sample():
    """
    将样本做最后的拼音处理
    :return:
    """
    for sample in [("clean_ads.csv", 1), ("clean_normal.csv", 2)]:
        file_name, label = sample
        print(f"正在处理文件 {file_name}")
        full_path = os.path.join(Config.DS_DIR, file_name)
        df = pd.read_csv(full_path)
        df["text"] = df["title"] + df["keywords"]
        df["text"] = df["text"].apply(text2py)
        df["label"] = str(label)
        # 删除无关列
        df.drop(["title", "keywords"], axis=1, inplace=True)
        df.to_csv(full_path.replace("clean", f"final"), index=False)

def gen_keyword_sample(
    s_path: str = f"{Config.DS_DIR}/ads.csv",
    c_path: str = f"{Config.DS_DIR}/clean_ads.csv",
):
    """
    广告文本提取关键词，前提是相关文本遵循了liuli定义的数据集格式
    :param s_path: 源路径
    :param c_path: 目标关键词提取后的路径
    :return:
    """
    # 根据标题去重
    s_df = pd.read_csv(s_path).drop_duplicates(subset=["title"])
    c_df = pd.read_csv(c_path).drop_duplicates(subset=["title"])
    s_data_res, c_data_res = [], []

    for each in c_df.values.tolist():
        c_data_res.append(
            {
                "title": each[0],
                "keywords": each[1],
            }
        )

    for each in s_df.values.tolist():
        title, url, is_process = each[0], each[1], each[2]
        cur_data = {
            "title": title,
            "url": url,
            "is_process": is_process,
        }
        if is_process == 0:
            # 进行提取，成功就改值为1
            keyword_list = extract_keyword_list(url)
            print(keyword_list)
            if keyword_list:
                # 判断是否被删除
                if keyword_list and "发布者" in keyword_list and "删除" in keyword_list:
                    cur_data["is_process"] = "0"
                    print(f"{title} {url} 需要重新收集有效链接")
                else:
                    cur_data["is_process"] = "1"
                    keywords = " ".join(keyword_list)
                    c_data_res.append({"title": title, "keywords": keywords})
                    print(f"新增成功：{title} {url} {keywords}")
        s_data_res.append(cur_data)

    # 持久化
    pd.DataFrame(s_data_res).to_csv(s_path, index=False)
    pd.DataFrame(c_data_res).to_csv(c_path, index=False)

def gen_normal_sample(nums: int = None):
    """
    生成正常样本数据
    :param nums: 样本数量，默认数量取异常样本
    :return:
    """
    if nums is None:
        ads_path = os.path.join(Config.DS_DIR, "clean_ads.csv")
        ads_title_list = load_text_to_list(ads_path)
        nums = len(ads_title_list) - 1
    mongo_base = MongodbManager.get_mongo_base(mongodb_config=Config.LL_MONGODB_CONFIG)
    coll = mongo_base.get_collection(coll_name="liuli_articles")
    query = {"cos_model.result": 0, "doc_source_name": "真没什么逻辑"}
    normal_path = os.path.join(Config.DS_DIR, "normal.csv")
    for each_data in coll.aggregate([{"$match": query}, {"$sample": {"size": nums}}]):
        title = each_data["doc_name"]
        url = each_data["doc_link"]
        title = f'"{title}"' if "," in title else title
        info = f"{title},{url},0\n"
        print(info)
    # with open(normal_path, "w") as fp:
    #     fp.write("title,url,is_process\n")
    #     for each_data in coll.aggregate(
    #         [{"$match": query}, {"$sample": {"size": nums}}]
    #     ):
    #         title = each_data["doc_name"]
    #         url = each_data["doc_link"]
    #         title = f'"{title}"' if "," in title else title
    #         info = f"{title},{url},0\n"
    #         fp.write(info)

if __name__ == "__main__":
    # url = "https://jishuin.proginn.com/p/763bfbd54d15"
    # keyword_list = extract_keyword_list(url)
    # print(keyword_list)
    gen_keyword_sample()
    # ads2txt()
    # gen_keyword_sample(
    #     s_path=f"{Config.DS_DIR}/normal.csv",
    #     c_path=f"{Config.DS_DIR}/clean_normal.csv",
    # )
    # gen_normal_sample()
    # gen_final_sample()


import os.path
from typing import Any, Dict

from jinja2 import Environment, PackageLoader, Template

import boson.configure as configure
from boson.lexer_generator.generator import LexerGenerator
from boson.option import option as boson_option
from boson.parser_generator.bottom_up_generator.canonical_generator import BottomUpCanonicalParserGenerator
from boson.system.logger import logger

class CodeGenerator:
    def __init__(self, output_path: str, language: str, mode: str, checker: bool):
        self._output_path: str = output_path
        self._language: str = language
        self._mode: str = mode
        self._checker: bool = checker
        self.__environment: Environment = Environment(
            loader=PackageLoader(
                configure.boson_package_name,
                os.path.join(configure.boson_template_directory, self._mode, self._language, 'checker' if self._checker else ''),
                encoding=configure.boson_default_encoding))
        self._template_data: Dict[str, Any] = {
            'configure': configure,
            'boson_code_option': boson_option['code'],
            'option': {
                'generate_lexer': False,
                'generate_parser': False,
            },
            'lexer': None,
            'parser': None,
        }

    def _generate_code(self, template_file: str, output_file: str) -> None:
        template: Template = self.__environment.get_template(template_file + configure.boson_template_postfix)
        code_text: str = template.render(self._template_data)
        with open(os.path.join(self._output_path, output_file), 'w', encoding=configure.boson_default_encoding) as code_file:
            code_file.write(code_text)

    def dispose_lexer(self, lexer_generator: LexerGenerator) -> None:
        logger.info('[Code Generator] Dispose Lexer.')
        self._template_data['option']['generate_lexer'] = True
        self._template_data['lexer'] = {
            'move_table': lexer_generator.move_table(),
            'compact_move_table': lexer_generator.compact_move_table(),
            'symbol_function_mapping': lexer_generator.symbol_function_mapping(),
            'non_greedy_state_set': lexer_generator.non_greedy_state_set(),
            'character_set': lexer_generator.character_set(),
            'start_state': lexer_generator.start_state(),
            'end_state_set': lexer_generator.end_state_set(),
            'lexical_symbol_mapping': lexer_generator.lexical_symbol_mapping(),
        }

    def dispose_parser(self, parser_generator):
        logger.info('[Code Generator] Dispose Parser.')
        self._template_data['option']['generate_parser'] = True
        if isinstance(parser_generator, BottomUpCanonicalParserGenerator):
            self._template_data['parser'] = {
                'terminal_index_mapping': parser_generator.terminal_index_mapping(),
                'action_table': parser_generator.action_table(),
                'sparse_action_table': parser_generator.sparse_action_table(),
                'goto_table': parser_generator.goto_table(),
                'sparse_goto_table': parser_generator.sparse_goto_table(),
                'sentence_index_grammar_tuple_mapping': parser_generator.sentence_index_grammar_tuple_mapping(),
                'reduce_symbol_count': parser_generator.reduce_symbol_count(),
                'reduce_non_terminal_index': parser_generator.reduce_non_terminal_index(),
                'none_grammar_tuple_sentence_index_set': parser_generator.none_grammar_tuple_sentence_index_set(),
                'reduce_number_grammar_name_mapping': parser_generator.reduce_number_grammar_name_mapping(),
                'naive_reduce_number_set': parser_generator.naive_reduce_number_set(),
            }
        else:
            raise ValueError(f'[Code Generator] Invalid Parser Generator Type: "{type(parser_generator)}".')


import yfinance as yf
import numpy as np
import pandas as pd
from sklearn.preprocessing import MinMaxScaler
from keras.models import Sequential
from keras.layers import Dense, LSTM, Dropout
import database as db

def model_run(company):
    # download stock data
    stock = yf.download(company, period="18mo")

    # create a new dataframe with only the 'Close' column
    data = stock.filter(['Close'])

    # convert the dataframe to a numpy array
    dataset = data.values

    # scale the data
    scaler = MinMaxScaler(feature_range=(0,1))
    scaled_data = scaler.fit_transform(dataset)

    # split the data into training and testing sets
    train_data = scaled_data[:-20, :]
    test_data = scaled_data[-20:, :]

    # split the training data into x_train and y_train datasets
    x_train = []
    y_train = []
    for i in range(60, len(train_data)):
        x_train.append(train_data[i-60:i, 0])
        y_train.append(train_data[i, 0])

    # convert the x_train and y_train datasets to numpy arrays
    x_train, y_train = np.array(x_train), np.array(y_train)

    # reshape the data for the LSTM model
    x_train = np.reshape(x_train, (x_train.shape[0], x_train.shape[1], 1))

    # build the LSTM model
    model = Sequential()
    model.add(LSTM(units=50, return_sequences=True, input_shape=(x_train.shape[1], 1)))
    model.add(Dropout(0.2))
    model.add(LSTM(units=50, return_sequences=True))
    model.add(Dropout(0.2))
    model.add(LSTM(units=50))
    model.add(Dropout(0.2))
    model.add(Dense(units=1))

    # compile the model
    model.compile(optimizer='adam', loss='mean_squared_error')

    # train the model
    model.fit(x_train, y_train, epochs=30, batch_size=32)

    # predict the future stock prices
    inputs = data[-80:].values
    inputs = scaler.transform(inputs)
    x_future = []
    for i in range(60, 80):
        x_future.append(inputs[i-60:i, 0])
    x_future = np.array(x_future)
    x_future = np.reshape(x_future, (x_future.shape[0], x_future.shape[1], 1))
    predicted_prices = model.predict(x_future)
    predicted_prices = scaler.inverse_transform(predicted_prices)

    # create a dataframe to store the predicted prices
    dates = pd.date_range(start=data.index[-1], periods=20, freq='B')
    future_prices = pd.DataFrame(data=predicted_prices, index=dates, columns=['Close'])

    val = data.Close[-1]-future_prices.Close[0]
    future_prices.Close = future_prices.Close + val
    # db.lstm_data(future_prices,company)

    return data,future_prices

    # import matplotlib.pyplot as plt
    # plt.figure(figsize=(16, 8))
    # plt.title('LSTM Model')
    # plt.xlabel('Date', fontsize=18)
    # plt.ylabel('Close Price USD ($)', fontsize=18)
    # plt.plot(data['Close'])
    # plt.plot(future_prices['Close'])
    # plt.legend(['Historical Prices', 'Predicted Prices'], loc='lower right')
    # plt.show()

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


from gql import gql, Client
from gql.transport.aiohttp import AIOHTTPTransport
import datetime

transport = AIOHTTPTransport(url='http://127.0.0.1:80/')

client = Client(transport=transport)

query = gql('''
  mutation SingleUpload($file: Upload!, $datetime: String!) {
    singleUpload(file: $file, datetime: $datetime) {
      filename
      mimetype
      encoding
    }
  }
''')

with open("Starship_SN8.mp4", "rb") as f:

    x = datetime.datetime.now()

    params = {
        "file": f,
        "datetime": x.strftime("%Y-%m-%d %H:%M:%S")
    }

    result = client.execute(
        query, variable_values=params, upload_files=True
    )

    print(result)


import sys

def parse(lines):
    sections = lines.split("\n\n")
    seeds = [int(i) for i in sections[0][6:].split()]
    mappings = []
    for section in sections[1:]:
        mapping = []
        for line in section.splitlines()[1:]:
            mapping.append([int(i) for i in line.split()])
        mapping.sort(key=lambda v: (v[1]+v[2], v[1]))
        mappings.append(mapping)
    return seeds, mappings

def find(seed, mappings):
    current = seed
    for mapping in mappings:
        for (dst, src, step) in mapping:
            if src <= current < src + step:
                current = dst + current - src
                break
    return current

def find_range(rng, mappings):
    rng_start, total_seeds = rng
    ranges = [[rng_start, rng_start+total_seeds]]
    for mapping in mappings:
        mapped_seeds = sum(b-a for a, b in ranges)
        # Do not lose seeds!
        assert (mapped_seeds == total_seeds), (mapped_seeds, total_seeds)
        next_ranges = []
        mappings_left = mapping[::-1]
        to_map = ranges[::-1]
        while to_map:
            current = to_map.pop()
            cur_start, cur_end = current
            while mappings_left and cur_start >= sum(mappings_left[-1][1:]):
                mappings_left.pop()
            if not mappings_left:
                next_ranges.append(current)
                continue
            dst, src, step = mappings_left[-1]
            if cur_end < src:
                next_ranges.append(current)
                continue
            if cur_start < src:
                next_ranges.append((cur_start, src))
                cur_start = src
            if cur_end >= src + step:
                to_map.append((src + step, cur_end))
                cur_end = src + step
            # Now we have only stuff in within bounds
            assert src <= cur_start < src + step, (src, cur_start, src + step)
            assert src < cur_end <= src + step, (src, cur_end, src + step)
            nxt_start = dst + cur_start - src
            nxt_end = dst + cur_end - src
            next_ranges.append((nxt_start, nxt_end))
        next_ranges.sort(key=lambda v: v[::-1])
        ranges = next_ranges
    return min(i[0] for i in ranges)

def solve(parsed):
    seeds, mappings = parsed
    part1 = min(find(seed, mappings) for seed in seeds)

    pairs = (seeds[2*i:2*i+2] for i in range(len(seeds)//2))
    part2 = min(find_range(pair, mappings) for pair in pairs)
    return part1, part2

data = open(sys.argv[-1]).read()
lines = data.strip().strip()
parsed = parse(lines)
part1, part2 = solve(parsed)
print(part1)
print(part2)

assert part1 == 309796150
assert part2 == 50716416


import matplotlib.pyplot as plt

class SensitivityAnalyser:
    def __init__(self, objectToChange, actionToExecute):
        self.objectToChange = objectToChange
        self.actionToExecute = actionToExecute

    def analyzeValues(self, dependentValues, attributeFormula):
        '''
        :param dependentValues: Values used to compute result
        :param attributeFormula: Supports '.' for attribute concatenation.
                                 Supports '&' for setting more than 1 attribute
                                 Example: 'obj1.att1&obj2.obj3.att3'
        :return: values calculated from dependent values by executing actionToExecute
        '''

        def mapFunc( aValue ):
            self._setValue( attributeFormula, aValue)
            return self.actionToExecute()

        return list(map(mapFunc, dependentValues))

    def _setValue(self, attributeFormula, aValue):
        def _setValueFunc(attributeFormula, aValue):
            attributes = attributeFormula.split('.')
            theObjectToChange = self.objectToChange
            i = 0
            while(i<len(attributes)-1):
                self._raiseExceptionIfHasNoAttr(theObjectToChange, attributes[i])
                theObjectToChange = getattr(theObjectToChange,attributes[i])
                i+=1

            self._raiseExceptionIfHasNoAttr(theObjectToChange, attributes[i])
            setattr(theObjectToChange, attributes[i], aValue)

        for attributeToSet in attributeFormula.split('&'):
            _setValueFunc( attributeToSet, aValue)

    def _raiseExceptionIfHasNoAttr(self, obj, attributeName):
        if not hasattr(obj, attributeName):
            raise Exception('{} has no attr {}'.format(obj, attributeName))

class ThreadData:
    def __init__(self, id, data, result=None):
        self.id = id
        self.data = data
        self.result = result

class ConvertibleBondSensitivityAnalyzer:
    def __init__(self, convertibleBondModel):
        self.convertibleBondModel = convertibleBondModel

    def analyzeBondPrice(self, attributeToAnalyze, dependentValues):
        helper = SensitivityAnalyser(self.convertibleBondModel.modelInput,self.convertibleBondModel.priceBond)
        return helper.analyzeValues( dependentValues, attributeToAnalyze)

    def analyzeBondConversionValue(self, attributeToAnalyze, dependentValues):
        helper = SensitivityAnalyser(self.convertibleBondModel.modelInput, self.convertibleBondModel.conversionValue)
        return helper.analyzeValues(dependentValues, attributeToAnalyze)

class Plotter:
    def __init__(self, title='Convertible Bond'):
        self._lastFigure = None
        self._lastPlot = None
        self.title = title
        self.newGraph = 1
        self._availableColors = ['b', 'g', 'r', 'c', 'm', 'y', 'k', 'w']
        self._currentColor = 0

    def plot(self, dataToPlot, newGraph=True):
        '''dataToPlot is a list of dictionaries'''
        figure,thePlot = self._initializePlot( newGraph )
        for aData in dataToPlot:
            xValues = aData['x']
            yValues = aData['y']
            color   = '-{}'.format( self._nextColor() )
            label   = aData.get('label','')
            thePlot.plot( xValues, yValues, color, label=label)
            thePlot.legend(loc='upper left')

        figure.show()
        plt.pause(0.05)

    def _nextColor(self):
        color = self._availableColors[self._currentColor % len(self._availableColors)]
        self._currentColor += 1

        return color

    def _initializePlot(self, newGraph):
        if newGraph or not self._lastFigure:
            self._currentColor = 0
            self._lastFigure = plt.figure('{} New Graph {}'.format(self.title, self.newGraph))
            self._lastPlot = self._lastFigure.add_subplot(111)
            self.newGraph += 1
        return self._lastFigure, self._lastPlot


import setuptools

with open("README.md", "r", encoding="utf-8") as fh:
    long_description = fh.read()

setuptools.setup(
    name="OCR_DataBases", # Replace with your own username
    version="0.1.0",
    author="Bohdan Shevchuk",
    author_email="shevdan007@gmail.com",
    description="Package to prepare data for ML training",
    long_description=long_description,
    long_description_content_type="text/markdown",
    url="https://github.com/shevdan/OCR_DataBases",
    classifiers=[
        "Programming Language :: Python :: 3",
        "License :: OSI Approved :: MIT License",
        "Operating System :: OS Independent",
    ],
    package_dir={"": "src"},
    install_requires=[
        'absl-py',
        'tensorflow',
        'alabaster',
        'astunparse',
        'azure-cognitiveservices-vision-computervision',
        'azure-common',
        'Babel',
        'cachetools',
        'certifi',
        'chardet',
        'docutils',
        'flatbuffers',
        'gast',
        'google-auth',
        'google-auth-oauthlib',
        'google-pasta',
        'grpcio',
        "h5py",
        'idna' ,
        'imagesize',
        'isodate',
        'Jinja2',
        'keras-nightly',
        'Keras-Preprocessing',
        'Markdown',
        'MarkupSafe',
        'msrest',
        'numpy',
        'oauthlib',
        'opt-einsum',
        'packaging',
        'pathlib',
        'Pillow',
        'protobuf',
        'pyasn1',
        'pyasn1-modules',
        'Pygments',
        'pyparsing',
        'pytz',
        'requests',
        'requests-oauthlib',
        'rsa',
        'six',
        'snowballstemmer',
        'Sphinx',
        'sphinxcontrib-applehelp',
        'sphinxcontrib-devhelp',
        'sphinxcontrib-htmlhelp',
        'sphinxcontrib-jsmath',
        'sphinxcontrib-qthelp',
        'sphinxcontrib-serializinghtml',
        'tensorboard',
        'tensorboard-data-server',
        'tensorboard-plugin-wit',
        'tensorflow-estimator',
        'termcolor',
        'typing-extensions',
        'urllib3',
        'Werkzeug',
        'wrapt',
        'imageio'
    ],
    packages=setuptools.find_packages(where="src"),
    python_requires=">=3.6",
)


"""
Created by Federico Amato
Save athletes codes and names in /codes folder
codes = np.load('/codes/codici_canottaggioservice.npy')
names = np.load('/codes/nomi_canottaggioservice.npy')
"""
import numpy as np
import requests
from bs4 import BeautifulSoup

from django.core.management.base import BaseCommand, CommandError

from pathlib import Path
ROOT_DIR = Path(__file__).resolve().parent.parent

class Command(BaseCommand):
    help = 'Scrape athletes registered in Canottaggioservice.net'
    headers = {
        'User-Agent': 'fantapoma',
    }

    def handle(self, *args, **options):
        names_url = 'https://canottaggioservice.canottaggio.net/cerca22.php'
        request_names = requests.get(names_url, headers=self.headers)

        soup = BeautifulSoup(request_names.text, 'html.parser')

        codes = [li.text for li in soup.find_all('li')]
        names = [name[1].strip() for name in np.char.split(codes, sep='-')]

        codes = np.array(codes)
        names = np.array(names)
        np.save(ROOT_DIR / 'data/codes/codici_canottaggioservice', codes)
        np.save(ROOT_DIR / 'data/codes/nomi_canottaggioservice', names)

# if __name__ == '__main__':
#     Command.handle()


import serial
import socket
import time

sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

ser = serial.Serial('/dev/ttymxc3', 115200, timeout=2.0)

# clear buffer
while ser.in_waiting:  # Or: while ser.inWaiting():
    print(ser.read(100))
print('Buffer Clear\n')

pckt_sz = 221
pckt_cnt = 0

while True:
    # assume newbytes create new packet
    pckt = ser.read(pckt_sz)
    if len(pckt) > 0:
        sock.sendto(pckt, ('localhost', 9027))
        print(pckt)
        pckt_cnt += 1
        print( 'Read {}\n'.format(pckt_cnt) )
        chk_sum = sum(pckt[:-1])%256
        if chk_sum == pckt[-1]:
            print( 'Checksum Valid {}\n'.format(chk_sum ) )
        else:
            print( 'Checksum Invalid {} not {}\n'.format(chk_sum,pckt[-1] ) )
    else:
        print('No Data')
        time.sleep(1.0)


import time
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.keys import Keys
from bs4 import BeautifulSoup
import lxml
import requests

FORM_URL = "https://docs.google.com/forms/d/e/1FAIpQLSdMv0_QZb9a5Rui0I578HifMvJrD0AX4jK3EeFHEB8UzInDNA/viewform?pli=1"
chrome_driver_path = "chromedriver.exe"
s= Service(chrome_driver_path)
URL = "https://www.magicbricks.com/property-for-rent/residential-real-estate?bedroom=1&proptype=Multistorey-Apartment,Builder-Floor-Apartment,Penthouse,Studio-Apartment,Service-Apartment&cityName=Bangalore"
header = {
    "User-Agent": "Defined",
    "Accept-Language": "en-US,en;q=0.9",
}

response = requests.get(url=URL,headers=header)

driver = webdriver.Chrome(service=s)
driver.get(URL)

address_list = []
price_list =[]
link_list = []

time.sleep(2)
all_address = driver.find_elements(By.CLASS_NAME,value="mb-srp__card--title")
for address in all_address:
    address = address.text
    address_list.append(address)

all_price = driver.find_elements(By.CLASS_NAME,value='mb-srp__card__price--amount')
for price in all_price:
    price = price.text
    price_list.append(price.replace("₹","").replace("\n",""))

url = ""
soup = BeautifulSoup(driver.page_source,'html.parser')
all_link = soup.find_all(name="div",class_="mb-srp__card")

for link in all_link:
    meta = link.find_all('meta')
    for m in meta:
        if m['itemprop'] == 'url':
            url = m['content']
    link_list.append(url)

for n in range(len(address_list)):
    driver.get(FORM_URL)

    time.sleep(2)
    address_input = driver.find_element(By.XPATH,value='//*[@id="mG61Hd"]/div[2]/div/div[2]/div[1]/div/div/div[2]/div/div[1]/div/div[1]/input')
    price_input = driver.find_element(By.XPATH,value='//*[@id="mG61Hd"]/div[2]/div/div[2]/div[2]/div/div/div[2]/div/div[1]/div/div[1]/input')
    link_input = driver.find_element(By.XPATH,value='//*[@id="mG61Hd"]/div[2]/div/div[2]/div[3]/div/div/div[2]/div/div[1]/div/div[1]/input')
    submit = driver.find_element(By.XPATH,value='//*[@id="mG61Hd"]/div[2]/div/div[3]/div[1]/div[1]/div/span/span')

    address_input.send_keys(address_list[n])
    price_input.send_keys(price_list[n])
    link_input.send_keys(link_list[n])
    submit.click()

    next_res = driver.find_element(By.LINK_TEXT, "Submit another response")
    next_res.click()
    time.sleep(1)


class Employee:

    num_of_emps = 0  # class variable
    raise_amount = 1.04  # class variable

    def __init__(self, first, last, pay):
        # all below are instance variables, unique to each instance.
        self.first = first
        self.last = last
        self.pay = pay
        self.email = first + "." + last + "@company.com"

        Employee.num_of_emps += 1

    def fullName(self):
        return "{} {}".format(self.first, self.last)

    def apply_raise(self):
        self.pay = int(
            self.pay * self.raise_amount
        )  # we can access raise_amount using Employee.raise_amount also

print(Employee.num_of_emps)

emp_1 = Employee("Ayush", "Garg", 50000)  # instance of class.
emp_2 = Employee("Arnim", "Garg", 60000)

print(Employee.num_of_emps)

# ========================================== classes and instances ==============================

# print(emp_1.first)
# print(emp_2.first)
# print(emp_1.fullName())
# print(Employee.fullName(emp_1))

# ==========================================  class variables ====================================

print(emp_1.__dict__)
emp_1.raise_amount = 1.05
print(emp_1.__dict__)
print(Employee.__dict__)
print(emp_2.__dict__)
print(
    emp_2.raise_amount
)  # raise amount fall back to class variable, since no raise_amount instance var is present.

print(emp_1.pay)
emp_1.apply_raise()
print(emp_1.pay)


#! /usr/bin/env python3

from random import randrange

nnicks={'1':1, '2':2, '3':3}
tnicks={'s':'solid', 't':'striped', 'o':'open'}
cnicks={'r':'red',   'g':'green',   'p':'purple'}
snicks={'r':'rect',  'o':'oval',    's':'squiggle'}

# three is the list of all three possibilities
# one and two are the two characteristics we have
# function returns that the third should be
def third(three, one, two):
    if one==two:
        return one # two the same-->third must be the same
    #else one and two are different, return the other one
    for other in three:
        if other != one and other != two:
            return other

class SetCard():
    def __init__(s, code):
        s.code = code
        if not s.valid():
            raise ValueError('Invalid code: '+code)

    def __eq__(one, two):
        return isinstance(two, SetCard) and one.code==two.code

    def __ne__(one, two):
        return not one.__eq__(two)

    def number (s): return    int(s.code[0])
    def texture(s): return tnicks[s.code[1]]
    def color  (s): return cnicks[s.code[2]]
    def shape  (s): return snicks[s.code[3]]

    def valid(s):
        if not s.code or len(s.code)!=4: return False
        if s.number()<1 or s.number()>3: return False
        return s.code[1] in tnicks and s.code[2] in cnicks and s.code[3] in snicks

    def describe(s):
        if s.number()==1:
            print(s.number(), s.texture(), s.color(), s.shape())
        else:
            print(s.number(), s.texture(), s.color(), s.shape()+'s')

    # given this card and a 2nd, return the third that would make a set
    def third(one, two):
        code = (str(third(nnicks.keys(), one.code[0], two.code[0])) +
                    third(tnicks.keys(), one.code[1], two.code[1]) +
                    third(cnicks.keys(), one.code[2], two.code[2])   +
                    third(snicks.keys(), one.code[3], two.code[3]))
        return SetCard(code)

def is_a_set(one, two, three):
    need = one.third(two)
    return three == one.third(two)

# returns 3-tuples the _indices_ of any sets among these cards
def find_sets(cards, force_last=False, quit_after_one=False):
    n = len(cards)
    sets = [];
    for i in range(0,n):
        for j in range(i+1,n):
            kmin = j+1
            kmax = n
            if force_last:
                kmin = n-1
            for k in range(kmin, kmax):
                if (is_a_set(cards[i], cards[j], cards[k])):
                    sets.append( (i,j,k) )
                    if quit_after_one:
                        return sets

    if len(sets):
        return sets
    # else
    return None

def has_a_set(cards, must_include_last=False):
    sets = find_sets(cards, force_last=must_include_last, quit_after_one=True)
    if sets: return True
    # else
    return False

def deck(shuffle=True):
    cards = []
    for    n in nnicks.keys():
     for   t in tnicks.keys():
      for  c in cnicks.keys():
       for s in snicks.keys():
        cards.append(SetCard(n+t+c+s))

    if shuffle:
        n = len(cards)
        for i in range(n):    # swap every card
            j = randrange(n)  # with a random card
            cards[i],cards[j] = cards[j],cards[i]

    return cards

def histogram(counts, maxchars=70):
    histr = ''

    firsti = 0
    while firsti<len(counts) and counts[firsti]==0:
        firsti += 1
    # now firsti is the index of the first nonzero

    lasti = len(counts)-1  # avoid empties at the end
    while lasti>=0 and counts[lasti]==0:
        lasti -= 1
    # now lasti is the index of the last nonzero
    lasti += 1 # bump back up one

    maxcount = counts[firsti]
    for c in counts:
        if c > maxcount:
            maxcount = c

    scale = 1.0
    if maxcount > maxchars:
        scale = maxchars/maxcount

    for i in range(firsti, lasti):
        if i<10:
            histr += ' '
        nchar = round(counts[i] * scale)
        histr += str(i) + ': ' + '#' * nchar + ' ' + str(counts[i]) + '\n'

    return histr

def mean(counts):
    sum = 0
    num = 0
    for i in range(len(counts)):
        num += counts[i]
        sum += counts[i]*i
    if num==0:
        return None
    return sum/num

#######################
##### UNIT TESTS ######
#######################
import unittest
if __name__ == '__main__':
    class SetCardTester(unittest.TestCase):
        def testSetCards(s):
            exception=False
            try:     osrr = SetCard('1srr')
            except:  exception=True
            s.assertFalse(exception)
            s.assertEqual(osrr.number(),   1)
            s.assertEqual(osrr.texture(), 'solid')
            s.assertEqual(osrr.color(),   'red')
            s.assertEqual(osrr.shape(),   'rect')

            exception=False
            try:     ttgo = SetCard('2tgo')
            except:  exception=True
            s.assertFalse(exception)
            s.assertEqual(ttgo.number(),   2)
            s.assertEqual(ttgo.texture(), 'striped')
            s.assertEqual(ttgo.color(),   'green')
            s.assertEqual(ttgo.shape(),   'oval')

            exception = False
            try:      tops = SetCard('3ops')
            except:   exception = True
            s.assertFalse(exception)
            s.assertEqual(tops.number(), 3)
            s.assertEqual(tops.texture(), 'open')
            s.assertEqual(tops.color(), 'purple')
            s.assertEqual(tops.shape(), 'squiggle')

            s.assertEqual(osrr.third(ttgo), tops)
            s.assertEqual(ttgo.third(osrr), tops)
            s.assertEqual(tops.third(ttgo), osrr)

            s.assertTrue( is_a_set(  osrr, ttgo, tops))
            s.assertTrue(has_a_set( [osrr, ttgo, tops] ))

            cards = deck()
            s.assertEqual(len(cards), 3*3*3*3) # 81

        def testShortcuts(s):
            for i in range(100):
                cards = deck()
                deal = []
                no_sets = True # with an empty deal!
                while no_sets:
                    deal.append(cards.pop())
                    all_sets    = find_sets(deal) # full search, trusted result
                    sets_w_last = find_sets(deal, force_last=True)
                    if all_sets:
                        stophere=1
                    sets_max_1  = find_sets(deal, quit_after_one=True)
                    sets_last_1 = find_sets(deal, force_last=True, quit_after_one=True)
                    if all_sets: # not None
                        s.assertEqual(sets_w_last, all_sets)
                        s.assertEqual(len(sets_max_1), 1)
                        s.assertEqual(len(sets_last_1), 1)
                        s.assertEqual(sets_max_1, sets_last_1)
                        s.assertEqual(sets_max_1[0], sets_w_last[0])
                        no_sets = False # go shuffle a new deal
                    else: # all_sets is None
                        s.assertIsNone(sets_w_last)
                        s.assertIsNone(sets_max_1)
                        s.assertIsNone(sets_last_1)

    unittest.main()


# import the Twist module from geometry_msgs messages interface
from geometry_msgs.msg import Twist
# import the MyCustomServiceMessage module from custom_interfaces_service interface
# from custom_interfaces.srv import FindWall
# import the Empty module from std_servs service interface
from std_srvs.srv import Empty
# import the ROS2 python client libraries
import rclpy
from rclpy.node import Node
from sensor_msgs.msg import LaserScan
from rclpy.qos import ReliabilityPolicy, QoSProfile
import time
import math
from rclpy.executors import MultiThreadedExecutor, SingleThreadedExecutor
from rclpy.callback_groups import MutuallyExclusiveCallbackGroup, ReentrantCallbackGroup

class FindwallService(Node):

    def __init__(self):
        # Here we have the class constructor

        # call the class constructor to initialize the node as service_stop
        super().__init__('findwall_server')
        # create the service server object
        # defines the type, name and callback function
        self.group1 = ReentrantCallbackGroup()  # MutuallyExclusiveCallbackGroup()
        self.group2 = ReentrantCallbackGroup()  # MutuallyExclusiveCallbackGroup()
        self.group3 = ReentrantCallbackGroup()  # MutuallyExclusiveCallbackGroup()

        # ros2 service call /find_wall std_srvs/srv/Empty
        self.srv = self.create_service(
            Empty, 'find_wall', self.CustomService_callback, callback_group=self.group1)

        # create the publisher object
        # in this case the publisher will publish on /cmd_vel topic with a queue size of 10 messages.
        # use the Twist module
        self.publisher_ = self.create_publisher(
            Twist, 'cmd_vel', 10, callback_group=self.group2)
        self.subscriber = self.create_subscription(
            LaserScan, '/scan', self.update_scan, QoSProfile(depth=10, reliability=ReliabilityPolicy.BEST_EFFORT), callback_group=self.group3)
        self.laser_f = 0
        self.MAX_ROTATE_SPEED = 1.0
        self.BUFFER = 3

# smith@ubuntu:~$ ros2 topic type /scan
# sensor_msgs/msg/LaserScan

# smith@ubuntu:~$ ros2 interface show sensor_msgs/msg/LaserScan
# # Single scan from a planar laser range-finder
# #
# # If you have another ranging device with different behavior (e.g. a sonar
# # array), please find or create a different message, since applications
# # will make fairly laser-specific assumptions about this data

# std_msgs/Header header # timestamp in the header is the acquisition time of
#         builtin_interfaces/Time stamp
#                 int32 sec
#                 uint32 nanosec
#         string frame_id
#                              # the first ray in the scan.
#                              #
#                              # in frame frame_id, angles are measured around
#                              # the positive Z axis (counterclockwise, if Z is up)
#                              # with zero angle being forward along the x axis

# float32 angle_min            # start angle of the scan [rad]
# float32 angle_max            # end angle of the scan [rad]
# float32 angle_increment      # angular distance between measurements [rad]

# float32 time_increment       # time between measurements [seconds] - if your scanner
#                              # is moving, this will be used in interpolating position
#                              # of 3d points
# float32 scan_time            # time between scans [seconds]

# float32 range_min            # minimum range value [m]
# float32 range_max            # maximum range value [m]

# float32[] ranges             # range data [m]
#                              # (Note: values < range_min or > range_max should be discarded)

# len(ranges)=
# angle_increment=0.052799832075834274 # 3 degree
# angle_min=-3.141590118408203
# angle_max=3.141590118408203

    def update_scan(self, msg):  # LaserScan
        self.get_logger().info(f'XXXXXX0 {msg.ranges[180//3]}, {msg.ranges[90//3]}, {msg.ranges[270//3]}, {msg.ranges[0]}')
        self.laser_f = msg.ranges[60]

    def getMinIndex(self, msg):
        min_idx = min_range = -1
        for i in msg.ranges:
            r = msg.ranges[i]
            if r == math.inf:
                continue
            if r < min_range:
                min_range = r
                min_idx = i
        return min_idx

    def rotate(self, msg, target=179):
        buffer = self.BUFFER
        while True:
            mi = self.getMinIndex(msg)
            if mi < 0:
                msg.linear.x = 0.0
                msg.angular.z = 0.0
            elif mi+360 < target-buffer + 360:
                msg.linear.x = 0.0
                msg.angular.z = -self.MAX_ROTATE_SPEED*(target-mi)/180
            elif mi+360 > target+1+buffer + 360:
                msg.linear.x = 0.0
                msg.angular.z = self.MAX_ROTATE_SPEED*(mi-target)/180
            else:  # mi == target +- buffer
                break
            self.publisher_.publish(msg)
            time.sleep(1)

        msg.linear.x = 0.0
        msg.angular.z = 0.0
        self.publisher_.publish(msg)

    def gotowall(self, msg):
        while True:
            self.get_logger().info(f'self.laser_f={self.laser_f}')
            if self.laser_f == math.inf:
                msg.linear.x = 0.5
            elif self.laser_f <= 3:
                break
            else:
                msg.linear.x = 0.3

            self.publisher_.publish(msg)
            time.sleep(1)

        msg.linear.x = 0.0
        msg.angular.z = 0.0
        self.publisher_.publish(msg)

    def CustomService_callback(self, request, response):
        # The callback function recives the self class parameter,
        # received along with two parameters called request and response
        # - receive the data by request
        # - return a result as response
        # create a Twist message
        msg = Twist()
        # self.rotate(msg, target=179)
        self.gotowall(msg)
        # self.rotate(msg, target=269)
        # response state
        # response.wallfound = True
        # response.message = "Found wall"

        # return the response parameter
        return response

def main(args=None):
    # initialize the ROS communication
    rclpy.init(args=args)

    # # declare the node constructor
    # service = FindwallService()
    # # pause the program execution, waits for a request to kill the node (ctrl+c)
    # rclpy.spin(service)
    # # shutdown the ROS communication
    # rclpy.shutdown()
    try:
        # declare the node constructor
        findwall_service = FindwallService()

        executor = MultiThreadedExecutor(num_threads=3)
        executor.add_node(findwall_service)

        try:
            # pause the program execution, waits for a request to kill the node (ctrl+c)
            executor.spin()
        finally:
            executor.shutdown()
            findwall_service.destroy_node()

    finally:
        # shutdown the ROS communication
        rclpy.shutdown()

if __name__ == '__main__':
    main()


from expo.gbe_logging import log_func
from gbe.models import Volunteer
from gbe.views import BidChangeStateView
from scheduler.idd import (
    set_person,
    remove_person,
)
from gbe.email.functions import send_schedule_update_mail
from gbe.scheduling.views.functions import show_general_status
from scheduler.data_transfer import (
    Person,
)

class VolunteerChangeStateView(BidChangeStateView):
    object_type = Volunteer
    coordinator_permissions = ('Volunteer Coordinator',)
    redirectURL = 'volunteer_review_list'

    def get_bidder(self):
        self.bidder = self.object.profile

    def groundwork(self, request, args, kwargs):
        self.prep_bid(request, args, kwargs)
        if request.POST['accepted'] != '3':
            self.notify_bidder(request)

    @log_func
    def bid_state_change(self, request):
        # Clear all commitments
        remove_response = remove_person(
            user=self.bidder.user_object,
            labels=[self.object.b_conference.conference_slug],
            roles=['Volunteer'])
        show_general_status(request, remove_response, self.__class__.__name__)

        # if the volunteer has been accepted, set the events.
        if request.POST['accepted'] == '3':
            person = Person(
                    user=self.bidder.user_object,
                    public_id=self.bidder.pk,
                    role='Volunteer')
            for assigned_event in request.POST.getlist('events'):
                set_response = set_person(
                    assigned_event,
                    person)
                show_general_status(request,
                                    set_response,
                                    self.__class__.__name__)

            email_status = send_schedule_update_mail('Volunteer', self.bidder)
            self.check_email_status(request, email_status)

        return super(VolunteerChangeStateView, self).bid_state_change(
            request)


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

class LinkedList:
    def __init__(self):
        self.head = None

    def printList(self):
        curr = self.head

        while curr:
            print(curr.data)
            curr = curr.next

    def append(self, data):
        newNode = Node(data)

        if not self.head:
            self.head = newNode
            return

        lastNode = self.head

        while lastNode.next:
            lastNode = lastNode.next

        lastNode.next = newNode

    def moveTailToHead(self):
        tail = self.head
        secondToTail = None

        while tail.next:
            secondToTail = tail
            tail = tail.next

        secondToTail.next = None
        tail.next = self.head
        self.head = tail

llist = LinkedList()
llist.append(1)
llist.append(2)
llist.append(3)
llist.moveTailToHead()
llist.printList()


def get_count(self, ngram, corpus=None):
        r"""Get the count of an n-gram in the corpus.

        Parameters
        ----------
        ngram : str
            The n-gram to retrieve the count of from the n-gram corpus
        corpus : Corpus
            The corpus

        Returns
        -------
        int
            The n-gram count

        Examples
        --------
        >>> tqbf = 'The quick brown fox jumped over the lazy dog.\n'
        >>> tqbf += 'And then it slept.\n And the dog ran off.'
        >>> ngcorp = NGramCorpus(Corpus(tqbf))
        >>> NGramCorpus(Corpus(tqbf)).get_count('the')
        2
        >>> NGramCorpus(Corpus(tqbf)).get_count('fox')
        1

        """
        if not corpus:
            corpus = self.ngcorpus

        # if ngram is empty, we're at our leaf node and should return the
        # value in None
        if not ngram:
            return corpus[None]

        # support strings or lists/tuples by splitting strings
        if isinstance(ngram, (text_type, str)):
            ngram = text_type(ngram).split()

        # if ngram is not empty, check whether the next element is in the
        # corpus; if so, recurse--if not, return 0
        if ngram[0] in corpus:
            return self.get_count(ngram[1:], corpus[ngram[0]])
        return 0


# Animation class for performing a smimple animation
# of rgb lights
#
# author: ulno
# created: 2017-05-23
#
import time
from ulnoiot import colors as _c

class Animation():
    def __init__(self, device, command_str):
        self.program=command_str.split()
        self.device=device
        self.playing = True
        self.program = command_str.split()
        self.step = 0
        self.fade_goals = {}
        self.length = 0
        self.starttime = 0
        self.delta = 0
        self.lasttime = time.ticks_ms()

    def stop(self):
        self.playing=False

    def start(self):
        if self.program is not None and len(self.program)>0:
            if self.step >= len(self.program):
                self.step=0
            self.playing = True

    def next(self):
        current_time = time.ticks_ms()
        while self.length <= 0:
            # find next command
            commands="sfpr"
            while self.step<len(self.program) \
                    and self.program[self.step] not in commands:
                self.step += 1
            if self.step>=len(self.program):
                self.stop()
                return
            cmd=self.program[self.step]
            # read arguments
            args=[]
            self.step += 1
            while self.step<len(self.program) \
                    and self.program[self.step] not in commands:
                args.append(self.program[self.step])
                self.step += 1
            if cmd=="s": # set
                self.device._command_list_rgb(args)
            elif cmd=="f": # fade goal
                led_num=int(args[0])-1
                if led_num<=0: led_num=0
                self.fade_goals[led_num] = \
                    (self.device.get(led_num=led_num), \
                     _c.get(args[1]))
                print("fade goal",led_num,self.fade_goals[led_num])
            elif cmd=="p":
                self.length =  int(args[0])
                self.starttime = current_time
            elif cmd=="r":
                self.step = 0
                break # even if this loses a bit of time, we want to prevent endless loops

        if self.length > 0: # play animation
            delta = time.ticks_diff(current_time, self.starttime)
            progress = min(1.0,delta/self.length)
            changed=False
            for i in self.fade_goals:
                ((fr,fg,fb),(tr,tg,tb)) = self.fade_goals[i]
                (cr,cg,cb) = self.device.get(led_num=i)
                if self.length <= delta:
                    (nr,ng,nb) = (tr,tg,tb)
                    self.length=0 # signal finished of this animation
                    del(self.fade_goals[i]) # clear them
                else:
                    nr = int(fr+(tr-fr)*progress)
                    #debug print("i",i,"new r",nr,"from r",fr,"to r",tr,"progress",progress)
                    ng = int(fg+(tg-fg)*progress)
                    nb = int(fb+(tb-fb)*progress)
                if (cr,cg,cb) != (nr,ng,nb):
                    self.device._set(nr,ng,nb,i)
                    changed=True
            if changed:
                self.device._write()


from itertools import permutations

k = 80  #현재 피로도
dungeons = [[80,10]]    # 0: 최소 피로도 1: 소모 피로도

def solution(k, dungeons):
    countlist = []
    allCase = list(permutations(dungeons, len(dungeons)))

    for i in allCase:
        tempk=k
        count = 0
        for need, use in i:
            if tempk >= need and tempk >=use:   #던전을 돌 피로도가 남아있고 소모피로도도 남아있음
                tempk -= use
                count += 1
            else:
                break
        countlist.append(count)

    return max(countlist)

print(solution(k, dungeons))


import dash
import dash_bootstrap_components as dbc

# meta_tags are required for the app layout to be mobile responsive
app = dash.Dash(__name__, external_stylesheets=[dbc.themes.FLATLY], suppress_callback_exceptions=True,  # NOQA E501
                meta_tags=[{'name': 'viewport',
                            'content': 'width=device-width, "background-color": "#D1CBC9", initial-scale=1.0'}]  # NOQA E501
                )
app.title = 'Floor Plan'
server = app.server


from rest_framework import serializers

from ....core.api.serializers import BaseSerializer
from ... import models

class PaymentObjectDataSerializer(serializers.Serializer):
    """Serializer present payment object data for `Payment` model."""

    client_secret = serializers.CharField(allow_null=True)
    status = serializers.CharField()

class PaymentSerializer(BaseSerializer):
    """Serializer for `Payment` model."""

    payment_object_data = PaymentObjectDataSerializer()

    class Meta:
        model = models.Payment
        fields = (
            'id',
            'payer',
            'recipient',
            'amount',
            'application_fee_amount',
            'description',
            'status',
            'payment_object_data',
        )

class StartPaymentParamsSerializer(serializers.Serializer):
    """Serializer for model retrieval for payments."""

    object_type = serializers.ChoiceField(choices=(
        'invoice', 'support'
    ))
    object_id = serializers.IntegerField()


import os
from .. import utils

class ModalKeymap():
    _keymap = {}
    _action_to_keymap = {}
    _events = set()
    def __init__(self, keymap):
        self._keymap = {v: k for k, v in keymap.items()}
        self._actions = {action for action in keymap.keys()}

    def update_mapping(self, action, event_type, event_value, ctrl=False, shift=False, alt=False):
        keymap_item = (event_type, 'PRESS', ctrl, shift, alt)

        if action in self._keymap.values():
            if keymap_item in self._keymap:
                if action != self._keymap[keymap_item]:
                    return False
            else:
                self.remove_mapping(action)
                self._keymap[keymap_item] = action
            return True

    def remove_mapping(self, event):
        for keymap, keymap_value in self._keymap.items():
            if event == keymap_value:
                del self._keymap[keymap]
                break

    def get_all_mappings(self):
        return self._keymap.items()

    def get_action_from_mapping(self, mapping):
        return self._keymap.get(mapping)

    def get_mapping_from_action(self, action):
        action_to_keymap = {v: k for k, v in self._keymap.items()}
        return action_to_keymap[action]

    def get_valid_keymap_actions(self):
        return self._actions

class ModalOperatorKeymapCache():
    keymaps = {}

    @classmethod
    def get_keymap(cls, operator_id) -> ModalKeymap:
        if operator_id in cls.keymaps:
            return cls.keymaps[operator_id]
        else:
            keymap = load_keymap(operator_id)
            cls.keymaps[operator_id] = ModalKeymap(keymap)
            return  cls.keymaps[operator_id]

    @classmethod
    def get_all_keymaps(cls):
        return cls.keymaps.items()

def load_keymap(operator_id):
    def repair_data(data):
        return {k: tuple(v) for k, v in data.items()}

    directory = os.path.dirname(os.path.abspath(__file__))
    parent_directory = os.path.dirname(directory)
    file_path = os.path.join(parent_directory, "HotkeyPrefs.JSON")

    deserializer = utils.serialization.JSONDeserializer(file_path)
    data = repair_data(deserializer.deserialize()[operator_id])
    return data

def save_keymap(operator_id, modal_keymap: ModalKeymap=None):
    directory = os.path.dirname(os.path.abspath(__file__))
    parent_directory = os.path.dirname(directory)
    file_path = os.path.join(parent_directory, "HotkeyPrefs.JSON")

    data = None
    if modal_keymap is not None:
        keymap_data = {v: k for k, v in modal_keymap.get_all_mappings()}
        data = {operator_id:
            keymap_data
        }
    else:
        data = {operator_id :
            {"even": ('e', 'PRESS', False, False, False),
            "flip": ('f', 'PRESS', False, False, False),
            "midpoint": ('c', 'PRESS', False, False, False),
            "mirrored": ('m', 'PRESS', False, False, False),
            "perpendicular": ('/', 'PRESS', False, False, False),
            "multi_loop_offset": ('o', 'PRESS', False, False, False),
            "scale": ('w', 'PRESS', False, False, False),
            "snap_points": ('s', 'PRESS', False, False, False),
            "lock_snap_points": ('x', 'PRESS', False, False, False),
            "freeze_edge": (',', 'PRESS', False, False, False),
            "increase_loop_count": ('+', 'PRESS', False, False, False),
            "decrease_loop_count": ('-', 'PRESS', False, False, False),
            }
        }

    utils.serialization.JSONSerializer(file_path).serialize(data)

    print(f" Saved modal keymap preferences to: {file_path}")


#Implementaion of hash table
TABLE_SIZE = 10

class Node:
    def __init__(self, key, value):
        self.key = key
        self.value = value
        self.next = None

    def __str__(self):
        res = f'key: {self.key} value: {self.value} next: {self.next.key if self.next is not None else "--"} \n'
        node = self.next
        while node is not None:
            res += f'key: {node.key} value: {node.value} next: {node.next.key if node.next is not None else "--"} \n'
            node = node.next
        return res

class HashTable:
    def __init__(self):
        self.capacity = TABLE_SIZE
        self.buckets = [None] * TABLE_SIZE
        self.size = 0

    def hash (self, key):
        hash_sum = 0
        for index, c in enumerate(key):
            hash_sum += (index + len(key)) ** ord(c)
        return hash_sum % self.capacity

    def last_node(self, hashed_key):
        node = self.buckets[hashed_key]
        if (node is None):
            return
        while node.next is not None:
            node = node.next
        return node

    def insert (self, key, value):
        hashed_key = self.hash(key)
        last = self.last_node(hashed_key)
        if last is None:
            self.buckets[hashed_key] = Node(key, value)
        else:
            last.next = Node(key, value)
        self.size += 1

    def get(self, key):
        hashed_key = self.hash(key)
        node = self.buckets[hashed_key]
        if node is None:
            return
        while True:
            if node.key == key:
                return node
            if node.next is None:
                break
        return

    def delete (self, key):
        hashed_key = self.hash(key)
        node = self.buckets[hashed_key]
        prev_node = None
        if node is None:
            return False
        while node is not None:
            if node.key == key:
                if prev_node is None:
                    self.buckets[hashed_key] = node.next
                prev_node.next = node.next
                return node

            prev_node = node
            node = node.next
        return

ht = HashTable()
ht.insert("myKey", "myValue")       #hash key = 1
ht.insert("test0", "test0->123")    #hash key = 1
ht.insert("test1", "test1->123")
ht.insert("test2", "test2->123")    #hash key = 1
ht.insert("test3", "test3->123")
ht.insert("test4", "test4->123")    #hash key = 1
ht.insert("test5", "test5->123")
ht.insert("test6", "test6->123")    #hash key = 1
ht.insert("test7", "test7->123")
ht.delete("test2")                  #deleted from hash bucket 1
print(ht.get("myKey"))


#!/usr/bin/env python

import math
import numpy as np
import rospy
from Tkinter import *
import tkFont
from geometry_msgs.msg import PoseStamped

# -----------  Settings -----------
inputtopic = "/rovioli/T_G_I"

fontsize = 60
fieldwidth = 5
xl = 0.15
xm = 0.35
xr = 0.6
yt = 0.25
yx = 0.4
yy = .55
yz = .7
title = "The Shepherd's most trustworthy \nLocalization-Device-Thingy "
goals = [[45.8, 17.3, 1.4], [24.4, -1.7, 1.2], [3.2, 9.9, 1.2]]  # Mav, Rob, Map
colors = ["#cccccc", "#ff5e33", "#ffda33", "#5de146", "#888888"]
# ---------------------------------

# Init window
window = Tk()
window.title("JGameMonitor")
window.attributes('-zoomed', True)

# General
the_font = tkFont.Font(family="Lucida Grande", size=fontsize)
current_goal = 0

# Gui definition
tt = Label(window, font=the_font)
tt.config(text=title)
tt.pack(side=TOP, expand=NO, fill=X)

t1 = Label(window, text="Current:", font=the_font)
t2 = Label(window, text="Goal:", font=the_font)
w_x = Label(window, text="X [m]:", font=the_font)
w_y = Label(window, text="Y [m]:", font=the_font)
w_z = Label(window, text="Z [m]:", font=the_font)

t1.place(relx=xm, rely=yt)
t2.place(relx=xr, rely=yt)
w_x.place(relx=xl, rely=yx)
w_y.place(relx=xl, rely=yy)
w_z.place(relx=xl, rely=yz)

e_x = Entry(window, font=the_font, justify='center')
e_y = Entry(window, font=the_font, justify='center')
e_z = Entry(window, font=the_font, justify='center')
e_x2 = Entry(window, font=the_font, justify='center')
e_y2 = Entry(window, font=the_font, justify='center')
e_z2 = Entry(window, font=the_font, justify='center')

e_x.config(width=fieldwidth)
e_y.config(width=fieldwidth)
e_z.config(width=fieldwidth)
e_x2.config(width=fieldwidth)
e_y2.config(width=fieldwidth)
e_z2.config(width=fieldwidth)

e_x.place(relx=xm, rely=yx)
e_y.place(relx=xm, rely=yy)
e_z.place(relx=xm, rely=yz)
e_x2.place(relx=xr, rely=yx)
e_y2.place(relx=xr, rely=yy)
e_z2.place(relx=xr, rely=yz)

class Buttons(object):
    def __init__(self):
        self.prevBtn = Button(window, text='Prev', command=self.prev_callback, font=the_font)
        self.prevBtn.place(rely=0.95, relx=0.05, anchor=SW)
        self.nextBtn = Button(window, text='Next', command=self.next_callback, font=the_font)
        self.nextBtn.place(rely=0.95, relx=0.95, anchor=SE)
        self.tb = Entry(window, font=the_font, justify='center')
        self.tb.place(rely=0.95, relx=0.5, anchor=S)

    def next_callback(self):
        global current_goal
        global colors
        if current_goal >= 3:
            return
        current_goal = current_goal + 1
        self.prevBtn.config(bg=colors[current_goal-1])
        self.tb.config(bg=colors[current_goal])
        self.nextBtn.config(bg=colors[current_goal+1])
        e_x2.delete(0, END)
        e_y2.delete(0, END)
        e_z2.delete(0, END)
        e_x2.insert(0, goals[current_goal-1][0])
        e_y2.insert(0, goals[current_goal-1][1])
        e_z2.insert(0, goals[current_goal-1][2])
        self.tb.delete(0, END)
        self.tb.insert(0, "Flock of Sheep %i / 3" % current_goal)

    def prev_callback(self):
        global current_goal
        global colors
        if current_goal <= 1:
            return
        current_goal = current_goal - 1
        self.prevBtn.config(bg=colors[current_goal - 1])
        self.tb.config(bg=colors[current_goal],
                       text="Goal %i / 3" % current_goal)
        self.nextBtn.config(bg=colors[current_goal + 1])
        e_x2.delete(0, END)
        e_y2.delete(0, END)
        e_z2.delete(0, END)
        e_x2.insert(0, goals[current_goal - 1][0])
        e_y2.insert(0, goals[current_goal - 1][1])
        e_z2.insert(0, goals[current_goal - 1][2])

buttons = Buttons()
buttons.next_callback()

# Update
def pose_callback(msg):
    e_x.delete(0, END)
    e_y.delete(0, END)
    e_z.delete(0, END)
    e_x.insert(0, ".1f" % msg.pose.position.x)
    e_y.insert(0, ".1f" % msg.pose.position.y)
    e_z.insert(0, ".1f" % msg.pose.position.z)

# Init ros
rospy.init_node("j_game_monitor")
sub = rospy.Subscriber(inputtopic, PoseStamped, pose_callback, queue_size=100)

# Start
window.mainloop()


from typing import Sized
import csv

import math
import numpy as np
size=100
class CrocMonitor:
    locationList =[]
    def __init__(self, size):

        self.locationList = []
        self.matrix = [[0 for x in range(size)]for y in range(size)]
        self.points=[]
        self.readData()
        self.storeDistance()

    def readData(self):
        with open('Locations.csv') as f:
            csv_reader = csv.reader(f)
            index = 0
            next(csv_reader)
            for line in csv_reader:

                pointName=line[0]
                x=line[1]
                y=line[2]
                number=line[3]
                edge=line[4]

                water=False
                if line[5] == "W":
                    water=True

                self.locationList.append([pointName,  x, y, number, edge, water]) # etc

                if not pointName in self.points:

                    self.points.append(pointName)
                index += 1

        f.close()

    def storeDistance(self):

        # Iterates through the location list and get the index at each location
        for index in range(0, len(self.locationList)-1):
            # Check if the neighbor column is null at current location row
            if self.locationList[index][4]!="":
                # If not null, assign the current location to be the start point of the edge
                startpoint = self.locationList[index][0]
                # Assign the neighbor of the start point to be the end point
                endpoint = self.locationList[index][4]
                # Calculate the distance between the start and end points
                distance = self.computeDistance(startpoint, endpoint)
                # Append the distance to the last column of the location row
                self.locationList[index].append(distance)
        return

    def computePathDistance (self,path):

        #provide the distance between two points a and b, as the end points on a path. Assume not adjacent
        distance=0
        return distance

    def findPath(self,a,b):
        path=[]
        #returns shortest path a to b
        return path

    def computeDistance (self, a, b):

        # provide the distance between two points a and b on a path. Assume adjacent

        # Initialize the distance and the x, y coordinates of location a and b
        distance=0
        xA = 0
        xB = 0
        yA = 0
        yB = 0
        # Find x, y coordinates of location a and b
        for location in self.locationList:
            if location[0] == a:
                xA = location[1]
                yA = location[2]
            if location[0] == b:
                xB = location[1]
                yB = location[2]
        # Calculate the distance between location a and b
        distance = math.sqrt((int(xA)-int(xB))**2 + (int(yA)-int(yB))**2)
        return distance

    def computeCosting(self, a, b):
    # unit costs for scanning all points on all paths between two locations and give exhaustive path for rangers to follow, returned as an list
        path=[]
        costing=0
        return costing,path

    def improveDistance (self, a, b):
    #return point blocked as a value on map (eg A1) and scaled increase in distance between points
        point="A1"
        scaledImprovement=0
        return point, scaledImprovement

    def countCroc(self, beach, x):
    #count the number of crocs likely in a x mile radius of a beach. Return an array [location, number]
        number=0
        return number

    def locateOptimalBlockage(self,a,b):
    # return the point blocked eg A1 and the increase in protection provided using some weighting
        point="A1"
        protection=1
        return point, protection

    def minTime(self,a,b):
    #return list of points trevelled and the time required
        path=[]
        return path

    def findScope(self, a, b):
        #provide start and end point of search, collect points to consider in search
        pointList=[a,b]

        #find location of a and b in points list
        for index in range(0, size-1):
            if self.points[index ]== a:
                indexa=index
            if self.points[index] == b:
                indexb = index
        #Find all paths a to b - Select direct routes only, no cycles or backtracking

        #Find shortest route from path options

        # Add side points to inspect
        #include all nodes that are linked to (neighbour of) any internal point on path (ie point crocodiles can enter)
        #       between a and b - this may add backtracking

        #Example findScope ("15","18")
            #paths are [15,16,18] and [15,16,17,19,20]
            #shortest path [15,16,18]
            #add neighbours [15,16,17,18]

        #This is the exhaustive list of points rangers need to inspect
        return pointList

if __name__ == '__main__':

    cm=CrocMonitor(size)
    #print (cm.locationList)

    for i in range(0,len(cm.locationList)):
        print(cm.locationList[i])

    #Changed examples
    cm.computeCosting("15","18")

    # exhaustive path is  [15,16, 17,16, 18] so return the length of this as unit cost - note data changes in Locations.csv
    #algorithm to find scope of spanning tree is provided as findScope()
    cm.improveDistance("15","18")
    #output will be 16  Ratio is "original distance on [15,16,18]:0"
    cm.locateOptimalBlockage("15", "18")
    #returns 16 as other routes have alternative paths
    #may use other data to decide optimum path, but explain in requirements for this method
    cm.minTime("15", "18")
    #returns [15,16,18] and time to travel that path


from __future__ import print_function

import sys
import time

import py_trees
from srunner.challenge.autoagents.agent_wrapper import AgentWrapper
from srunner.challenge.challenge_statistics_manager import ChallengeStatisticsManager
from srunner.scenariomanager.carla_data_provider import CarlaDataProvider, CarlaActorPool
from srunner.scenariomanager.result_writer import ResultOutputProvider
from srunner.scenariomanager.timer import GameTime, TimeOut
from srunner.scenariomanager.watchdog import Watchdog

class Scenario(object):

    """
    Basic scenario class. This class holds the behavior_tree describing the
    scenario and the test criteria.

    The user must not modify this class.

    Important parameters:
    - behavior: User defined scenario with py_tree
    - criteria_list: List of user defined test criteria with py_tree
    - timeout (default = 60s): Timeout of the scenario in seconds
    - terminate_on_failure: Terminate scenario on first failure
    """

    def __init__(self, behavior, criteria, name, timeout=60, terminate_on_failure=False):
        self.behavior = behavior
        self.test_criteria = criteria
        self.timeout = timeout
        self.name = name

        if self.test_criteria is not None and not isinstance(self.test_criteria, py_trees.composites.Parallel):
            # list of nodes
            for criterion in self.test_criteria:
                criterion.terminate_on_failure = terminate_on_failure

            # Create py_tree for test criteria
            self.criteria_tree = py_trees.composites.Parallel(name="Test Criteria")
            self.criteria_tree.add_children(self.test_criteria)
            self.criteria_tree.setup(timeout=1)
        else:
            self.criteria_tree = criteria

        # Create node for timeout
        self.timeout_node = TimeOut(self.timeout, name="TimeOut")

        # Create overall py_tree
        self.scenario_tree = py_trees.composites.Parallel(name, policy=py_trees.common.ParallelPolicy.SUCCESS_ON_ONE)
        if behavior is not None:
            self.scenario_tree.add_child(self.behavior)
        self.scenario_tree.add_child(self.timeout_node)
        if criteria is not None:
            self.scenario_tree.add_child(self.criteria_tree)
        self.scenario_tree.setup(timeout=1)

    def _extract_nodes_from_tree(self, tree):  # pylint: disable=no-self-use
        """
        Returns the list of all nodes from the given tree
        """
        node_list = [tree]
        more_nodes_exist = True
        while more_nodes_exist:
            more_nodes_exist = False
            for node in node_list:
                if node.children:
                    node_list.remove(node)
                    more_nodes_exist = True
                    for child in node.children:
                        node_list.append(child)

        if len(node_list) == 1 and isinstance(node_list[0], py_trees.composites.Parallel):
            return []

        return node_list

    def get_criteria(self):
        """
        Return the list of test criteria (all leave nodes)
        """
        criteria_list = self._extract_nodes_from_tree(self.criteria_tree)
        return criteria_list

    def terminate(self):
        """
        This function sets the status of all leaves in the scenario tree to INVALID
        """
        # Get list of all nodes in the tree
        node_list = self._extract_nodes_from_tree(self.scenario_tree)

        # Set status to INVALID
        for node in node_list:
            node.terminate(py_trees.common.Status.INVALID)

class ScenarioManager(object):

    """
    Basic scenario manager class. This class holds all functionality
    required to start, and analyze a scenario.

    The user must not modify this class.

    To use the ScenarioManager:
    1. Create an object via manager = ScenarioManager()
    2. Load a scenario via manager.load_scenario()
    3. Trigger the execution of the scenario manager.execute()
       This function is designed to explicitly control start and end of
       the scenario execution
    4. Trigger a result evaluation with manager.analyze()
    5. Cleanup with manager.stop_scenario()
    """

    def __init__(self, debug_mode=False, challenge_mode=False, timeout=2.0):
        """
        Init requires scenario as input
        """
        self.scenario = None
        self.scenario_tree = None
        self.scenario_class = None
        self.ego_vehicles = None
        self.other_actors = None

        self._debug_mode = debug_mode
        self._challenge_mode = challenge_mode
        self._agent = None
        self._running = False
        self._timestamp_last_run = 0.0
        self._timeout = timeout
        self._watchdog = Watchdog(float(self._timeout))

        self.scenario_duration_system = 0.0
        self.scenario_duration_game = 0.0
        self.start_system_time = None
        self.end_system_time = None

    def _reset(self):
        """
        Reset all parameters
        """
        self._running = False
        self._timestamp_last_run = 0.0
        self.scenario_duration_system = 0.0
        self.scenario_duration_game = 0.0
        self.start_system_time = None
        self.end_system_time = None
        GameTime.restart()

    def cleanup(self):
        """
        This function triggers a proper termination of a scenario
        """

        if self.scenario is not None:
            self.scenario.terminate()

        if self._agent is not None:
            self._agent.cleanup()
            self._agent = None

        CarlaDataProvider.cleanup()
        CarlaActorPool.cleanup()

    def load_scenario(self, scenario, agent=None):
        """
        Load a new scenario
        """
        self._reset()
        self._agent = AgentWrapper(agent, self._challenge_mode) if agent else None
        self.scenario_class = scenario
        self.scenario = scenario.scenario
        self.scenario_tree = self.scenario.scenario_tree
        self.ego_vehicles = scenario.ego_vehicles
        self.other_actors = scenario.other_actors

        CarlaDataProvider.register_actors(self.ego_vehicles)
        CarlaDataProvider.register_actors(self.other_actors)
        # To print the scenario tree uncomment the next line
        # py_trees.display.render_dot_tree(self.scenario_tree)

        if self._challenge_mode:
            ChallengeStatisticsManager.next_scenario(self.scenario)

        if self._agent is not None:
            self._agent.setup_sensors(self.ego_vehicles[0], self._debug_mode)

    def run_scenario(self):
        """
        Trigger the start of the scenario and wait for it to finish/fail
        """
        print("ScenarioManager: Running scenario {}".format(self.scenario_tree.name))
        self.start_system_time = time.time()
        start_game_time = GameTime.get_time()

        self._watchdog.start()
        self._running = True

        while self._running:
            timestamp = None
            world = CarlaDataProvider.get_world()
            if world:
                snapshot = world.get_snapshot()
                if snapshot:
                    timestamp = snapshot.timestamp
            if timestamp:
                self._tick_scenario(timestamp)

        self._watchdog.stop()

        self.cleanup()

        self.end_system_time = time.time()
        end_game_time = GameTime.get_time()

        self.scenario_duration_system = self.end_system_time - \
            self.start_system_time
        self.scenario_duration_game = end_game_time - start_game_time

        if self.scenario_tree.status == py_trees.common.Status.FAILURE:
            print("ScenarioManager: Terminated due to failure")

    def _tick_scenario(self, timestamp):
        """
        Run next tick of scenario
        This function is a callback for world.on_tick()

        Important:
        - It has to be ensured that the scenario has not yet completed/failed
          and that the time moved forward.
        - A thread lock should be used to avoid that the scenario tick is performed
          multiple times in parallel.
        """

        if self._timestamp_last_run < timestamp.elapsed_seconds and self._running:
            self._timestamp_last_run = timestamp.elapsed_seconds

            self._watchdog.update()

            if self._debug_mode:
                print("\n--------- Tick ---------\n")

            # Update game time and actor information
            GameTime.on_carla_tick(timestamp)
            CarlaDataProvider.on_carla_tick()

            if self._agent is not None:
                ego_action = self._agent()

            # Tick scenario
            self.scenario_tree.tick_once()

            if self._debug_mode:
                print("\n")
                py_trees.display.print_ascii_tree(self.scenario_tree, show_status=True)
                sys.stdout.flush()

            if self.scenario_tree.status != py_trees.common.Status.RUNNING:
                self._running = False

            if self._challenge_mode:
                ChallengeStatisticsManager.compute_current_statistics()

            if self._agent is not None:
                self.ego_vehicles[0].apply_control(ego_action)

        if self._agent and self._running and self._watchdog.get_status():
            CarlaDataProvider.perform_carla_tick(self._timeout)

    def get_running_status(self):
        """
        returns:
           bool:  False if watchdog exception occured, True otherwise
        """
        return self._watchdog.get_status()

    def stop_scenario(self):
        """
        This function is used by the overall signal handler to terminate the scenario execution
        """
        self._running = False

    def analyze_scenario(self, stdout, filename, junit):
        """
        This function is intended to be called from outside and provide
        the final statistics about the scenario (human-readable, in form of a junit
        report, etc.)
        """

        failure = False
        timeout = False
        result = "SUCCESS"

        if self.scenario.test_criteria is None:
            return True

        for criterion in self.scenario.get_criteria():
            if (not criterion.optional and
                    criterion.test_status != "SUCCESS" and
                    criterion.test_status != "ACCEPTABLE"):
                failure = True
                result = "FAILURE"
            elif criterion.test_status == "ACCEPTABLE":
                result = "ACCEPTABLE"

        if self.scenario.timeout_node.timeout and not failure:
            timeout = True
            result = "TIMEOUT"

        output = ResultOutputProvider(self, result, stdout, filename, junit)
        output.write()

        if self._challenge_mode:
            ChallengeStatisticsManager.record_scenario_statistics()

        return failure or timeout


import os
import json
import logging
from typing import Dict, List, Union

from cpdupload.csvingest import CsvIngest, CsvIngestException
from cpdupload.jsonbuilder import JSONBuilder, JSONBuilderException
from cpdupload.api import API, APIException

class Loader:
    """
    The Loader class unifies the API load workflow. It has a method to accept a filename
    and attempt to upload it to the API.
    """

    def __init__(self, input_filename: str, api: str, token: str):
        """
        This constructor accepts an input filename as a parameter and checks to
        ensure the filename exists before any load operation happens.

        Parameters
        ----------
        input_filename: str
            The input filename for the load operation.

        api: str
            The base URL of the CPD API server.

        token: str
            The bearer token to use for API authentication.

        Raises
        ------
        LoaderException
            Raises a LoaderException if the filename is not found or the API health check
            endpoint cannot be contacted.
        """
        if not os.path.isfile(input_filename):
            raise LoaderException(
                f"Cannot import {input_filename} because the file was not found."
            )

        self.input_filename = input_filename
        self.token = token
        self.logger = logging.getLogger(__name__)

        try:
            api_check = API(api, token)
            api_check.health_check()
            self.api = api
        except APIException as e:
            raise LoaderException(str(e))

    def send_adsorption_measurement_to_api(self):
        """
        send_file_to_api loads the file given, checks to see if it
        is JSON or CSV, parses a CSV if necessary, and then sends the JSON payload
        to the API.

        Raises
        ------
        LoaderException
            Raises an exception if something goes wrong with the file parsing or
            upload to the API.
        """
        try:
            api = API(self.api, self.token)

            if self.input_filename.endswith(".csv"):
                self.logger.info(f"Loading {self.input_filename} as a CSV.")
                ingest = CsvIngest(self.input_filename)
                rows: List[Dict[str, Union[int, str, float]]] = ingest.load_csv()
                self.logger.info(
                    f"Attempting to build JSON from {len(rows)} CSV row(s)."
                )
                builder = JSONBuilder()
                json_for_upload = builder.parse_rows(rows)
            else:
                # Attempt to parse as JSON, throw errors for others
                self.logger.info(f"Loading {self.input_filename} as a JSON.")
                with open(self.input_filename, "r") as file:
                    json_for_upload = json.loads(file.read())

            api.adsorption_measurement_load(json_for_upload)

        except CsvIngestException as err:
            raise LoaderException(f"Error while parsing CSV file: {err}")
        except JSONBuilderException as err:
            raise LoaderException(f"Error while building the JSON: {err}")
        except APIException as err:
            raise LoaderException(f"Error connecting to the CPD API: {err}")

class LoaderException(Exception):
    """
    The LoaderException class is for exceptions raised during a load operation. It is
    raised as part of the exception handling of the Loader class. Use of this exception
    generally follows a two step process:

    1. A JSONBuilderException, CsvIngestException, or APIException is caught by an
    instance of the Loader class.

    2. That original exception is reported to the user with a print statement.

    3. A loader exception is raised that contains the original message as well as
    any additional context information of for the Loader exception.

    4. The code calling the instance of this Loader class can then catch the
    LoaderException and report it to the user.

    Additionally, a LoaderException can be raised on its own by the Loader class
    for errors that fall outside the scope of the other three exceptions.

    For the message in the exception, emphasis should be placed on an error message
    that can be shown to a user with some actionable meaning.
    """

    def __init__(self, message: str):
        """
        Accepts a message that should be descriptive for display to a user.

        Parameters
        ----------
        message: str
            An error message useful to an end user.
        """
        super(LoaderException, self).__init__(message)


#!/usr/bin/python3
"""
Maria & Ben are playing a game. given integers
make list then determine winner when can't play next round.
"""

def isWinner(x, nums):
    """
    checks to find the winner of the game
    """
    # checks if num is prime
    def is_prime(num):
        """
        checks if num is a prime
        """
        if num < 2:
            return False
        for i in range(2, int(num ** 0.5) + 1):
            if num % i == 0:
                return False
        return True

    # makes a list of primes
    def get_primes(n):
        """
        Gathers Prime Numbers and returns list
        """
        primes = []
        for i in range(n+1):
            if is_prime(i):
                primes.append(i)
        return primes

    # Remove prime and multiples
    def p_n_m(prime, numbers):
        """
        Removes the prime number and its multiples
        """
        # using shallow copy for iteration
        for num in numbers.copy():
            if num % prime == 0:
                numbers.remove(num)
        return numbers

    # main code
    maria_win = 0
    ben_win = 0

    for _ in range(x):
        if _ >= len(nums):
            _ %= len(nums)
        maria_turn = True
        primes = get_primes(nums[_])
        turn = [*range(nums[_] + 1)]

        while primes:  # while list not empty
            prime = min(primes)
            primes.remove(prime)
            p_n_m(prime, turn)
            maria_turn = not maria_turn

        if maria_turn:
            ben_win += 1
        else:
            maria_win += 1

    # determine overall winner
    if maria_win > ben_win:
        return "Maria"
    elif ben_win > maria_win:
        return "Ben"
    else:
        return None


import random

def _swap(lst, ix_1, ix_2):
    lst[ix_1], lst[ix_2] = lst[ix_2], lst[ix_1]

def _partition(lst, start, end):
    pivot_ix = random.randrange(start, end)
    pivot = lst[pivot_ix]
    _swap(lst, pivot_ix, start)

    bound_ix = start + 1
    swap = False

    for ix in range(start + 1, end):
        if lst[ix] < pivot:
            if swap:
                _swap(lst, bound_ix, ix)

            bound_ix += 1
            continue

        swap = True

    _swap(lst, start, bound_ix - 1)

    return bound_ix - 1

def _quicksort(lst, start, end):
    if end - start > 1:
        pivot_ix = _partition(lst, start, end)
        _quicksort(lst, start, pivot_ix)
        _quicksort(lst, pivot_ix + 1, end)

def quicksort(lst):
    _quicksort(lst, 0, len(lst))


# -*- coding: utf-8 -*-
import pandas as pd

def read_data(filename):
    reader = pd.read_csv(filename, delimiter=",", encoding='GB18030', iterator=True)
    loop = True
    chunk_size = 100000
    chunks = []
    while loop:
        try:
            chunk = reader.get_chunk(chunk_size)
            chunks.append(chunk)
        except StopIteration:
            loop = False
            print("read data : Iteration Success!")
    df = pd.concat(chunks, ignore_index=True)
    return df


#this file creates another file called item_bin.py which contains the volumes and costs of the items and bins
import sys
import random
from sorting_objects import *

original_stdout = sys.stdout
f = open('item_bin2.py', 'w')
sys.stdout = f

quantity = [18000, 26000, 32000, 42000, 49000, 51000, 45000, 34000, 17000, 4500, 1000]
volume = [(1, 2), (2, 4), (4, 8), (8, 16), (16, 32), (32, 64), (64, 128), (128, 256), (256, 512), (512, 1024), (1024, 2048)]
item_objects = "item_objects = ["
counter = 0
for q in range(len(quantity)):
    item_number = quantity[q]
    for i in range(item_number):
        i_volume = random.uniform(volume[q][0], volume[q][1])
        #print(i_volume)
        counter += 1
        item_objects += ("items('i" + str(counter) + "', " + str(i_volume) + "), ")
item_objects += ("]")
print("from sorting_objects import *")
print(item_objects)

bin_number = int(counter / 2)
bin_objects = "bin_objects = ["
for b in range(bin_number):
    b_volume = random.uniform(20000, 40000)
    b_cost = random.randint(100, 600)
    #b_cost = b_volume / 5
    bin_objects += ("bins('b" + str(b+1) + "', " + str(b_volume) + ", " +  str(b_volume) + ", " +  str(b_cost) + ", 0, []), ")
bin_objects += "]"
print(bin_objects)

#with open('item_bin.py', 'w') as f:
#    sys.stdout = f
    #randomly choosing the number of items from a list
#    item_number_list = [50000]
    #item_number_list = [2000, 2100, 2200, 2300]
    #item_number_list = [100, 200, 300, 350]
    #item_number_list = [10, 11, 12, 13, 14]
    #item_number_list = [40, 50, 60, 70]
#    item_number = random.choice(item_number_list)
    #randomly assigning volumes valued between 1 and 20 to the items
#    item_objects = "item_objects = ["
#    for i in range(item_number-1):
#        i_volume = random.randint(100, 500)
#        item_objects += ("items('i" + str(i+1) + "', " + str(i_volume) + "), ")
#    i_volume = random.randint(100, 500)
#    item_objects += ("items('i" + str(item_number) + "', " + str(i_volume) + ")]")
#    print("from sorting_objects import *")
#    print(item_objects)

    #choosing the number of bins (number of items / 2)
#    bin_number = int(item_number / 2)
#    bin_objects = "bin_objects = ["
#    for i in range(bin_number-1):
#        b_volume = random.randint(2000, 4000)
#        b_cost = random.randint(50, 600)
#        bin_objects += ("bins('b" + str(i+1) + "', " + str(b_volume) + ", " +  str(b_volume) + ", " +  str(b_cost) + ", 0, []), ")
#    b_volume = random.randint(2000, 4000)
#    b_cost = random.randint(50, 600)
#    bin_objects += ("bins('b" + str(bin_number) + "', " + str(b_volume) + ", " +  str(b_volume) + ", " +  str(b_cost) + ", 0, [])]")
#    print(bin_objects)


from time import sleep
from random import choice,randint

class Domino:

    def __init__(self,a,b):
        self.valeur = [a,b]

    def retourner(self):
        if self.valeur != []:
            a,b = self.valeur
            self.valeur[0] = b
            self.valeur[1] = a

    def somme_points(self):
        a,b = self.valeur
        return a+b

    def difference_points(self):
        a,b = self.valeur
        return abs(a-b)

    def __repr__(self):
        a,b = self.valeur
        domino = "[%s|%s]" % (a,b)
        return domino

class JeuDomino:

    def __init__(self):
        self.dominos = [Domino(i,j) for i in range(7) for j in range(i,7)]

    def jouable(self,tapis,joueurs):
        if self.dominos == []:
            return False
        else:
            jouable = True
            for joueur in joueurs:
                if joueur.dominos == []:
                    return False
                else:
                    if joueur.jouable(tapis) != []:
                        jouable = jouable or True
                    else:
                        jouable = jouable or False
            return jouable

class Joueur:

    def __init__(self,nom):
        self.nom = nom
        self.dominos = []
        self.dominos_jouables = []
        self.somme_points = 0

    def est_vide(self):
        return self.dominos == []

    def calculer_points(self):
        if not self.est_vide():
            for domino in self.dominos:
                self.somme_points += domino.somme_points()
        return self.somme_points

    def piocher(self,jeu):
        domino = []
        if jeu.dominos != []:
            domino = choice(jeu.dominos)
            self.dominos.append(domino)
            jeu.dominos.remove(domino)
        return domino

    def poser(self,tapis,domino):
        if not tapis.est_vide():
            domino_left = tapis.a_gauche()
            domino_right = tapis.a_droite()

            if domino_left.valeur[0] == domino.valeur[1]:
                tapis.inserer_gauche(domino)
                self.dominos.remove(domino)
            elif domino_right.valeur[1] == domino.valeur[0]:
                tapis.inserer_droite(domino)
                self.dominos.remove(domino)
        else:
            tapis.dominos.append(domino)
            self.dominos.remove(domino)

    def jouable(self,tapis):
        self.dominos_jouables = []
        if not tapis.est_vide():
            domino_left = tapis.a_gauche()
            domino_right = tapis.a_droite()
            for domino in self.dominos:
                if domino_left.valeur[0] == domino.valeur[0] :
                    domino.retourner()
                    self.dominos_jouables.append(domino)
                elif domino_left.valeur[0] == domino.valeur[1] :
                    self.dominos_jouables.append(domino)
                elif domino_right.valeur[1] == domino.valeur[0] :
                    self.dominos_jouables.append(domino)
                elif domino_right.valeur[1] == domino.valeur[1] :
                    domino.retourner()
                    self.dominos_jouables.append(domino)
        return self.dominos_jouables

    def domino_fort(self,dominos):
        """
        Renvoie le domino qui a la plus forte valeur:
        - plus grande somme de points
        - plus petite différence de points en cas d'égalité sur la somme
        """
        if not dominos == []:
            s = dominos[0].somme_points()
            d = dominos[0].difference_points()
            position = 0
            i = 0
            for domino in dominos:
                if  s < domino.somme_points() :
                    s = domino.somme_points()
                    d = domino.difference_points()
                    position = i
                elif s == domino.somme_points() :
                    if d > domino.difference_points():
                        s = domino.somme_points()
                        d = domino.difference_points()
                        position = i
                i += 1
            return dominos[position]

class Tapis:

    def __init__(self):
        self.dominos = []

    def est_vide(self):
        return self.dominos == []

    def a_gauche(self):
        """
        Renvoie le domino le plus à gauche du tapis
        """
        if not self.est_vide():
            return self.dominos[0]

    def a_droite(self):
        """
        Renvoie le domino le plus à droite du tapis
        """
        if not self.est_vide():
            return self.dominos[-1]

    def inserer_gauche(self,domino):
        liste_domino = []
        liste_domino.append(domino)
        self.dominos = liste_domino + self.dominos
        return self.dominos

    def inserer_droite(self,domino):
        liste_domino = []
        liste_domino.append(domino)
        self.dominos = self.dominos + liste_domino
        return self.dominos

if __name__ == '__main__':
    partie = JeuDomino()
    tapis = Tapis()
    J1 = Joueur('Bob')
    J2 = Joueur('Alice')
    joueurs = [J1,J2]

    # on distribue les dominos
    for i in range(7):
        J1.piocher(partie)
        J2.piocher(partie)

    # début du jeu
    print(J1.nom,"joue et pose le domino :",J1.domino_fort(J1.dominos))
    J1.poser(tapis,J1.domino_fort(J1.dominos))
    print("Tapis:",tapis.dominos)
    joueur = J2

    partie_jouable = True

    while partie_jouable:
        print(joueur.nom," joue ! il a les dominos :",joueur.dominos)
        dominos_jouables = joueur.jouable(tapis)
        print(joueur.nom,"peut jouer :",dominos_jouables)
        if joueur.dominos_jouables != []:
            print(joueur.nom,"joue le domino ",joueur.domino_fort(joueur.dominos_jouables))
            joueur.poser(tapis,joueur.domino_fort(joueur.dominos_jouables))
            print("tapis:",tapis.dominos)
        else:
            print(joueur.nom," ne peut pas jouer!")
            if partie.dominos != []:
                pioche = joueur.piocher(partie)
                print(joueur.nom," a pioché ",pioche,"ses dominos: ",joueur.dominos)
            else:
                print(joueur.nom,"passe son tour!")
        partie_jouable = partie.jouable(tapis,joueurs)
        if partie_jouable:
            i = joueurs.index(joueur)
            if i < len(joueurs)-1:
                joueur = joueurs[i+1]
            else:
                joueur = joueurs[0]
        sleep(1)

    # Fin de partie
    vainqueur = joueurs[0]
    for joueur in joueurs:
        if joueur.est_vide():
            vainqueur = joueur
            #print(vainqueur.nom," a gagné la partie.")
            break
        else:
            joueur.calculer_points()
            print(joueur.nom," a encore les dominos ",joueur.dominos,"pour un total de ",joueur.somme_points,"points.")
            if joueur.somme_points < vainqueur.somme_points:
                vainqueur = joueur
    print(vainqueur.nom,"a gagné la partie avec ",vainqueur.somme_points,"points")
    print("Tapis:",tapis.dominos)