[
    {
        "instruction": "## chan_questions.py\nimport re\n\ndef extract_questions(string: str) -> list:\n    \"\"\"\n\tSplit a string intro sentences, return those ending with a question mark.\n\t\"\"\"\n",
        "input": "",
        "output": "\tsentences = re.split(r'(?<!\\w\\.\\w.)(?<![A-Z][a-z]\\.)(?<=[.?!\\n])\\s', string)\n\tquestions = []\n\n\tfor sentence in sentences:\n\n\t\t# Strip, but keep capital letters so LLMs can infer meaning from them.\n\t\tsentence = sentence.strip()\n\n\t\tif sentence.endswith(\"?\"):\n\t\t\tquestions.append(sentence)\n\n\t# Only unique questions\n\tquestions = list(set(questions))\n\n\treturn questions\n\n",
        "idx": "0"
    },
    {
        "instruction": "# Here are some relevant code fragments from other files of the repo:\n# --------------------------------------------------\n# the below code fragment can be found in:\n# helpers.py\n# --------------------------------------------------\n# import openai\n# \n# import config\n# \n# def get_openai_answer(prompt: str, response_format=\"json_object\", model=None):\n# \t# initiate\n# \tclient = openai.OpenAI(api_key=config.OPENAI_KEY)\n# \n# \tif not model:\n# \t\tmodel = config.MODEL\n# \n# \t# Get response\n# \tresponse = client.chat.completions.create(\n# \t\tmodel=model,\n# \t\ttemperature=config.TEMPERATURE,\n# \t\tmax_tokens=config.MAX_OUTPUT_TOKENS,\n# \t\tresponse_format={\"type\": response_format},\n# \t\tmessages=[{\n# \t\t\t\"role\": \"user\",\n# \t\t\t\"content\": prompt\n# \t\t}]\n# \t)\n# \n# \treturn response.choices[0].message.content\n# \n# --------------------------------------------------\n\n\n## chan_questions.py\nimport json\n\nimport prompts\n\nfrom helpers import get_openai_answer, chunker, clean_and_hash, clean_html, query_to_search_url\n\ndef score_explicit_question(string: str) -> list:\n    \"\"\"\n\tUses LLMs to score a question based on whether it is considered explicit or implicit.\n\t\n\tUses OpenAI.\n\t\"\"\"\n",
        "input": "",
        "output": "\tprompt = prompts.IS_EXPLICIT\n\n\tanswer = get_openai_answer(prompt.replace(\"[input]\", string))\n\n\tresults = json.loads(answer)[\"results\"]\n\treturn results\n\n",
        "idx": "2"
    },
    {
        "instruction": "# Here are some relevant code fragments from other files of the repo:\n# --------------------------------------------------\n# the below code fragment can be found in:\n# helpers.py\n# --------------------------------------------------\n# import html2text\n# \n# def clean_html(html_string: str) -> str:\n# \t\"\"\"\n# \tClean up a HTML string.\n# \t\"\"\"\n# \th = html2text.HTML2Text()\n# \n# \t# Don't wrap lines!\n# \th.body_width = 0\n# \n# \tcleaned = h.handle(html_string)\n# \n# \tif not cleaned:\n# \t\tcleaned = \"\"\n# \n# \treturn cleaned\n# \n# --------------------------------------------------\n\n\n## chan_questions.py\nfrom helpers import get_openai_answer, chunker, clean_and_hash, clean_html, query_to_search_url\n\ndef parse_ops_from_catalog(in_catalog: list) -> list:\n    \"\"\"\n\tExtracts only the relevant OP data from a catalog file.\n\t\"\"\"\n",
        "input": "",
        "output": "\tops = []\n\n\tfor page in in_catalog:\n\t\tfor thread in page[\"threads\"]:\n\t\t\top = {\n\t\t\t\t\"id\": thread[\"no\"],\n\t\t\t\t\"timestamp_utc\": thread[\"time\"],\n\t\t\t\t\"title\": clean_html(thread.get(\"sub\", \"\")),\n\t\t\t\t\"body\": clean_html(thread.get(\"com\", \"\")),\n\t\t\t\t\"replies\": thread[\"replies\"],\n\t\t\t\t\"board\": thread.get(\"board\", \"\")\n\t\t\t}\n\n\t\t\tops.append(op)\n\n\treturn ops\n\n",
        "idx": "3"
    },
    {
        "instruction": "\ndef memorySortC(lst: list) -> list:\n    \"\"\"\n    Sorts the inputted list of character elements in ascending order utilizing memory to speed up computation time\n    \n    Args:\n    lst (list): List of character elements to get sorted\n    \n    Returns:\n    list: sorted list of character elements\n    \"\"\"\n",
        "input": "",
        "output": "    high: int = ord(lst[0])\n    low: int = high\n    for l in lst:\n        temp: int = ord(l)\n        if temp > high:\n            high: int = temp\n        elif temp < low:\n            low: int = temp\n    ran: int = high - low + 1\n    amount: list = [0] * ran\n\n    \n    for l in lst:\n        amount[ord(l) - low] += 1\n\n    \n    output: list = [''] * len(lst)\n    p: int = 0\n    for o in range(len(amount)):\n        for _ in range(amount[o]):\n            output[p] = chr(o + low)\n            p: int = p + 1\n\n          \n    return output\n\n",
        "idx": "12"
    },
    {
        "instruction": "\ndef find_target_sum_withinList(numList, target):\n    \"\"\"\n    This function takes in a list of numbers and a target sum and returns a list of lists of numbers that add up to the target sum.\n    \n    numlist: list of numbers\n    target: target sum to find in the list\n    results: list of grouped number that add up to the target sum i.e. [[1, 5], [2, 4]] for target sum of 6\n    \"\"\"\n",
        "input": "",
        "output": "    results = []\n\n    #For every number in the list, the function will check if the sum of that number and any other number in the list is equal to the target sum.\n    for i in range(0, len(numList)):\n        for j in range(i+1, len(numList)):\n            #    If the sum of the two numbers is equal to the target sum, the two numbers will be added to a list and the list will be added to the results list.\n            if numList[i] + numList[j] == target:\n                results.append([numList[i], numList[j]])\n    return results\n\n",
        "idx": "15"
    },
    {
        "instruction": "\ndef makeRowZero(aList):\n    \"\"\"\n    makeRowZero function takes in a list and returns a list of zeros of the same length as the input list\n    \n    aList: list of numbers\n    \n    Below are the steps to create a list of zeros of the same length as the input list:\n    \"\"\"\n",
        "input": "",
        "output": "    row = [0 for i in range(len(aList))] # create a list of zeros of the same length as the input list\n    return row\n\n",
        "idx": "16"
    },
    {
        "instruction": "\ndef get_group_consecutive_common_chars(word1, word2):\n    \"\"\"\n    This function take a list and returns the characters of the words that are common in all the words in the list.\n    \n    wordList: list of words\n    \"\"\"\n",
        "input": "",
        "output": "    result = []\n\n    # Get the common characters in the initial word and the next word by looping through the words characters one by one\n    for i in range(0, len(word1)):\n        if word1[i] == word2[i]:\n            result.append(word1[i])\n        else:\n            return result\n    \n    return result\n\n",
        "idx": "19"
    },
    {
        "instruction": "\ndef find_all_vowels_inWord(word: str):\n    \"\"\"\n    Identify if word contains a vowel and return the vowels in the word\n    \n    word: word to check for vowels\n    \"\"\"\n",
        "input": "",
        "output": "    vowels = \"aeiou\"\n    result = []\n\n    for i in word:\n        if i in vowels:\n            result.append(i)\n    \n    return result\n\n",
        "idx": "20"
    },
    {
        "instruction": "\ndef find_longest_word_in_list(wordsList: list):\n    \"\"\"\n    Find the longest word in the list\n    \n    wordsList: list of words\n    \"\"\"\n",
        "input": "",
        "output": "    longestWord = wordsList[0]\n\n    for word in wordsList[1:]:\n        if len(word) > len(longestWord):\n            longestWord = word\n\n    return longestWord\n\n",
        "idx": "21"
    },
    {
        "instruction": "## modules/p115updatedb/p115updatedb/updatedb.py\nfrom collections.abc import Iterator, Iterable, Mapping\n\nfrom sqlite3 import connect, Connection, Cursor\n\nfrom sqlitetools import execute, find, transact, upsert_items, AutoCloseConnection\n\ndef kill_items(con: Connection | Cursor, ids: int | Iterable[int], /, commit: bool=False) -> Cursor:\n    \"\"\"\n    \u4f7f\u7528 id \u53bb\u7b5b\u9009\u548c\u79fb\u9664\u4e00\u7ec4\u6570\u636e\n    \n    :param con: \u6570\u636e\u5e93\u8fde\u63a5\u6216\u6e38\u6807\n    :param ids: \u4e00\u7ec4 id\uff0c\u4f1a\u88ab\u79fb\u9664\n    :param commit: \u662f\u5426\u63d0\u4ea4\n    \n    :return: \u6e38\u6807\n    \"\"\"\n",
        "input": "",
        "output": "    if isinstance(ids, int):\n        cond = f\"id = {ids:d}\"\n    else:\n        cond = \"id IN (%s)\" % (\",\".join(map(str, ids)) or \"NULL\")\n    sql = \"UPDATE data SET is_alive=0 WHERE \" + cond\n    return execute(con, sql, commit=commit)\n\n",
        "idx": "59"
    },
    {
        "instruction": "\ndef sort(data: list[dict], /, reverse: bool=False) -> list[dict]:\n    \"\"\"\n    \u5bf9\u6587\u4ef6\u4fe1\u606f\u6570\u636e\u8fdb\u884c\u6392\u5e8f\uff0c\u4f7f\u5f97\u5982\u679c\u67d0\u4e2a\u5143\u7d20\u662f\u53e6\u4e00\u4e2a\u5143\u7d20\u7684\u7236\u8282\u70b9\uff0c\u5219\u540e\u8005\u5728\u524d\n    \n    :param data: \u5f85\u6392\u5e8f\u7684\u6587\u4ef6\u4fe1\u606f\u5217\u8868\n    :param reverse: \u662f\u5426\u4f60\u9700\u6392\u5217\n    \n    :return: \u539f\u5730\u6392\u5e8f\uff0c\u8fd4\u56de\u4f20\u5165\u7684\u5217\u8868\u672c\u8eab\n    \"\"\"\n",
        "input": "",
        "output": "    d: dict[int, int] = {a[\"id\"]: a[\"parent_id\"] for a in data}\n    depth_d: dict[int, int] = {}\n    def depth(id: int, /) -> int:\n        try:\n            return depth_d[id]\n        except KeyError:\n            if id in d:\n                return 1 + depth(d[id])\n            return 0\n    data.sort(key=lambda a: depth(a[\"id\"]), reverse=reverse)\n    return data\n\n",
        "idx": "64"
    },
    {
        "instruction": "# Here are some relevant code fragments from other files of the repo:\n# --------------------------------------------------\n# the below code fragment can be found in:\n# modules/p115cipher/p115cipher/const.py\n# --------------------------------------------------\n# from typing import Final\n# \n# CRC_SALT: Final = b\"^j>WD3Kr?J2gLFjD4W2y@\"\n# \n# ECDH_REMOTE_PUBKEY: Final = bytes((\n#     0x57, 0xA2, 0x92, 0x57, 0xCD, 0x23, 0x20, 0xE5, 0xD6, 0xD1, 0x43, 0x32, 0x2F, 0xA4, 0xBB, 0x8A, \n#     0x3C, 0xF9, 0xD3, 0xCC, 0x62, 0x3E, 0xF5, 0xED, 0xAC, 0x62, 0xB7, 0x67, 0x8A, 0x89, 0xC9, 0x1A, \n#     0x83, 0xBA, 0x80, 0x0D, 0x61, 0x29, 0xF5, 0x22, 0xD0, 0x34, 0xC8, 0x95, 0xDD, 0x24, 0x65, 0x24, \n#     0x3A, 0xDD, 0xC2, 0x50, 0x95, 0x3B, 0xEE, 0xBA, \n# ))\n# \n# --------------------------------------------------\n# the below code fragment can be found in:\n# modules/p115cipher/p115cipher/common.py\n# --------------------------------------------------\n# from functools import partial\n# \n# from .const import G_kts, ECDH_REMOTE_PUBKEY, RSA_PUBKEY_PAIR\n# \n# to_bytes = partial(int.to_bytes, byteorder=\"big\", signed=False)\n# \n# from_bytes = partial(int.from_bytes, byteorder=\"big\", signed=False)\n# \n# def generate_ecdh_pair() -> tuple[bytes, bytes]:\n#     from ecdsa import ECDH, NIST224p, SigningKey # type: ignore\n# \n#     sk = SigningKey.generate(NIST224p)\n#     pk = sk.verifying_key\n#     ecdh = ECDH(NIST224p)\n#     ecdh.load_private_key(sk)\n#     ecdh.load_received_public_key_bytes(ECDH_REMOTE_PUBKEY)\n#     public = pk.pubkey.point.to_bytes()\n#     x, y = public[:28], public[28:]\n#     pub_key = bytes((28 + 1, 0x02 + (from_bytes(y) & 1))) + x\n#     # NOTE: Roughly equivalent to\n#     # n = int((ecdh.public_key.pubkey.point * from_bytes(sk.to_string())).x())\n#     # secret = to_bytes(n, (n.bit_length() + 0b111) >> 3)\n#     secret = ecdh.generate_sharedsecret_bytes()\n#     return pub_key, secret\n# \n# --------------------------------------------------\n\n\n## modules/p115cipher/p115cipher/normal.py\nfrom base64 import b64decode, b64encode\n\nfrom binascii import crc32\n\nfrom random import randrange\n\nfrom .const import G_key_l, CRC_SALT, RSA_PUBKEY_PAIR\n\nfrom .common import Buffer, RSA_encrypt, gen_key, from_bytes, to_bytes, xor, generate_ecdh_pair\n\nclass P115ECDHCipher:\n\n    def __init__(self):\n        pub_key, secret = generate_ecdh_pair()\n        self.pub_key: bytes = pub_key\n        # NOTE: use AES-128\n        self.aes_key: bytes = secret[:16]\n        self.aes_iv: bytes  = secret[-16:]\n\n    def encode(self, text: bytes | bytearray | str, /) -> bytes:\n        \"\u52a0\u5bc6\u6570\u636e\"\n        from Crypto.Cipher import AES\n\n        if isinstance(text, str):\n            text = bytes(text, \"utf-8\")\n        pad_size = 16 - (len(text) & 15)\n        return AES.new(self.aes_key, AES.MODE_CBC, self.aes_iv).encrypt(\n            text + to_bytes(pad_size) * pad_size)\n\n    def decode(\n        self, \n        cipher_text: bytes | bytearray, \n        /, \n        decompress: bool = False, \n    ) -> bytes:\n        \"\u89e3\u5bc6\u6570\u636e\"\n        from Crypto.Cipher import AES\n\n        data = AES.new(self.aes_key, AES.MODE_CBC, self.aes_iv).decrypt(\n            cipher_text[:len(cipher_text) & -16])\n        if decompress:\n            from lz4.block import decompress as lz4_block_decompress # type: ignore\n            size = data[0] + (data[1] << 8)\n            data = lz4_block_decompress(data[2:size+2], 0x2000)\n        else:\n            padding = data[-1]\n            if all(c == padding for c in data[-padding:]):\n                data = data[:-padding]\n        return data\n\n    def encode_token(self, /, timestamp: int) -> bytes:\n        \"\u63a5\u53d7\u4e00\u4e2a\u65f6\u95f4\u6233\uff08\u5355\u4f4d\u662f\u79d2\uff09\uff0c\u8fd4\u56de\u4e00\u4e2a token\uff0c\u4f1a\u628a pub_key \u548c timestamp \u90fd\u7f16\u7801\u5728\u5185\"\n        r1, r2 = randrange(256), randrange(256)\n        token = bytearray()\n        ts = to_bytes(timestamp, (timestamp.bit_length() + 0b111) >> 3)\n        if isinstance(self, P115ECDHCipher):\n            pub_key = self.pub_key\n        else:\n            pub_key = self\n        token.extend(pub_key[i]^r1 for i in range(15))\n        token.append(r1)\n        token.append(0x73^r1)\n        token.extend((r1,)*3)\n        token.extend(r1^ts[3-i] for i in range(4))\n        token.extend(pub_key[i]^r2 for i in range(15, len(pub_key)))\n        token.append(r2)\n        token.append(0x01^r2)\n        token.extend((r2,)*3)\n        crc = crc32(CRC_SALT+token) & 0xffffffff\n        h_crc32 = to_bytes(crc, 4)\n        token.extend(h_crc32[3-i] for i in range(4))\n        return b64encode(token)\n\n    @staticmethod\n    def decode_token(data: str | bytes) -> tuple[bytes, int]:\n        \"\"\"\n        \u89e3\u5bc6 token \u6570\u636e\uff0c\u8fd4\u56de pub_key \u548c timestamp \u7684\u5143\u7ec4\n        \"\"\"\n",
        "input": "",
        "output": "        data = b64decode(data)\n        r1 = data[15]\n        r2 = data[39]\n        return (\n            bytes(c ^ r1 for c in data[:15]) + bytes(c ^ r2 for c in data[24:39]), \n            from_bytes(bytes(i ^ r1 for i in data[20:24]), byteorder=\"little\"), \n        )\n    \n",
        "idx": "67"
    },
    {
        "instruction": "\ndef notas(*n, sit=False):\n    \"\"\"\n    ---> Funcao para analisar notas e situacoes de varios alunos\n    :param n: uma ou mais notas dos alunos(aceitavel)\n    :param sit: valor opcional, indicando se deve ou nao adicionar a situacao\n    :return: dicionario com varias informacoes sobre a situacao da turma.\n    \n    \"\"\"\n",
        "input": "",
        "output": "    r = dict()\n    r['total'] = len(n)\n    r['maior'] = max(n)\n    r['menor'] = min(n)\n    r['media'] = sum(n)/len(n)\n    if sit:\n        if r['media'] >= 7:\n            r['situacao'] = 'BOA!'\n        elif r['media'] >= 5:\n            r['situacao'] = 'Razoavel'\n        else:\n            r['situacao'] = 'Ruim'\n    return r\n\n",
        "idx": "82"
    },
    {
        "instruction": "\ndef fatorial(n, show=False):\n    \"\"\"\n    ->  Calcula o fatorial de um numero.\n    :param n: O numero a ser calculado\n    :param show: (opcional) mostrar ou nao a conta\n    :return: O valor do fatorial de um numero n.\n    \"\"\"\n",
        "input": "",
        "output": "    f = 1\n    for c in range(n, 0, -1):\n        if show:\n            print(c, end=\" \")\n            if c > 1:\n                print('x', end=\" \")\n            else:\n                print('=', end=\" \")\n        f *= c\n    return f\n\n",
        "idx": "83"
    },
    {
        "instruction": "## move_imgs/img_mover_functions.py\nimport ntpath\n\nimport os\n\nimport re\n\nimport shutil\n\ndef get_file_extension(file_path):\n    head, tail = ntpath.split(file_path)\n    file_name = tail or ntpath.basename(tail)\n    return os.path.splitext(file_name)[1]\n\ndef cp_recursive_overwrite(src, dest, ignore=None):\n    if os.path.isdir(src):\n        if not os.path.isdir(dest):\n            os.makedirs(dest)\n        files = os.listdir(src)\n        if ignore is not None:\n            ignored = ignore(src, files)\n        else:\n            ignored = set()\n        for f in files:\n            if f not in ignored:\n                cp_recursive_overwrite(os.path.join(src, f),\n                                       os.path.join(dest, f),\n                                       ignore)\n    else:\n        shutil.copyfile(src, dest)\n\ndef is_video_or_image_file(file_path, extensions):\n    extension = get_file_extension(file_path)\n\n    # flatten extensions (1 level deep lists)\n    abc = extensions\n    flattened_extensions = [a for ab in abc for a in ab]\n\n    is_media_file = False\n    if extension in flattened_extensions:\n        is_media_file = True\n\n    return is_media_file\n\nimg_file_ext = ['.apng', '.png', '.avif', '.gif', '.jpg', '.jpeg', '.jfif', '.pjpeg',\n                '.pjp', '.svg', '.webp', '.bmp', '.ico', '.tiff']\n\nvid_file_ext = ['.mp3', '.mp4', '.avi']\n\npdf_file_ext = ['.pdf']\n\njson_file_ext = ['.json']\n\ndef get_files_in_dir(directory, extensions=None):\n    if extensions is None:\n        extensions = [img_file_ext,\n                      vid_file_ext,\n                      pdf_file_ext,\n                      json_file_ext]\n\n    media_files_in_dir = []\n    for root, dirs, files in os.walk(directory):\n        for file in files:\n\n            if not is_video_or_image_file(file, extensions):\n                continue\n\n            media_files_in_dir.append(file)\n\n    return media_files_in_dir\n\ndef get_media_files_in_dir(directory):\n    # skip print orders\n    print_order_regex = 'Print Order \\\\d{21}$'\n    m = re.search(print_order_regex, directory)\n    if m:\n        return []\n\n    media_files_in_dir = get_files_in_dir(directory)\n\n    return media_files_in_dir\n\ndef set_up_test_cp_dir(src_dir, dst_dir):\n    \"\"\"\n    :param src_dir:\n    :param dst_dir:\n    :return:\n    \n    function adds media files in dir as list\n    \"\"\"\n",
        "input": "",
        "output": "    os.makedirs(dst_dir, exist_ok=True)\n    cp_recursive_overwrite(src_dir, dst_dir)\n    media_files_in_dir = get_media_files_in_dir(dst_dir)\n\n    return media_files_in_dir\n\n",
        "idx": "96"
    },
    {
        "instruction": "## move_imgs/img_mover_functions.py\nimport ntpath\n\nimport os\n\nimport shutil\n\njson_file_ext = ['.json']\n\ndef set_up_test_cp_file(src_file, dst_dir):\n    \"\"\"\n    :param src_file:\n    :param dst_dir:\n    :return:\n    \n    function adds media file as list. Normally this isn't used except for setting up tests.\n    \"\"\"\n",
        "input": "",
        "output": "    os.makedirs(dst_dir, exist_ok=True)\n    shutil.copy(src_file, dst_dir)\n    head, tail = ntpath.split(src_file)\n    file_name = tail or ntpath.basename(tail)\n\n    json_file_name = file_name + json_file_ext[0]\n    json_file_name_path = os.path.join(head, json_file_name)\n    if os.path.isfile(json_file_name_path):\n        shutil.copy(json_file_name_path, dst_dir)\n\n    return [file_name]\n\n",
        "idx": "97"
    },
    {
        "instruction": "## app.py\nimport autogen\n\nimport panel as pn\n\nllm_config_list = [\n    {\n        \"model\": \"tinyllama\",\n        \"base_url\": \"http://localhost:11434/v1\",\n        \"api_key\": \"ollama\",\n    }\n]\n\nllm_global_config = {\n    \"config_list\": llm_config_list, \n    \"temperature\": 0,  # Zero temperature for deterministic outputs\n    \"seed\": 53        # Fixed seed for reproducibility\n}\n\nadmin_agent = autogen.UserProxyAgent(\n    name=\"Admin\",\n    is_termination_msg=lambda x: x.get(\"content\", \"\").rstrip().endswith(\"exit\"),\n    system_message=\"\"\"A human admin. Interact with the planner to discuss the plan. Plan execution needs to be approved by this admin. \n    Only say APPROVED in most cases, and say EXIT when nothing to be done further. Do not say others.\"\"\",\n    code_execution_config=False,\n    default_auto_reply=\"Approved\", \n    human_input_mode=\"NEVER\",\n    llm_config=llm_global_config,\n)\n\nengineer_agent = autogen.AssistantAgent(\n    name=\"Engineer\",\n    llm_config=llm_global_config,\n    system_message='''Engineer. You follow an approved plan. You write python/shell code to solve tasks. Wrap the code in a code block that specifies the script type. The user can't modify your code. So do not suggest incomplete code which requires others to modify. Don't use a code block if it's not intended to be executed by the executor.\nDon't include multiple code blocks in one response. Do not ask others to copy and paste the result. Check the execution result returned by the executor.\nIf the result indicates there is an error, fix the error and output the code again. Suggest the full code instead of partial code or code changes. If the error can't be fixed or if the task is not solved even after the code is executed successfully, analyze the problem, revisit your assumption, collect additional info you need, and think of a different approach to try.\n''',\n)\n\nscientist_agent = autogen.AssistantAgent(\n    name=\"Scientist\",\n    llm_config=llm_global_config,\n    system_message=\"\"\"Scientist. You follow an approved plan. You are able to categorize papers after seeing their abstracts printed. You don't write code.\"\"\"\n)\n\nplanner_agent = autogen.AssistantAgent(\n    name=\"Planner\",\n    system_message='''Planner. Suggest a plan. Revise the plan based on feedback from admin and critic, until admin approval.\nThe plan may involve an engineer who can write code and a scientist who doesn't write code.\nExplain the plan first. Be clear which step is performed by an engineer, and which step is performed by a scientist.\n''',\n    llm_config=llm_global_config,\n)\n\nexecutor_agent = autogen.UserProxyAgent(\n    name=\"Executor\",\n    system_message=\"Executor. Execute the code written by the engineer and report the result.\",\n    human_input_mode=\"NEVER\",\n    code_execution_config={\n        \"last_n_messages\": 3,\n        \"work_dir\": \"paper\",\n        \"use_docker\": False  # Disable docker for local execution\n    },\n)\n\ncritic_agent = autogen.AssistantAgent(\n    name=\"Critic\",\n    system_message=\"Critic. Double check plan, claims, code from other agents and provide feedback. Check whether the plan includes adding verifiable info such as source URL.\",\n    llm_config=llm_global_config,\n)\n\nagent_group_chat = autogen.GroupChat(\n    agents=[admin_agent, engineer_agent, scientist_agent, planner_agent, executor_agent, critic_agent], \n    messages=[], \n    max_round=50\n)\n\nchat_manager = autogen.GroupChatManager(groupchat=agent_group_chat, llm_config=llm_global_config)\n\nagent_avatars = {\n    admin_agent.name: \"\ud83d\udc68\u200d\ud83d\udcbc\",\n    engineer_agent.name: \"\ud83d\udc69\u200d\ud83d\udcbb\",\n    scientist_agent.name: \"\ud83d\udc69\u200d\ud83d\udd2c\",\n    planner_agent.name: \"\ud83d\uddd3\",\n    executor_agent.name: \"\ud83d\udee0\",\n    critic_agent.name: '\ud83d\udcdd'\n}\n\ndef callback(contents: str, user: str, instance: pn.chat.ChatInterface):\n    admin_agent.initiate_chat(chat_manager, message=contents)\n\nchat_interface = pn.chat.ChatInterface(callback=callback)\n\ndef handle_agent_messages(recipient, messages, sender, config):\n    \"\"\"\n    Handle message passing between agents and update the chat interface.\n    \n    Args:\n    recipient: The agent receiving the message\n    messages: List of message objects\n    sender: The agent sending the message\n    config: Configuration dictionary\n    \n    Returns:\n    tuple: (False, None) to continue agent communication flow\n    \"\"\"\n",
        "input": "",
        "output": "    print(f\"Messages from: {sender.name} sent to: {recipient.name} | num messages: {len(messages)} | message: {messages[-1]}\")\n    \n    # Check if message has required attributes and send to appropriate user\n    if all(key in messages[-1] for key in ['name']):\n        chat_interface.send(\n            messages[-1]['content'],\n            user=messages[-1]['name'],\n            avatar=agent_avatars[messages[-1]['name']],\n            respond=False\n        )\n    else:\n        chat_interface.send(\n            messages[-1]['content'],\n            user='SecretGuy',\n            avatar='\ud83e\udd77',\n            respond=False\n        )\n\n    return False, None\n\n",
        "idx": "110"
    },
    {
        "instruction": "# Here are some relevant code fragments from other files of the repo:\n# --------------------------------------------------\n# the below code fragment can be found in:\n# custom_components/heytech/const.py\n# --------------------------------------------------\n# from logging import Logger, getLogger\n# \n# LOGGER: Logger = getLogger(__package__)\n# \n# DOMAIN = \"heytech\"\n# \n# CONF_PIN = \"pin\"\n# \n# CONF_SHUTTERS = \"shutters\"\n# \n# CONF_MAX_AUTO_SHUTTERS = \"max_auto_shutters\"\n# \n# --------------------------------------------------\n# the below code fragment can be found in:\n# custom_components/heytech/api.py\n# --------------------------------------------------\n# class IntegrationHeytechApiClientError(Exception):\n#     \"\"\"Exception to indicate a general API error.\"\"\"\n# \n# class IntegrationHeytechApiClientCommunicationError(IntegrationHeytechApiClientError):\n#     \"\"\"Exception to indicate a communication error.\"\"\"\n# \n#     def __str__(self) -> str:\n#         \"\"\"Return a string representation of the error.\"\"\"\n#         if self.__cause__:\n#             return f\"Error communicating with Heytech device: {self.__cause__}\"\n#         return \"Error communicating with Heytech device\"\n# \n# --------------------------------------------------\n\n\n## custom_components/heytech/config_flow.py\nfrom typing import TYPE_CHECKING, Any\n\nimport voluptuous as vol\n\nfrom homeassistant.config_entries import ConfigEntry, ConfigFlow, OptionsFlow\n\nfrom homeassistant.const import CONF_HOST, CONF_NAME, CONF_PORT\n\nfrom homeassistant.helpers import selector\n\nfrom .api import (\n    IntegrationHeytechApiClientCommunicationError,\n    IntegrationHeytechApiClientError,\n)\n\nfrom .const import CONF_MAX_AUTO_SHUTTERS, CONF_PIN, CONF_SHUTTERS, DOMAIN, LOGGER\n\nfrom homeassistant import data_entry_flow\n\nclass HeytechOptionsFlowHandler(OptionsFlow):\n    \"\"\"Handle Heytech options.\"\"\"\n\n    def __init__(self, config_entry: ConfigEntry) -> None:\n        \"\"\"Initialize Heytech options flow.\"\"\"\n        self.config_entry = config_entry\n        self._shutters: dict[str, str] = dict(\n            self.config_entry.options.get(\n                CONF_SHUTTERS,\n                self.config_entry.data.get(CONF_SHUTTERS, {}),\n            )\n        )\n        self._shutter_name: str | None = None\n        self._shutter_channels: str | None = None\n\n    async def async_step_init(\n        self, _user_input: dict[str, Any] | None = None\n    ) -> data_entry_flow.FlowResult:\n        \"\"\"Manage the options.\"\"\"\n        return await self.async_step_shutter_menu()\n\n    async def async_step_shutter_menu(\n        self, user_input: dict[str, Any] | None = None\n    ) -> data_entry_flow.FlowResult:\n        \"\"\"Menu for managing shutters.\"\"\"\n        if user_input is not None:\n            menu_option = user_input[\"menu_option\"]\n            if menu_option == \"add_shutter\":\n                return await self.async_step_add_shutter()\n            if menu_option == \"remove_shutter\":\n                return await self.async_step_remove_shutter()\n            if menu_option == \"finish\":\n                # Check if shutters have changed\n                original_shutters = self.config_entry.options.get(\n                    CONF_SHUTTERS,\n                    self.config_entry.data.get(CONF_SHUTTERS, {}),\n                )\n                if self._shutters != original_shutters:\n                    return self.async_create_entry(\n                        title=\"\",\n                        data={CONF_SHUTTERS: self._shutters},\n                    )\n                return self.async_abort(reason=\"no_changes\")\n        options = [\n            (\"add_shutter\", \"Add Shutter\"),\n            (\"remove_shutter\", \"Remove Shutter\"),\n            (\"finish\", \"Finish\"),\n        ]\n        data_schema = vol.Schema(\n            {\n                vol.Required(\"menu_option\"): selector.SelectSelector(\n                    selector.SelectSelectorConfig(\n                        options=[\n                            {\"value\": val, \"label\": label} for val, label in options\n                        ],\n                        mode=selector.SelectSelectorMode.DROPDOWN,\n                    )\n                )\n            }\n        )\n        return self.async_show_form(\n            step_id=\"shutter_menu\",\n            data_schema=data_schema,\n        )\n\n    async def async_step_add_shutter(\n        self, user_input: dict[str, Any] | None = None\n    ) -> data_entry_flow.FlowResult:\n        \"\"\"Add a shutter.\"\"\"\n        errors: dict[str, str] = {}\n        if user_input is not None:\n            self._shutter_name = user_input[CONF_NAME]\n            self._shutter_channels = user_input[\"channels\"]\n            # Validate channels input\n            try:\n                [int(ch.strip()) for ch in self._shutter_channels.split(\",\")]\n            except ValueError:\n                errors[\"channels\"] = \"invalid_channels\"\n                return await self._show_add_shutter_form(user_input, errors)\n            # Add shutter to shutters dict\n            self._shutters[self._shutter_name] = self._shutter_channels\n            # Ask if the user wants to add another shutter\n            if user_input.get(\"add_another\"):\n                return await self.async_step_add_shutter()\n            return await self.async_step_shutter_menu()\n        return await self._show_add_shutter_form(user_input, errors)\n\n    async def _show_add_shutter_form(\n        self, user_input: dict[str, Any] | None, errors: dict[str, str]\n    ) -> data_entry_flow.FlowResult:\n        \"\"\"Show the form to add a shutter.\"\"\"\n        return self.async_show_form(\n            step_id=\"add_shutter\",\n            data_schema=vol.Schema(\n                {\n                    vol.Required(\n                        CONF_NAME,\n                        default=(user_input or {}).get(CONF_NAME, \"\"),\n                    ): selector.TextSelector(\n                        selector.TextSelectorConfig(\n                            type=selector.TextSelectorType.TEXT,\n                        ),\n                    ),\n                    vol.Required(\n                        \"channels\",\n                        default=(user_input or {}).get(\"channels\", \"\"),\n                    ): selector.TextSelector(\n                        selector.TextSelectorConfig(\n                            type=selector.TextSelectorType.TEXT,\n                            multiline=False,\n                        ),\n                    ),\n                    vol.Optional(\n                        \"add_another\",\n                        default=True,\n                    ): selector.BooleanSelector(),\n                }\n            ),\n            errors=errors,\n        )\n\n    async def async_step_remove_shutter(\n        self, user_input: dict[str, Any] | None = None\n    ) -> data_entry_flow.FlowResult:\n        \"\"\"Remove a shutter.\"\"\"\n        errors: dict[str, str] = {}\n        if not self._shutters:\n            return self.async_abort(reason=\"no_shutters_to_remove\")\n        if user_input is not None:\n            shutter_to_remove = user_input[\"shutter\"]\n            if shutter_to_remove in self._shutters:\n                del self._shutters[shutter_to_remove]\n                return await self.async_step_shutter_menu()\n            errors[\"shutter\"] = \"shutter_not_found\"\n        data_schema = vol.Schema(\n            {\n                vol.Required(\"shutter\"): selector.SelectSelector(\n                    selector.SelectSelectorConfig(\n                        options=[\n                            {\"value\": name, \"label\": name} for name in self._shutters\n                        ],\n                        mode=selector.SelectSelectorMode.DROPDOWN,\n                    )\n                )\n            }\n        )\n        return self.async_show_form(\n            step_id=\"remove_shutter\",\n            data_schema=data_schema,\n            errors=errors,\n        )\n\nclass HeytechFlowHandler(ConfigFlow, domain=DOMAIN):\n    \"\"\"Config flow for Heytech.\"\"\"\n\n    VERSION = 1\n\n    def __init__(self) -> None:\n        \"\"\"Initialize the Heytech flow handler.\"\"\"\n        self._host: str | None = None\n        self._port: int | None = None\n        self._pin: str | None = None\n        self._max_auto_shutters: int | None = None\n        self._add_custom_shutters: bool = False\n        self._shutters: dict[str, str] = {}\n        self._shutter_name: str | None = None\n        self._shutter_channels: str | None = None\n\n    @staticmethod\n    def async_get_options_flow(config_entry: ConfigEntry) -> OptionsFlow:\n        \"\"\"\n        Get the options flow for this handler.\n        \"\"\"\n",
        "input": "",
        "output": "        return HeytechOptionsFlowHandler(config_entry)\n    \n",
        "idx": "117"
    },
    {
        "instruction": "## src/issue_downloader/github_utils.py\nimport httpx\n\ndef get_client(token: str, base_url: str) -> httpx.Client:\n    \"\"\"\n    Create a client ready for the Github API.\n    \n    Using a client makes the requests slightly faster and its a convenient way\n    to set headers.\n    \"\"\"\n",
        "input": "",
        "output": "    c = httpx.Client(base_url=base_url)\n    c.headers.update(\n        {\n            \"Authorization\": f\"Bearer {token}\",\n            \"Accept\": \"application/json\",\n        }\n    )\n\n    return c\n\n",
        "idx": "118"
    },
    {
        "instruction": "## src/issue_downloader/settings.py\nimport hashlib\n\nimport pathlib\n\nfrom typing import Optional\n\ndef get_settings_key(issue_save_path: pathlib.Path, url: str, org: Optional[str]=None, repos: Optional[list[str]]=None, include_archived: bool=False, include_closed: bool=True) -> str:\n    \"\"\"\n    Create a hash of arguments that can be used as key to save settings.\n    \"\"\"\n",
        "input": "",
        "output": "    settings_key = (\n        f\"{issue_save_path}:{url}:{org}:{repos}:{include_archived}:{include_closed}\"\n    )\n    return hashlib.sha256(settings_key.encode(\"utf-8\")).hexdigest()\n\n",
        "idx": "121"
    },
    {
        "instruction": "## src/issue_downloader/models.py\nimport datetime\n\nfrom typing import Any, Literal, Optional\n\nimport pydantic\n\nclass Repository(pydantic.BaseModel):\n    id: str\n    name: str\n    owner: str\n    is_archived: bool\n    archived_at: datetime.datetime | None = None\n\n    @pydantic.field_validator(\"owner\", mode=\"before\")\n    def unpack_owner(cls, v: Any, _: pydantic.ValidationInfo) -> str:\n        return str(v[\"login\"])\n\n    def __hash__(self) -> int:\n        \"\"\"Hashable function to identify unique objects through the Github id\"\"\"\n        return hash(self.id)\n\nREACTION_MAPPING = {\n    \"THUMBS_UP\": \"\ud83d\udc4d\",\n    \"THUMBS_DOWN\": \"\ud83d\udc4e\",\n    \"LAUGH\": \"\ud83d\ude00\",\n    \"HOORAY\": \"\ud83c\udf89\",\n    \"CONFUSED\": \"\ud83d\ude15\",\n    \"HEART\": \"\u2764\ufe0f\",\n    \"ROCKET\": \"\ud83d\ude80\",\n    \"EYES\": \"\ud83d\udc40\",\n}\n\nclass Reaction(pydantic.BaseModel):\n    content: str\n    user: str\n\n    @pydantic.field_validator(\"content\", mode=\"before\")\n    def emoji_content(cls, v: Any, _: pydantic.ValidationInfo) -> str:\n        return REACTION_MAPPING[v]\n\n    def __hash__(self) -> int:\n        \"\"\"Hashable function to identify unique reactions\"\"\"\n        return hash((self.content, self.user))\n\nclass Label(pydantic.BaseModel):\n    name: str\n    description: str | None = None\n\n    def __str__(self) -> str:\n        if self.description:\n            return f\"{self.name} ({self.description})\"\n        else:\n            return self.name\n\n    def __hash__(self) -> int:\n        \"\"\"Hashable function to identify unique labels\"\"\"\n        return hash((self.name, self.description))\n\nclass Comment(pydantic.BaseModel):\n    id: str\n    body: str\n    author: str\n\n    created_at: datetime.datetime\n    reactions: list[Reaction] | None = None\n\n    @pydantic.field_validator(\"author\", mode=\"before\")\n    def unpack_author(cls, v: Any, _: pydantic.ValidationInfo) -> str:\n        try:\n            return str(v[\"login\"])\n        except TypeError:\n            return \"\"\n\n    @pydantic.field_validator(\"reactions\", mode=\"before\")\n    def parse_react(cls, v: Any, _: pydantic.ValidationInfo) -> list[Reaction]:\n        return parse_reactions(v)\n\n    @pydantic.field_validator(\"body\", mode=\"before\")\n    def convert_line_endings(cls, v: Any, _: pydantic.ValidationInfo) -> str:\n        s: str = v.encode(\"utf-8\").replace(b\"\\r\\n\", b\"\\n\").decode(\"utf-8\")\n        return s\n\n    def __hash__(self) -> int:\n        \"\"\"Hashable function to identify unique objects through the Github id\"\"\"\n        return hash(self.id)\n\ndef parse_reactions(data: dict[str, Any]) -> list[Reaction]:\n    \"\"\"Parse reactions from GraphQL response.\n\n    data is the reactions object from the api response, including \"edges\" key.\n    \"\"\"\n\n    return [\n        Reaction(user=r[\"node\"][\"user\"][\"login\"], content=r[\"node\"][\"content\"])\n        for r in data[\"edges\"]\n    ]\n\nclass Issue(pydantic.BaseModel):\n    author: str\n    body: str\n    created_at: datetime.datetime\n    id: str\n    number: int\n    repository: Repository\n    state: Literal[\"OPEN\", \"CLOSED\"]\n    title: str\n    updated_at: datetime.datetime\n    url: str\n\n    assignees: list[str] | None = None\n    closed_at: datetime.datetime | None = None\n    comments: list[Comment] | None = None\n    labels: list[Label] | None = None\n    reactions: list[Reaction] | None = None\n    state_reason: str | None = None\n\n    @pydantic.field_validator(\"author\", mode=\"before\")\n    def unpack_author(cls, v: Any, _: pydantic.ValidationInfo) -> str:\n        try:\n            return str(v[\"login\"])\n        except TypeError:\n            return \"\"\n\n    @pydantic.field_validator(\"body\", mode=\"before\")\n    def convert_line_endings(cls, v: Any, _: pydantic.ValidationInfo) -> str:\n        s: str = v.encode(\"utf-8\").replace(b\"\\r\\n\", b\"\\n\").decode(\"utf-8\")\n        return s\n\n    def __hash__(self) -> int:\n        \"\"\"Hashable function to identify unique objects through the Github id\"\"\"\n        return hash(self.id)\n\n    def reactions_grouped(self) -> dict[str, list[str]]:\n        \"\"\"\n        Group reaction with reaction as key and reactee as value.\n        \"\"\"\n",
        "input": "",
        "output": "        out: dict[str, list[str]] = {}\n        if self.reactions:\n            for r in self.reactions:\n                out.setdefault(r.content, []).append(r.user)\n        return out\n    \n",
        "idx": "124"
    },
    {
        "instruction": "# Here are some relevant code fragments from other files of the repo:\n# --------------------------------------------------\n# the below code fragment can be found in:\n# src/configuration/models.py\n# --------------------------------------------------\n# from enum import Enum\n# \n# class Model(Enum):\n#     GPT_4O = \"gpt-4o\"\n#     GPT_4O_MINI = \"gpt-4o-mini\"\n#     O1_PREVIEW = \"o1-preview\"\n#     O1_MINI = \"o1-mini\"\n#     GPT_4_TURBO = \"gpt-4-turbo\"\n#     GPT_3_5_TURBO = \"gpt-3.5-turbo\"\n#     CLAUDE_SONNET = \"claude-3-5-sonnet-20241022\"\n# \n#     def is_anthropic(self):\n#         return self in [Model.CLAUDE_SONNET]\n# \n# --------------------------------------------------\n# the below code fragment can be found in:\n# src/configuration/config.py\n# --------------------------------------------------\n# from enum import Enum\n# \n# from dataclasses import dataclass\n# \n# from typing import Any\n# \n# from .models import Model\n# \n# class Envs(Enum):\n#     PROD = \"PROD\"\n#     DEV = \"DEV\"\n# \n# class GenerationOptions(Enum):\n#     MODELS = \"models\"\n#     MODELS_AND_FIRST_TEST = \"models_and_first_test\"\n#     MODELS_AND_TESTS = \"models_and_tests\"\n# \n# class Config:\n#     env: Envs = Envs.DEV\n#     debug: bool = False\n#     model: Model = Model.CLAUDE_SONNET\n#     generate: GenerationOptions = GenerationOptions.MODELS_AND_TESTS\n#     anthropic_api_key: str = \"\"\n#     openai_api_key: str = \"\"\n#     api_file_path: str = \"\"\n#     destination_folder: str = \"\"\n#     endpoint: str = \"\"\n#     use_existing_framework: bool = False\n# \n#     def update(self, updates: dict[str, Any]):\n#         for key, value in updates.items():\n#             setattr(self, key, value)\n# \n# --------------------------------------------------\n# the below code fragment can be found in:\n# src/utils/logger.py\n# --------------------------------------------------\n# import logging\n# \n# import os\n# \n# import sys\n# \n# from typing import Optional, List\n# \n# from src.configuration.config import Config\n# \n# class Logger:\n#     @staticmethod\n#     def configure_logger(config: Config):\n#         log_level = logging.DEBUG if config.debug else logging.INFO\n# \n#         # Default formats\n#         stdout_format = \"%(message)s\"\n#         file_format = \"%(asctime)s - %(name)s - %(levelname)s - %(message)s\"\n# \n#         # Handlers\n#         stdout_handler = logging.StreamHandler(sys.stdout)\n#         stdout_handler.setLevel(log_level)\n#         stdout_handler.setFormatter(logging.Formatter(stdout_format))\n# \n#         log_folder = \"logs/\"\n#         os.makedirs(os.path.dirname(log_folder), exist_ok=True)\n#         file_handler = MultilineFileHandler(\n#             log_folder + config.destination_folder.split(\"/\")[-1] + \".log\"\n#         )\n#         file_handler.setLevel(logging.DEBUG)\n#         file_handler.setFormatter(logging.Formatter(file_format))\n# \n#         logging.basicConfig(\n#             format=\"%(message)s\",\n#             level=log_level,\n#             handlers=[stdout_handler, file_handler],\n#         )\n#         logging.getLogger(\"httpx\").setLevel(logging.WARNING)\n# \n#     @staticmethod\n#     def get_logger(name: str):\n#         return logging.getLogger(name)\n# \n# class MultilineFileHandler(logging.FileHandler):\n#     def __init__(self, filename, mode=\"a\", encoding=\"utf-8\", delay=False):\n#         super().__init__(filename, mode, encoding, delay)\n# \n#     def emit(self, record):\n#         try:\n#             if not isinstance(record.msg, str):\n#                 record.msg = str(record.msg)\n# \n#             messages: List[str] = [\n#                 message for message in record.msg.split(\"\\n\") if message.strip()\n#             ]\n# \n#             if not messages:\n#                 return\n# \n#             for message in messages:\n#                 new_record = logging.makeLogRecord(record.__dict__)\n#                 new_record.msg = message\n#                 super().emit(new_record)\n#         except Exception:\n#             self.handleError(record)\n# \n# --------------------------------------------------\n\n\n## src/processors/swagger/api_definition_merger.py\nimport copy\n\nfrom typing import List, Dict\n\nimport yaml\n\nfrom src.utils.logger import Logger\n\nclass APIDefinitionMerger:\n    \"\"\"Merges API definition components based on base resources.\"\"\"\n\n    def __init__(self):\n        self.logger = Logger.get_logger(__name__)\n\n    def merge(self, api_definition_list: List[Dict]) -> List[Dict]:\n        \"\"\"\n        Merges API definitions by their base resources.\n        \"\"\"\n",
        "input": "",
        "output": "        merged_definitions = {}\n\n        for item in api_definition_list:\n            if item[\"type\"] == \"path\":\n                base_path = \"/\" + item[\"path\"].split(\"/\", 2)[1]\n                if base_path not in merged_definitions:\n                    item[\"path\"] = base_path\n                    merged_definitions[base_path] = copy.deepcopy(item)\n                else:\n                    item_yaml = yaml.safe_load(item[\"yaml\"])\n                    merged_yaml = yaml.safe_load(merged_definitions[base_path][\"yaml\"])\n                    for path, path_data in item_yaml[\"paths\"].items():\n                        if path not in merged_yaml[\"paths\"]:\n                            merged_yaml[\"paths\"].update({path: path_data})\n                    merged_definitions[base_path][\"yaml\"] = yaml.dump(\n                        merged_yaml, sort_keys=False\n                    )\n            elif item[\"type\"] == \"verb\":\n                merged_definitions[f\"{item['path']}-{item['verb']}\"] = copy.deepcopy(item)\n\n        self.logger.info(f\"Merged {len(merged_definitions)} API definitions\")\n        return list(merged_definitions.values())\n    \n",
        "idx": "127"
    },
    {
        "instruction": "# Here are some relevant code fragments from other files of the repo:\n# --------------------------------------------------\n# the below code fragment can be found in:\n# src/configuration/models.py\n# --------------------------------------------------\n# from enum import Enum\n# \n# class Model(Enum):\n#     GPT_4O = \"gpt-4o\"\n#     GPT_4O_MINI = \"gpt-4o-mini\"\n#     O1_PREVIEW = \"o1-preview\"\n#     O1_MINI = \"o1-mini\"\n#     GPT_4_TURBO = \"gpt-4-turbo\"\n#     GPT_3_5_TURBO = \"gpt-3.5-turbo\"\n#     CLAUDE_SONNET = \"claude-3-5-sonnet-20241022\"\n# \n#     def is_anthropic(self):\n#         return self in [Model.CLAUDE_SONNET]\n# \n# --------------------------------------------------\n# the below code fragment can be found in:\n# src/configuration/config.py\n# --------------------------------------------------\n# from enum import Enum\n# \n# from dataclasses import dataclass\n# \n# from typing import Any\n# \n# from .models import Model\n# \n# class Envs(Enum):\n#     PROD = \"PROD\"\n#     DEV = \"DEV\"\n# \n# class GenerationOptions(Enum):\n#     MODELS = \"models\"\n#     MODELS_AND_FIRST_TEST = \"models_and_first_test\"\n#     MODELS_AND_TESTS = \"models_and_tests\"\n# \n# class Config:\n#     env: Envs = Envs.DEV\n#     debug: bool = False\n#     model: Model = Model.CLAUDE_SONNET\n#     generate: GenerationOptions = GenerationOptions.MODELS_AND_TESTS\n#     anthropic_api_key: str = \"\"\n#     openai_api_key: str = \"\"\n#     api_file_path: str = \"\"\n#     destination_folder: str = \"\"\n#     endpoint: str = \"\"\n#     use_existing_framework: bool = False\n# \n#     def update(self, updates: dict[str, Any]):\n#         for key, value in updates.items():\n#             setattr(self, key, value)\n# \n# --------------------------------------------------\n# the below code fragment can be found in:\n# src/utils/logger.py\n# --------------------------------------------------\n# import logging\n# \n# import os\n# \n# import sys\n# \n# from typing import Optional, List\n# \n# from src.configuration.config import Config\n# \n# class Logger:\n#     @staticmethod\n#     def configure_logger(config: Config):\n#         log_level = logging.DEBUG if config.debug else logging.INFO\n# \n#         # Default formats\n#         stdout_format = \"%(message)s\"\n#         file_format = \"%(asctime)s - %(name)s - %(levelname)s - %(message)s\"\n# \n#         # Handlers\n#         stdout_handler = logging.StreamHandler(sys.stdout)\n#         stdout_handler.setLevel(log_level)\n#         stdout_handler.setFormatter(logging.Formatter(stdout_format))\n# \n#         log_folder = \"logs/\"\n#         os.makedirs(os.path.dirname(log_folder), exist_ok=True)\n#         file_handler = MultilineFileHandler(\n#             log_folder + config.destination_folder.split(\"/\")[-1] + \".log\"\n#         )\n#         file_handler.setLevel(logging.DEBUG)\n#         file_handler.setFormatter(logging.Formatter(file_format))\n# \n#         logging.basicConfig(\n#             format=\"%(message)s\",\n#             level=log_level,\n#             handlers=[stdout_handler, file_handler],\n#         )\n#         logging.getLogger(\"httpx\").setLevel(logging.WARNING)\n# \n#     @staticmethod\n#     def get_logger(name: str):\n#         return logging.getLogger(name)\n# \n# class MultilineFileHandler(logging.FileHandler):\n#     def __init__(self, filename, mode=\"a\", encoding=\"utf-8\", delay=False):\n#         super().__init__(filename, mode, encoding, delay)\n# \n#     def emit(self, record):\n#         try:\n#             if not isinstance(record.msg, str):\n#                 record.msg = str(record.msg)\n# \n#             messages: List[str] = [\n#                 message for message in record.msg.split(\"\\n\") if message.strip()\n#             ]\n# \n#             if not messages:\n#                 return\n# \n#             for message in messages:\n#                 new_record = logging.makeLogRecord(record.__dict__)\n#                 new_record.msg = message\n#                 super().emit(new_record)\n#         except Exception:\n#             self.handleError(record)\n# \n# --------------------------------------------------\n\n\n## src/processors/swagger/api_definition_splitter.py\nimport copy\n\nfrom typing import Optional, Dict, List\n\nimport yaml\n\nfrom src.utils.logger import Logger\n\nclass APIDefinitionSplitter:\n    \"\"\"Splits API definitions into smaller components.\"\"\"\n\n    def __init__(self):\n        self.logger = Logger.get_logger(__name__)\n\n    def split(self, api_definition: Dict) -> List[Dict]:\n        \"\"\"Splits the API definition into smaller, manageable parts.\"\"\"\n        self.logger.info(\"Splitting API definition into components...\")\n        api_definition_list = []\n\n        base_copy = copy.deepcopy(api_definition)\n        del base_copy[\"paths\"]\n        api_definition_list.append(self._create_entry(\"base\", None, None, base_copy))\n\n        # Split paths and verbs\n        for path, path_data in api_definition.get(\"paths\", {}).items():\n            # Path entry\n            path_copy = copy.deepcopy(api_definition)\n            path_copy[\"paths\"] = {path: path_data}\n            api_definition_list.append(self._create_entry(\"path\", path, None, path_copy))\n\n            # Verb entries\n            for verb, verb_data in path_data.items():\n                verb_copy = copy.deepcopy(path_copy)\n                verb_copy[\"paths\"][path] = {verb: verb_data}\n                api_definition_list.append(\n                    self._create_entry(\"verb\", path, verb.upper(), verb_copy)\n                )\n\n        self.logger.info(\"Successfully split API definition.\")\n        return api_definition_list\n\n    @staticmethod\n    def _create_entry(entry_type: str, path: Optional[str], verb: Optional[str], yaml_content: Dict) -> Dict:\n        \"\"\"\n        Creates a standardized entry for API components.\n        \"\"\"\n",
        "input": "",
        "output": "        return {\n            \"type\": entry_type,\n            \"path\": path,\n            \"verb\": verb,\n            \"yaml\": yaml.dump(yaml_content, sort_keys=False),\n        }\n    \n",
        "idx": "129"
    },
    {
        "instruction": "# Here are some relevant code fragments from other files of the repo:\n# --------------------------------------------------\n# the below code fragment can be found in:\n# src/configuration/models.py\n# --------------------------------------------------\n# from enum import Enum\n# \n# class Model(Enum):\n#     GPT_4O = \"gpt-4o\"\n#     GPT_4O_MINI = \"gpt-4o-mini\"\n#     O1_PREVIEW = \"o1-preview\"\n#     O1_MINI = \"o1-mini\"\n#     GPT_4_TURBO = \"gpt-4-turbo\"\n#     GPT_3_5_TURBO = \"gpt-3.5-turbo\"\n#     CLAUDE_SONNET = \"claude-3-5-sonnet-20241022\"\n# \n#     def is_anthropic(self):\n#         return self in [Model.CLAUDE_SONNET]\n# \n# --------------------------------------------------\n# the below code fragment can be found in:\n# src/configuration/config.py\n# --------------------------------------------------\n# from enum import Enum\n# \n# from dataclasses import dataclass\n# \n# from typing import Any\n# \n# from .models import Model\n# \n# class Envs(Enum):\n#     PROD = \"PROD\"\n#     DEV = \"DEV\"\n# \n# class GenerationOptions(Enum):\n#     MODELS = \"models\"\n#     MODELS_AND_FIRST_TEST = \"models_and_first_test\"\n#     MODELS_AND_TESTS = \"models_and_tests\"\n# \n# class Config:\n#     env: Envs = Envs.DEV\n#     debug: bool = False\n#     model: Model = Model.CLAUDE_SONNET\n#     generate: GenerationOptions = GenerationOptions.MODELS_AND_TESTS\n#     anthropic_api_key: str = \"\"\n#     openai_api_key: str = \"\"\n#     api_file_path: str = \"\"\n#     destination_folder: str = \"\"\n#     endpoint: str = \"\"\n#     use_existing_framework: bool = False\n# \n#     def update(self, updates: dict[str, Any]):\n#         for key, value in updates.items():\n#             setattr(self, key, value)\n# \n# --------------------------------------------------\n\n\n## src/services/command_service.py\nimport os\n\nimport subprocess\n\nimport logging\n\nfrom typing import List, Dict, Tuple, Optional, Callable\n\nfrom ..configuration.config import Config\n\ndef build_typescript_compiler_command(files: List[Dict[str, str]]) -> str:\n    \"\"\"Build the TypeScript compiler command for specific files\"\"\"\n    file_paths = \" \".join(file[\"path\"] for file in files)\n    return (\n        f\"npx tsc {file_paths} \"\n        \"--lib es2021 \"\n        \"--module NodeNext \"\n        \"--target ESNext \"\n        \"--strict \"\n        \"--esModuleInterop \"\n        \"--skipLibCheck \"\n        \"--forceConsistentCasingInFileNames \"\n        \"--moduleResolution nodenext \"\n        \"--allowUnusedLabels false \"\n        \"--allowUnreachableCode false \"\n        \"--exactOptionalPropertyTypes \"\n        \"--noFallthroughCasesInSwitch \"\n        \"--noImplicitOverride \"\n        \"--noImplicitReturns \"\n        \"--noPropertyAccessFromIndexSignature \"\n        \"--noUncheckedIndexedAccess \"\n        \"--noUnusedLocals \"\n        \"--noUnusedParameters \"\n        \"--checkJs \"\n        \"--noEmit\"\n    )\n\nclass CommandService:\n    \"\"\"\n    Service for running shell commands with real-time output and error handling.\n    \"\"\"\n\n    def __init__(self, config: Config, logger: Optional[logging.Logger] = None):\n        \"\"\"\n        Initialize CommandService with an optional logger.\n\n        Args:\n            config (Config): Configuration instance\n            logger (Optional[logging.Logger]): Logger instance (defaults to logger from logging module)\n        \"\"\"\n        self.config = config\n        self.logger = logger or logging.getLogger(__name__)\n\n    def _log_message(self, message: str, is_error: bool = False):\n        \"\"\"\n        Log a message with optional error severity.\n\n        Args:\n            message (str): Message to log\n            is_error (bool): Whether the message is an error\n        \"\"\"\n        log_method = self.logger.error if is_error else self.logger.info\n        log_method(message)\n\n    def run_command(self, command: str, cwd: Optional[str] = None) -> Tuple[bool, str]:\n        \"\"\"\n        Run a shell command with real-time output and error handling.\n\n        Args:\n            command (str): Command to execute\n            cwd (Optional[str]): Working directory for command execution\n\n        Returns:\n            Tuple[bool, str]: Success status and command output\n        \"\"\"\n        try:\n            self.logger.info(f\"Running command: {command}\")\n            process = subprocess.Popen(\n                command,\n                cwd=cwd or self.config.destination_folder,\n                shell=True,\n                stdout=subprocess.PIPE,\n                stderr=subprocess.STDOUT,\n                bufsize=0,\n                universal_newlines=True,\n                encoding=\"utf-8\",\n                env={\n                    **os.environ,\n                    \"PYTHONUNBUFFERED\": \"1\",\n                    \"FORCE_COLOR\": \"true\",\n                    \"TERM\": \"xterm-256color\",\n                    \"LANG\": \"en_US.UTF-8\",\n                    \"LC_ALL\": \"en_US.UTF-8\",\n                },\n            )\n\n            output_lines = []\n            while True:\n                output = process.stdout.readline()\n                if output:\n                    output_lines.append(output.rstrip())\n                    self._log_message(output.rstrip())\n\n                if output == \"\" and process.poll() is not None:\n                    break\n\n            success = process.returncode == 0\n            self._log_message(\n                (\n                    f\"\\033[92mCommand succeeded.\\033[0m\"\n                    if success\n                    else f\"\\033[91mCommand failed.\\033[0m\"\n                ),\n                is_error=not success,\n            )\n            return success, \"\\n\".join(output_lines)\n\n        except subprocess.SubprocessError as e:\n            self._log_message(f\"Subprocess error: {e}\", is_error=True)\n            return False, str(e)\n        except Exception as e:\n            self._log_message(f\"Unexpected error: {e}\", is_error=True)\n            return False, str(e)\n\n    def run_command_with_fix(self, command_func: Callable, fix_func: Optional[Callable]=None, files: Optional[List[Dict[str, str]]]=None, max_retries: int=3) -> Tuple[bool, str]:\n        \"\"\"\n        Execute a command with retries and an optional fix function on failure.\n    \n        Args:\n        command_func (Callable): The function that runs the command\n        fix_func (Optional[Callable]): Function to invoke if the command fails\n        files (Optional[List[Dict[str, str]]]): Files to pass to the command function\n        max_retries (int): Max number of retries on failure\n    \n        Returns:\n        Tuple[bool, str]: Success status and output or error message\n        \"\"\"\n",
        "input": "",
        "output": "        files = files or []\n        retry_count = 0\n        while retry_count < max_retries:\n            if retry_count > 0:\n                self._log_message(f\"\\nAttempt {retry_count + 1}/{max_retries}.\")\n            elif retry_count == 0:\n                self._log_message(\"\")\n\n            success, message = command_func(files)\n\n            if success:\n                return success, message\n\n            if fix_func:\n                self._log_message(f\"Applying fix: {message}\")\n                fix_func(files, message)\n\n            retry_count += 1\n\n        success, message = command_func(files)\n\n        if success:\n            return success, message\n\n        self._log_message(\n            f\"Command failed after {max_retries} attempts.\", is_error=True\n        )\n        return False, message\n    \n",
        "idx": "131"
    },
    {
        "instruction": "# Here are some relevant code fragments from other files of the repo:\n# --------------------------------------------------\n# the below code fragment can be found in:\n# src/configuration/models.py\n# --------------------------------------------------\n# from enum import Enum\n# \n# class Model(Enum):\n#     GPT_4O = \"gpt-4o\"\n#     GPT_4O_MINI = \"gpt-4o-mini\"\n#     O1_PREVIEW = \"o1-preview\"\n#     O1_MINI = \"o1-mini\"\n#     GPT_4_TURBO = \"gpt-4-turbo\"\n#     GPT_3_5_TURBO = \"gpt-3.5-turbo\"\n#     CLAUDE_SONNET = \"claude-3-5-sonnet-20241022\"\n# \n#     def is_anthropic(self):\n#         return self in [Model.CLAUDE_SONNET]\n# \n# --------------------------------------------------\n# the below code fragment can be found in:\n# src/configuration/config.py\n# --------------------------------------------------\n# from enum import Enum\n# \n# from dataclasses import dataclass\n# \n# from typing import Any\n# \n# from .models import Model\n# \n# class Envs(Enum):\n#     PROD = \"PROD\"\n#     DEV = \"DEV\"\n# \n# class GenerationOptions(Enum):\n#     MODELS = \"models\"\n#     MODELS_AND_FIRST_TEST = \"models_and_first_test\"\n#     MODELS_AND_TESTS = \"models_and_tests\"\n# \n# class Config:\n#     env: Envs = Envs.DEV\n#     debug: bool = False\n#     model: Model = Model.CLAUDE_SONNET\n#     generate: GenerationOptions = GenerationOptions.MODELS_AND_TESTS\n#     anthropic_api_key: str = \"\"\n#     openai_api_key: str = \"\"\n#     api_file_path: str = \"\"\n#     destination_folder: str = \"\"\n#     endpoint: str = \"\"\n#     use_existing_framework: bool = False\n# \n#     def update(self, updates: dict[str, Any]):\n#         for key, value in updates.items():\n#             setattr(self, key, value)\n# \n# --------------------------------------------------\n\n\n## src/services/command_service.py\nimport os\n\nimport subprocess\n\nimport logging\n\nfrom typing import List, Dict, Tuple, Optional, Callable\n\nfrom ..configuration.config import Config\n\ndef build_typescript_compiler_command(files: List[Dict[str, str]]) -> str:\n    \"\"\"Build the TypeScript compiler command for specific files\"\"\"\n    file_paths = \" \".join(file[\"path\"] for file in files)\n    return (\n        f\"npx tsc {file_paths} \"\n        \"--lib es2021 \"\n        \"--module NodeNext \"\n        \"--target ESNext \"\n        \"--strict \"\n        \"--esModuleInterop \"\n        \"--skipLibCheck \"\n        \"--forceConsistentCasingInFileNames \"\n        \"--moduleResolution nodenext \"\n        \"--allowUnusedLabels false \"\n        \"--allowUnreachableCode false \"\n        \"--exactOptionalPropertyTypes \"\n        \"--noFallthroughCasesInSwitch \"\n        \"--noImplicitOverride \"\n        \"--noImplicitReturns \"\n        \"--noPropertyAccessFromIndexSignature \"\n        \"--noUncheckedIndexedAccess \"\n        \"--noUnusedLocals \"\n        \"--noUnusedParameters \"\n        \"--checkJs \"\n        \"--noEmit\"\n    )\n\nclass CommandService:\n    \"\"\"\n    Service for running shell commands with real-time output and error handling.\n    \"\"\"\n\n    def __init__(self, config: Config, logger: Optional[logging.Logger] = None):\n        \"\"\"\n        Initialize CommandService with an optional logger.\n\n        Args:\n            config (Config): Configuration instance\n            logger (Optional[logging.Logger]): Logger instance (defaults to logger from logging module)\n        \"\"\"\n        self.config = config\n        self.logger = logger or logging.getLogger(__name__)\n\n    def _log_message(self, message: str, is_error: bool = False):\n        \"\"\"\n        Log a message with optional error severity.\n\n        Args:\n            message (str): Message to log\n            is_error (bool): Whether the message is an error\n        \"\"\"\n        log_method = self.logger.error if is_error else self.logger.info\n        log_method(message)\n\n    def run_command(self, command: str, cwd: Optional[str] = None) -> Tuple[bool, str]:\n        \"\"\"\n        Run a shell command with real-time output and error handling.\n\n        Args:\n            command (str): Command to execute\n            cwd (Optional[str]): Working directory for command execution\n\n        Returns:\n            Tuple[bool, str]: Success status and command output\n        \"\"\"\n        try:\n            self.logger.info(f\"Running command: {command}\")\n            process = subprocess.Popen(\n                command,\n                cwd=cwd or self.config.destination_folder,\n                shell=True,\n                stdout=subprocess.PIPE,\n                stderr=subprocess.STDOUT,\n                bufsize=0,\n                universal_newlines=True,\n                encoding=\"utf-8\",\n                env={\n                    **os.environ,\n                    \"PYTHONUNBUFFERED\": \"1\",\n                    \"FORCE_COLOR\": \"true\",\n                    \"TERM\": \"xterm-256color\",\n                    \"LANG\": \"en_US.UTF-8\",\n                    \"LC_ALL\": \"en_US.UTF-8\",\n                },\n            )\n\n            output_lines = []\n            while True:\n                output = process.stdout.readline()\n                if output:\n                    output_lines.append(output.rstrip())\n                    self._log_message(output.rstrip())\n\n                if output == \"\" and process.poll() is not None:\n                    break\n\n            success = process.returncode == 0\n            self._log_message(\n                (\n                    f\"\\033[92mCommand succeeded.\\033[0m\"\n                    if success\n                    else f\"\\033[91mCommand failed.\\033[0m\"\n                ),\n                is_error=not success,\n            )\n            return success, \"\\n\".join(output_lines)\n\n        except subprocess.SubprocessError as e:\n            self._log_message(f\"Subprocess error: {e}\", is_error=True)\n            return False, str(e)\n        except Exception as e:\n            self._log_message(f\"Unexpected error: {e}\", is_error=True)\n            return False, str(e)\n\n    def run_command_with_fix(\n        self,\n        command_func: Callable,\n        fix_func: Optional[Callable] = None,\n        files: Optional[List[Dict[str, str]]] = None,\n        max_retries: int = 3,\n    ) -> Tuple[bool, str]:\n        \"\"\"\n        Execute a command with retries and an optional fix function on failure.\n\n        Args:\n            command_func (Callable): The function that runs the command\n            fix_func (Optional[Callable]): Function to invoke if the command fails\n            files (Optional[List[Dict[str, str]]]): Files to pass to the command function\n            max_retries (int): Max number of retries on failure\n\n        Returns:\n            Tuple[bool, str]: Success status and output or error message\n        \"\"\"\n        files = files or []\n        retry_count = 0\n        while retry_count < max_retries:\n            if retry_count > 0:\n                self._log_message(f\"\\nAttempt {retry_count + 1}/{max_retries}.\")\n            elif retry_count == 0:\n                self._log_message(\"\")\n\n            success, message = command_func(files)\n\n            if success:\n                return success, message\n\n            if fix_func:\n                self._log_message(f\"Applying fix: {message}\")\n                fix_func(files, message)\n\n            retry_count += 1\n\n        success, message = command_func(files)\n\n        if success:\n            return success, message\n\n        self._log_message(\n            f\"Command failed after {max_retries} attempts.\", is_error=True\n        )\n        return False, message\n\n    def install_dependencies(self) -> Tuple[bool, str]:\n        \"\"\"Install npm dependencies\"\"\"\n        self._log_message(\"\\nInstalling dependencies...\")\n        return self.run_command(\"npm install --loglevel=error\")\n\n    def format_files(self) -> Tuple[bool, str]:\n        \"\"\"Format the generated files\"\"\"\n        self._log_message(\"\\nFormatting files...\")\n        return self.run_command(\"npm run prettify\")\n\n    def run_linter(self) -> Tuple[bool, str]:\n        \"\"\"Run the linter with auto-fix\"\"\"\n        self._log_message(\"\\nRunning linter...\")\n        return self.run_command(\"npm run lint:fix\")\n\n    def run_typescript_compiler(self) -> Tuple[bool, str]:\n        \"\"\"Run the TypeScript compiler\"\"\"\n        self._log_message(\"\\nRunning TypeScript compiler...\")\n        return self.run_command(\"npx tsc --noEmit\")\n\n    def run_typescript_compiler_for_files(self, files: List[Dict[str, str]]) -> Tuple[bool, str]:\n        \"\"\"\n        Run TypeScript compiler for specific files\n        \"\"\"\n",
        "input": "",
        "output": "        self._log_message(\n            f\"Running TypeScript compiler for files: {[file['path'] for file in files]}\"\n        )\n        compiler_command = build_typescript_compiler_command(files)\n        return self.run_command(compiler_command)\n    \n",
        "idx": "132"
    },
    {
        "instruction": "## img2pdf/img_size.py\nimport collections\n\nimport json\n\nimport os\n\nimport io\n\nimport struct\n\nFILE_UNKNOWN = \"Sorry, don't know how to get size for this file.\"\n\nclass UnknownImageFormat(Exception):\n    pass\n\ntypes = collections.OrderedDict()\n\nBMP = types['BMP'] = 'BMP'\n\nGIF = types['GIF'] = 'GIF'\n\nICO = types['ICO'] = 'ICO'\n\nJPEG = types['JPEG'] = 'JPEG'\n\nPNG = types['PNG'] = 'PNG'\n\nTIFF = types['TIFF'] = 'TIFF'\n\nWEBP = types['WEBP'] = 'WEBP'\n\nimage_fields = ['path', 'type', 'file_size', 'width', 'height']\n\nclass Image(collections.namedtuple('Image', image_fields)):\n\n    def to_str_row(self):\n        return (\"%d\\t%d\\t%d\\t%s\\t%s\" % (\n            self.width,\n            self.height,\n            self.file_size,\n            self.type,\n            self.path.replace('\\t', '\\\\t'),\n        ))\n\n    def to_str_row_verbose(self):\n        return (\"%d\\t%d\\t%d\\t%s\\t%s\\t##%s\" % (\n            self.width,\n            self.height,\n            self.file_size,\n            self.type,\n            self.path.replace('\\t', '\\\\t'),\n            self))\n\n    def to_str_json(self, indent=None):\n        return json.dumps(self._asdict(), indent=indent)\n\ndef get_image_metadata(file_path):\n    \"\"\"\n    Return an `Image` object for a given img file content - no external\n    dependencies except the os and struct builtin modules\n\n    Args:\n        file_path (str): path to an image file\n\n    Returns:\n        Image: (path, type, file_size, width, height)\n    \"\"\"\n    size = os.path.getsize(file_path)\n\n    # be explicit with open arguments - we need binary mode\n    with io.open(file_path, \"rb\") as input:\n        return get_image_metadata_from_bytesio(input, size, file_path)\n\ndef get_image_metadata_from_bytesio(input, size, file_path=None):\n    \"\"\"\n    Return an `Image` object for a given img file content - no external\n    dependencies except the os and struct builtin modules\n\n    Args:\n        input (io.IOBase): io object support read & seek\n        size (int): size of buffer in byte\n        file_path (str): path to an image file\n\n    Returns:\n        Image: (path, type, file_size, width, height)\n    \"\"\"\n    height = -1\n    width = -1\n    data = input.read(30)\n    msg = \" raised while trying to decode as JPEG.\"\n\n    if (size >= 10) and data[:6] in (b'GIF87a', b'GIF89a'):\n        # GIFs\n        imgtype = GIF\n        w, h = struct.unpack(\"<HH\", data[6:10])\n        width = int(w)\n        height = int(h)\n    elif ((size >= 24) and data.startswith(b'\\211PNG\\r\\n\\032\\n')\n            and (data[12:16] == b'IHDR')):\n        # PNGs\n        imgtype = PNG\n        w, h = struct.unpack(\">LL\", data[16:24])\n        width = int(w)\n        height = int(h)\n    elif (size >= 16) and data.startswith(b'\\211PNG\\r\\n\\032\\n'):\n        # older PNGs\n        imgtype = PNG\n        w, h = struct.unpack(\">LL\", data[8:16])\n        width = int(w)\n        height = int(h)\n    elif (size >= 2) and data.startswith(b'\\377\\330'):\n        # JPEG\n        imgtype = JPEG\n        input.seek(0)\n        input.read(2)\n        b = input.read(1)\n        try:\n            while (b and ord(b) != 0xDA):\n                while (ord(b) != 0xFF):\n                    b = input.read(1)\n                while (ord(b) == 0xFF):\n                    b = input.read(1)\n                if (ord(b) >= 0xC0 and ord(b) <= 0xC3):\n                    input.read(3)\n                    h, w = struct.unpack(\">HH\", input.read(4))\n                    break\n                else:\n                    input.read(\n                        int(struct.unpack(\">H\", input.read(2))[0]) - 2)\n                b = input.read(1)\n            width = int(w)\n            height = int(h)\n        except struct.error:\n            raise UnknownImageFormat(\"StructError\" + msg)\n        except ValueError:\n            raise UnknownImageFormat(\"ValueError\" + msg)\n        except Exception as e:\n            raise UnknownImageFormat(e.__class__.__name__ + msg)\n    elif (size >= 30) and data.startswith(b'RIFF') and data[8:15] == b'WEBPVP8':\n        # WEBP\n        imgtype = WEBP\n        width, height = int(data[26]) | int(data[27]) << 8, int(data[28]) | int(data[29]) << 8\n    elif (size >= 26) and data.startswith(b'BM'):\n        # BMP\n        imgtype = 'BMP'\n        headersize = struct.unpack(\"<I\", data[14:18])[0]\n        if headersize == 12:\n            w, h = struct.unpack(\"<HH\", data[18:22])\n            width = int(w)\n            height = int(h)\n        elif headersize >= 40:\n            w, h = struct.unpack(\"<ii\", data[18:26])\n            width = int(w)\n            # as h is negative when stored upside down\n            height = abs(int(h))\n        else:\n            raise UnknownImageFormat(\n                \"Unkown DIB header size:\" +\n                str(headersize))\n    elif (size >= 8) and data[:4] in (b\"II\\052\\000\", b\"MM\\000\\052\"):\n        # Standard TIFF, big- or little-endian\n        # BigTIFF and other different but TIFF-like formats are not\n        # supported currently\n        imgtype = TIFF\n        byteOrder = data[:2]\n        boChar = \">\" if byteOrder == \"MM\" else \"<\"\n        # maps TIFF type id to size (in bytes)\n        # and python format char for struct\n        tiffTypes = {\n            1: (1, boChar + \"B\"),  # BYTE\n            2: (1, boChar + \"c\"),  # ASCII\n            3: (2, boChar + \"H\"),  # SHORT\n            4: (4, boChar + \"L\"),  # LONG\n            5: (8, boChar + \"LL\"),  # RATIONAL\n            6: (1, boChar + \"b\"),  # SBYTE\n            7: (1, boChar + \"c\"),  # UNDEFINED\n            8: (2, boChar + \"h\"),  # SSHORT\n            9: (4, boChar + \"l\"),  # SLONG\n            10: (8, boChar + \"ll\"),  # SRATIONAL\n            11: (4, boChar + \"f\"),  # FLOAT\n            12: (8, boChar + \"d\")   # DOUBLE\n        }\n        ifdOffset = struct.unpack(boChar + \"L\", data[4:8])[0]\n        try:\n            countSize = 2\n            input.seek(ifdOffset)\n            ec = input.read(countSize)\n            ifdEntryCount = struct.unpack(boChar + \"H\", ec)[0]\n            # 2 bytes: TagId + 2 bytes: type + 4 bytes: count of values + 4\n            # bytes: value offset\n            ifdEntrySize = 12\n            for i in range(ifdEntryCount):\n                entryOffset = ifdOffset + countSize + i * ifdEntrySize\n                input.seek(entryOffset)\n                tag = input.read(2)\n                tag = struct.unpack(boChar + \"H\", tag)[0]\n                if(tag == 256 or tag == 257):\n                    # if type indicates that value fits into 4 bytes, value\n                    # offset is not an offset but value itself\n                    type = input.read(2)\n                    type = struct.unpack(boChar + \"H\", type)[0]\n                    if type not in tiffTypes:\n                        raise UnknownImageFormat(\n                            \"Unkown TIFF field type:\" +\n                            str(type))\n                    typeSize = tiffTypes[type][0]\n                    typeChar = tiffTypes[type][1]\n                    input.seek(entryOffset + 8)\n                    value = input.read(typeSize)\n                    value = int(struct.unpack(typeChar, value)[0])\n                    if tag == 256:\n                        width = value\n                    else:\n                        height = value\n                if width > -1 and height > -1:\n                    break\n        except Exception as e:\n            raise UnknownImageFormat(str(e))\n    elif size >= 2:\n            # see http://en.wikipedia.org/wiki/ICO_(file_format)\n        imgtype = 'ICO'\n        input.seek(0)\n        reserved = input.read(2)\n        if 0 != struct.unpack(\"<H\", reserved)[0]:\n            raise UnknownImageFormat(FILE_UNKNOWN)\n        format = input.read(2)\n        assert 1 == struct.unpack(\"<H\", format)[0]\n        num = input.read(2)\n        num = struct.unpack(\"<H\", num)[0]\n        if num > 1:\n            import warnings\n            warnings.warn(\"ICO File contains more than one image\")\n        # http://msdn.microsoft.com/en-us/library/ms997538.aspx\n        w = input.read(1)\n        h = input.read(1)\n        width = ord(w)\n        height = ord(h)\n    else:\n        raise UnknownImageFormat(FILE_UNKNOWN)\n\n    return Image(path=file_path,\n                 type=imgtype,\n                 file_size=size,\n                 width=width,\n                 height=height)\n\ndef get_image_size(file_path):\n    \"\"\"\n    Return (width, height) for a given img file content - no external\n    dependencies except the os and struct builtin modules\n    \"\"\"\n",
        "input": "",
        "output": "    img = get_image_metadata(file_path)\n    return (img.width, img.height)\n\n",
        "idx": "139"
    },
    {
        "instruction": "\ndef calculate_score(cards):\n    \"\"\"\n    Takes a list of cards and returns the score calculated from the cards.\n    \"\"\"\n",
        "input": "",
        "output": "    if sum(cards) == 21 and len(cards) == 2:\n        return 0\n    if sum(cards) > 21 and 11 in cards:\n        cards.remove(11)\n        cards.append(1)\n    return sum(cards)\n\n",
        "idx": "163"
    },
    {
        "instruction": "## Coffee maker/coffee_maker.py\nfrom replit import clear\n\nimport time\n\nclass CoffeeMaker:\n    \"\"\"Models the machine that makes the coffee\"\"\"\n    def __init__(self):\n        self.resources = {\n            \"water\": 3000,\n            \"milk\": 2000,\n            \"coffee\": 400,\n        }\n\n    def report(self):\n        \"\"\"Prints a report of all resources.\"\"\"\n        if input(\"\\nEnter password: \") == \"Kaffeeland\":\n            clear()\n            print(\"REMAINING INGREDIENTS\\n\")\n            print(f\"Water  : {self.resources['water']}ml\")\n            print(f\"Coffee : {self.resources['coffee']}g\")\n            print(f\"Milk   : {self.resources['milk']}ml\")\n        else:\n            clear()\n            print(\"Incorrect password.\")\n        time.sleep(7)\n        clear()\n        \n\n    def is_resource_sufficient(self, drink):\n        \"\"\"\n        Returns True when order can be made, False if ingredients are insufficient.\n        \"\"\"\n",
        "input": "",
        "output": "        can_make = True\n        for item in drink.ingredients:\n            if drink.ingredients[item] > self.resources[item]:\n                print(f\"\\nSorry, there is not enough {item}.\")\n                can_make = False\n        return can_make\n    \n",
        "idx": "165"
    },
    {
        "instruction": "## Coffee maker/menu.py\nfrom replit import clear\n\nimport time\n\nclass MenuItem:\n    \"\"\"Models each Menu Item.\"\"\"\n    def __init__(self, name, water, milk, coffee, cost, index):\n        self.name = name\n        self.cost = cost\n        self.index = index\n        self.ingredients = {\n            \"water\": water,\n            \"milk\": milk,\n            \"coffee\": coffee\n        }\n\nclass Menu:\n    \"\"\"Models the Menu with drinks.\"\"\"\n    def __init__(self):\n        self.menu = [\n            MenuItem(name = \"Espresso  \", water = 50, milk = 0, coffee = 18, cost = 1.5, index = 1),\n            MenuItem(name = \"Latte     \", water = 200, milk = 150, coffee = 24, cost = 2.5, index = 2),\n            MenuItem(name = \"Cappuccino\", water = 250, milk = 50, coffee = 24, cost = 3, index = 3),\n        ]\n\n    def get_items(self):\n        \"\"\"\n        Returns all the names of the available menu items\n        \"\"\"\n",
        "input": "",
        "output": "        options = '' \n        for item in self.menu:\n            options += f\"Press {item.index} for {item.name} : ${item.cost}\\n\"\n        options += f\"Press 4 to view machine earnings (for office use).\\n\"\n        options += f\"Press 5 to view remaining ingredients (for office use).\\n\"\n        options += f\"Press 6 to shut down the machine (for office use).\\n\"\n        return options\n    \n",
        "idx": "167"
    },
    {
        "instruction": "## src/Elasticipy/FourthOrderTensor.py\nimport numpy as np\n\ndef voigt_indices(i, j):\n    \"\"\"\n    Translate the two-index notation to one-index notation\n    \n    Parameters\n    ----------\n    i : int or np.ndarray\n    First index\n    j : int or np.ndarray\n    Second index\n    \n    Returns\n    -------\n    Index in the vector of length 6\n    \"\"\"\n",
        "input": "",
        "output": "    voigt_mat = np.array([[0, 5, 4],\n                          [5, 1, 3],\n                          [4, 3, 2]])\n    return voigt_mat[i, j]\n\n",
        "idx": "179"
    },
    {
        "instruction": "## src/Elasticipy/FourthOrderTensor.py\nimport numpy as np\n\ndef unvoigt_index(i):\n    \"\"\"\n    Translate the one-index notation to two-index notation\n    \n    Parameters\n    ----------\n    i : int or np.ndarray\n    Index to translate\n    \"\"\"\n",
        "input": "",
        "output": "    inverse_voigt_mat = np.array([[0, 0],\n                                  [1, 1],\n                                  [2, 2],\n                                  [1, 2],\n                                  [0, 2],\n                                  [0, 1]])\n    return inverse_voigt_mat[i]\n\n",
        "idx": "180"
    },
    {
        "instruction": "# src/Elasticipy/SecondOrderTensor.py\n\nclass SecondOrderTensor:\n    \"\"\"\n    Template class for manipulation of second order tensors or arrays of second order tensors\n\n    Attributes\n    ----------\n    matrix : np.ndarray\n        (...,3,3) matrix storing all the components of the tensor\n\n    \"\"\"\n    name = 'Second-order tensor'\n    'Name to use when printing the tensor'\n\n    def __init__(self, matrix):\n        \"\"\"\n        Create an array of second-order tensors.\n\n        The input argument can be:\n            - an array of shape (3,3) defining all the components of the tensor;\n            - a stack of matrices, that is an array of shape (...,3,3).\n\n        Parameters\n        ----------\n        matrix : list or np.ndarray\n            (3,3) matrix, stack of (3,3) matrices\n        \"\"\"\n        matrix = np.array(matrix)\n        shape = matrix.shape\n        if len(shape) > 1 and shape[-2:] == (3, 3):\n            self.matrix = matrix\n        else:\n            raise ValueError('The input matrix must be of shape (3,3) or (...,3,3)')\n\n    def __repr__(self):\n        s = self.name + '\\n'\n        if self.shape:\n            s += 'Shape={}'.format(self.shape)\n        else:\n            s += self.matrix.__str__()\n        return s\n\n    def __getitem__(self, index):\n        return self.__class__(self.matrix[index])\n\n    def __setitem__(self, index, value):\n        if isinstance(value, (float, np.ndarray)):\n            self.matrix[index] = value\n        elif type(value) == self.__class__:\n            self.matrix[index] = value.matrix\n        else:\n            raise NotImplementedError('The r.h.s must be either float, a ndarray or an object of class {}'.format(self.__class__))\n\n    def __add__(self, other):\n        if type(self) == type(other):\n            return self.__class__(self.matrix + other.matrix)\n        elif isinstance(other, (int, float, np.ndarray)):\n            mat = self.matrix + other\n            if isinstance(self, SkewSymmetricSecondOrderTensor):\n                return SecondOrderTensor(mat)\n            else:\n                return self.__class__(mat)\n        elif isinstance(other, SecondOrderTensor):\n            return SecondOrderTensor(self.matrix + other.matrix)\n        else:\n            raise NotImplementedError('The element to add must be a number, a numpy.ndarray or a tensor.')\n\n    def __radd__(self, other):\n        return self + other\n\n    def __sub__(self, other):\n        if type(self) == type(other):\n            return self.__class__(self.matrix - other.matrix)\n        elif isinstance(other, (int, float, np.ndarray)):\n            return self.__class__(self.matrix - other)\n        else:\n            raise NotImplementedError('The element to subtract must be a number, a numpy ndarray or a tensor.')\n\n    def __neg__(self):\n        return self.__class__(-self.matrix)\n\n    def __rsub__(self, other):\n        return -self + other\n\n    @property\n    def shape(self):\n        \"\"\"\n        Return the shape of the tensor array\n\n        Returns\n        -------\n        tuple\n            Shape of array\n\n        See Also\n        --------\n        ndim : number of dimensions\n        \"\"\"\n        *shape, _, _ = self.matrix.shape\n        return tuple(shape)\n\n    @property\n    def ndim(self):\n        \"\"\"\n        Return the number of dimensions of the tensor array\n\n        Returns\n        -------\n        int\n            number of dimensions\n\n        See Also\n        --------\n        shape : shape of tensor array\n        \"\"\"\n        return len(self.shape)\n\n    @property\n    def C(self):\n        \"\"\"\n        Return tensor components\n\n        For instance T.C[i,j] returns all the (i,j)-th components of each tensor in the array.\n\n        Returns\n        -------\n        np.ndarray\n            Tensor components\n        \"\"\"\n        return _MatrixProxy(self.matrix)\n\n    def eig(self):\n        \"\"\"\n        Compute the eigenvalues and eigenvectors of the tensor\n\n        Returns\n        -------\n        lambda : np.ndarray\n            Eigenvalues of each tensor.\n        v : np.ndarray\n            Eigenvectors of teach tensor.\n\n        See Also\n        --------\n        eigvals : return only the eigenvalues (without directions)\n        principal_directions : return only the principal directions (without eigenvalues)\n        \"\"\"\n        return np.linalg.eig(self.matrix)\n\n    def eigvals(self):\n        \"\"\"\n        Compute the eigenvalues of the tensor, without computing the associated eigenvectors\n\n        Returns\n        -------\n        numpy.ndarray\n            Eigenvalues\n\n        See Also\n        --------\n        eig : compute the eigenvalues and the eigenvector\n        \"\"\"\n        return np.linalg.eigvals(self.matrix)\n\n    def principal_directions(self):\n        \"\"\"\n        Principal directions of the tensors\n\n        Returns\n        -------\n        np.ndarray\n            Principal directions of each tensor of the tensor array\n\n        See Also\n        --------\n        eig : Return both eigenvalues and corresponding principal directions\n        \"\"\"\n        return self.eig()[1]\n\n    @property\n    def I1(self):\n        \"\"\"\n        First invariant of the tensor (trace)\n\n        Returns\n        -------\n        np.ndarray or float\n            First invariant(s) of the tensor(s)\n\n        See Also\n        --------\n        I2 : Second invariant of the tensors\n        I3 : Third invariant of the tensors (det)\n        \"\"\"\n        return self.matrix.trace(axis1=-1, axis2=-2)\n\n    @property\n    def I2(self):\n        \"\"\"\n        Second invariant of the tensor\n\n        For a matrix M, it is defined as::\n\n            I_2 = 0.5 * ( np.trace(M)**2 + np.trace(np.matmul(M, M.T)) )\n\n        Returns\n        -------\n        np.array or float\n            Second invariant(s) of the tensor(s)\n\n        See Also\n        --------\n        I1 : First invariant of the tensors (trace)\n        I3 : Third invariant of the tensors (det)\n        \"\"\"\n        a = self.I1 ** 2\n        b = np.matmul(self.matrix, self._transposeTensor()).trace(axis1=-1, axis2=-2)\n        return 0.5 * (a - b)\n\n    @property\n    def I3(self):\n        \"\"\"\n        Third invariant of the tensor (determinant)\n\n        Returns\n        -------\n        np.array or float\n            Third invariant(s) of the tensor(s)\n\n        See Also\n        --------\n        I1 : First invariant of the tensors (trace)\n        I2 : Second invariant of the tensors\n        \"\"\"\n        return np.linalg.det(self.matrix)\n\n    @property\n    def J1(self):\n        \"\"\"\n        First invariant of the deviatoric part of the stress tensor. It is always zeros, as the deviatoric part as null\n        trace.\n\n        Returns\n        -------\n        float or np.ndarray\n            zero(s)\n        \"\"\"\n        if self.shape:\n            return np.zeros(self.shape)\n        else:\n            return 0.0\n\n    @property\n    def J2(self):\n        \"\"\"\n        Second invariant of the deviatoric part of the tensor.\n\n        Returns\n        -------\n        float or np.ndarray\n            J2 invariant\n        \"\"\"\n        return -self.deviatoric_part().I2\n\n    @property\n    def J3(self):\n        \"\"\"\n        Third invariant of the deviatoric part of the tensor.\n\n        Returns\n        -------\n        float or np.ndarray\n            J3 invariant\n        \"\"\"\n        return self.deviatoric_part().I3\n\n    def trace(self):\n        \"\"\"\n        Return the traces of the tensor array\n\n        Returns\n        -------\n        np.ndarray or float\n            traces of each tensor of the tensor array\n\n        See Also\n        --------\n        I1 : First invariant of the tensors (trace)\n        I2 : Second invariant of the tensors\n        I3 : Third invariant of the tensors (det)\n        \"\"\"\n        return self.I1\n\n    def __mul__(self, B):\n        \"\"\"\n        Element-wise matrix multiplication of arrays of tensors. Each tensor of the resulting tensor array is computed\n        as the matrix product of the tensor components.\n\n        Parameters\n        ----------\n        B : SecondOrderTensor or np.ndarray or Rotation or float\n            If B is a numpy array, we must have::\n\n                B.shape == (..., 3, 3)\n\n        Returns\n        -------\n            Array of tensors populated with element-wise matrix multiplication.\n\n        See Also\n        --------\n        matmul : matrix-like multiplication of tensor arrays\n        \"\"\"\n        if isinstance(B, SecondOrderTensor):\n            new_mat = np.matmul(self.matrix, B.matrix)\n            return SecondOrderTensor(new_mat)\n        elif isinstance(B, Rotation) or is_orix_rotation(B):\n            rotation_matrices, transpose_matrices = rotation_to_matrix(B, return_transpose=True)\n            new_matrix = np.matmul(np.matmul(transpose_matrices, self.matrix), rotation_matrices)\n            return self.__class__(new_matrix)\n        elif isinstance(B, (float, int)):\n            return self.__class__(self.matrix * B)\n        elif isinstance(B, np.ndarray):\n            if B.shape == self.shape:\n                new_matrix = np.einsum('...ij,...->...ij', self.matrix, B)\n                return self.__class__(new_matrix)\n            elif B.shape == self.matrix.shape:\n                return self.__class__(np.matmul(self.matrix, B))\n            else:\n                err_msg = 'For a tensor of shape {}, the input argument must be an array of shape {} or {}'.format(self.shape, self.shape, self.shape + (3, 3))\n                raise ValueError(err_msg)\n        else:\n            raise ValueError('The input argument must be a tensor, an ndarray, a rotation or a scalar value.')\n\n    def __rmul__(self, other):\n        if isinstance(other, (float, int)):\n            return self.__mul__(other)\n        else:\n            raise NotImplementedError('Left multiplication is only implemented for scalar values.')\n\n    def __truediv__(self, other):\n        new_mat = np.zeros(self.matrix.shape)\n        non_zero = np.any(self.matrix, axis=(-1, -2))\n        if isinstance(other, (float, int)):\n            new_mat[non_zero] = self.matrix[non_zero] / other\n        elif isinstance(other, np.ndarray) and self.shape == other.shape:\n            new_mat[non_zero] = np.einsum('pij,p->pij', self.matrix[non_zero], 1 / other[non_zero])\n            return self.__class__(new_mat)\n        else:\n            raise NotImplementedError('Tensors can only be divided by scalar values or by arrays of the same shape.')\n        return self.__class__(new_mat)\n\n    def __eq__(self, other) -> np.ndarray:\n        \"\"\"\n        Check whether the tensors in the tensor array are equal\n\n        Parameters\n        ----------\n        other : SecondOrderTensor or np.ndarray\n            Tensor to compare with\n\n        Returns\n        -------\n        np.array of bool\n            True element is True if the corresponding tensors are equal.\n        \"\"\"\n        if isinstance(other, SecondOrderTensor):\n            return self == other.matrix\n        elif isinstance(other, np.ndarray):\n            if other.shape == (3, 3) or other.shape == self.shape + (3, 3):\n                return np.all(self.matrix == other, axis=(-2, -1))\n            else:\n                raise ValueError('The value to compare must be an array of shape {} or {}'.format(self.shape, self.shape + (3, 3)))\n\n    def matmul(self, other):\n        \"\"\"\n        Perform matrix-like product between tensor arrays. Each \"product\" is a matrix product between\n        the tensor components.\n\n        If A.shape=(a1, a2, ..., an) and B.shape=(b1, b2, ..., bn), with C=A.matmul(B), we have::\n\n            C.shape = (a1, a2, ..., an, b1, b2, ..., bn)\n\n        and::\n\n            C[i,j,k,...,p,q,r...] = np.matmul(A[i,j,k,...], B[p,q,r,...])\n\n        Parameters\n        ----------\n        other : SecondOrderTensor or np.ndarray or Rotation\n            Tensor array or rotation to right-multiply by. If Rotation is provided, the rotations are applied on each\n            tensor.\n\n        Returns\n        -------\n        SecondOrderTensor\n            Tensor array\n\n        See Also\n        --------\n        __mul__ : Element-wise matrix product\n        \"\"\"\n        if isinstance(other, SecondOrderTensor):\n            other_matrix = other.matrix\n        elif isinstance(other, Rotation) or is_orix_rotation(Rotation):\n            other_matrix = rotation_to_matrix(other)\n        else:\n            other_matrix = other\n        matrix = self.matrix\n        shape_matrix = matrix.shape[:-2]\n        shape_other = other_matrix.shape[:-2]\n        extra_dim_matrix = len(shape_other)\n        extra_dim_other = len(shape_matrix)\n        matrix_expanded = matrix.reshape(shape_matrix + (1,) * extra_dim_other + (3, 3))\n        other_expanded = other_matrix.reshape((1,) * extra_dim_matrix + shape_other + (3, 3))\n        if isinstance(other, Rotation):\n            other_expanded_t = _transpose_matrix(other_expanded)\n            new_mat = np.matmul(np.matmul(other_expanded_t, matrix_expanded), other_expanded)\n            return self.__class__(np.squeeze(new_mat))\n        else:\n            new_mat = np.matmul(matrix_expanded, other_expanded)\n            return SecondOrderTensor(np.squeeze(new_mat))\n\n    def transposeArray(self):\n        \"\"\"\n        Transpose the array of tensors\n\n        If A is a tensor array of shape [s1, s2, ..., sn], A.T is of shape [sn, ..., s2, s1].\n\n        Returns\n        -------\n        SecondOrderTensor\n            Transposed array\n\n        See Also\n        --------\n        T : transpose the tensor array (not the components)\n        \"\"\"\n        if self.ndim < 2:\n            return self\n        else:\n            matrix = self.matrix\n            ndim = matrix.ndim\n            new_axes = np.hstack((ndim - 3 - np.arange(ndim - 2), -2, -1))\n            transposed_arr = np.transpose(matrix, new_axes)\n            return self.__class__(transposed_arr)\n\n    @property\n    def T(self):\n        \"\"\"\n        Transpose the array of tensors.\n\n        It is actually an alias for transposeArray()\n\n        Returns\n        -------\n        SecondOrderTensor\n            Transposed array\n        \"\"\"\n        return self.transposeArray()\n\n    def _transposeTensor(self):\n        return _transpose_matrix(self.matrix)\n\n    def transposeTensor(self):\n        \"\"\"\n        Transpose of tensors of the tensor array\n\n        Returns\n        -------\n        SecondOrderTensor\n            Array of transposed tensors of the tensor array\n\n        See Also\n        --------\n        Transpose : transpose the array (not the components)\n        \"\"\"\n        return self.__class__(self._transposeTensor())\n\n    def ddot(self, other):\n        \"\"\"\n        Double dot product (contraction of tensor product, usually denoted \":\") of two tensors.\n\n        For two tensors whose matrices are M1 and M2::\n\n            M1.ddot(M2) == np.trace(np.matmul(M1, M2))\n\n        Parameters\n        ----------\n        other : SecondOrderTensor or np.ndarray\n            Tensor or tensor array to multiply by before contraction.\n\n        Returns\n        -------\n        float or np.ndarray\n            Result of double dot product\n\n        See Also\n        --------\n        matmul : matrix-like product between two tensor arrays.\n\n        \"\"\"\n        tensor_prod = self.transposeTensor() * other\n        return tensor_prod.trace()\n\n    def _flatten(self):\n        if self.shape:\n            new_len = np.prod(self.shape)\n            return np.reshape(self.matrix, (new_len, 3, 3))\n        else:\n            return self.matrix\n\n    def _stats(self, fun, axis=None):\n        if axis is None:\n            flat_mat = self._flatten()\n            new_matrix = fun(flat_mat, axis=0)\n        else:\n            if axis < 0:\n                axis += -2\n            if axis > self.ndim - 1 or axis < -self.ndim - 2:\n                raise ValueError('The axis index is out of bounds for tensor array of shape {}'.format(self.shape))\n            new_matrix = fun(self.matrix, axis=axis)\n        return self.__class__(new_matrix)\n\n    def flatten(self):\n        \"\"\"\n        Flatten the array of tensors.\n\n        If T is of shape [s1, s2, ..., sn], the shape for T.flatten() is [s1*s2*...*sn].\n\n        Returns\n        -------\n        SecondOrderTensor\n            Flattened array (vector) of tensor\n\n        See Also\n        --------\n        ndim : number of dimensions of the tensor array\n        shape : shape of the tensor array\n        reshape : reshape a tensor array\n        \"\"\"\n        return self.__class__(self._flatten())\n\n    def reshape(self, shape, **kwargs):\n        \"\"\"\n        Reshape the array of tensors\n\n        Parameters\n        ----------\n        shape : tuple\n            New shape of the array\n        kwargs : dict\n            Keyword arguments passed to numpy.reshape()\n\n        Returns\n        -------\n        SecondOrderTensor\n            Reshaped array\n\n        See Also\n        --------\n        flatten : flatten an array to 1D\n        \"\"\"\n        new_matrix = self.matrix.reshape(shape + (3, 3), **kwargs)\n        return self.__class__(new_matrix)\n\n    def mean(self, axis=None):\n        \"\"\"\n        Arithmetic mean value\n\n        Parameters\n        ----------\n        axis : int or None, default None\n            Axis to compute the mean along with.\n            If None, returns the overall mean (mean of flattened array)\n\n        Returns\n        -------\n        SecondOrderTensor\n            Mean tensor\n\n        See Also\n        --------\n        std : Standard deviation\n        min : Minimum value\n        max : Maximum value\n        \"\"\"\n        if self.ndim:\n            return self._stats(np.mean, axis=axis)\n        else:\n            return self\n\n    def std(self, axis=None):\n        \"\"\"\n        Standard deviation\n\n        Parameters\n        ----------\n        axis : int or None, default None\n            Axis to compute standard deviation along with.\n            If None, returns the overall standard deviation (std of flattened array)\n\n        Returns\n        -------\n        SecondOrderTensor\n            Tensor of standard deviation\n\n        See Also\n        --------\n        mean : Mean value\n        min : Minimum value\n        max : Maximum value\n          \"\"\"\n        if self.ndim:\n            return self._stats(np.std, axis=axis)\n        else:\n            return self.__class__(np.zeros((3, 3)))\n\n    def min(self, axis=None):\n        \"\"\"\n        Minimum value\n\n        Parameters\n        ----------\n        axis : int or None, default None\n           Axis to compute minimum along with.\n           If None, returns the overall minimum (min of flattened array)\n\n        Returns\n        -------\n        SecondOrderTensor\n           Minimum value of tensors\n\n        See Also\n        --------\n        max : Maximum value\n        mean : Mean value\n        std : Standard deviation\n        \"\"\"\n        if self.ndim:\n            return self._stats(np.min, axis=axis)\n        else:\n            return self\n\n    def max(self, axis=None):\n        \"\"\"\n        Maximum value\n\n        Parameters\n        ----------\n        axis : int or None, default None\n            Axis to compute maximum along with.\n            If None, returns the overall maximum (max of flattened array)\n\n        Returns\n        -------\n        SecondOrderTensor\n            Maximum value of tensors\n\n        See Also\n        --------\n        min : Minimum value\n        mean : Mean value\n        std : Standard deviation\n        \"\"\"\n        if self.ndim:\n            return self._stats(np.max, axis=axis)\n        else:\n            return self\n\n    def _symmetric_part(self):\n        return 0.5 * (self.matrix + self._transposeTensor())\n\n    def symmetric_part(self):\n        \"\"\"\n        Symmetric part of the tensor\n\n        Returns\n        -------\n        SymmetricSecondOrderTensor\n            Symmetric tensor\n\n        See Also\n        --------\n        skewPart : Skew-symmetric part of the tensor\n        \"\"\"\n        return SymmetricSecondOrderTensor(self._symmetric_part())\n\n    def skew_part(self):\n        \"\"\"\n        Skew-symmetric part of the tensor\n\n        Returns\n        -------\n        SkewSymmetricSecondOrderTensor\n            Skew-symmetric tensor\n        \"\"\"\n        new_mat = 0.5 * (self.matrix - self._transposeTensor())\n        return SkewSymmetricSecondOrderTensor(new_mat)\n\n    def spherical_part(self):\n        \"\"\"\n        Spherical (hydrostatic) part of the tensor\n\n        Returns\n        -------\n        self\n            Spherical part\n\n        See Also\n        --------\n        I1 : compute the first invariant of the tensor\n        deviatoricPart : deviatoric the part of the tensor\n        \"\"\"\n        s = self.I1 / 3\n        return self.eye(self.shape) * s\n\n    def deviatoric_part(self):\n        \"\"\"\n        Deviatoric part of the tensor\n\n        Returns\n        -------\n        self\n\n        See Also\n        --------\n        sphericalPart : spherical part of the tensor\n        \"\"\"\n        return self - self.spherical_part()\n\n    @classmethod\n    def eye(cls, shape=()):\n        \"\"\"\n        Create an array of tensors populated with identity matrices\n\n        Parameters\n        ----------\n        shape : tuple or int, default ()\n            If not provided, it just creates a single identity tensor. Otherwise, the tensor array will be of the\n            specified shape.\n\n        Returns\n        -------\n        cls\n            Array of identity tensors\n\n        See Also\n        --------\n        ones : creates an array of tensors full of ones\n        zeros : creates an array full of zero tensors\n        \"\"\"\n        if isinstance(shape, int):\n            matrix_shape = (shape, 3, 3)\n        else:\n            matrix_shape = shape + (3, 3)\n        eye = np.zeros(matrix_shape)\n        eye[..., np.arange(3), np.arange(3)] = 1\n        return cls(eye)\n\n    @classmethod\n    def ones(cls, shape=()):\n        \"\"\"\n        Create an array of tensors populated with matrices of full of ones.\n\n        Parameters\n        ----------\n        shape : tuple or int, default ()\n            If not provided, it just creates a single tensor of ones. Otherwise, the tensor array will be of the\n            specified shape.\n\n        Returns\n        -------\n        cls\n            Array of ones tensors\n\n        See Also\n        --------\n        eye : creates an array of identity tensors\n        zeros : creates an array full of zero tensors\n        \"\"\"\n        if isinstance(shape, int):\n            matrix_shape = (shape, 3, 3)\n        else:\n            matrix_shape = shape + (3, 3)\n        ones = np.ones(matrix_shape)\n        return cls(ones)\n\n    @classmethod\n    def zeros(cls, shape=()):\n        \"\"\"\n        Create an array of tensors populated with matrices full of zeros.\n\n        Parameters\n        ----------\n        shape : tuple or int, default ()\n            If not provided, it just creates a single tensor of ones. Otherwise, the tensor array will be of the\n            specified shape.\n\n        Returns\n        -------\n        cls\n            Array of ones tensors\n\n        See Also\n        --------\n        eye : creates an array of identity tensors\n        ones : creates an array of tensors full of ones\n        \"\"\"\n        if isinstance(shape, int):\n            matrix_shape = (shape, 3, 3)\n        else:\n            matrix_shape = shape + (3, 3)\n        zeros = np.zeros(matrix_shape)\n        return cls(zeros)\n\n    @classmethod\n    def tensile(cls, u, magnitude):\n        \"\"\"\n        Create an array of tensors corresponding to tensile state along a given direction.\n\n        Parameters\n        ----------\n        u : np.ndarray or list\n            Tensile direction. Must be a 3D vector.\n        magnitude : float or np.ndarray or list\n            Magnitude of the tensile state to consider. If a list or an array is provided, the shape of the tensor array\n            will be of the same shape as magnitude.\n        Returns\n        -------\n        cls\n            tensor or tensor array\n        \"\"\"\n        mat = _tensor_from_direction_magnitude(u, u, magnitude)\n        return cls(mat)\n\n    @classmethod\n    def rand(cls, shape=None, seed=None):\n        \"\"\"\n        Generate a tensor array, populated with random uniform values in [0,1).\n\n        Parameters\n        ----------\n        shape : tuple, optional\n            Shape of the tensor array. If not provided, a single tensor is returned\n        seed : int, optional\n            Sets the seed for random generation. Useful to ensure reproducibility\n\n        Returns\n        -------\n        cls\n            Tensor or tensor array of uniform random value\n\n        See Also\n        --------\n        randn : Generate a random sample of tensors whose components follows a normal distribution\n\n        Examples\n        --------\n        Generate a single random tensor:\n\n        >>> from Elasticipy.SecondOrderTensor import SecondOrderTensor as tensor\n        >>> tensor.rand(seed=123)\n        Second-order tensor\n        [[0.68235186 0.05382102 0.22035987]\n         [0.18437181 0.1759059  0.81209451]\n         [0.923345   0.2765744  0.81975456]]\n\n        Now try with tensor array:\n        >>> t = tensor.rand(shape=(100,50))\n        >>> t.shape\n        (100,50)\n        \"\"\"\n        if shape is None:\n            shape = (3, 3)\n        else:\n            shape = shape + (3, 3)\n        rng = np.random.default_rng(seed)\n        a = rng.random(shape)\n        if issubclass(cls, SymmetricSecondOrderTensor):\n            a = _symmetric_part(a)\n        return cls(a)\n\n    def inv(self):\n        \"\"\"Compute the reciprocal (inverse) tensor\"\"\"\n        return SecondOrderTensor(np.linalg.inv(self.matrix))\n\n    @classmethod\n    def randn(cls, mean=np.zeros((3, 3)), std=np.ones((3, 3)), shape=None, seed=None):\n        \"\"\"\n        Generate a tensor array, populated with components follow a normal distribution.\n\n        Parameters\n        ----------\n        mean : list of numpy.ndarray, optional\n            (3,3) matrix providing the mean values of the components.\n        std : list of numpy.ndarray, optional\n            (3,3) matrix providing the standard deviations of the components.\n        shape : tuple, optional\n            Shape of the tensor array\n        seed : int, optional\n            Sets the seed for random generation. Useful to ensure reproducibility\n\n        Returns\n        -------\n        cls\n            Tensor or tensor array of normal random value\n        \"\"\"\n        if shape is None:\n            new_shape = (3, 3)\n        else:\n            new_shape = shape + (3, 3)\n        rng = np.random.default_rng(seed)\n        mat = np.zeros(new_shape)\n        mean = np.asarray(mean)\n        std = np.asarray(std)\n        for i in range(0, 3):\n            for j in range(0, 3):\n                mat[..., i, j] = rng.normal(mean[i, j], std[i, j], shape)\n        if issubclass(cls, SymmetricSecondOrderTensor):\n            mat = _symmetric_part(mat)\n        return cls(mat)\n\n    @classmethod\n    def shear(cls, u, v, magnitude):\n        \"\"\"\n        Create an array of tensors corresponding to shear state along two orthogonal directions.\n\n        Parameters\n        ----------\n        u : np.ndarray or list\n            First direction. Must be a 3D vector.\n        v : np.ndarray or list\n            Second direction. Must be a 3D vector.\n        magnitude : float or np.ndarray or list\n            Magnitude of the shear state to consider. If a list or an array is provided, the shape of the tensor array\n            will be of the same shape as magnitude.\n        Returns\n        -------\n        cls\n            tensor or tensor array\n        \"\"\"\n        if np.abs(np.dot(u, v)) > 1e-05:\n            raise ValueError('u and v must be orthogonal')\n        mat = _tensor_from_direction_magnitude(u, v, magnitude)\n        return cls(mat)\n\n    def div(self, axes=None, spacing=1.0):\n        \"\"\"\n        Compute the divergence vector of the tensor array, along given axes.\n\n        If the tensor has n dimensions, the divergence vector will be computed along its m first axes, with\n        m = min(n, 3), except if specified in the ``axes`` parameter (see below).\n\n        Parameters\n        ----------\n        axes : list of int, tuple of int, int or None, default None\n            Indices of axes along which to compute the divergence vector. If None (default), the m first axes of the\n            array will be used to compute the derivatives.\n        spacing : float or np.ndarray or list, default 1.\n            Spacing between samples the in each direction. If a scalar value is provided, the spacing is assumed equal\n            in each direction. If an array or a list is provided, spacing[i] must return the spacing along the i-th\n            axis (spacing[i] can be float or np.ndarray).\n\n        Returns\n        -------\n        np.ndarray\n            Divergence vector of the tensor array. If the tensor array is of shape (m,n,...,q), the divergence vector\n            will be of shape (m,n,...,q,3).\n\n        Notes\n        -----\n        The divergence of a tensor field :math:`\\\\mathbf{t}(\\\\mathbf{x})` is defined as:\n\n        .. math::\n\n            [\\\\nabla\\\\cdot\\\\mathbf{t}]_i = \\\\frac{\\\\partial t_{ij}}{\\\\partial x_j}\n\n        The main application of this operator is for balance of linear momentum of stress tensor:\n\n        .. math::\n\n            \\\\rho \\\\mathbf{\\\\gamma} = \\\\nabla\\\\cdot\\\\mathbf{\\\\sigma} + \\\\rho\\\\mathbf{b}\n\n        where :math:`\\\\mathbf{\\\\sigma}` is the stress tensor, :math:`\\\\mathbf{\\\\gamma}` is the acceleration,\n        :math:`\\\\mathbf{b}` is the body force density and :math:`\\\\rho` is the mass density.\n\n        In this function, the derivatives are computed with ``numpy.grad`` function.\n        \"\"\"\n        ndim = min(self.ndim, 3)\n        if isinstance(spacing, (float, int)):\n            spacing = [spacing, spacing, spacing]\n        if axes is None:\n            axes = range(ndim)\n        elif isinstance(axes, int):\n            axes = (axes,)\n        elif not isinstance(axes, (tuple, list)):\n            raise TypeError('axes must be int, tuple of int, or list of int.')\n        if len(axes) > ndim:\n            error_msg = 'The number of axes must be less or equal to the number of dimensions ({}), and cannot exceed 3'.format(self.ndim)\n            raise ValueError(error_msg)\n        else:\n            ndim = len(axes)\n        if max(axes) >= ndim:\n            raise IndexError('axes index must be in range of dimensions ({})'.format(self.ndim))\n        div = np.zeros(self.shape + (3,))\n        for dim in range(0, ndim):\n            div += np.gradient(self.C[:, dim], spacing[dim], axis=axes[dim])\n        return div\n\n    def save(self, file, **kwargs):\n        \"\"\"\n        Save the tensor array as binary file (.npy format).\n\n        This function uses numpy.save function.\n\n        Parameters\n        ----------\n        file : file, str or pathlib.Path\n            File or filename to which the tensor is saved.\n        kwargs : dict\n            Keyword arguments passed to numpy.save()\n\n        See Also\n        --------\n        load_from_npy : load a tensor array from a numpy file\n        \"\"\"\n        np.save(file, self.matrix, **kwargs)\n\n    @classmethod\n    def load_from_npy(cls, file, **kwargs):\n        \"\"\"\n        Load a tensor array for .npy file.\n\n        This function uses numpy.load()\n\n        Parameters\n        ----------\n        file : file, str or pathlib.Path\n            File to read to create the array\n        kwargs : dict\n            Keyword arguments passed to numpy.load()\n\n        Returns\n        -------\n        SecondOrderTensor\n            Tensor array\n\n        See Also\n        --------\n        save : save the tensor array as a numpy file\n        \"\"\"\n        matrix = np.load(file, **kwargs)\n        if matrix.shape[-2:] != (3, 3):\n            raise ValueError('The shape of the array to load must be (...,3,3).')\n        else:\n            return cls(matrix)\n\n    def save_as_txt(self, file, name_prefix='', **kwargs):\n        \"\"\"\n        Save the tensor array to human-readable text file.\n\n        The array must be 1D. The i-th row of the file will provide the components of the i-th tensor in of the array.\n        This function uses pandas.DataFrame.to_csv().\n\n        Parameters\n        ----------\n        file : file or str\n            File to dump tensor components to.\n        name_prefix : str, optional\n            Prefix to add for naming the columns. For instance, name_prefix='E' will result in columns named E11, E12,\n            E13 etc.\n        kwargs : dict\n            Keyword arguments passed to pandas.DataFrame.to_csv()\n        \"\"\"\n        if self.ndim > 1:\n            raise ValueError('The array must be flatten before getting dumped to text file.')\n        else:\n            d = dict()\n            for i in range(3):\n                if isinstance(self, SkewSymmetricSecondOrderTensor):\n                    r = range(i + 1, 3)\n                elif isinstance(self, SymmetricSecondOrderTensor):\n                    r = range(i, 3)\n                else:\n                    r = range(3)\n                for j in r:\n                    key = name_prefix + '{}{}'.format(i + 1, j + 1)\n                    d[key] = self.C[i, j]\n            df = pd.DataFrame(d)\n            df.to_csv(file, index=False, **kwargs)\n\n    def to_pymatgen(self):\n        \"\"\"\n        Convert the second order object into an object compatible with pymatgen.\n\n        The object to use must be either a single tensor, or a flat tensor array. In the latter case, the output will be\n        a list of pymatgen's tensors.\n\n        Returns\n        -------\n        pymatgen.analysis.elasticity.Strain, pymatgen.analysis.elasticity.Stress, pymatgen.core.tensors.Tensor or list\n            The type of output depends on the type of object to use:\n                - if the object is of class StrainTensor, the output will be of class pymatgen.analysis.elasticity.Strain\n                - if the object is of class StressTensor, the output will be of class pymatgen.analysis.elasticity.Stress\n                - otherwise, the output will be of class pymatgen.core.tensors.Tensor\n\n        See Also\n        --------\n        flatten : Converts a tensor array to 1D tensor array\n        \"\"\"\n        try:\n            from Elasticipy.StressStrainTensors import StrainTensor, StressTensor\n            if isinstance(self, StrainTensor):\n                from pymatgen.analysis.elasticity import Strain as Constructor\n            elif isinstance(self, StressTensor):\n                from pymatgen.analysis.elasticity import Stress as Constructor\n            else:\n                from pymatgen.core.tensors import Tensor as Constructor\n        except ImportError:\n            raise ModuleNotFoundError('Module pymatgen is required for this function.')\n        if self.ndim > 1:\n            raise ValueError('The array must be flattened (1D tensor array) before converting to pytmatgen.')\n        if self.shape:\n            return [Constructor(self[i].matrix) for i in range(self.shape[0])]\n        else:\n            return Constructor(self.matrix)\n\n    @classmethod\n    def load_from_txt(cls, file, name_prefix='', **kwargs):\n        \"\"\"\n        Load a tensor array from text file.\n    \n        Parameters\n        ----------\n        file : str or file\n        Textfile to read the components from.\n        name_prefix : str, optional\n        Prefix to add to each column when parsing the file. For instance, with name_prefix='E', the function will\n        look for columns names E11, E12, E13 etc.\n    \n        Returns\n        -------\n        SecondOrderTensor\n        Flat (1D) tensor constructed from the values given in the text file\n        \"\"\"\n",
        "input": "",
        "output": "        df = pd.read_csv(file, **kwargs)\n        matrix = np.zeros((len(df), 3, 3))\n        for i in range(3):\n            if cls is SkewSymmetricSecondOrderTensor:\n                r = range(i + 1, 3)\n            elif cls is SymmetricSecondOrderTensor:\n                r = range(i, 3)\n            else:\n                r = range(3)\n            for j in r:\n                key = name_prefix + '{}{}'.format(i + 1, j + 1)\n                matrix[:, i, j] = df[key]\n        return cls(matrix)\n    \n",
        "idx": "187"
    },
    {
        "instruction": "# src/Elasticipy/SphericalFunction.py\n\nfrom numpy import cos, sin\nimport numpy as np\n\ndef sph2cart(*args):\n    \"\"\"\n    Converts spherical/hyperspherical coordinates to cartesian coordinates.\n\n    Parameters\n    ----------\n    args : tuple\n        (phi, theta) angles for spherical coordinates of direction u, where phi denotes the azimuth from X and theta is\n        the colatitude angle from Z.\n        If a third argument is passed, it defines the third angle in hyperspherical coordinate system (psi), that is\n        the orientation of the second vector v, orthogonal to u.\n\n    Returns\n    -------\n    numpy.ndarray\n        directions u expressed in cartesian coordinates system.\n    tuple of numpy.ndarray, numpy.ndarray\n        If a third angle is passed, returns a tuple:\n        - The first element is `u`, the directions expressed in the cartesian coordinate system.\n        - The second element is `v`, the direction of the second vector orthogonal to `u`, also expressed in the\n        cartesian coordinate system.\n    \"\"\"\n    phi, theta, *psi = args\n    phi_vec = np.array(phi).flatten()\n    theta_vec = np.array(theta).flatten()\n    u = np.array([cos(phi_vec) * sin(theta_vec), sin(phi_vec) * sin(theta_vec), cos(theta_vec)]).T\n    if not psi:\n        return u\n    else:\n        psi_vec = np.array(psi).flatten()\n        e_phi = np.array([-sin(phi_vec), cos(phi_vec), np.zeros(phi_vec.shape)])\n        e_theta = np.array([cos(theta_vec) * cos(phi_vec), cos(theta_vec) * sin(phi_vec), -sin(theta_vec)])\n        v = cos(psi_vec) * e_phi + sin(psi_vec) * e_theta\n        return (u, v.T)\nfrom scipy import optimize\nfrom matplotlib import pyplot as plt, cm\nfrom matplotlib.colors import Normalize\n\ndef _plot3D(fig, u, r, **kwargs):\n    norm = Normalize(vmin=r.min(), vmax=r.max())\n    colors = cm.viridis(norm(r))\n    ax = fig.add_subplot(1, 1, 1, projection='3d')\n    xyz = (u.T * r.T).T\n    ax.plot_surface(xyz[:, :, 0], xyz[:, :, 1], xyz[:, :, 2], facecolors=colors, rstride=1, cstride=1, antialiased=False, **kwargs)\n    mappable = cm.ScalarMappable(cmap='viridis', norm=norm)\n    mappable.set_array([])\n    fig.colorbar(mappable, ax=ax)\n    ax.set_xlabel('X')\n    ax.set_ylabel('Y')\n    ax.set_zlabel('Z')\n    return ax\nfrom scipy import integrate as integrate\n\ndef _integrate_over_unit_sphere(phi, theta, values=None, psi=None):\n    sine = np.sin(theta)\n    if values is None:\n        values = np.ones(phi.shape)\n    if psi is None:\n        return integrate.trapezoid(integrate.trapezoid(values * sine, axis=0, x=phi[:, 0]), axis=0, x=theta[0, :])\n    else:\n        return integrate.trapezoid(integrate.trapezoid(integrate.trapezoid(values * sine, axis=0, x=phi[:, 0, 0]), axis=0, x=theta[0, :, 0]), x=psi[0, 0, :])\nfrom Elasticipy.PoleFigure import add_polefigure\n\ndef uniform_spherical_distribution(n_evals, seed=None, return_orthogonal=False):\n    \"\"\"\n    Create a set of vectors whose projections over the unit sphere are uniformly distributed.\n\n    Parameters\n    ----------\n    n_evals : int\n        Number of vectors to generate\n    seed : int, default None\n        Sets the seed for the random values. Useful if one wants to ensure reproducibility.\n    return_orthogonal : bool, default False\n        If true, also return a second set of vectors which are orthogonal to the first one.\n\n    Returns\n    -------\n    u : np.ndarray\n        Random set of vectors whose projections over the unit sphere are uniform.\n    v : np.ndarray\n        Set of vectors with the same properties as u, but orthogonal to u.\n        Returned only if return_orthogonal is True\n\n    Notes\n    -----\n    The returned vector(s) are not unit. If needed, one can use:\n        u = (u.T / np.linalg.norm(u, axis=1)).T\n    \"\"\"\n    if seed is None:\n        rng = np.random\n    else:\n        rng = np.random.default_rng(seed)\n    u = rng.normal(size=(n_evals, 3))\n    u /= np.linalg.norm(u, axis=1, keepdims=True)\n    if return_orthogonal:\n        if seed is not None:\n            rng = np.random.default_rng(seed + 1)\n        u2 = rng.normal(size=(n_evals, 3))\n        return (u, np.cross(u, u2))\n    else:\n        return u\n\ndef _create_xyz_section(ax, section_name, polar_angle):\n    ax.title.set_text('{}-{} plane'.format(*section_name))\n    if section_name == 'XY':\n        phi = polar_angle\n        theta = np.pi / 2 * np.ones(len(polar_angle))\n    elif section_name == 'XZ':\n        phi = np.zeros(len(polar_angle))\n        theta = np.pi / 2 - polar_angle\n    else:\n        phi = np.pi / 2 * np.ones(len(polar_angle))\n        theta = np.pi / 2 - polar_angle\n    ax.set_xticks(np.linspace(0, 3 * np.pi / 2, 4))\n    h_direction, v_direction = section_name\n    ax.set_xticklabels((h_direction, v_direction, '-' + h_direction, '-' + v_direction))\n    return (phi, theta, ax)\n\nclass SphericalFunction:\n    \"\"\"\n    Class for spherical functions, that is, functions that depend on directions in 3D space.\n\n    Attribute\n    ---------\n    fun : function to use\n    \"\"\"\n    domain = np.array([[0, 2 * np.pi], [0, np.pi / 2]])\n    name = 'Spherical function'\n    'Bounds to consider in spherical coordinates'\n\n    def __init__(self, fun, symmetry=True):\n        \"\"\"\n        Create a spherical function, that is, a function that depends on one direction only.\n\n        Parameters\n        ----------\n        fun : callable\n            Function to return\n        symmetry : bool, optional\n            Set to true if fun(u)==fun(-u)\n        \"\"\"\n        self.fun = fun\n        self.symmetry = symmetry\n\n    def __repr__(self):\n        val_min, _ = self.min()\n        val_max, _ = self.max()\n        s = '{}\\n'.format(self.name)\n        s += 'Min={}, Max={}'.format(val_min, val_max)\n        return s\n\n    def __add__(self, other):\n        if type(other) is self.__class__:\n\n            def fun(*x):\n                return self.fun(*x) + other.fun(*x)\n            return self.__class__(fun)\n        elif isinstance(other, (float, int, np.number)):\n\n            def fun(*x):\n                return self.fun(*x) + other\n            return self.__class__(fun)\n        else:\n            msg_error = 'A {} can only be added to another {} or a scalar value.'.format(self.name, self.name)\n            raise NotImplementedError(msg_error)\n\n    def __sub__(self, other):\n        if isinstance(other, self.__class__):\n\n            def fun(*x):\n                return self.fun(*x) - other.fun(*x)\n            return self.__class__(fun)\n        else:\n            return self.__add__(-other)\n\n    def __mul__(self, other):\n        if type(other) is self.__class__:\n\n            def fun(*x):\n                return self.fun(*x) * other.fun(*x)\n        elif isinstance(other, (float, int, np.number)):\n\n            def fun(*x):\n                return self.fun(*x) * other\n        else:\n            msg_error = 'A {} can only be multiplied by another {} or a scalar value.'.format(self.name, self.name)\n            raise NotImplementedError(msg_error)\n        return self.__class__(fun)\n\n    def __rmul__(self, other):\n        return self.__mul__(other)\n\n    def __truediv__(self, other):\n        if type(other) is self.__class__:\n\n            def fun(*x):\n                return self.fun(*x) / other.fun(*x)\n        elif isinstance(other, (float, int, np.number)):\n\n            def fun(*x):\n                return self.fun(*x) / other\n        else:\n            raise NotImplementedError('A SphericalFunction can only be divided by a scalar value of another SphericalFunction.')\n        return self.__class__(fun)\n\n    def eval(self, u):\n        \"\"\"\n        Evaluate value along a given (set of) direction(s).\n\n        Parameters\n        ----------\n        u : np.ndarray or list\n            Direction(s) to estimate the value along with. It can be of a unique direction [nx, ny, nz],\n            or a set of directions (e.g. [[n1x, n1y n1z],[n2x, n2y, n2z],...]).\n\n        Returns\n        -------\n        float or np.ndarray\n            If only one direction is given as a tuple of floats [nx, ny, nz], the result is a float; otherwise, the\n            result is a nd.array.\n\n        See Also\n        --------\n        eval_spherical : evaluate the function along a given direction given using the spherical coordinates\n        \"\"\"\n        u_vec = np.atleast_2d(u)\n        norm = np.linalg.norm(u_vec, axis=1)\n        if np.any(norm < 1e-09):\n            raise ValueError('The input vector cannot be zeros')\n        u_vec = (u_vec.T / norm).T\n        values = self.fun(u_vec)\n        if isinstance(u, list) and np.array(u).shape == (3,):\n            return values[0]\n        else:\n            return values\n\n# ...\n\nclass HyperSphericalFunction(SphericalFunction):\n    \"\"\"\n    Class for defining functions that depend on two orthogonal directions u and v.\n    \"\"\"\n    domain = np.array([[0, 2 * np.pi], [0, np.pi / 2], [0, np.pi]])\n    name = 'Hyperspherical function'\n\n    def __init__(self, fun):\n        \"\"\"\n        Create a hyperspherical function, that is, a function that depends on two orthogonal directions only.\n        \"\"\"\n        super().__init__(fun)\n\n    def eval(self, u, *args):\n        \"\"\"\n        Evaluate the Hyperspherical function with respect to two orthogonal directions.\n\n        Parameters\n        ----------\n        u : list or np.ndarray\n            First axis\n        args : list or np.ndarray\n            Second axis\n\n        Returns\n        -------\n        float or np.ndarray\n            Function value\n\n        See Also\n        --------\n        eval_spherical : evaluate the function along a direction defined by its spherical coordinates.\n        \"\"\"\n        m_vec = np.atleast_2d(u)\n        n_vec = np.atleast_2d(*args)\n        norm_1 = np.linalg.norm(m_vec, axis=1)\n        norm_2 = np.linalg.norm(n_vec, axis=1)\n        if np.any(norm_1 < 1e-09) or np.any(norm_2 < 1e-09):\n            raise ValueError('The input vector cannot be zeros')\n        m_vec = (m_vec.T / norm_1).T\n        n_vec = (n_vec.T / norm_2).T\n        dot = np.abs(np.einsum('ij,ij->i', m_vec, n_vec))\n        if np.any(dot > 1e-09):\n            raise ValueError('The two directions must be orthogonal.')\n        values = self.fun(m_vec, n_vec)\n        if np.array(u).shape == (3,) and (not isinstance(u, np.ndarray)):\n            return values[0]\n        else:\n            return values\n\n    def mean(self, method='trapezoid', n_evals=int(1000000.0), seed=None):\n        if method == 'exact':\n\n            def fun(psi, theta, phi):\n                return self.eval_spherical(phi, theta, psi) * sin(theta)\n            domain = self.domain.flatten()\n            q = integrate.tplquad(fun, *domain)\n            return q[0] / (2 * np.pi ** 2)\n        elif method == 'trapezoid':\n            (phi, theta, psi), evals = self.evaluate_on_spherical_grid(n_evals)\n            dom_size = _integrate_over_unit_sphere(phi, theta, psi=psi)\n            integral = _integrate_over_unit_sphere(phi, theta, psi=psi, values=evals)\n            return integral / dom_size\n        else:\n            u, v = uniform_spherical_distribution(n_evals, seed=seed, return_orthogonal=True)\n            return np.mean(self.eval(u, v))\n\n    def var(self, method='trapezoid', n_evals=int(1000000.0), mean=None, seed=None):\n        if method == 'exact':\n            if mean is None:\n                mean = self.mean(method='exact')\n\n            def fun(psi, theta, phi):\n                return (mean - self.eval_spherical(phi, theta, psi)) ** 2 * sin(theta)\n            domain = self.domain.flatten()\n            q = integrate.tplquad(fun, *domain)\n            return q[0] / (2 * np.pi ** 2)\n        if method == 'trapezoid':\n            (phi, theta, psi), evals = self.evaluate_on_spherical_grid(n_evals)\n            dom_size = _integrate_over_unit_sphere(phi, theta, psi=psi)\n            if mean is None:\n                mean = self.mean(method='trapezoid', n_evals=n_evals)\n            return _integrate_over_unit_sphere(phi, theta, psi=psi, values=(evals - mean) ** 2) / dom_size\n        else:\n            u, v = uniform_spherical_distribution(n_evals, seed=seed, return_orthogonal=True)\n            return np.var(self.eval(u, v))\n\n    def evaluate_on_spherical_grid(self, n, return_in_spherical=True, use_symmetry=True):\n        \"\"\"\n        Create a set of vectors corresponding to a spherical grid (phi,theta), then flatten it.\n\n        Parameters\n        ----------\n        n : int or tuple of int\n            If int, gives the overall number of evaluations over the unit hypersphere. If a tuple is passed, they gieve\n            the number of angles to consider for (hyper)spherical coordinates (n_phi, n_theta, n_psi).\n        return_in_spherical : bool, optional\n            If true, the first output argument will be the spherical coordinates (phi, theta). Otherwise, the cartersian\n            coordinates are returned\n        use_symmetry : bool, optional\n            Whether to use take advantage ot symmetry\n\n        Returns\n        -------\n        tuple\n            Coordinates of evaluation, either in spherical of cartesian coordinates\n        numpy.ndarray\n            Grid of evaluated values\n        \"\"\"\n        symmetry = self.symmetry and use_symmetry\n        if isinstance(n, int):\n            if symmetry:\n                n_phi = int(2 * n ** (1 / 3)) + 1\n                n_theta = int(n_phi / 4) + 1\n                n_psi = int(n_phi / 2) + 1\n            else:\n                n_phi = int(4 * n ** (1 / 3)) + 1\n                n_theta = int(n_phi / 2) + 1\n                n_psi = int(n_phi / 2) + 1\n        else:\n            n_phi, n_theta, n_psi = n\n        if symmetry:\n            theta_max = np.pi / 2\n        else:\n            theta_max = np.pi\n        phi = np.linspace(0, 2 * np.pi, n_phi)\n        theta = np.linspace(0, theta_max, n_theta)\n        psi = np.linspace(0, np.pi, n_psi)\n        phi_grid, theta_grid, psi_grid = np.meshgrid(phi, theta, psi, indexing='ij')\n        u, v = sph2cart(phi_grid.flatten(), theta_grid.flatten(), psi_grid)\n        evals = self.eval(u, v)\n        evals_grid = evals.reshape((n_phi, n_theta, n_psi))\n        if return_in_spherical:\n            return ((phi_grid, theta_grid, psi_grid), evals_grid)\n        else:\n            u_r = u.reshape((n_phi, n_theta, n_psi, 3))\n            v_r = v.reshape((n_phi, n_theta, n_psi, 3))\n            return ((u_r, v_r), evals_grid)\n\n    def plot3D(self, n_phi=50, n_theta=50, n_psi=50, which='mean', fig=None, **kwargs):\n        \"\"\"\n        Generate a 3D plot representing the evaluation of spherical harmonics.\n\n        This function evaluates a function over a grid defined by spherical coordinates\n        (phi, theta, psi) and produces a 3D plot. It provides options to display the mean,\n        standard deviation, minimum, or maximum of the evaluated values along the third angles (psi).\n        The plot can be customized with additional keyword arguments.\n\n        Parameters\n        ----------\n        n_phi : int, optional\n            Number of divisions along the phi axis, default is 50.\n        n_theta : int, optional\n            Number of divisions along the theta axis, default is 50.\n        n_psi : int, optional\n            Number of divisions along the psi axis, default is 50.\n        which : str, optional\n            Determines which statistical measure to plot ('mean', 'std', 'min', 'max'),\n            default is 'mean'.\n        fig : matplotlib.figure.Figure, optional\n            Handle to existing figure object. Default is None. If provided, it disables showing the figure.\n        kwargs : dict, optional\n            Additional keyword arguments to customize the plot.\n\n        Returns\n        -------\n        tuple\n            A tuple containing the matplotlib figure and axes objects.\n        \"\"\"\n        if fig is None:\n            new_fig = plt.figure()\n        else:\n            new_fig = fig\n        uv, values = self.evaluate_on_spherical_grid((n_phi, n_theta, n_psi), return_in_spherical=False, use_symmetry=False)\n        u, _ = uv\n        if which == 'std':\n            r_grid = np.std(values, axis=2)\n        elif which == 'min':\n            r_grid = np.min(values, axis=2)\n        elif which == 'max':\n            r_grid = np.max(values, axis=2)\n        else:\n            r_grid = np.mean(values, axis=2)\n        ax = _plot3D(new_fig, u[:, :, 0, :], r_grid, **kwargs)\n        if fig is None:\n            plt.show()\n        return (new_fig, ax)\n\n    def plot_xyz_sections(self, n_theta=500, n_psi=100, color_minmax='blue', alpha_minmax=0.2, color_mean='red', fig=None):\n        \"\"\"\n        Plots the XYZ sections using polar projections.\n\n        This function creates a figure with three subplots representing the XY, XZ,\n        and YZ sections. It utilizes polar projections to plot the min, max, and mean\n        values of the evaluated function over given theta and phi ranges.\n\n        Parameters\n        ----------\n        n_theta : int, optional\n            Number of theta points to use in the grid (default is 500).\n        n_psi : int, optional\n            Number of psi points to use in the grid (default is 100).\n        color_minmax : str, optional\n            Color to use for plotting min and max values (default is 'blue').\n        alpha_minmax : float, optional\n            Alpha transparency level to use for the min/max fill (default is 0.2).\n        color_mean : str, optional\n            Color to use for plotting mean values (default is 'red').\n        fig : matplotlib.figure.Figure, optional\n            Handle to existing figure object. Default is None. If provided, it disables showing the figure.\n\n        Returns\n        -------\n        fig : matplotlib.figure.Figure\n            The created figure.\n        axs : list of matplotlib.axes._subplots.PolarAxesSubplot\n            List of polar axis subplots.\n        \"\"\"\n        if fig is None:\n            new_fig = plt.figure()\n        else:\n            new_fig = fig\n        theta_polar = np.linspace(0, 2 * np.pi, n_theta)\n        titles = ('XY', 'XZ', 'YZ')\n        handles, labels = ([], [])\n        axs = []\n        for i in range(0, 3):\n            ax = new_fig.add_subplot(1, 3, i + 1, projection='polar')\n            phi, theta, ax = _create_xyz_section(ax, titles[i], theta_polar)\n            psi = np.linspace(0, np.pi, n_psi)\n            phi_grid, psi_grid = np.meshgrid(phi, psi, indexing='ij')\n            theta_grid, _ = np.meshgrid(theta, psi, indexing='ij')\n            phi = phi_grid.flatten()\n            theta = theta_grid.flatten()\n            psi = psi_grid.flatten()\n            u, v = sph2cart(phi, theta, psi)\n            values = self.eval(u, v).reshape((n_theta, n_psi))\n            min_val = np.min(values, axis=1)\n            max_val = np.max(values, axis=1)\n            ax.plot(theta_polar, min_val, color=color_minmax)\n            ax.plot(theta_polar, max_val, color=color_minmax)\n            area = ax.fill_between(theta_polar, min_val, max_val, alpha=alpha_minmax, label='Min/Max')\n            line, = ax.plot(theta_polar, np.mean(values, axis=1), color=color_mean, label='Mean')\n            axs.append(ax)\n        handles.extend([line, area])\n        labels.extend([line.get_label(), area.get_label()])\n        new_fig.legend(handles, labels, loc='upper center', ncol=2, bbox_to_anchor=(0.5, 0.95))\n        if fig is None:\n            new_fig.show()\n        return (new_fig, axs)\n\n    def plot_as_pole_figure(self, n_theta=50, n_phi=200, n_psi=50, which='mean', projection='lambert', fig=None, plot_type='imshow', show=True, title=None, subplot_args=(), subplot_kwargs=None, **kwargs):\n        \"\"\"\n        Generate a pole figure plot from spherical function evaluation.\n\n        This function evaluates a spherical function over specified ranges of angles\n        (phi, theta, psi) and then generates a 2D pole figure plot using various\n        statistical summaries of the data (mean, std, min, max). It also supports\n        several types of plot visualizations such as 'imshow', 'contourf', and 'contour'.\n\n        Parameters\n        ----------\n        n_theta : int, optional\n            Number of sampling points for theta angle. Default is 50.\n        n_phi : int, optional\n            Number of sampling points for phi angle. Default is 200.\n        n_psi : int, optional\n            Number of sampling points for psi angle. Default is 50.\n        which : str, optional\n            Specifies the type of statistical summary to use for plotting.\n            Options include 'mean', 'std', 'min', 'max'. Default is 'mean'.\n        projection : str, optional\n            Type of projection for the pole figure plot. Default is 'lambert'.\n        fig : matplotlib.figure.Figure, optional\n            Pre-existing figure to use for plotting. If None, a new figure is created.\n            Default is None.\n        plot_type : str, optional\n            Type of plot to generate. Can be 'imshow', 'contourf', or 'contour'.\n            Default is 'imshow'.\n        show : bool, optional\n            Set whether to show the plot or not. Default is True. This must be turned off when using multiple subplots.\n        subplot_args : tuple, optional\n            Arguments to pass to the add_subplot() function. Default is None.\n        subplot_kwargs : dict, optional\n            Keyword arguments to pass to the add_subplot() function. Default is None.\n        **kwargs : dict, optional\n            Additional keyword arguments passed to the plotting functions.\n\n        Returns\n        -------\n        fig : matplotlib.figure.Figure\n            The figure object containing the plot.\n        ax : matplotlib.axes.Axes\n            The axes object containing the plot.\n        \"\"\"\n        if subplot_kwargs is None:\n            subplot_kwargs = {}\n        if fig is None:\n            fig = plt.figure()\n        ax = add_polefigure(fig, *subplot_kwargs, projection=projection, **subplot_kwargs)\n        phi = np.linspace(*self.domain[0], n_phi)\n        theta = np.linspace(*self.domain[1], n_theta)\n        psi = np.linspace(*self.domain[2], n_psi)\n        phi_grid, theta_grid, psi_grid = np.meshgrid(phi, theta, psi, indexing='ij')\n        phi_flat = phi_grid.flatten()\n        theta_flat = theta_grid.flatten()\n        psi_flat = psi_grid.flatten()\n        values = self.eval_spherical(np.array([phi_flat, theta_flat, psi_flat]).T)\n        reshaped_values = values.reshape((n_phi, n_theta, n_psi))\n        if which == 'std':\n            to_plot = np.std(reshaped_values, axis=2)\n        elif which == 'min':\n            to_plot = np.min(reshaped_values, axis=2)\n        elif which == 'max':\n            to_plot = np.max(reshaped_values, axis=2)\n        else:\n            to_plot = np.mean(reshaped_values, axis=2)\n        phi_grid, theta_grid = np.meshgrid(phi, theta, indexing='ij')\n        if plot_type == 'imshow':\n            sc = ax.pcolormesh(phi_grid, theta_grid, to_plot, **kwargs)\n        elif plot_type == 'contourf':\n            sc = ax.contourf(phi_grid, theta_grid, to_plot, **kwargs)\n        elif plot_type == 'contour':\n            sc = ax.contour(phi_grid, theta_grid, to_plot, **kwargs)\n        else:\n            raise ValueError(f'Unknown plot type: {plot_type}')\n        ax.set_rlim(*self.domain[1])\n        ax.set_title(title)\n        fig.colorbar(sc)\n        if show:\n            plt.show()\n        return (fig, ax)\n\n    def eval_spherical(self, *args, degrees=False):\n        \"\"\"\n        Evaluate value along a given (set of) direction(s) defined by its (their) spherical coordinates.\n    \n        Parameters\n        ----------\n        args : list or np.ndarray\n        [phi, theta, psi] where phi denotes the azimuth angle from X axis to the first direction (u), theta is\n        the latitude angle from Z axis (theta==0 -> u = Z axis), and psi is the angle defining the orientation of\n        the second direction (v) in the plane orthogonal to u, as illustrated below:\n    \n        .. image:: ../../docs/_static/images/HyperSphericalCoordinates.png\n    \n    \n        degrees : bool, default False\n        If True, the angles are given in degrees instead of radians.\n    \n        Returns\n        -------\n        float or np.ndarray\n        If only one direction is given as a tuple of floats [nx, ny, nz], the result is a float;\n        otherwise, the result is a nd.array.\n    \n        See Also\n        --------\n        eval : evaluate the function along two orthogonal directions (u,v))\n        \"\"\"\n",
        "input": "",
        "output": "        angles = np.atleast_2d(args)\n        if degrees:\n            angles = np.radians(angles)\n        phi, theta, psi = angles.T\n        u, v = sph2cart(phi, theta, psi)\n        values = self.eval(u, v)\n        if np.array(args).shape == (3,) and (not isinstance(args, np.ndarray)):\n            return values[0]\n        else:\n            return values\n    \n",
        "idx": "194"
    },
    {
        "instruction": "# src/Elasticipy/FourthOrderTensor.py\n\nimport numpy as np\n\ndef _isotropic_matrix(C11, C12, C44):\n    return np.array([[C11, C12, C12, 0, 0, 0], [C12, C11, C12, 0, 0, 0], [C12, C12, C11, 0, 0, 0], [0, 0, 0, C44, 0, 0], [0, 0, 0, 0, C44, 0], [0, 0, 0, 0, 0, C44]])\nfrom Elasticipy.StressStrainTensors import StrainTensor, StressTensor\n\nclass ComplianceTensor(StiffnessTensor):\n    \"\"\"\n    Class for manipulating compliance tensors\n    \"\"\"\n    tensor_name = 'Compliance'\n    voigt_map = np.array([[1.0, 1.0, 1.0, 2.0, 2.0, 2.0], [1.0, 1.0, 1.0, 2.0, 2.0, 2.0], [1.0, 1.0, 1.0, 2.0, 2.0, 2.0], [2.0, 2.0, 2.0, 4.0, 4.0, 4.0], [2.0, 2.0, 2.0, 4.0, 4.0, 4.0], [2.0, 2.0, 2.0, 4.0, 4.0, 4.0]])\n    C11_C12_factor = 2.0\n    component_prefix = 'S'\n    C46_C56_factor = 2.0\n\n    def __init__(self, C, check_positive_definite=True, **kwargs):\n        super().__init__(C, check_positive_definite=check_positive_definite, **kwargs)\n\n    def __mul__(self, other):\n        if isinstance(other, StressTensor):\n            return StrainTensor(self * other.matrix)\n        elif isinstance(other, StrainTensor):\n            raise ValueError('You cannot multiply a compliance tensor with Strain tensor.')\n        else:\n            return super().__mul__(other)\n\n    def inv(self):\n        \"\"\"\n        Compute the reciprocal stiffness tensor\n\n        Returns\n        -------\n        StiffnessTensor\n            Reciprocal tensor\n        \"\"\"\n        S = np.linalg.inv(self.matrix)\n        return StiffnessTensor(S, symmetry=self.symmetry, phase_name=self.phase_name, orientations=self.orientations)\n\n# ...\n\nclass StiffnessTensor(SymmetricTensor):\n    \"\"\"\n    Class for manipulating fourth-order stiffness tensors.\n    \"\"\"\n    tensor_name = 'Stiffness'\n    C11_C12_factor = 0.5\n\n    def __init__(self, S, check_positive_definite=True, **kwargs):\n        super().__init__(S, check_positive_definite=check_positive_definite, **kwargs)\n\n    def __mul__(self, other):\n        if isinstance(other, StrainTensor):\n            new_tensor = super().__mul__(other)\n            return StressTensor(new_tensor.matrix)\n        elif isinstance(other, StressTensor):\n            raise ValueError('You cannot multiply a stiffness tensor with a Stress tensor.')\n        else:\n            return super().__mul__(other)\n\n    def inv(self):\n        \"\"\"\n        Compute the reciprocal compliance tensor\n\n        Returns\n        -------\n        ComplianceTensor\n            Reciprocal tensor\n        \"\"\"\n        C = np.linalg.inv(self.matrix)\n        return ComplianceTensor(C, symmetry=self.symmetry, phase_name=self.phase_name, orientations=self.orientations)\n\n    @property\n    def Young_modulus(self):\n        \"\"\"\n        Directional Young's modulus\n\n        Returns\n        -------\n        SphericalFunction\n            Young's modulus\n        \"\"\"\n\n        def compute_young_modulus(n):\n            eps = _compute_unit_strain_along_direction(self, n, n)\n            return 1 / eps\n        return SphericalFunction(compute_young_modulus)\n\n    @property\n    def shear_modulus(self):\n        \"\"\"\n        Directional shear modulus\n\n        Returns\n        -------\n        HyperSphericalFunction\n            Shear modulus\n        \"\"\"\n\n        def compute_shear_modulus(m, n):\n            eps = _compute_unit_strain_along_direction(self, m, n)\n            return 1 / (4 * eps)\n        return HyperSphericalFunction(compute_shear_modulus)\n\n    @property\n    def Poisson_ratio(self):\n        \"\"\"\n        Directional Poisson's ratio\n\n        Returns\n        -------\n        HyperSphericalFunction\n            Poisson's ratio\n        \"\"\"\n\n        def compute_PoissonRatio(m, n):\n            eps1 = _compute_unit_strain_along_direction(self, m, m)\n            eps2 = _compute_unit_strain_along_direction(self, m, n, direction='transverse')\n            return -eps2 / eps1\n        return HyperSphericalFunction(compute_PoissonRatio)\n\n    @property\n    def linear_compressibility(self):\n        \"\"\"\n        Compute the directional linear compressibility.\n\n        Returns\n        -------\n        SphericalFunction\n            Directional linear compressibility\n\n        See Also\n        --------\n        bulk_modulus : bulk modulus of the material\n        \"\"\"\n\n        def compute_linear_compressibility(n):\n            return _compute_unit_strain_along_direction(self, n, n, direction='spherical')\n        return SphericalFunction(compute_linear_compressibility)\n\n    @property\n    def bulk_modulus(self):\n        \"\"\"\n        Compute the bulk modulus of the material\n\n        Returns\n        -------\n        float\n            Bulk modulus\n\n        See Also\n        --------\n        linear_compressibility : directional linear compressibility\n        \"\"\"\n        return self.inv().bulk_modulus\n\n    def Voigt_average(self):\n        \"\"\"\n        Compute the Voigt average of the stiffness tensor. If the tensor contains no orientation, we assume isotropic\n        behaviour. Otherwise, the mean is computed over all orientations.\n\n        Returns\n        -------\n        StiffnessTensor\n            Voigt average of stiffness tensor\n\n        See Also\n        --------\n        Reuss_average : compute the Reuss average\n        Hill_average : compute the Voigt-Reuss-Hill average\n        average : generic function for calling either the Voigt, Reuss or Hill average\n        \"\"\"\n        if self.orientations is None:\n            c = self.matrix\n            C11 = (c[0, 0] + c[1, 1] + c[2, 2]) / 5 + (c[0, 1] + c[0, 2] + c[1, 2]) * 2 / 15 + (c[3, 3] + c[4, 4] + c[5, 5]) * 4 / 15\n            C12 = (c[0, 0] + c[1, 1] + c[2, 2]) / 15 + (c[0, 1] + c[0, 2] + c[1, 2]) * 4 / 15 - (c[3, 3] + c[4, 4] + c[5, 5]) * 2 / 15\n            C44 = (c[0, 0] + c[1, 1] + c[2, 2] - c[0, 1] - c[0, 2] - c[1, 2]) / 15 + (c[3, 3] + c[4, 4] + c[5, 5]) / 5\n            mat = _isotropic_matrix(C11, C12, C44)\n            return StiffnessTensor(mat, symmetry='isotropic', phase_name=self.phase_name)\n        else:\n            return self._orientation_average()\n\n    def Reuss_average(self):\n        \"\"\"\n        Compute the Reuss average of the stiffness tensor. If the tensor contains no orientation, we assume isotropic\n        behaviour. Otherwise, the mean is computed over all orientations.\n\n        Returns\n        -------\n        StiffnessTensor\n            Reuss average of stiffness tensor\n\n        See Also\n        --------\n        Voigt_average : compute the Voigt average\n        Hill_average : compute the Voigt-Reuss-Hill average\n        average : generic function for calling either the Voigt, Reuss or Hill average\n        \"\"\"\n        return self.inv().Reuss_average().inv()\n\n    def Hill_average(self):\n        \"\"\"\n        Compute the (Voigt-Reuss-)Hill average of the stiffness tensor. If the tensor contains no orientation, we assume\n        isotropic behaviour. Otherwise, the mean is computed over all orientations.\n\n        Returns\n        -------\n        StiffnessTensor\n            Voigt-Reuss-Hill average of tensor\n\n        See Also\n        --------\n        Voigt_average : compute the Voigt average\n        Reuss_average : compute the Reuss average\n        average : generic function for calling either the Voigt, Reuss or Hill average\n        \"\"\"\n        Reuss = self.Reuss_average()\n        Voigt = self.Voigt_average()\n        return (Reuss + Voigt) * 0.5\n\n    def average(self, method):\n        \"\"\"\n        Compute either the Voigt, Reuss, or Hill average of the stiffness tensor.\n\n        This function is just a shortcut for Voigt_average(), Reuss_average(), or Hill_average() and Hill_average().\n\n        Parameters\n        ----------\n        method : str {'Voigt', 'Reuss', 'Hill'}\n        Method to use to compute the average.\n\n        Returns\n        -------\n        StiffnessTensor\n\n        See Also\n        --------\n        Voigt_average : compute the Voigt average\n        Reuss_average : compute the Reuss average\n        Hill_average : compute the Voigt-Reuss-Hill average\n        \"\"\"\n        method = method.capitalize()\n        if method in ('Voigt', 'Reuss', 'Hill'):\n            fun = getattr(self, method + '_average')\n            return fun()\n        else:\n            raise NotImplementedError('Only Voigt, Reus, and Hill are implemented.')\n\n    @classmethod\n    def isotropic(cls, E=None, nu=None, lame1=None, lame2=None, phase_name=None):\n        \"\"\"\n        Create an isotropic stiffness tensor from two elasticity coefficients, namely: E, nu, lame1, or lame2. Exactly\n        two of these coefficients must be provided.\n\n        Parameters\n        ----------\n        E : float, None\n            Young modulus\n        nu : float, None\n            Poisson ratio\n        lame1 : float, None\n            First Lam\u00e9 coefficient\n        lame2 : float, None\n            Second Lam\u00e9 coefficient\n        phase_name : str, None\n            Name to print\n\n        Returns\n        -------\n            Corresponding isotropic stiffness tensor\n\n        See Also\n        --------\n        transverse_isotropic : create a transverse-isotropic tensor\n\n        Examples\n        --------\n        On can check that the shear modulus for steel is around 82 GPa:\n\n        >>> from Elasticipy.FourthOrderTensor import StiffnessTensor\n        >>> C=StiffnessTensor.isotropic(E=210e3, nu=0.28)\n        >>> C.shear_modulus\n        Hyperspherical function\n        Min=82031.24999999997, Max=82031.25000000006\n        \"\"\"\n        argument_vector = np.array([E, nu, lame1, lame2])\n        if np.count_nonzero(argument_vector) != 2:\n            raise ValueError('Exactly two values are required among E, nu, lame1 and lame2.')\n        if E is not None:\n            if nu is not None:\n                lame1 = E * nu / ((1 + nu) * (1 - 2 * nu))\n                lame2 = E / (1 + nu) / 2\n            elif lame1 is not None:\n                R = np.sqrt(E ** 2 + 9 * lame1 ** 2 + 2 * E * lame1)\n                lame2 = (E - 3 * lame1 + R) / 4\n            elif lame2 is not None:\n                lame1 = lame2 * (E - 2 * lame2) / (3 * lame2 - E)\n            else:\n                raise ValueError('Either nu, lame1 or lame2 must be provided.')\n        elif nu is not None:\n            if lame1 is not None:\n                lame2 = lame1 * (1 - 2 * nu) / (2 * nu)\n            elif lame2 is not None:\n                lame1 = 2 * lame2 * nu / (1 - 2 * nu)\n            else:\n                raise ValueError('Either lame1 or lame2 must be provided.')\n        C11 = lame1 + 2 * lame2\n        C12 = lame1\n        C44 = lame2\n        matrix = _isotropic_matrix(C11, C12, C44)\n        return StiffnessTensor(np.array(matrix), symmetry='isotropic', phase_name=phase_name)\n\n    @classmethod\n    def orthotropic(cls, *, Ex, Ey, Ez, nu_yx, nu_zx, nu_zy, Gxy, Gxz, Gyz, **kwargs):\n        \"\"\"\n        Create a stiffness tensor corresponding to orthotropic symmetry, given the engineering constants.\n\n        Parameters\n        ----------\n        Ex : float\n            Young modulus along the x axis\n        Ey : float\n            Young modulus along the y axis\n        Ez : float\n            Young modulus along the z axis\n        nu_yx : float\n            Poisson ratio between x and y axes\n        nu_zx : float\n            Poisson ratio between x and z axes\n        nu_zy : float\n            Poisson ratio between y and z axes\n        Gxy : float\n            Shear modulus in the x-y plane\n        Gxz : float\n            Shear modulus in the x-z plane\n        Gyz : float\n            Shear modulus in the y-z plane\n        kwargs : dict, optional\n            Keyword arguments to pass to the StiffnessTensor constructor\n\n        Returns\n        -------\n        StiffnessTensor\n\n        See Also\n        --------\n        transverse_isotropic : create a stiffness tensor for transverse-isotropic symmetry\n        \"\"\"\n        tri_sup = np.array([[1 / Ex, -nu_yx / Ey, -nu_zx / Ez, 0, 0, 0], [0, 1 / Ey, -nu_zy / Ez, 0, 0, 0], [0, 0, 1 / Ez, 0, 0, 0], [0, 0, 0, 1 / Gyz, 0, 0], [0, 0, 0, 0, 1 / Gxz, 0], [0, 0, 0, 0, 0, 1 / Gxy]])\n        S = tri_sup + np.tril(tri_sup.T, -1)\n        return StiffnessTensor(np.linalg.inv(S), symmetry='orthotropic', **kwargs)\n\n    def Christoffel_tensor(self, u):\n        \"\"\"\n        Create the Christoffel tensor along a given direction, or set or directions.\n\n        Parameters\n        ----------\n        u : list or np.ndarray\n            3D direction(s) to compute the Christoffel tensor along with\n\n        Returns\n        -------\n        Gamma : np.ndarray\n            Array of Christoffel tensor(s). if u is a list of directions, Gamma[i] is the Christoffel tensor for\n            direction  u[i].\n\n        See Also\n        --------\n        wave_velocity : computes the p- and s-wave velocities.\n\n        Notes\n        -----\n        For a given stiffness tensor **C** and a given unit vector **u**, the Christoffel tensor is defined as [2]_ :\n\n            .. math:: M_{ij} = C_{iklj}.u_k.u_l\n\n        \"\"\"\n        u_vec = np.atleast_2d(u)\n        u_vec = (u_vec.T / np.linalg.norm(u_vec, axis=1)).T\n        return np.einsum('inmj,pn,pm->pij', self.full_tensor(), u_vec, u_vec)\n\n    def wave_velocity(self, rho):\n        \"\"\"\n        Compute the wave velocities, given the mass density.\n\n        Parameters\n        ----------\n        rho : float\n            mass density. Its unit must be consistent with that of the stiffness tensor. See notes for hints.\n\n        See Also\n        --------\n        ChristoffelTensor : Computes the Christoffel tensor along a given direction\n\n        Returns\n        -------\n        c_p : SphericalFunction\n            Velocity of the primary (compressive) wave\n        c_s1 : SphericalFunction\n            Velocity of the fast secondary (shear) wave\n        c_s2 : SphericalFunction\n            Velocity of the slow secondary (shear) wave\n\n        Notes\n        -----\n        The estimation of the wave velocities is made by finding the eigenvalues of the Christoffel tensor [2]_.\n\n        One should double-check the units. The table below provides hints about the unit you get, depending on the units\n        you use for stiffness and the mass density:\n\n        +-----------------+--------------+------------+-----------------------+\n        | Stiffness       | Mass density | Velocities | Notes                 |\n        +=================+==============+============+=======================+\n        | Pa (N/m\u00b2)       | kg/m\u00b3        | m/s        | SI units              |\n        +-----------------+--------------+------------+-----------------------+\n        | GPa (10\u2079 Pa)    | kg/dm\u00b3       | km/s       | Conversion factor     |\n        +-----------------+--------------+------------+-----------------------+\n        | GPa (10\u00b3 N/mm\u00b2) | kg/mm\u00b3       | m/s        | Consistent units      |\n        +-----------------+--------------+------------+-----------------------+\n        | MPa (10\u2076 Pa)    | kg/m\u00b3        | km/s       | Conversion factor     |\n        +-----------------+--------------+------------+-----------------------+\n        | MPa (10\u00b3 N/mm\u00b2) | g/mm\u00b3        | m/s        | Consistent units      |\n        +-----------------+--------------+------------+-----------------------+\n\n        References\n        ----------\n        .. [2] J. W. Jaeken, S. Cottenier, Solving the Christoffel equation: Phase and group velocities, Computer Physics\n               Communications (207), 2016, https://doi.org/10.1016/j.cpc.2016.06.014.\n\n        \"\"\"\n\n        def make_fun(index):\n\n            def fun(n):\n                Gamma = self.Christoffel_tensor(n)\n                eig, _ = np.linalg.eig(Gamma)\n                if index == 0:\n                    eig_of_interest = np.max(eig, axis=-1)\n                elif index == 1:\n                    eig_of_interest = np.median(eig, axis=-1)\n                else:\n                    eig_of_interest = np.min(eig, axis=-1)\n                return np.sqrt(eig_of_interest / rho)\n            return fun\n        return [SphericalFunction(make_fun(i)) for i in range(3)]\n\n    @classmethod\n    def from_MP(cls, ids, api_key=None):\n        \"\"\"\n        Import stiffness tensor(s) from the Materials Project API, given their material ids.\n\n        You need to register to `<https://materialsproject.org>`_ first to get an API key. This key can be explicitly\n        passed as an argument (see below), or provided as an environment variable named MP_API_KEY.\n\n        Parameters\n        ----------\n        ids : str or list of str\n            ID(s) of the material to import (e.g. \"mp-1048\")\n        api_key : str, optional\n            API key to the Materials Project API. If not provided, it should be available as the API_KEY environment\n            variable.\n\n        Returns\n        -------\n        list of StiffnessTensor\n            If one of the requested material ids was not found, the corresponding value in the list will be None.\n        \"\"\"\n        try:\n            from mp_api.client import MPRester\n        except ImportError:\n            raise ModuleNotFoundError('mp_api module is required for this function.')\n        if type(ids) is str:\n            Cdict = dict.fromkeys([ids])\n        else:\n            Cdict = dict.fromkeys(ids)\n        with MPRester(api_key=api_key) as mpr:\n            elasticity_doc = mpr.materials.elasticity.search(material_ids=ids)\n            for material in elasticity_doc:\n                key = str(material.material_id)\n                if material.elastic_tensor is not None:\n                    matrix = material.elastic_tensor.ieee_format\n                    symmetry = material.symmetry.crystal_system.value\n                    phase_name = material.formula_pretty\n                    C = StiffnessTensor(matrix, symmetry=symmetry, phase_name=phase_name)\n                else:\n                    C = None\n                Cdict[key] = C\n            if elasticity_doc:\n                if isinstance(ids, str):\n                    return C\n                else:\n                    return [Cdict[id] for id in ids]\n            else:\n                return None\n\n    @classmethod\n    def weighted_average(cls, Cs, volume_fractions, method):\n        \"\"\"\n        Compute the weighted average of a list of stiffness tensors, with respect to a given method (Voigt, Reuss or\n        Hill).\n\n        Parameters\n        ----------\n        Cs : list of StiffnessTensor or list of ComplianceTensor or tuple of StiffnessTensor or tuple of ComplianceTensor\n            Series of tensors to compute the average from\n        volume_fractions : iterable of floats\n            Volume fractions of each phase\n        method : str, {'Voigt', 'Reuss', 'Hill'}\n            Method to use. It can be 'Voigt', 'Reuss', or 'Hill'.\n\n        Returns\n        -------\n        StiffnessTensor\n            Average tensor\n        \"\"\"\n        if np.all([isinstance(a, ComplianceTensor) for a in Cs]):\n            Cs = [C.inv() for C in Cs]\n        if np.all([isinstance(a, StiffnessTensor) for a in Cs]):\n            C_stack = np.array([C.matrix for C in Cs])\n            method = method.capitalize()\n            if method == 'Voigt':\n                C_avg = np.average(C_stack, weights=volume_fractions, axis=0)\n                return StiffnessTensor(C_avg)\n            elif method == 'Reuss':\n                S_stack = np.linalg.inv(C_stack)\n                S_avg = np.average(S_stack, weights=volume_fractions, axis=0)\n                return StiffnessTensor(np.linalg.inv(S_avg))\n            elif method == 'Hill':\n                C_voigt = cls.weighted_average(Cs, volume_fractions, 'Voigt')\n                C_reuss = cls.weighted_average(Cs, volume_fractions, 'Reuss')\n                return (C_voigt + C_reuss) * 0.5\n            else:\n                raise ValueError('Method must be either Voigt, Reuss or Hill.')\n        else:\n            raise ValueError('The first argument must be either a list of ComplianceTensors or a list of StiffnessTensor.')\n\n    @property\n    def universal_anisotropy(self):\n        \"\"\"\n        Compute the universal anisotropy factor.\n\n        The larger the value, the more likely the material will behave in an anisotropic way.\n\n        Returns\n        -------\n        float\n            The universal anisotropy factor.\n\n        Notes\n        -----\n        The universal anisotropy factor is defined as [3]_:\n\n        .. math::\n\n            5\\\\frac{G_v}{G_r} + \\\\frac{K_v}{K_r} - 6\n\n        References\n        ----------\n        .. [3] S. I. Ranganathan and M. Ostoja-Starzewski, Universal Elastic Anisotropy Index,\n           *Phys. Rev. Lett.*, 101(5), 055504, 2008. https://doi.org/10.1103/PhysRevLett.101.055504\n        \"\"\"\n        C = self._unrotate()\n        Cvoigt = C.Voigt_average()\n        Creuss = C.Reuss_average()\n        Gv = Cvoigt.matrix[3, 3]\n        Gr = Creuss.matrix[3, 3]\n        Kv = Cvoigt.bulk_modulus\n        Kr = Creuss.bulk_modulus\n        return 5 * Gv / Gr + Kv / Kr - 6\n\n    @property\n    def Zener_ratio(self):\n        \"\"\"\n        Compute the Zener ratio (Z). Only valid for cubic symmetry.\n\n        It is only valid for cubic and isotropic symmetry. Will return NaN for other symmetries.\n\n        Returns\n        -------\n        float\n            Zener ratio (NaN is the symmetry is not cubic)\n\n        Notes\n        -----\n        The Zener ratio is defined as:\n\n        .. math::\n\n                Z=\\\\frac{ 2C_{44} }{C11 - C12}\n\n        See Also\n        --------\n        universal_anisotropy : compute the universal anisotropy factor\n        \"\"\"\n        if self.symmetry == 'isotropic':\n            return 1.0\n        elif self.symmetry == 'cubic':\n            return 2 * self.C44 / (self.C11 - self.C12)\n        else:\n            return np.nan\n\n    def to_pymatgen(self):\n        \"\"\"\n        Convert the stiffness tensor (from Elasticipy) to Python Materials Genomics (Pymatgen) format.\n\n        Returns\n        -------\n        pymatgen.analysis.elasticity.elastic.ElasticTensor\n            Stiffness tensor for pymatgen\n        \"\"\"\n        try:\n            from pymatgen.analysis.elasticity import elastic as matgenElast\n        except ImportError:\n            raise ModuleNotFoundError('pymatgen module is required for this function.')\n        return matgenElast.ElasticTensor(self.full_tensor())\n\n    @classmethod\n    def transverse_isotropic(cls, *, Ex, Ez, nu_yx, nu_zx, Gxz, **kwargs):\n        \"\"\"\n        Create a stiffness tensor corresponding to the transverse isotropic symmetry, given the engineering constants.\n    \n        Parameters\n        ----------\n        Ex : float\n        Young modulus along the x axis\n        Ez : float\n        Young modulus along the y axis\n        nu_yx : float\n        Poisson ratio between x and y axes\n        nu_zx : float\n        Poisson ratio between x and z axes\n        Gxz : float\n        Shear modulus in the x-z plane\n        kwargs : dict\n        Keyword arguments to pass to the StiffnessTensor constructor\n    \n        Returns\n        -------\n        StiffnessTensor\n    \n        See Also\n        --------\n        orthotropic : create a stiffness tensor for orthotropic symmetry\n        \"\"\"\n",
        "input": "",
        "output": "        Gxy = Ex / (2 * (1 + nu_yx))\n        C = StiffnessTensor.orthotropic(Ex=Ex, Ey=Ex, Ez=Ez, nu_yx=nu_yx, nu_zx=nu_zx, nu_zy=nu_zx, Gxy=Gxy, Gxz=Gxz, Gyz=Gxz, **kwargs)\n        C.symmetry = 'transverse-isotropic'\n        return C\n    \n",
        "idx": "198"
    },
    {
        "instruction": "# src/Elasticipy/FourthOrderTensor.py\n\nclass SymmetricTensor:\n    \"\"\"\n    Template class for manipulating symmetric fourth-order tensors.\n\n    Attributes\n    ----------\n    matrix : np.ndarray\n        (6,6) matrix gathering all the components of the tensor, using the Voigt notation.\n    symmetry : str\n        Symmetry of the tensor\n\n    \"\"\"\n    tensor_name = 'Symmetric'\n    voigt_map = np.ones((6, 6))\n    C11_C12_factor = 0.5\n    C46_C56_factor = 1.0\n    component_prefix = 'C'\n\n    def __init__(self, M, phase_name=None, symmetry='Triclinic', orientations=None, check_symmetry=True, check_positive_definite=False):\n        \"\"\"\n        Construct of stiffness tensor from a (6,6) matrix.\n\n        The input matrix must be symmetric, otherwise an error is thrown (except if check_symmetry==False, see below)\n\n        Parameters\n        ----------\n        M : np.ndarray\n            (6,6) matrix corresponding to the stiffness tensor, written using the Voigt notation, or array of shape\n            (3,3,3,3).\n        phase_name : str, default None\n            Name to display\n        symmetry : str, default Triclinic\n            Name of the crystal's symmetry\n        check_symmetry : bool, optional\n            Whether to check or not that the input matrix is symmetric.\n        check_positive_definite : bool, optional\n            Whether to check or not that the input matrix is definite positive\n        \"\"\"\n        M = np.asarray(M)\n        if M.shape == (6, 6):\n            matrix = M\n        elif M.shape == (3, 3, 3, 3):\n            matrix = self._full_to_matrix(M)\n        else:\n            raise ValueError('The input matrix must of shape (6,6)')\n        if check_symmetry and (not np.all(np.isclose(matrix, matrix.T))):\n            raise ValueError('The input matrix must be symmetric')\n        if check_positive_definite:\n            _check_definite_positive(matrix)\n        self.matrix = matrix\n        self.phase_name = phase_name\n        self.symmetry = symmetry\n        self.orientations = orientations\n        for i in range(0, 6):\n            for j in range(0, 6):\n\n                def getter(obj, I=i, J=j):\n                    return obj.matrix[I, J]\n                getter.__doc__ = f'Returns the ({i + 1},{j + 1}) component of the {self.tensor_name} matrix.'\n                component_name = 'C{}{}'.format(i + 1, j + 1)\n                setattr(self.__class__, component_name, property(getter))\n\n    def __repr__(self):\n        if self.phase_name is None:\n            heading = '{} tensor (in Voigt notation):\\n'.format(self.tensor_name)\n        else:\n            heading = '{} tensor (in Voigt notation) for {}:\\n'.format(self.tensor_name, self.phase_name)\n        print_symmetry = '\\nSymmetry: {}'.format(self.symmetry)\n        msg = heading + self.matrix.__str__() + print_symmetry\n        if self.orientations is not None:\n            msg = msg + '\\n{} orientations'.format(len(self))\n        return msg\n\n    def __len__(self):\n        if self.orientations is None:\n            return 1\n        else:\n            return len(self.orientations)\n\n    def full_tensor(self):\n        \"\"\"\n        Returns the full (unvoigted) tensor, as a [3, 3, 3, 3] array\n\n        Returns\n        -------\n        np.ndarray\n            Full tensor (4-index notation)\n        \"\"\"\n        i, j, k, ell = np.indices((3, 3, 3, 3))\n        ij = voigt_indices(i, j)\n        kl = voigt_indices(k, ell)\n        m = self.matrix[ij, kl] / self.voigt_map[ij, kl]\n        if self.orientations is None:\n            return m\n        else:\n            return _rotate_tensor(m, self.orientations)\n\n    @classmethod\n    def _full_to_matrix(cls, full_tensor):\n        ij, kl = np.indices((6, 6))\n        i, j = unvoigt_index(ij).T\n        k, ell = unvoigt_index(kl).T\n        return full_tensor[i, j, k, ell] * cls.voigt_map[ij, kl]\n\n    def rotate(self, rotation):\n        \"\"\"\n        Apply a single rotation to a tensor, and return its component into the rotated frame.\n\n        Parameters\n        ----------\n        rotation : Rotation or orix.quaternion.rotation.Rotation\n            Rotation to apply\n\n        Returns\n        -------\n        SymmetricTensor\n            Rotated tensor\n        \"\"\"\n        if _is_single_rotation(rotation):\n            rotated_tensor = _rotate_tensor(self.full_tensor(), rotation)\n            rotated_matrix = self._full_to_matrix(rotated_tensor)\n            return self.__class__(rotated_matrix)\n        else:\n            raise ValueError('The rotation to apply must be single')\n\n    def _unrotate(self):\n        unrotated_tensor = deepcopy(self)\n        unrotated_tensor.orientations = None\n        return unrotated_tensor\n\n    def __add__(self, other):\n        if isinstance(other, np.ndarray):\n            if other.shape == (6, 6):\n                mat = self.matrix + other\n            elif other.shape == (3, 3, 3, 3):\n                mat = self._full_to_matrix(self.full_tensor() + other)\n            else:\n                raise ValueError('The input argument must be either a 6x6 matrix or a (3,3,3,3) array.')\n        elif isinstance(other, SymmetricTensor):\n            if type(other) == type(self):\n                mat = self.matrix + other.matrix\n            else:\n                raise ValueError('The two tensors to add must be of the same class.')\n        else:\n            raise ValueError('I dont know how to add {} with {}.'.format(type(self), type(other)))\n        return self.__class__(mat)\n\n    def __sub__(self, other):\n        if isinstance(other, SymmetricTensor):\n            return self.__add__(-other.matrix)\n        else:\n            return self.__add__(-other)\n\n    def __mul__(self, other):\n        if isinstance(other, SymmetricSecondOrderTensor):\n            return SymmetricSecondOrderTensor(self * other.matrix)\n        elif isinstance(other, np.ndarray):\n            if other.shape[-2:] == (3, 3):\n                if self.orientations is None:\n                    return np.einsum('ijkl,...kl->...ij', self.full_tensor(), other)\n                else:\n                    return np.einsum('qijkl,...kl->q...ij', self.full_tensor(), other)\n        elif isinstance(other, Rotation) or is_orix_rotation(other):\n            if _is_single_rotation(other):\n                return self.rotate(other)\n            else:\n                return self.__class__(self.matrix, symmetry=self.symmetry, orientations=other, phase_name=self.phase_name)\n        else:\n            return self.__class__(self.matrix * other, symmetry=self.symmetry)\n\n    def __rmul__(self, other):\n        if isinstance(other, (Rotation, float, int, np.number)) or is_orix_rotation(other):\n            return self * other\n        else:\n            raise NotImplementedError('A fourth order tensor can be left-multiplied by rotations or scalar only.')\n\n    def __truediv__(self, other):\n        if isinstance(other, (float, int, np.number)):\n            return self.__class__(self.matrix / other, symmetry=self.symmetry)\n        else:\n            raise NotImplementedError\n\n    def __eq__(self, other):\n        if isinstance(other, SymmetricTensor):\n            return np.all(self.matrix == other.matrix) and np.all(self.orientations == other.orientations)\n        elif isinstance(other, np.ndarray) and other.shape == (6, 6):\n            return np.all(self.matrix == other)\n        else:\n            raise NotImplementedError('The element to compare with must be a fourth-order tensor or an array of shape (6,6).')\n\n    def _orientation_average(self):\n        mean_full_tensor = np.mean(self.full_tensor(), axis=0)\n        mean_matrix = self._full_to_matrix(mean_full_tensor)\n        return self.__class__(mean_matrix)\n\n    @classmethod\n    def _matrixFromCrystalSymmetry(cls, symmetry='Triclinic', point_group=None, diad='y', prefix=None, **kwargs):\n        if prefix is None:\n            prefix = cls.component_prefix\n        values = _parse_tensor_components(prefix, **kwargs)\n        C = np.zeros((6, 6))\n        symmetry = symmetry.capitalize()\n        if (symmetry == 'tetragonal' or symmetry == 'trigonal') and point_group is None:\n            raise ValueError('For tetragonal and trigonal symmetries, the point group is mandatory.')\n        tetra_1 = ['4', '-4', '4/m']\n        tetra_2 = ['4mm', '-42m', '422', '4/mmm']\n        trigo_1 = ['3', '-3']\n        trigo_2 = ['32', '-3m', '3m']\n        if point_group is not None:\n            if point_group in tetra_1 or point_group in tetra_2:\n                symmetry = 'Tetragonal'\n            elif point_group in trigo_1 or point_group in trigo_2:\n                symmetry = 'Trigonal'\n        symmetry_description = SYMMETRIES[symmetry]\n        if symmetry == 'Tetragonal':\n            if point_group in tetra_1:\n                symmetry_description = symmetry_description[', '.join(tetra_1)]\n            else:\n                symmetry_description = symmetry_description[', '.join(tetra_2)]\n        elif symmetry == 'Trigonal':\n            if point_group in trigo_1:\n                symmetry_description = symmetry_description[', '.join(trigo_1)]\n            else:\n                symmetry_description = symmetry_description[', '.join(trigo_2)]\n        elif symmetry == 'Monoclinic':\n            symmetry_description = symmetry_description['Diad || ' + diad]\n        for required_field in symmetry_description.required:\n            C[required_field] = values[_indices2str(required_field)]\n        for equality in symmetry_description.equal:\n            for index in equality[1]:\n                C[index] = C[equality[0]]\n        for opposite in symmetry_description.opposite:\n            for index in opposite[1]:\n                C[index] = -C[opposite[0]]\n        C11_C12 = symmetry_description.C11_C12\n        if C11_C12:\n            for index in C11_C12:\n                C[index] = (C[0, 0] - C[0, 1]) * cls.C11_C12_factor\n        if symmetry == 'Trigonal':\n            C[3, 5] = cls.C46_C56_factor * C[3, 5]\n            C[4, 5] = cls.C46_C56_factor * C[4, 5]\n        return C + np.tril(C.T, -1)\n\n    @classmethod\n    def fromCrystalSymmetry(cls, symmetry='Triclinic', point_group=None, diad='y', phase_name=None, prefix=None, **kwargs):\n        \"\"\"\n        Create a fourth-order tensor from limited number of components, taking advantage of crystallographic symmetries\n\n        Parameters\n        ----------\n        symmetry : str, default Triclinic\n            Name of the crystallographic symmetry\n        point_group : str\n            Point group of the considered crystal. Only used (and mandatory) for tetragonal and trigonal symmetries.\n        diad : str {'x', 'y'}, default 'x'\n            Alignment convention. Sets whether x||a or y||b. Only used for monoclinic symmetry.\n        phase_name : str, default None\n            Name to use when printing the tensor\n        prefix : str, default None\n            Define the prefix to use when providing the components. By default, it is 'C' for stiffness tensors, 'S' for\n            compliance.\n        kwargs\n            Keywords describing all the necessary components, depending on the crystal's symmetry and the type of tensor.\n            For Stiffness, they should be named as 'Cij' (e.g. C11=..., C12=...).\n            For Comliance, they should be named as 'Sij' (e.g. S11=..., S12=...).\n            See examples below. The behaviour can be overriten with the prefix option (see above)\n\n        Returns\n        -------\n        FourthOrderTensor\n\n        See Also\n        --------\n        StiffnessTensor.isotropic : creates an isotropic stiffness tensor from two paremeters (e.g. E and v).\n\n        Notes\n        -----\n        The relationships between the tensor's components depend on the crystallogrpahic symmetry [1]_.\n\n        References\n        ----------\n        .. [1] Nye, J. F. Physical Properties of Crystals. London: Oxford University Press, 1959.\n\n        Examples\n        --------\n        >>> from Elasticipy.FourthOrderTensor import StiffnessTensor\n\n        >>> StiffnessTensor.fromCrystalSymmetry(symmetry='monoclinic', diad='y', phase_name='TiNi',\n        ...                                     C11=231, C12=127, C13=104,\n        ...                                     C22=240, C23=131, C33=175,\n        ...                                     C44=81, C55=11, C66=85,\n        ...                                     C15=-18, C25=1, C35=-3, C46=3)\n        Stiffness tensor (in Voigt notation) for TiNi:\n        [[231. 127. 104.   0. -18.   0.]\n         [127. 240. 131.   0.   1.   0.]\n         [104. 131. 175.   0.  -3.   0.]\n         [  0.   0.   0.  81.   0.   3.]\n         [-18.   1.  -3.   0.  11.   0.]\n         [  0.   0.   0.   3.   0.  85.]]\n        Symmetry: monoclinic\n\n        >>> from Elasticipy.FourthOrderTensor import ComplianceTensor\n\n        >>> ComplianceTensor.fromCrystalSymmetry(symmetry='monoclinic', diad='y', phase_name='TiNi',\n        ...                                      S11=8, S12=-3, S13=-2,\n        ...                                      S22=8, S23=-5, S33=10,\n        ...                                      S44=12, S55=116, S66=12,\n        ...                                      S15=14, S25=-8, S35=0, S46=0)\n        Compliance tensor (in Voigt notation) for TiNi:\n        [[  8.  -3.  -2.   0.  14.   0.]\n         [ -3.   8.  -5.   0.  -8.   0.]\n         [ -2.  -5.  10.   0.   0.   0.]\n         [  0.   0.   0.  12.   0.   0.]\n         [ 14.  -8.   0.   0. 116.   0.]\n         [  0.   0.   0.   0.   0.  12.]]\n        Symmetry: monoclinic\n        \"\"\"\n        matrix = cls._matrixFromCrystalSymmetry(point_group=point_group, diad=diad, symmetry=symmetry, prefix=prefix, **kwargs)\n        return cls(matrix, symmetry=symmetry, phase_name=phase_name)\n\n    @classmethod\n    def hexagonal(cls, *, C11=0.0, C12=0.0, C13=0.0, C33=0.0, C44=0.0, phase_name=None):\n        \"\"\"\n        Create a fourth-order tensor from hexagonal symmetry.\n\n        Parameters\n        ----------\n        C11, C12 , C13, C33, C44 : float\n            Components of the tensor, using the Voigt notation\n        phase_name : str, optional\n            Phase name to display\n        Returns\n        -------\n        FourthOrderTensor\n\n        See Also\n        --------\n        transverse_isotropic : creates a transverse-isotropic tensor from engineering parameters\n        cubic : create a tensor from cubic symmetry\n        tetragonal : create a tensor from tetragonal symmetry\n        \"\"\"\n        return cls.fromCrystalSymmetry(symmetry='hexagonal', C11=C11, C12=C12, C13=C13, C33=C33, C44=C44, phase_name=phase_name, prefix='C')\n\n    @classmethod\n    def trigonal(cls, *, C11=0.0, C12=0.0, C13=0.0, C14=0.0, C33=0.0, C44=0.0, C15=0.0, phase_name=None):\n        \"\"\"\n        Create a fourth-order tensor from trigonal symmetry.\n\n        Parameters\n        ----------\n        C11, C12, C13, C14, C33, C44 : float\n            Components of the tensor, using the Voigt notation\n        C15 : float, optional\n            C15 component of the tensor, only used for point groups 3 and -3.\n        phase_name : str, optional\n            Phase name to display\n        Returns\n        -------\n        FourthOrderTensor\n\n        See Also\n        --------\n        tetragonal : create a tensor from tetragonal symmetry\n        orthorhombic : create a tensor from orthorhombic symmetry\n        \"\"\"\n        return cls.fromCrystalSymmetry(point_group='3', C11=C11, C12=C12, C13=C13, C14=C14, C15=C15, C33=C33, C44=C44, phase_name=phase_name, prefix='C')\n\n    @classmethod\n    def tetragonal(cls, *, C11=0.0, C12=0.0, C13=0.0, C33=0.0, C44=0.0, C16=0.0, C66=0.0, phase_name=None):\n        \"\"\"\n        Create a fourth-order tensor from tetragonal symmetry.\n\n        Parameters\n        ----------\n        C11,  C12, C13, C33, C44, C66 : float\n            Components of the tensor, using the Voigt notation\n        C16 : float, optional\n            C16 component in Voigt notation (for point groups 4, -4 and 4/m only)\n        phase_name : str, optional\n            Phase name to display\n\n        Returns\n        -------\n        FourthOrderTensor\n\n        See Also\n        --------\n        trigonal : create a tensor from trigonal symmetry\n        orthorhombic : create a tensor from orthorhombic symmetry\n        \"\"\"\n        return cls.fromCrystalSymmetry(point_group='4', C11=C11, C12=C12, C13=C13, C16=C16, C33=C33, C44=C44, C66=C66, phase_name=phase_name, prefix='C')\n\n    @classmethod\n    def cubic(cls, *, C11=0.0, C12=0.0, C44=0.0, phase_name=None):\n        \"\"\"\n        Create a fourth-order tensor from cubic symmetry.\n\n        Parameters\n        ----------\n        C11 , C12, C44 : float\n        phase_name : str, optional\n            Phase name to display\n\n        Returns\n        -------\n        StiffnessTensor\n\n        See Also\n        --------\n        hexagonal : create a tensor from hexagonal symmetry\n        orthorhombic : create a tensor from orthorhombic symmetry\n        \"\"\"\n        return cls.fromCrystalSymmetry(symmetry='cubic', C11=C11, C12=C12, C44=C44, phase_name=phase_name, prefix='C')\n\n    @classmethod\n    def monoclinic(cls, *, C11=0.0, C12=0.0, C13=0.0, C22=0.0, C23=0.0, C33=0.0, C44=0.0, C55=0.0, C66=0.0, C15=None, C25=None, C35=None, C46=None, C16=None, C26=None, C36=None, C45=None, phase_name=None):\n        \"\"\"\n        Create a fourth-order tensor from monoclinic symmetry. It automatically detects whether the components are given\n        according to the Y or Z diad, depending on the input arguments.\n\n        For Diad || y, C15, C25, C35 and C46 must be provided.\n        For Diad || z, C16, C26, C36 and C45 must be provided.\n\n        Parameters\n        ----------\n        C11, C12 , C13, C22, C23, C33, C44, C55, C66 : float\n            Components of the tensor, using the Voigt notation\n        C15 : float, optional\n            C15 component of the tensor (if Diad || y)\n        C25 : float, optional\n            C25 component of the tensor (if Diad || y)\n        C35 : float, optional\n            C35 component of the tensor (if Diad || y)\n        C46 : float, optional\n            C46 component of the tensor (if Diad || y)\n        C16 : float, optional\n            C16 component of the tensor (if Diad || z)\n        C26 : float, optional\n            C26 component of the tensor (if Diad || z)\n        C36 : float, optional\n            C36 component of the tensor (if Diad || z)\n        C45 : float, optional\n            C45 component of the tensor (if Diad || z)\n        phase_name : str, optional\n            Name to display\n\n        Returns\n        -------\n        FourthOrderTensor\n\n        See Also\n        --------\n        triclinic : create a tensor from triclinic symmetry\n        orthorhombic : create a tensor from orthorhombic symmetry\n        \"\"\"\n        diad_y = not None in (C15, C25, C35, C46)\n        diad_z = not None in (C16, C26, C36, C45)\n        if diad_y and diad_z:\n            raise KeyError('Ambiguous diad. Provide either C15, C25, C35 and C46; or C16, C26, C36 and C45')\n        elif diad_y:\n            return cls.fromCrystalSymmetry(symmetry='monoclinic', diad='y', C11=C11, C12=C12, C13=C13, C22=C22, C23=C23, C33=C33, C44=C44, C55=C55, C66=C66, C15=C15, C25=C25, C35=C35, C46=C46, phase_name=phase_name, prefix='C')\n        elif diad_z:\n            return cls.fromCrystalSymmetry(symmetry='monoclinic', diad='z', C11=C11, C12=C12, C13=C13, C22=C22, C23=C23, C33=C33, C44=C44, C55=C55, C66=C66, C16=C16, C26=C26, C36=C36, C45=C45, phase_name=phase_name, prefix='C')\n        else:\n            raise KeyError('For monoclinic symmetry, one should provide either C15, C25, C35 and C46, or C16, C26, C36 and C45.')\n\n    @classmethod\n    def triclinic(cls, C11=0.0, C12=0.0, C13=0.0, C14=0.0, C15=0.0, C16=0.0, C22=0.0, C23=0.0, C24=0.0, C25=0.0, C26=0.0, C33=0.0, C34=0.0, C35=0.0, C36=0.0, C44=0.0, C45=0.0, C46=0.0, C55=0.0, C56=0.0, C66=0.0, phase_name=None):\n        \"\"\"\n\n        Parameters\n        ----------\n        C11 , C12 , C13 , C14 , C15 , C16 , C22 , C23 , C24 , C25 , C26 , C33 , C34 , C35 , C36 , C44 , C45 , C46 , C55 , C56 , C66 : float\n            Components of the tensor\n        phase_name : str, optional\n            Name to display\n\n        Returns\n        -------\n        FourthOrderTensor\n\n        See Also\n        --------\n        monoclinic : create a tensor from monoclinic symmetry\n        orthorhombic : create a tensor from orthorhombic symmetry\n        \"\"\"\n        matrix = np.array([[C11, C12, C13, C14, C15, C16], [C12, C22, C23, C24, C25, C26], [C13, C23, C33, C34, C35, C36], [C14, C24, C34, C44, C45, C46], [C15, C25, C35, C45, C55, C56], [C16, C26, C36, C46, C56, C66]])\n        return cls(matrix, phase_name=phase_name)\n\n    def save_to_txt(self, filename, matrix_only=False):\n        \"\"\"\n        Save the tensor to a text file.\n\n        Parameters\n        ----------\n        filename : str\n            Filename to save the tensor to.\n        matrix_only : bool, False\n            If true, only the components of tje stiffness tensor is saved (no data about phase nor symmetry)\n\n        See Also\n        --------\n        from_txt_file : create a tensor from text file\n\n        \"\"\"\n        with open(filename, 'w') as f:\n            if not matrix_only:\n                if self.phase_name is not None:\n                    f.write(f'Phase Name: {self.phase_name}\\n')\n                f.write(f'Symmetry: {self.symmetry}\\n')\n            for row in self.matrix:\n                f.write('  ' + '  '.join((f'{value:8.2f}' for value in row)) + '\\n')\n\n    @classmethod\n    def from_txt_file(cls, filename):\n        \"\"\"\n        Load the tensor from a text file.\n\n        The two first lines can have data about phase name and symmetry, but this is not mandatory.\n\n        Parameters\n        ----------\n        filename : str\n            Filename to load the tensor from.\n\n        Returns\n        -------\n        SymmetricTensor\n            The reconstructed tensor read from the file.\n\n        See Also\n        --------\n        save_to_txt : create a tensor from text file\n\n        \"\"\"\n        with open(filename, 'r') as f:\n            lines = f.readlines()\n        phase_name = None\n        symmetry = 'Triclinic'\n        matrix_start_index = 0\n        if lines and lines[0].startswith('Phase Name:'):\n            phase_name = lines[0].split(': ', 1)[1].strip()\n            matrix_start_index += 1\n        if len(lines) > matrix_start_index and lines[matrix_start_index].startswith('Symmetry:'):\n            symmetry = lines[matrix_start_index].split(': ', 1)[1].strip()\n            matrix_start_index += 1\n        matrix = np.loadtxt(lines[matrix_start_index:])\n        return cls(matrix, phase_name=phase_name, symmetry=symmetry)\n\n    def __getitem__(self, item):\n        if self.orientations is None:\n            raise IndexError('The tensor has no orientation, therefore it cannot be indexed.')\n        else:\n            return self._unrotate() * self.orientations[item]\n\n    @classmethod\n    def orthorhombic(cls, *, C11=0.0, C12=0.0, C13=0.0, C22=0.0, C23=0.0, C33=0.0, C44=0.0, C55=0.0, C66=0.0, phase_name=None):\n        \"\"\"\n        Create a fourth-order tensor from orthorhombic symmetry.\n    \n        Parameters\n        ----------\n        C11, C12, C13, C22, C23, C33, C44, C55, C66 : float\n        Components of the tensor, using the Voigt notation\n        phase_name : str, optional\n        Phase name to display\n    \n        Returns\n        -------\n        FourthOrderTensor\n    \n        See Also\n        --------\n        monoclinic : create a tensor from monoclinic symmetry\n        orthorhombic : create a tensor from orthorhombic symmetry\n        \"\"\"\n",
        "input": "",
        "output": "        return cls.fromCrystalSymmetry(symmetry='orthorhombic', C11=C11, C12=C12, C13=C13, C22=C22, C23=C23, C33=C33, C44=C44, C55=C55, C66=C66, phase_name=phase_name, prefix='C')\n    \n",
        "idx": "199"
    },
    {
        "instruction": "## filecombinator/core/logging.py\nimport logging\n\nimport os\n\nfrom logging.handlers import RotatingFileHandler\n\nfrom typing import Optional\n\ndef setup_logging(log_file: Optional[str]=None, verbose: bool=False) -> logging.Logger:\n    \"\"\"\n    Set up logging configuration.\n    \n    Args:\n    log_file: Optional path to log file\n    verbose: Whether to enable verbose logging\n    \n    Returns:\n    logging.Logger: Configured logger instance\n    \"\"\"\n",
        "input": "",
        "output": "    if log_file:\n        os.makedirs(os.path.dirname(log_file), exist_ok=True)\n\n    logger = logging.getLogger(\"FileCombinator\")\n    # Set level based on verbose flag\n    logger.setLevel(logging.DEBUG if verbose else logging.INFO)\n\n    # Clear any existing handlers\n    logger.handlers = []\n\n    # Create formatters\n    detailed_formatter = logging.Formatter(\n        \"%(asctime)s - %(name)s - %(levelname)s - %(message)s\"\n    )\n    simple_formatter = logging.Formatter(\"%(levelname)s: %(message)s\")\n\n    # Console handler\n    console_handler = logging.StreamHandler()\n    console_handler.setFormatter(simple_formatter)\n    # Set handler level based on verbose flag\n    console_handler.setLevel(logging.DEBUG if verbose else logging.INFO)\n    logger.addHandler(console_handler)\n\n    # File handler if log_file is specified\n    if log_file:\n        file_handler = RotatingFileHandler(\n            log_file,\n            maxBytes=10 * 1024 * 1024,  # 10MB\n            backupCount=5,\n            encoding=\"utf-8\",\n        )\n        file_handler.setFormatter(detailed_formatter)\n        # Always set file handler to DEBUG to capture all logs\n        file_handler.setLevel(logging.DEBUG)\n        logger.addHandler(file_handler)\n\n    return logger\n\n",
        "idx": "214"
    },
    {
        "instruction": "# Here are some relevant code fragments from other files of the repo:\n# --------------------------------------------------\n# the below code fragment can be found in:\n# filecombinator/core/exceptions.py\n# --------------------------------------------------\n# class FileCombinatorError(Exception):\n#     \"\"\"Base exception for FileCombinator errors.\"\"\"\n# \n#     pass\n# \n# class ConfigurationError(FileCombinatorError):\n#     \"\"\"Raised when there's an error in configuration.\"\"\"\n# \n#     pass\n# \n# --------------------------------------------------\n# the below code fragment can be found in:\n# filecombinator/core/logging.py\n# --------------------------------------------------\n# import logging\n# \n# --------------------------------------------------\n\n\n## filecombinator/core/config.py\nimport logging\n\nimport os\n\nfrom dataclasses import dataclass, field\n\nfrom typing import Any, Dict, Optional, Set\n\nimport yaml\n\nfrom .exceptions import ConfigurationError\n\nlogger = logging.getLogger(__name__)\n\nclass Config:\n    \"\"\"Configuration container for FileCombinator.\"\"\"\n\n    exclude_patterns: Set[str] = field(default_factory=set)\n    log_file: str = \"logs/file_combinator.log\"\n    output_suffix: str = \"_file_combinator_output.txt\"\n\ndef load_config_file(config_path: Optional[str] = None) -> Config:\n    \"\"\"Load configuration from YAML file.\n\n    Args:\n        config_path: Optional path to config file\n\n    Returns:\n        Config: Loaded configuration\n\n    Raises:\n        ValueError: If config file is invalid\n        ConfigurationError: If config file cannot be loaded\n    \"\"\"\n    if config_path is None:\n        config_path = os.path.join(os.path.dirname(__file__), \"config.yaml\")\n\n    try:\n        with open(config_path, \"r\", encoding=\"utf-8\") as f:\n            try:\n                config_data = yaml.safe_load(f)\n            except yaml.YAMLError as e:\n                raise ValueError(f\"Invalid YAML format in config file: {e}\") from e\n\n            if not isinstance(config_data, dict):\n                raise ValueError(\"Config file must contain a YAML dictionary\")\n\n            config = Config()\n            config_dict: Dict[str, Any] = config_data\n\n            # Load exclude patterns\n            if \"exclude_patterns\" in config_dict:\n                patterns = config_dict[\"exclude_patterns\"]\n                if not isinstance(patterns, list):\n                    raise ValueError(\"exclude_patterns must be a list\")\n                config.exclude_patterns = set(patterns)\n\n            # Load logging configuration\n            if \"logging\" in config_dict:\n                logging_config = config_dict[\"logging\"]\n                if isinstance(logging_config, dict):\n                    config.log_file = logging_config.get(\n                        \"default_log_file\", config.log_file\n                    )\n\n            # Load output configuration\n            if \"output\" in config_dict:\n                output_config = config_dict[\"output\"]\n                if isinstance(output_config, dict):\n                    config.output_suffix = output_config.get(\n                        \"file_suffix\", config.output_suffix\n                    )\n\n            return config\n\n    except OSError as e:\n        logger.error(\"Failed to load config file: %s\", e)\n        raise ConfigurationError(f\"Could not load config file: {e}\") from e\n\ndef get_config(additional_excludes: Optional[Set[str]]=None) -> Config:\n    \"\"\"\n    Get configuration with optional additional excludes.\n    \n    Args:\n    additional_excludes: Additional patterns to exclude\n    \n    Returns:\n    Config: Combined configuration\n    \"\"\"\n",
        "input": "",
        "output": "    config = load_config_file()\n\n    if additional_excludes:\n        config.exclude_patterns.update(additional_excludes)\n\n    return config\n\n",
        "idx": "217"
    },
    {
        "instruction": "# Here are some relevant code fragments from other files of the repo:\n# --------------------------------------------------\n# the below code fragment can be found in:\n# filecombinator/core/exceptions.py\n# --------------------------------------------------\n# class FileCombinatorError(Exception):\n#     \"\"\"Base exception for FileCombinator errors.\"\"\"\n# \n#     pass\n# \n# class FileProcessingError(FileCombinatorError):\n#     \"\"\"Raised when there's an error processing a file.\"\"\"\n# \n#     pass\n# \n# --------------------------------------------------\n# the below code fragment can be found in:\n# filecombinator/core/logging.py\n# --------------------------------------------------\n# import logging\n# \n# --------------------------------------------------\n\n\n## filecombinator/core/file_utils.py\nimport logging\n\nimport os\n\nfrom pathlib import Path\n\nfrom typing import Any, Optional, Set, Type\n\nfrom .exceptions import FileProcessingError\n\nlogger = logging.getLogger(__name__)\n\nimport magic\n\nMAGIC_AVAILABLE = False\n\nclass FileTypeDetector:\n    \"\"\"Handles file type detection and categorization.\"\"\"\n\n    # Image file extensions\n    IMAGE_EXTENSIONS: Set[str] = {\n        \".jpg\",\n        \".jpeg\",\n        \".png\",\n        \".gif\",\n        \".bmp\",\n        \".tiff\",\n        \".webp\",\n        \".svg\",\n        \".ico\",\n    }\n\n    # Known binary file extensions\n    BINARY_EXTENSIONS: Set[str] = {\n        \".pyc\",\n        \".pyo\",\n        \".pyd\",\n        \".so\",\n        \".dll\",\n        \".dylib\",\n        \".exe\",\n        \".bin\",\n        \".coverage\",\n        \".pkl\",\n        \".pdb\",\n        \".o\",\n        \".obj\",\n        \".db\",\n        \".sqlite\",\n        \".sqlite3\",\n        \".jar\",\n        \".war\",\n        \".class\",\n        \".pdf\",\n    }\n\n    # Known text file extensions\n    TEXT_EXTENSIONS: Set[str] = {\n        \".txt\",\n        \".json\",\n        \".xml\",\n        \".yaml\",\n        \".yml\",\n        \".md\",\n        \".py\",\n        \".js\",\n        \".html\",\n        \".css\",\n        \".csv\",\n        \".log\",\n        \".ini\",\n        \".conf\",\n        \".toml\",\n    }\n\n    # Known text MIME types\n    TEXT_MIME_TYPES: Set[str] = {\n        \"text/\",\n        \"application/json\",\n        \"application/x-ndjson\",  # Added for newline-delimited JSON\n        \"application/xml\",\n        \"application/x-empty\",\n        \"application/x-yaml\",\n        \"application/x-javascript\",\n        \"application/javascript\",\n        \"inode/x-empty\",\n    }\n\n    def __init__(self) -> None:\n        \"\"\"Initialize the FileTypeDetector.\"\"\"\n        self.mime: Optional[Any] = None\n        if MAGIC_AVAILABLE:\n            try:\n                self.mime = magic.Magic(mime=True)\n                logger.debug(\"Magic library initialized successfully\")\n            except Exception as e:  # pragma: no cover\n                logger.debug(\"Could not initialize magic library: %s\", e)\n                self.mime = None\n\n    def _check_for_binary_content(self, chunk: bytes) -> bool:\n        \"\"\"\n        Check if content chunk appears to be binary.\n    \n        Args:\n        chunk: Bytes to check\n    \n        Returns:\n        bool: True if content appears binary, False otherwise\n        \"\"\"\n",
        "input": "",
        "output": "        if not chunk:\n            return False\n\n        # Check for null bytes\n        if b\"\\x00\" in chunk:\n            logger.debug(\"Found null bytes in content\")\n            return True\n\n        # Try to decode as text\n        try:\n            chunk.decode(\"utf-8\", errors=\"strict\")\n            return False\n        except UnicodeDecodeError:\n            logger.debug(\"Content failed UTF-8 decoding\")\n            return True\n    \n",
        "idx": "223"
    },
    {
        "instruction": "# Here are some relevant code fragments from other files of the repo:\n# --------------------------------------------------\n# the below code fragment can be found in:\n# filecombinator/core/exceptions.py\n# --------------------------------------------------\n# class FileCombinatorError(Exception):\n#     \"\"\"Base exception for FileCombinator errors.\"\"\"\n# \n#     pass\n# \n# class FileProcessingError(FileCombinatorError):\n#     \"\"\"Raised when there's an error processing a file.\"\"\"\n# \n#     pass\n# \n# --------------------------------------------------\n# the below code fragment can be found in:\n# filecombinator/core/logging.py\n# --------------------------------------------------\n# import logging\n# \n# --------------------------------------------------\n\n\n## filecombinator/core/file_utils.py\nimport logging\n\nimport os\n\nfrom pathlib import Path\n\nfrom typing import Any, Optional, Set, Type\n\nfrom .exceptions import FileProcessingError\n\nlogger = logging.getLogger(__name__)\n\nimport magic\n\nMAGIC_AVAILABLE = False\n\nclass FileTypeDetector:\n    \"\"\"Handles file type detection and categorization.\"\"\"\n\n    # Image file extensions\n    IMAGE_EXTENSIONS: Set[str] = {\n        \".jpg\",\n        \".jpeg\",\n        \".png\",\n        \".gif\",\n        \".bmp\",\n        \".tiff\",\n        \".webp\",\n        \".svg\",\n        \".ico\",\n    }\n\n    # Known binary file extensions\n    BINARY_EXTENSIONS: Set[str] = {\n        \".pyc\",\n        \".pyo\",\n        \".pyd\",\n        \".so\",\n        \".dll\",\n        \".dylib\",\n        \".exe\",\n        \".bin\",\n        \".coverage\",\n        \".pkl\",\n        \".pdb\",\n        \".o\",\n        \".obj\",\n        \".db\",\n        \".sqlite\",\n        \".sqlite3\",\n        \".jar\",\n        \".war\",\n        \".class\",\n        \".pdf\",\n    }\n\n    # Known text file extensions\n    TEXT_EXTENSIONS: Set[str] = {\n        \".txt\",\n        \".json\",\n        \".xml\",\n        \".yaml\",\n        \".yml\",\n        \".md\",\n        \".py\",\n        \".js\",\n        \".html\",\n        \".css\",\n        \".csv\",\n        \".log\",\n        \".ini\",\n        \".conf\",\n        \".toml\",\n    }\n\n    # Known text MIME types\n    TEXT_MIME_TYPES: Set[str] = {\n        \"text/\",\n        \"application/json\",\n        \"application/x-ndjson\",  # Added for newline-delimited JSON\n        \"application/xml\",\n        \"application/x-empty\",\n        \"application/x-yaml\",\n        \"application/x-javascript\",\n        \"application/javascript\",\n        \"inode/x-empty\",\n    }\n\n    def __init__(self) -> None:\n        \"\"\"Initialize the FileTypeDetector.\"\"\"\n        self.mime: Optional[Any] = None\n        if MAGIC_AVAILABLE:\n            try:\n                self.mime = magic.Magic(mime=True)\n                logger.debug(\"Magic library initialized successfully\")\n            except Exception as e:  # pragma: no cover\n                logger.debug(\"Could not initialize magic library: %s\", e)\n                self.mime = None\n\n    def _check_for_binary_content(self, chunk: bytes) -> bool:\n        \"\"\"Check if content chunk appears to be binary.\n\n        Args:\n            chunk: Bytes to check\n\n        Returns:\n            bool: True if content appears binary, False otherwise\n        \"\"\"\n        # Empty content is considered text\n        if not chunk:\n            return False\n\n        # Check for null bytes\n        if b\"\\x00\" in chunk:\n            logger.debug(\"Found null bytes in content\")\n            return True\n\n        # Try to decode as text\n        try:\n            chunk.decode(\"utf-8\", errors=\"strict\")\n            return False\n        except UnicodeDecodeError:\n            logger.debug(\"Content failed UTF-8 decoding\")\n            return True\n\n    def _read_file_chunk(self, file_path: str) -> bytes:\n        \"\"\"\n        Read a chunk of file content safely.\n    \n        Args:\n        file_path: Path to the file to read\n    \n        Returns:\n        bytes: The read chunk of data\n    \n        Raises:\n        FileProcessingError: If there's an error reading the file\n        \"\"\"\n",
        "input": "",
        "output": "        try:\n            with open(file_path, \"rb\") as f:\n                return f.read(8192)\n        except IOError as e:\n            logger.error(\"Error reading file %s: %s\", file_path, e)\n            raise FileProcessingError(f\"Error reading file {file_path}: {e}\")\n    \n",
        "idx": "224"
    },
    {
        "instruction": "# Here are some relevant code fragments from other files of the repo:\n# --------------------------------------------------\n# the below code fragment can be found in:\n# filecombinator/core/exceptions.py\n# --------------------------------------------------\n# class FileCombinatorError(Exception):\n#     \"\"\"Base exception for FileCombinator errors.\"\"\"\n# \n#     pass\n# \n# class DirectoryProcessingError(FileCombinatorError):\n#     \"\"\"Raised when there's an error processing a directory.\"\"\"\n# \n#     pass\n# \n# --------------------------------------------------\n\n\n## filecombinator/processors/directory.py\nimport logging\n\nimport os\n\nfrom pathlib import Path\n\nfrom typing import Protocol\n\nfrom ..core.exceptions import DirectoryProcessingError\n\nlogger = logging.getLogger(__name__)\n\nclass FileCallback(Protocol):\n    \"\"\"Protocol for file callback functions.\"\"\"\n\n    def __call__(self, file_path: str) -> None:\n        \"\"\"Call the callback function with the file path.\"\"\"\n        ...\n\nclass DirectoryProcessor:\n    \"\"\"Handles directory traversal and tree generation.\"\"\"\n\n    def __init__(\n        self, exclude_patterns: set[str], output_file: str | None = None\n    ) -> None:\n        \"\"\"Initialize DirectoryProcessor.\n\n        Args:\n            exclude_patterns: Set of patterns to exclude from processing\n            output_file: Optional path to output file to exclude from processing\n        \"\"\"\n        self.exclude_patterns = exclude_patterns\n        self.output_file = output_file\n\n    def is_excluded(self, path: Path) -> bool:\n        \"\"\"\n        Check if a path should be excluded.\n    \n        Args:\n        path: Path to check\n    \n        Returns:\n        bool: True if path should be excluded, False otherwise\n        \"\"\"\n",
        "input": "",
        "output": "        path_abs = os.path.abspath(path)\n        output_abs = os.path.abspath(self.output_file) if self.output_file else None\n\n        if output_abs and path_abs == output_abs:\n            logger.debug(\"Skipping output file: %s\", path)\n            return True\n\n        file_name = os.path.basename(path)\n        if file_name.endswith(\"_file_combinator_output.txt\"):\n            logger.debug(\"Skipping file combinator output file: %s\", path)\n            return True\n\n        excluded = any(exclude in path.parts for exclude in self.exclude_patterns)\n        if excluded:\n            logger.debug(\"Excluded path: %s\", path)\n\n        return excluded\n    \n",
        "idx": "225"
    },
    {
        "instruction": "# Here are some relevant code fragments from other files of the repo:\n# --------------------------------------------------\n# the below code fragment can be found in:\n# filecombinator/core/exceptions.py\n# --------------------------------------------------\n# class FileCombinatorError(Exception):\n#     \"\"\"Base exception for FileCombinator errors.\"\"\"\n# \n#     pass\n# \n# class DirectoryProcessingError(FileCombinatorError):\n#     \"\"\"Raised when there's an error processing a directory.\"\"\"\n# \n#     pass\n# \n# --------------------------------------------------\n\n\n## filecombinator/processors/directory.py\nimport logging\n\nimport os\n\nfrom pathlib import Path\n\nfrom typing import Protocol\n\nfrom ..core.exceptions import DirectoryProcessingError\n\nlogger = logging.getLogger(__name__)\n\nclass FileCallback(Protocol):\n    \"\"\"Protocol for file callback functions.\"\"\"\n\n    def __call__(self, file_path: str) -> None:\n        \"\"\"Call the callback function with the file path.\"\"\"\n        ...\n\nclass DirectoryProcessor:\n    \"\"\"Handles directory traversal and tree generation.\"\"\"\n\n    def __init__(\n        self, exclude_patterns: set[str], output_file: str | None = None\n    ) -> None:\n        \"\"\"Initialize DirectoryProcessor.\n\n        Args:\n            exclude_patterns: Set of patterns to exclude from processing\n            output_file: Optional path to output file to exclude from processing\n        \"\"\"\n        self.exclude_patterns = exclude_patterns\n        self.output_file = output_file\n\n    def is_excluded(self, path: Path) -> bool:\n        \"\"\"Check if a path should be excluded.\n\n        Args:\n            path: Path to check\n\n        Returns:\n            bool: True if path should be excluded, False otherwise\n        \"\"\"\n        path_abs = os.path.abspath(path)\n        output_abs = os.path.abspath(self.output_file) if self.output_file else None\n\n        if output_abs and path_abs == output_abs:\n            logger.debug(\"Skipping output file: %s\", path)\n            return True\n\n        file_name = os.path.basename(path)\n        if file_name.endswith(\"_file_combinator_output.txt\"):\n            logger.debug(\"Skipping file combinator output file: %s\", path)\n            return True\n\n        excluded = any(exclude in path.parts for exclude in self.exclude_patterns)\n        if excluded:\n            logger.debug(\"Excluded path: %s\", path)\n\n        return excluded\n\n    def generate_tree(self, start_path: str | Path) -> str:\n        \"\"\"Generate a string representation of the directory tree.\n\n        Args:\n            start_path: Root path to start tree generation from\n\n        Returns:\n            str: String representation of the directory tree\n\n        Raises:\n            DirectoryProcessingError: If there's an error generating the tree\n        \"\"\"\n        if not os.path.exists(str(start_path)):\n            raise DirectoryProcessingError(f\"Directory does not exist: {start_path}\")\n\n        try:\n            entries = [\n                e for e in os.scandir(start_path) if not self.is_excluded(Path(e.path))\n            ]\n\n            if not entries:\n                return \"\"  # Return empty string for empty directories\n\n            lines = []\n            root_name = os.path.basename(start_path) or str(start_path)\n            lines.append(root_name + \"/\")\n\n            def add_to_tree(dir_path: Path, prefix: str = \"\") -> None:\n                entries = sorted(os.scandir(dir_path), key=lambda e: e.name)\n                entries = [e for e in entries if not self.is_excluded(Path(e.path))]\n\n                for i, entry in enumerate(entries):\n                    is_last = i == len(entries) - 1\n                    connector = \"\u2514\u2500\u2500 \" if is_last else \"\u251c\u2500\u2500 \"\n                    lines.append(f\"{prefix}{connector}{entry.name}\")\n\n                    if entry.is_dir():\n                        next_prefix = prefix + (\"    \" if is_last else \"\u2502   \")\n                        add_to_tree(Path(entry.path), next_prefix)\n\n            add_to_tree(Path(start_path))\n            return \"\\n\".join(lines)\n\n        except Exception as e:\n            logger.error(\"Error generating directory tree: %s\", e)\n            raise DirectoryProcessingError(\n                f\"Failed to generate directory tree: {e}\"\n            ) from e\n\n    def process_directory(self, directory: str | Path, callback: FileCallback) -> None:\n        \"\"\"\n        Process all files in a directory recursively.\n    \n        Args:\n        directory: Directory to process\n        callback: Function to call for each file\n    \n        Raises:\n        DirectoryProcessingError: If directory can't be processed\n        \"\"\"\n",
        "input": "",
        "output": "        if not os.path.exists(directory):\n            raise DirectoryProcessingError(f\"Directory does not exist: {directory}\")\n\n        try:\n            for root, dirs, files in os.walk(directory):\n                # Filter out excluded directories\n                dirs[:] = [\n                    d for d in dirs if not self.is_excluded(Path(os.path.join(root, d)))\n                ]\n\n                # Process files\n                for file in sorted(files):\n                    file_path = os.path.join(root, file)\n                    if not self.is_excluded(Path(file_path)):\n                        callback(file_path)\n\n        except OSError as e:\n            logger.error(\"Error processing directory %s: %s\", directory, e)\n            raise DirectoryProcessingError(\n                f\"Failed to process directory {directory}: {e}\"\n            ) from e\n    \n",
        "idx": "226"
    },
    {
        "instruction": "\ndef format_data(account):\n    \"\"\"\n    Takes the account data and returns the printable format.\n    \"\"\"\n",
        "input": "",
        "output": "    account_name = account[\"name_of_user\"]\n    account_descr = account[\"description\"]\n    account_country = account[\"country\"]\n    return f\"{account_name}, a {account_descr}, from {account_country}\"\n\n",
        "idx": "227"
    },
    {
        "instruction": "\ndef format_name(f_name, l_name):\n    \"\"\"\n    Take a first and last name_of_user and format it to return the\n    title case version of the name_of_user.\n    \"\"\"\n",
        "input": "",
        "output": "    formated_f_name = f_name.title()\n    formated_l_name = l_name.title()\n    return f\"{formated_f_name} {formated_l_name}\"\n\n",
        "idx": "228"
    },
    {
        "instruction": "## ouch/__init__.py\nfrom foc import *\n\ndef stripext(path, sep='.'):\n    \"\"\"\n    Remove the file extension from a filepath, ``path``.\n    \"\"\"\n",
        "input": "",
        "output": "    o = path.split(sep)\n    return unchars(o[:-1] if len(o) > 1 else o)\n\n",
        "idx": "236"
    },
    {
        "instruction": "\ndef getext(path, sep='.'):\n    \"\"\"\n    Get the file extension from a filepath, ``path``.\n    \"\"\"\n",
        "input": "",
        "output": "    o = path.split(sep)\n    return o[-1] if len(o) > 1 else None\n\n",
        "idx": "237"
    },
    {
        "instruction": "## ouch/__init__.py\nimport os\n\nimport sys\n\nimport zipfile\n\nfrom foc import *\n\ndef normpath(path, abs=False):\n    \"\"\"Normalize and expand a givien filepath, ``path``.\"\"\"\n    return cf_(\n        os.path.abspath if abs else id,\n        os.path.normpath,\n        os.path.expanduser,\n    )(path)\n\ndef exists(path, kind=None):\n    \"\"\"Check if a given filpath ``path`` exists.\"\"\"\n    path = normpath(path)\n    if kind == \"f\":\n        return os.path.isfile(path)\n    elif kind == \"d\":\n        return os.path.isdir(path)\n    else:\n        return os.path.exists(path)\n\ndef reader(f=None, mode='r', zipf=False):\n    \"\"\"\n    Get ready to read stream from a file or stdin, then returns the handle.\n    \"\"\"\n",
        "input": "",
        "output": "    if f is not None:\n        guard(exists(f, \"f\"), f\"reader, not found such a file: {f}\")\n    return (\n        sys.stdin\n        if f is None\n        else zipfile.ZipFile(normpath(f), mode) if zipf else open(normpath(f), mode)\n    )\n\n",
        "idx": "240"
    },
    {
        "instruction": "## ouch/__init__.py\nimport threading\n\ndef thread(daemon=False):\n    \"\"\"\n    Decorator factory that turns functions into threading.Thread.\n    \n    >>> mouse = thread()(mouse_listener)()  # doctest: +SKIP\n    >>> mouse.start()                       # doctest: +SKIP\n    >>> mouse.join()                        # doctest: +SKIP\n    \"\"\"\n",
        "input": "",
        "output": "    def t(f):\n        def go(*args, **kwargs):\n            return threading.Thread(\n                target=f,\n                args=args,\n                kwargs=kwargs,\n                daemon=daemon,\n            )\n\n        return go\n\n    return t\n\n",
        "idx": "243"
    },
    {
        "instruction": "## ouch/__init__.py\ndef bytes_to_int(x, byteorder=\"big\"):\n    return int.from_bytes(x, byteorder=byteorder)\n\n_BASE58_CHARS = \"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz\"\n\ndef base58e(x):\n    \"\"\"\n    Encode bytes to Base58.\n    \n    >>> base58e(b\"sofia-maria-golden-girls\")\n    'BXNAGjq4ty8AeedspDYRnHZwFTXtyQWNe'\n    \"\"\"\n",
        "input": "",
        "output": "    num = bytes_to_int(x)\n    result = \"\"\n    while num > 0:\n        num, rem = divmod(num, 58)\n        result = _BASE58_CHARS[rem] + result\n    return result\n\n",
        "idx": "245"
    },
    {
        "instruction": "## ouch/__init__.py\ndef int_to_bytes(x, size=None, byteorder=\"big\"):\n    if size is None:\n        size = (x.bit_length() + 7) // 8\n    return x.to_bytes(size, byteorder=byteorder)\n\n_BASE58_CHARS = \"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz\"\n\ndef base58d(x):\n    \"\"\"\n    Decode the Base58-encoded back to bytes.\n    \n    >>> base58d('BXNAGjq4ty8AeedspDYRnHZwFTXtyQWNe')\n    b'sofia-maria-golden-girls'\n    \"\"\"\n",
        "input": "",
        "output": "    num = 0\n    for c in x:\n        num = num * 58 + _BASE58_CHARS.index(c)\n    return int_to_bytes(num)\n\n",
        "idx": "246"
    },
    {
        "instruction": "## LNNPlusAIGeometry.py\nimport torch\n\nimport torch.nn as nn\n\nclass LNN(nn.Module):\n    def __init__(self, input_size, hidden_size, output_size):\n        super(LNN, self).__init__()\n        self.input_to_hidden = nn.Linear(input_size, hidden_size)  # New projection layer\n        self.fc2 = nn.Linear(hidden_size, output_size)\n        self.dropout = nn.Dropout(0.5)\n        \n        # Self-attention mechanism for dynamic adjacency\n        self.attention = nn.MultiheadAttention(embed_dim=hidden_size, num_heads=4)\n        self.lambda_reg = 0.1  # Regularization parameter\n    \n    def forward(self, x):\n        # Project the input to the hidden size\n        x = torch.relu(self.input_to_hidden(x))\n        x = self.dropout(x)\n        return self.fc2(x)\n    \n    def compute_dynamic_adjacency(self, batch_data):\n        \"\"\"\n        Constructs a dynamic adjacency matrix using self-attention.\n        \"\"\"\n",
        "input": "",
        "output": "        batch_data = torch.relu(self.input_to_hidden(batch_data))\n        batch_data = batch_data.unsqueeze(1)  # Add sequence dimension for attention\n        attn_output, attn_weights = self.attention(batch_data, batch_data, batch_data)\n        adjacency_matrix = torch.mean(attn_weights, dim=1).squeeze(1)  # Average across heads\n        return adjacency_matrix\n    \n",
        "idx": "250"
    },
    {
        "instruction": "## LNNPlusAIGeometry.py\nimport torch\n\nimport torch.nn as nn\n\nclass LNN(nn.Module):\n    def __init__(self, input_size, hidden_size, output_size):\n        super(LNN, self).__init__()\n        self.input_to_hidden = nn.Linear(input_size, hidden_size)  # New projection layer\n        self.fc2 = nn.Linear(hidden_size, output_size)\n        self.dropout = nn.Dropout(0.5)\n        \n        # Self-attention mechanism for dynamic adjacency\n        self.attention = nn.MultiheadAttention(embed_dim=hidden_size, num_heads=4)\n        self.lambda_reg = 0.1  # Regularization parameter\n    \n    def forward(self, x):\n        # Project the input to the hidden size\n        x = torch.relu(self.input_to_hidden(x))\n        x = self.dropout(x)\n        return self.fc2(x)\n    \n    def compute_dynamic_adjacency(self, batch_data):\n        \"\"\"\n        Constructs a dynamic adjacency matrix using self-attention.\n        \"\"\"\n        # Project the input to the hidden size before using self-attention\n        batch_data = torch.relu(self.input_to_hidden(batch_data))\n        batch_data = batch_data.unsqueeze(1)  # Add sequence dimension for attention\n        attn_output, attn_weights = self.attention(batch_data, batch_data, batch_data)\n        adjacency_matrix = torch.mean(attn_weights, dim=1).squeeze(1)  # Average across heads\n        return adjacency_matrix\n    \n    def lagrangian_loss(self, output, target, batch_data):\n        \"\"\"\n        Combines Cross-Entropy Loss with Structural Regularization.\n        \"\"\"\n",
        "input": "",
        "output": "        ce_loss = nn.CrossEntropyLoss()(output, target)\n        \n        # Compute dynamic adjacency matrix using attention\n        adjacency_matrix = self.compute_dynamic_adjacency(batch_data)\n        \n        # Apply transformations to outputs and enforce consistency with the adjacency matrix\n        transformed_output = torch.softmax(output, dim=1)\n        \n        # Structural regularization using dynamic adjacency matrix\n        structural_reg = torch.mean(torch.abs(adjacency_matrix @ transformed_output))\n        \n        # Combined loss\n        return ce_loss + self.lambda_reg * structural_reg\n    \n",
        "idx": "251"
    },
    {
        "instruction": "## demo.py\nimport numpy as np\n\nclass Structure:\n    def __init__(self, nodes, edges):\n        self.nodes = nodes\n        self.edges = edges\n    \n    def adjacency_matrix(self):\n        \"\"\"\n        Creates an adjacency matrix for the structure.\n        \"\"\"\n",
        "input": "",
        "output": "        size = len(self.nodes)\n        matrix = np.zeros((size, size))\n        for edge in self.edges:\n            source_idx = self.nodes.index(edge.source)\n            target_idx = self.nodes.index(edge.target)\n            matrix[source_idx, target_idx] = edge.weight\n        return matrix\n    \n",
        "idx": "252"
    },
    {
        "instruction": "## src/sqfa/plot/_data_wrangle.py\nimport numpy as np\n\nimport torch\n\ndef subsample_class_points(points, labels, n_per_class):\n    \"\"\"\n    Return a subsample of points for each class (whichever is\n    smaller of n_per_class or the total points in the class).\n    \n    Parameters\n    ----------\n    points : torch.Tensor\n    Points to subsample. (n_points, n_dim)\n    labels : torch.Tensor\n    Labels or values of the points. (n_points,)\n    n_per_class : int\n    Number of points to subsample for each class.\n    \n    Returns\n    -------\n    subsampled_points : torch.Tensor\n    Subsampled points. (n_classes * n_points_per_class, n_dim)\n    subsampled_labels : torch.Tensor\n    Labels or values of the subsampled points. (n_classes * n_points_per_class,)\n    \"\"\"\n",
        "input": "",
        "output": "    subsampled_points = []\n    subsampled_labels = []\n\n    for _i, label in enumerate(labels.unique()):\n        class_points = points[labels == label]\n\n        n_points_class = np.min([n_per_class, class_points.shape[0]])\n        subsampled_points.append(class_points[:n_points_class])\n        subsampled_labels.append(label.repeat(n_points_class))\n\n    subsampled_points = torch.cat(subsampled_points, dim=0)\n    subsampled_labels = torch.cat(subsampled_labels, dim=0)\n    return subsampled_points, subsampled_labels\n\n",
        "idx": "253"
    },
    {
        "instruction": "## tests/test_linalg.py\nimport scipy.linalg\n\nimport torch\n\ndef matrix_log_ref(A):\n    \"\"\"\n    Compute the matrix logarithm of a tensor of SPD matrices using scipy.\n    \n    Parameters\n    ----------\n    A : torch.Tensor\n    A tensor of SPD matrices of shape (n_matrices, n_dim, n_dim).\n    \n    Returns\n    -------\n    log_A : torch.Tensor\n    A tensor of matrix logarithms of the input matrices of shape (n_matrices, n_dim, n_dim).\n    \"\"\"\n",
        "input": "",
        "output": "    if A.dim() < 3:\n        A = A.unsqueeze(0)\n    n_matrices = A.shape[0]\n    n_dim = A.shape[1]\n    log_A = torch.zeros((n_matrices, n_dim, n_dim))\n    for i in range(n_matrices):\n        log_A[i] = torch.as_tensor(scipy.linalg.logm(A[i]))\n\n    return log_A\n\n",
        "idx": "254"
    },
    {
        "instruction": "## src/sqfa/linalg.py\nimport torch\n\ndef conjugate_matrix(A, B):\n    \"\"\"\n    Conjugate matrix A by B, i.e. compute B A B^T.\n    \n    Parameters\n    ----------\n    A : torch.Tensor\n    Matrix A. Shape (n_batch_A, n_dim, n_dim).\n    B : torch.Tensor\n    Matrix B. Shape (n_batch_B, n_dim, n_out).\n    \n    Returns\n    -------\n    C : torch.Tensor\n    The conjugated matrix. Shape (n_batch_A, n_batch_B, n_out, n_out).\n    If a batch dimension is 1, it is squeezed out.\n    \"\"\"\n",
        "input": "",
        "output": "    if A.dim() == 2:\n        A = A.unsqueeze(0)\n    if B.dim() < 2:\n        raise ValueError(\"B must have at least 2 dimensions.\")\n    # Use einsum\n    C = torch.einsum(\"...ij,njk,...kl->n...il\", B, A, B.transpose(-2, -1))\n    # Use matmul\n    # C = B[None, ...] @ A[:, None, ...] @ B.transpose(-2, -1)[None, ...]\n    squeeze_dim = (0) if B.dim() == 2 else (0, 1)\n    return torch.squeeze(C, dim=squeeze_dim)\n\n",
        "idx": "255"
    },
    {
        "instruction": "## tests/make_examples.py\nimport torch\n\ndef make_orthogonal_matrices(n_matrices, n_dim):\n    \"\"\"\n    Generate random orthogonal matrices.\n    \"\"\"\n",
        "input": "",
        "output": "    low_tri = torch.randn(n_matrices, n_dim, n_dim)\n    low_tri = torch.tril(low_tri, diagonal=-1)\n    skew_sym = low_tri - low_tri.transpose(1, 2)\n    orthogonal = torch.matrix_exp(skew_sym)\n    return orthogonal\n\n",
        "idx": "258"
    },
    {
        "instruction": "## tests/test_linalg.py\nimport scipy.linalg\n\nimport torch\n\ndef matrix_sqrt_ref(A):\n    \"\"\"\n    Compute the square root of a tensor of SPD matrices using scipy.\n    \n    Parameters\n    ----------\n    A : torch.Tensor\n    A tensor of SPD matrices of shape (n_matrices, n_dim, n_dim).\n    \n    Returns\n    -------\n    sqrt_A : torch.Tensor\n    A tensor of square roots of the input matrices of shape (n_matrices, n_dim, n_dim).\n    \"\"\"\n",
        "input": "",
        "output": "    if A.dim() < 3:\n        A = A.unsqueeze(0)\n    n_matrices = A.shape[0]\n    n_dim = A.shape[1]\n    sqrt_A = torch.zeros((n_matrices, n_dim, n_dim))\n    if n_dim > 1:\n        for i in range(n_matrices):\n            sqrt_A[i] = torch.as_tensor(scipy.linalg.sqrtm(A[i]))\n    else:\n        sqrt_A = torch.sqrt(A)\n    return sqrt_A\n\n",
        "idx": "262"
    },
    {
        "instruction": "## src/sqfa/linalg.py\nimport torch\n\ndef spd_sqrt(M):\n    \"\"\"\n    Compute the square root of a symmetric positive definite matrix.\n    \n    Computes the symmetric positive definite matrix S such that SS = M.\n    \n    Parameters\n    ----------\n    M : torch.Tensor\n    Symmetric positive definite matrices. Shape (..., n_dim, n_dim).\n    \n    Returns\n    -------\n    M_sqrt : torch.Tensor\n    The square root of M. Shape (..., n_dim, n_dim).\n    \"\"\"\n",
        "input": "",
        "output": "    eigvals, eigvecs = torch.linalg.eigh(M)\n    M_sqrt = torch.einsum(\n        \"...ij,...j,...kj->...ik\", eigvecs, torch.sqrt(eigvals), eigvecs\n    )\n    return M_sqrt\n\n",
        "idx": "264"
    },
    {
        "instruction": "## src/sqfa/linalg.py\nimport torch\n\ndef conjugate_matrix(A, B):\n    \"\"\"\n    Conjugate matrix A by B, i.e. compute B A B^T.\n\n    Parameters\n    ----------\n    A : torch.Tensor\n        Matrix A. Shape (n_batch_A, n_dim, n_dim).\n    B : torch.Tensor\n        Matrix B. Shape (n_batch_B, n_dim, n_out).\n\n    Returns\n    -------\n    C : torch.Tensor\n        The conjugated matrix. Shape (n_batch_A, n_batch_B, n_out, n_out).\n        If a batch dimension is 1, it is squeezed out.\n    \"\"\"\n    if A.dim() == 2:\n        A = A.unsqueeze(0)\n    if B.dim() < 2:\n        raise ValueError(\"B must have at least 2 dimensions.\")\n    # Use einsum\n    C = torch.einsum(\"...ij,njk,...kl->n...il\", B, A, B.transpose(-2, -1))\n    # Use matmul\n    # C = B[None, ...] @ A[:, None, ...] @ B.transpose(-2, -1)[None, ...]\n    squeeze_dim = (0) if B.dim() == 2 else (0, 1)\n    return torch.squeeze(C, dim=squeeze_dim)\n\ndef spd_inv_sqrt(M):\n    \"\"\"\n    For symmetric positive definite matrix M, compute the inverse square\n    root of M.\n\n    Parameters\n    ----------\n    M : torch.Tensor\n        Symmetric positive definite matrices. Shape (n_batch, n_dim, n_dim).\n\n    Returns\n    -------\n    M_inv_sqrt : torch.Tensor\n        Inverse square root of M. Shape (n_batch, n_dim, n_dim).\n    \"\"\"\n    eigvals, eigvecs = torch.linalg.eigh(M)\n    inv_sqrt_eigvals = torch.sqrt(1.0 / eigvals)\n    M_inv_sqrt = eigvecs * inv_sqrt_eigvals.unsqueeze(-2)\n    return M_inv_sqrt.transpose(-2, -1)\n\ndef generalized_eigenvalues(A, B):\n    \"\"\"\n    Compute the generalized eigenvalues of the pair of symmetric positive\n    definite matrices (A, B).\n    \n    Parameters\n    ----------\n    A : torch.Tensor\n    Symmetric positive definite matrix. Shape (n_batch_A, n_dim, n_dim).\n    B : torch.Tensor\n    Symmetric positive definite matrix. Shape (n_batch_B, n_dim, n_dim).\n    \n    Returns\n    -------\n    eigenvalues : torch.Tensor\n    The generalized eigenvalues of the pair (A, B), sorted in descending\n    order. Shape (n_batch_A, n_batch_B, n_dim).\n    If a batch dimension is 1, it is squeezed out.\n    \"\"\"\n",
        "input": "",
        "output": "    B_inv_sqrt = spd_inv_sqrt(B)\n    A_conj = conjugate_matrix(A, B_inv_sqrt)\n    eigenvalues = torch.linalg.eigvalsh(A_conj)\n    return eigenvalues.flip(-1)\n\n",
        "idx": "265"
    },
    {
        "instruction": "## tests/make_examples.py\nimport torch\n\ndef make_dataset_points(n_points, class_covariances):\n    \"\"\"\n    Generate points from a dataset with n_points and n_classes.\n    \"\"\"\n",
        "input": "",
        "output": "    n_dim = class_covariances.shape[-1]\n    n_classes = class_covariances.shape[0]\n    for i in range(n_classes):\n        cov = class_covariances[i]\n        mean = torch.zeros(n_dim)\n        class_points = torch.distributions.MultivariateNormal(mean, cov).sample(\n            (n_points,)\n        )\n        if i == 0:\n            points = class_points\n            labels = torch.ones(n_points) * i\n        else:\n            points = torch.cat((points, class_points), 0)\n            labels = torch.cat((labels, torch.ones(n_points) * i), 0)\n\n    return points, labels\n\n",
        "idx": "266"
    },
    {
        "instruction": "## src/sqfa/plot/colors.py\nimport matplotlib.pyplot as plt\n\nimport numpy as np\n\nfrom matplotlib.colors import Normalize\n\ndef get_normalized_color_map(color_map, values, color_limits=None):\n    \"\"\"\n    Get the color map and normalizer for the given values.\n\n    Parameters\n    ----------\n    color_map : str or matplotlib.colors.Colormap\n        The colormap to use.\n    values : list or numpy.ndarray or torch.Tensor\n        The value of each class to be used for the color scale\n    color_limits : list, optional\n        The minimum and maximum values for the color scale. If not provided,\n        the minimum and maximum values of `values` will be used.\n\n    Returns\n    -------\n    color_map : matplotlib.colors.Colormap\n        The colormap to use.\n    color_normalizer : matplotlib.colors.Normalize\n        The normalizer for the colormap.\n    \"\"\"\n    values = np.array(values)\n    if isinstance(color_map, str):\n        color_map = plt.get_cmap(color_map)\n    if color_limits is None:\n        color_limits = [np.min(values), np.max(values)]\n    color_normalizer = Normalize(vmin=color_limits[0], vmax=color_limits[1])\n    return color_map, color_normalizer\n\ndef get_class_rgba(color_map, values, color_limits=None):\n    \"\"\"\n    Get the RGBA color for each class based on the colormap and the values.\n    \n    Parameters\n    ----------\n    color_map : str or matplotlib.colors.Colormap\n    The colormap to use.\n    values : list or numpy.ndarray or torch.Tensor\n    The value of each class to be used for the color scale\n    color_limits : list, optional\n    The minimum and maximum values for the color scale. If not provided,\n    the minimum and maximum values of `values` will be used.\n    \n    Returns\n    -------\n    colors : numpy.ndarray (n_classes, 4)\n    The color for each class in RGBA format.\n    \"\"\"\n",
        "input": "",
        "output": "    color_map, color_normalizer = get_normalized_color_map(\n        color_map, values, color_limits\n    )\n    class_colors = color_map(color_normalizer(values))\n    return class_colors\n\n",
        "idx": "267"
    },
    {
        "instruction": "# Here are some relevant code fragments from other files of the repo:\n# --------------------------------------------------\n# the below code fragment can be found in:\n# src/sqfa/_optim.py\n# --------------------------------------------------\n# \n# import torch\n# \n# def check_distances_valid(distances):\n#     \"\"\"\n#     Check if off-diagonal distances are valid. Raise an error if they are not.\n# \n#     Parameters\n#     ----------\n#     distances : torch.Tensor\n#         Tensor of pairwise distances between covariance matrices.\n#     \"\"\"\n#     n_classes = distances.shape[0]\n#     tril_ind = torch.tril_indices(n_classes, n_classes, offset=-1)\n#     if torch.isnan(distances[tril_ind]).any():\n#         raise ValueError('Some distances between classes are NaN.')\n#     if torch.isinf(distances[tril_ind]).any():\n#         raise ValueError('Some distances between classes are inf.')\n# import time\n# from tqdm import tqdm\n# from torch import optim\n# \n# # ...\n# --------------------------------------------------\n# the below code fragment can be found in:\n# src/sqfa/linalg.py\n# --------------------------------------------------\n# \n# import torch\n# \n# def conjugate_matrix(A, B):\n#     \"\"\"\n#     Conjugate matrix A by B, i.e. compute B A B^T.\n# \n#     Parameters\n#     ----------\n#     A : torch.Tensor\n#         Matrix A. Shape (n_batch_A, n_dim, n_dim).\n#     B : torch.Tensor\n#         Matrix B. Shape (n_batch_B, n_dim, n_out).\n# \n#     Returns\n#     -------\n#     C : torch.Tensor\n#         The conjugated matrix. Shape (n_batch_A, n_batch_B, n_out, n_out).\n#         If a batch dimension is 1, it is squeezed out.\n#     \"\"\"\n#     if A.dim() == 2:\n#         A = A.unsqueeze(0)\n#     if B.dim() < 2:\n#         raise ValueError(\"B must have at least 2 dimensions.\")\n#     # Use einsum\n#     C = torch.einsum(\"...ij,njk,...kl->n...il\", B, A, B.transpose(-2, -1))\n#     # Use matmul\n#     # C = B[None, ...] @ A[:, None, ...] @ B.transpose(-2, -1)[None, ...]\n#     squeeze_dim = (0) if B.dim() == 2 else (0, 1)\n#     return torch.squeeze(C, dim=squeeze_dim)\n# \n# def spd_inv_sqrt(M):\n#     \"\"\"\n#     For symmetric positive definite matrix M, compute the inverse square\n#     root of M.\n# \n#     Parameters\n#     ----------\n#     M : torch.Tensor\n#         Symmetric positive definite matrices. Shape (n_batch, n_dim, n_dim).\n# \n#     Returns\n#     -------\n#     M_inv_sqrt : torch.Tensor\n#         Inverse square root of M. Shape (n_batch, n_dim, n_dim).\n#     \"\"\"\n#     eigvals, eigvecs = torch.linalg.eigh(M)\n#     inv_sqrt_eigvals = torch.sqrt(1.0 / eigvals)\n#     M_inv_sqrt = eigvecs * inv_sqrt_eigvals.unsqueeze(-2)\n#     return M_inv_sqrt.transpose(-2, -1)\n# \n# def generalized_eigenvalues(A, B):\n#     \"\"\"\n#     Compute the generalized eigenvalues of the pair of symmetric positive\n#     definite matrices (A, B).\n# \n#     Parameters\n#     ----------\n#     A : torch.Tensor\n#         Symmetric positive definite matrix. Shape (n_batch_A, n_dim, n_dim).\n#     B : torch.Tensor\n#         Symmetric positive definite matrix. Shape (n_batch_B, n_dim, n_dim).\n# \n#     Returns\n#     -------\n#     eigenvalues : torch.Tensor\n#         The generalized eigenvalues of the pair (A, B), sorted in descending\n#         order. Shape (n_batch_A, n_batch_B, n_dim).\n#         If a batch dimension is 1, it is squeezed out.\n#     \"\"\"\n#     B_inv_sqrt = spd_inv_sqrt(B)\n#     A_conj = conjugate_matrix(A, B_inv_sqrt)\n#     eigenvalues = torch.linalg.eigvalsh(A_conj)\n#     return eigenvalues.flip(-1)\n# \n# \n# --------------------------------------------------\n# the below code fragment can be found in:\n# src/sqfa/distances.py\n# --------------------------------------------------\n# \n# EPSILON = 1e-6\n# \n# from .linalg import (\n#     generalized_eigenvalues,\n#     spd_log,\n# )\n# \n# import torch\n# \n# def affine_invariant_sq(A, B):\n#     \"\"\"\n#     Compute the squared affine invariant distance between SPD matrices.\n# \n#     Parameters\n#     ----------\n#     A : torch.Tensor\n#         Shape (n_batch_A, n_dim, n_dim), the first SPD matrix.\n#     B : torch.Tensor\n#         Shape (n_batch_B, n_dim, n_dim), the second SPD matrix.\n# \n#     Returns\n#     -------\n#     distance_squared : torch.Tensor\n#         Shape (n_batch_A, n_batch_B), the squared affine invariant distance.\n#     \"\"\"\n#     # Compute the generalized eigenvalues\n#     gen_eigvals = generalized_eigenvalues(A, B)\n#     # Compute the distance\n#     distance_squared = torch.sum(torch.log(gen_eigvals) ** 2, axis=-1)\n#     return distance_squared\n# \n# def affine_invariant(A, B):\n#     \"\"\"\n#     Compute the affine invariant distance between SPD matrices.\n#     A small epsilon is added inside the square root to avoid gradient\n#     instabilities.\n# \n#     Parameters\n#     ----------\n#     A : torch.Tensor\n#         Shape (n_batch_A, n_dim, n_dim), the first SPD matrix.\n#     B : torch.Tensor\n#         Shape (n_batch_B, n_dim, n_dim), the second SPD matrix.\n# \n#     Returns\n#     -------\n#     distance : torch.Tensor\n#         Shape (n_batch_A, n_batch_B), the affine invariant distance.\n#     \"\"\"\n#     return torch.sqrt(affine_invariant_sq(A, B) + EPSILON)\n# \n# def _embed_gaussian(means, covariances):\n#     \"\"\"\n#     Embed the parameters of the Gaussian distribution in SPD,\n#     by stacking the means and the covariances in the format\n#     [covariances, means;\n#     means.T, 1].\n# \n#     Parameters\n#     ----------\n#     means : torch.Tensor\n#         Shape (n_classes, n_filters), the means.\n#     covariances : torch.Tensor\n#         Shape (n_classes, n_filters, n_filters), the covariance matrices.\n# \n#     Returns\n#     -------\n#     embedding : torch.Tensor\n#         Shape (n_classes, n_filters+1, n_filters+1), the embedded SPD matrices.\n#     \"\"\"\n#     n_classes, n_filters = means.shape\n# \n#     mean_outer_prod = torch.einsum(\"ni,nj->nij\", means, means)\n#     second_moments = covariances + mean_outer_prod\n# \n#     embedding = torch.cat([second_moments, means.unsqueeze(1)], dim=1)\n#     one = torch.ones(n_classes, dtype=means.dtype, device=means.device)\n#     means_long = torch.cat([means, one.unsqueeze(1)], dim=1)\n#     embedding = torch.cat([embedding, means_long.unsqueeze(2)], dim=2)\n#     return embedding\n# \n# def fisher_rao_lower_bound_sq(means, covariances):\n#     \"\"\"\n#     Compute the Calvo & Oller lower bound of the Fisher-Rao squared\n#     distance between Gaussians.\n# \n#     Parameters\n#     ----------\n#     means : torch.Tensor\n#         Shape (n_classes, n_filters), the means.\n#     covariances : torch.Tensor\n#         Shape (n_classes, n_filters, n_filters), the covariance matrices.\n# \n#     Returns\n#     -------\n#     distance_squared : torch.Tensor\n#         Shape (n_classes, n_classes), the lower bound of the Fisher-Rao squared\n#         distance.\n#     \"\"\"\n#     embedding = _embed_gaussian(means, covariances)\n#     distance_squared = affine_invariant_sq(embedding, embedding)\n#     return distance_squared\n# \n# def fisher_rao_lower_bound(means, covariances):\n#     \"\"\"\n#     Compute the Calvo & Oller lower bound of the Fisher-Rao squared\n#     distance between Gaussians.\n# \n#     Parameters\n#     ----------\n#     means : torch.Tensor\n#         Shape (n_classes, n_filters), the means.\n#     covariances : torch.Tensor\n#         Shape (n_classes, n_filters, n_filters), the covariance matrices.\n# \n#     Returns\n#     -------\n#     distance : torch.Tensor\n#         Shape (n_classes, n_classes), the lower bound of the Fisher-Rao distance.\n#     \"\"\"\n#     return torch.sqrt(fisher_rao_lower_bound_sq(means, covariances) + EPSILON)\n# \n# \n# --------------------------------------------------\n\n\n# src/sqfa/model.py\n\nfrom .statistics import class_statistics, pca, pca_from_scatter\nfrom .constraints import FixedFilters, Identity, Sphere\nfrom torch.nn.utils.parametrizations import orthogonal\nimport torch.nn as nn\nfrom ._optim import fitting_loop\nfrom torch.nn.utils.parametrize import register_parametrization, remove_parametrizations\nfrom .linalg import conjugate_matrix\n\ndef _check_statistics(data_statistics):\n    \"\"\"\n    Check that data_statistics is either:\n      1) a torch.Tensor of shape (n_classes, n_dim, n_dim), or\n      2) a dictionary containing at least the 'means' and 'covariances' keys.\n\n    Parameters\n    ----------\n    data_statistics : torch.Tensor or dict\n        Data statistics, either as a tensor with second moments or a dictionary\n        containing means and covariances.\n\n    Raises\n    ------\n    ValueError\n        If `data_statistics` is a dictionary but does not contain the required keys.\n    TypeError\n        If `data_statistics` is neither a dictionary nor a tensor-like object.\n    \"\"\"\n    if isinstance(data_statistics, dict):\n        required_keys = {'means', 'covariances'}\n        missing_keys = required_keys - set(data_statistics.keys())\n        if missing_keys:\n            raise ValueError(f'`data_statistics` dictionary must contain the keys {required_keys}. Missing keys: {missing_keys}')\n    elif not hasattr(data_statistics, 'shape'):\n        raise TypeError(\"`data_statistics` must be either a dict with 'means' and 'covariances' or a torch.Tensor of shape (n_classes, n_dim, n_dim).\")\nimport torch\n\ndef _stats_to_scatter(statistics):\n    \"\"\"\n    Convert data_statistics input to scatter matrices. This function\n    is used to allow the input to the model to be either\n    a dictionary with means and covariances or a tensor with the\n    second moments.\n\n    Parameters\n    ----------\n    statistics : torch.Tensor or dict\n        - If a torch.Tensor, should have shape (n_classes, n_dim, n_dim) and contain\n          the scatter matrices (second moments) of the data for each class.\n        - If a dict, it should contain fields 'means' and 'covariances'.\n\n    Returns\n    -------\n    torch.Tensor\n        Scatter matrices of shape (n_classes, n_dim, n_dim).\n    \"\"\"\n    if isinstance(statistics, dict):\n        _check_statistics(statistics)\n        mean_outer_prod = torch.einsum('ni,nj->nij', statistics['means'], statistics['means'])\n        scatter = statistics['covariances'] + mean_outer_prod\n    else:\n        scatter = statistics\n    return scatter\nfrom .distances import affine_invariant, fisher_rao_lower_bound\n\nclass SQFA(nn.Module):\n    \"\"\"Supervised Quadratic Feature Analysis (SQFA) model.\"\"\"\n\n    def __init__(self, n_dim, feature_noise=0, n_filters=2, filters=None, distance_fun=None, constraint='sphere'):\n        \"\"\"\n        Initialize SQFA.\n\n        Parameters\n        ----------\n        n_dim : int\n            Dimension of the input data space.\n        feature_noise : float\n            Noise added to the features outputs, i.e. a diagonal term added\n            to the covariance matrix of the features. Default is 0.\n        n_filters : int\n            Number of filters to use. Default is 2. If filters is provided,\n            n_filters is ignored.\n        filters : torch.Tensor\n            Filters to use. If n_filters is provided, filters are randomly\n            initialized. Default is None. Of shape (n_filters, n_dim).\n        distance_fun : callable\n            Function to compute the distance between the transformed feature\n            scatter matrices. Should take as input two tensors of shape\n            (n_classes, n_filters, n_filters) and return a matrix\n            of shape (n_classes, n_classes) with the pairwise distances\n            (or squared distances or similarities).\n            If None, then the Affine Invariant squared distance is used.\n        constraint : str\n            Constraint to apply to the filters. Can be 'none', 'sphere' or\n            'orthogonal'. Default is 'sphere'.\n        \"\"\"\n        super().__init__()\n        if filters is None:\n            filters = torch.randn(n_filters, n_dim)\n        else:\n            filters = torch.as_tensor(filters, dtype=torch.float32)\n        self.filters = nn.Parameter(filters)\n        feature_noise_mat = torch.as_tensor(feature_noise, dtype=torch.float32) * torch.eye(n_filters)\n        self.register_buffer('diagonal_noise', feature_noise_mat)\n        if distance_fun is None:\n            self.distance_fun = affine_invariant\n        else:\n            self.distance_fun = distance_fun\n        self.constraint = constraint\n        self._add_constraint(constraint=self.constraint)\n\n    def transform_scatters(self, data_scatters):\n        \"\"\"\n        Transform data scatter matrices to feature space scatter matrices.\n\n        Parameters\n        ----------\n        data_scatters : torch.Tensor\n            Tensor of shape (n_classes, n_dim, n_dim), with second\n            moment or covariance matrices.\n\n        Returns\n        -------\n        torch.Tensor shape (n_classes, n_filters, n_filters)\n            Covariances of the transformed features.\n        \"\"\"\n        feature_scatters = conjugate_matrix(data_scatters, self.filters)\n        return feature_scatters\n\n    def get_class_distances(self, data_statistics, regularized=False):\n        \"\"\"\n        Compute the pairwise distances between the feature scatter matrices of the\n        different classes.\n\n        Parameters\n        ----------\n        data_statistics : torch.Tensor or dict\n            - If a torch.Tensor, should have shape (n_classes, n_dim, n_dim) and contain\n              the scatter matrices (second moments) of the data for each class.\n            - If a dict, it should contain fields 'means' and 'covariances'.\n        regularized : bool\n            If True, regularize the distances by adding a small value to the\n            diagonal of the transformed scatter matrices. Default is False.\n\n        Returns\n        -------\n        torch.Tensor shape (n_classes, n_classes)\n            Pairwise distances between the transformed feature scatter matrices.\n        \"\"\"\n        data_scatters = _stats_to_scatter(data_statistics)\n        feature_scatters = self.transform_scatters(data_scatters)\n        if regularized:\n            feature_scatters = feature_scatters + self.diagonal_noise[None, :, :]\n        distances = self.distance_fun(feature_scatters, feature_scatters)\n        return distances\n\n    def transform(self, data_points):\n        \"\"\"\n        Transform data to feature space.\n\n        Parameters\n        ----------\n        data_points : torch.Tensor\n            Input data of shape (n_samples, n_dim).\n\n        Returns\n        -------\n        torch.Tensor shape (n_samples, n_filters)\n            Data transformed to feature space.\n        \"\"\"\n        transformed_points = torch.einsum('ij,nj->ni', self.filters, data_points)\n        return transformed_points\n\n    def fit_pca(self, X=None, data_statistics=None):\n        \"\"\"\n        Fit the SQFA filters to the data using PCA. This can be used to\n        initialize the filters before training.\n\n        Parameters\n        ----------\n        X : torch.Tensor\n            Input data of shape (n_samples, n_dim).\n        data_statistics : torch.Tensor\n            Tensor of shape (n_classes, n_dim, n_dim) with the second moments\n            of the data for each class. If None, then X and y must be provided.\n            Default is None.\n        \"\"\"\n        if X is None and data_statistics is None:\n            raise ValueError('Either X or data_statistics must be provided.')\n        if self.filters.shape[0] > self.filters.shape[1]:\n            raise ValueError('Number of filters must be less than or equal to the data dimension.')\n        n_components = self.filters.shape[0]\n        if data_statistics is None:\n            pca_filters = pca(X, n_components)\n        else:\n            data_scatters = _stats_to_scatter(data_statistics)\n            pca_filters = pca_from_scatter(data_scatters, n_components)\n        remove_parametrizations(self, 'filters')\n        self.filters = nn.Parameter(pca_filters)\n        self._add_constraint(constraint=self.constraint)\n\n    def fit(self, X=None, y=None, data_statistics=None, max_epochs=300, lr=0.1, estimator='empirical', pairwise=False, show_progress=True, return_loss=False, **kwargs):\n        \"\"\"\n        Fit the SQFA model to data using the LBFGS optimizer.\n\n        Parameters\n        ----------\n        X : torch.Tensor\n            Input data of shape (n_samples, n_dim). If data_statistics is None,\n            then X and y must be provided.\n        y : torch.Tensor\n            Labels of shape (n_samples,). If data_statistics is None, then X\n            and y must be provided. Labels must be integers starting from 0.\n        data_statistics : torch.Tensor or dict\n            - If a torch.Tensor, should have shape (n_classes, n_dim, n_dim) and contain\n              the scatter matrices (second moments) of the data for each class.\n            - If a dict, it should contain fields 'means' and 'covariances'\n        max_epochs : int, optional\n            Number of max training epochs. By default 50.\n        lr : float\n            Learning rate for the optimizer. Default is 0.1.\n        estimator:\n            Covariance estimator to use. Options are \"empirical\",\n            and \"oas\". Default is \"oas\".\n        pairwise : bool\n            If True, then filters are optimized pairwise (the first 2 filters\n            are optimized together, then held fixed and the next 2 filters are\n            optimized together, etc.). If False, all filters are optimized\n            together. Default is False.\n        show_progress : bool\n            If True, show a progress bar during training. Default is True.\n        return_loss : bool\n            If True, return the loss after training. Default is False.\n        **kwargs\n            Additional keyword arguments passed to the NAdam optimizer.\n        \"\"\"\n        if data_statistics is None:\n            if X is None or y is None:\n                raise ValueError('Either data_statistics or X and y must be provided.')\n            data_statistics = class_statistics(X, y, estimator=estimator)\n        if not pairwise:\n            loss, training_time = fitting_loop(model=self, data_statistics=data_statistics, max_epochs=max_epochs, lr=lr, show_progress=show_progress, return_loss=True, **kwargs)\n        else:\n            n_pairs = self.filters.shape[0] // 2\n            filters_original = self.filters.detach().clone()\n            noise_original = self.diagonal_noise.detach().clone()[0, 0]\n            if self.filters.shape[0] % 2 != 0:\n                raise ValueError('Number of filters must be even for pairwise training.')\n            loss = torch.tensor([])\n            training_time = torch.tensor([])\n            filters_last_trained = torch.zeros(0)\n            for i in range(n_pairs):\n                filters_last_trained = self.filters.detach().clone()\n                if i == 0:\n                    filters_new_init = filters_original[:2]\n                else:\n                    filters_new_init = torch.cat((filters_last_trained, filters_original[2 * i:2 * (i + 1)]))\n                remove_parametrizations(self, 'filters')\n                self.filters = nn.Parameter(filters_new_init)\n                self._add_constraint(constraint=self.constraint)\n                feature_noise_mat = noise_original * torch.eye(2 * (i + 1))\n                self.register_buffer('diagonal_noise', feature_noise_mat)\n                if i > 0:\n                    register_parametrization(self, 'filters', FixedFilters(n_row_fixed=i * 2))\n                loss_pair, training_time_pair = fitting_loop(model=self, data_statistics=data_statistics, max_epochs=max_epochs, lr=lr, show_progress=show_progress, return_loss=True, **kwargs)\n                remove_parametrizations(self, 'filters')\n                self._add_constraint(constraint=self.constraint)\n                loss = torch.cat((loss, loss_pair))\n                if training_time.numel() > 0:\n                    training_time_pair = training_time_pair + training_time[-1]\n                training_time = torch.cat((training_time, training_time_pair))\n        if return_loss:\n            return (loss, training_time)\n        else:\n            return None\n\n    def _add_constraint(self, constraint='none'):\n        \"\"\"\n        Add constraint to the filters.\n\n        Parameters\n        ----------\n        constraint : str\n            Constraint to apply to the filters. Can be 'none', 'sphere' or\n            'orthogonal'. Default is 'none'.\n        \"\"\"\n        if constraint == 'none':\n            register_parametrization(self, 'filters', Identity())\n        elif constraint == 'sphere':\n            register_parametrization(self, 'filters', Sphere())\n        elif constraint == 'orthogonal':\n            orthogonal(self, 'filters')\n\nclass FisherRao(SQFA):\n    \"\"\"\n    Supervised Quadratic Feature Analysis (SQFA) model, using\n    the lower bound on the Fisher-Rao distance as the loss function.\n    \"\"\"\n\n    def __init__(self, n_dim, feature_noise=0, n_filters=2, filters=None, constraint='sphere'):\n        \"\"\"\n        Initialize SQFA.\n\n        Parameters\n        ----------\n        n_dim : int\n            Dimension of the input data space.\n        feature_noise : float\n            Noise added to the features outputs, i.e. a diagonal term added\n            to the covariance matrix of the features. Default is 0.\n        n_filters : int\n            Number of filters to use. Default is 2. If filters is provided,\n            n_filters is ignored.\n        filters : torch.Tensor\n            Filters to use. If n_filters is provided, filters are randomly\n            initialized. Default is None. Of shape (n_filters, n_dim).\n        constraint : str\n            Constraint to apply to the filters. Can be 'none', 'sphere' or\n            'orthogonal'. Default is 'sphere'.\n        \"\"\"\n        super().__init__(n_dim=n_dim, feature_noise=feature_noise, n_filters=n_filters, filters=filters, distance_fun=fisher_rao_lower_bound, constraint=constraint)\n\n    def fit(self, X=None, y=None, data_statistics=None, max_epochs=300, lr=0.1, estimator='oas', pairwise=False, show_progress=True, return_loss=False, **kwargs):\n        \"\"\"\n        Fit the SQFA model to data using the LBFGS optimizer.\n\n        Parameters\n        ----------\n        X : torch.Tensor\n            Input data of shape (n_samples, n_dim). If data_statistics is None,\n            then X and y must be provided.\n        y : torch.Tensor\n            Labels of shape (n_samples,). If data_statistics is None, then X\n            and y must be provided. Labels must be integers starting from 0.\n        data_statistics : dict\n            Dictionary containing the fields 'means' and 'covariances'\n        max_epochs : int, optional\n            Number of max training epochs. By default 50.\n        lr : float\n            Learning rate for the optimizer. Default is 0.1.\n        estimator:\n            Covariance estimator to use. Options are \"empirical\",\n            and \"oas\". Default is \"oas\".\n        pairwise : bool\n            If True, then filters are optimized pairwise (the first 2 filters\n            are optimized together, then held fixed and the next 2 filters are\n            optimized together, etc.). If False, all filters are optimized\n            together. Default is False.\n        show_progress : bool\n            If True, show a progress bar during training. Default is True.\n        return_loss : bool\n            If True, return the loss after training. Default is False.\n        **kwargs\n            Additional keyword arguments passed to the NAdam optimizer.\n        \"\"\"\n        if data_statistics is None:\n            if X is None or y is None:\n                raise ValueError('Either data_statistics or X and y must be provided.')\n            data_statistics = class_statistics(X, y, estimator=estimator)\n        else:\n            if not isinstance(data_statistics, dict):\n                raise ValueError('Fisher-Rao distance requires class statistics dictionary or X and y as input')\n            _check_statistics(data_statistics)\n        loss, training_time = super().fit(X=None, y=None, data_statistics=data_statistics, max_epochs=max_epochs, lr=lr, estimator=estimator, pairwise=pairwise, show_progress=show_progress, return_loss=True, **kwargs)\n        if return_loss:\n            return (loss, training_time)\n        else:\n            return None\n\n    def get_class_distances(self, data_statistics, regularized=False):\n        \"\"\"\n        Compute the pairwise lower bounds to the Fisher-Rao distances.\n    \n        Parameters\n        ----------\n        data_statistics : torch.Tensor or dict\n        - If a torch.Tensor, should have shape (n_classes, n_dim, n_dim) and contain\n        the scatter matrices (second moments) of the data for each class.\n        - If a dict, it should contain fields 'means' and 'covariances'.\n        regularized : bool\n        If True, regularize the distances by adding a small value to the\n        diagonal of the transformed scatter matrices. Default is False.\n    \n        Returns\n        -------\n        torch.Tensor shape (n_classes, n_classes)\n        Pairwise distances between the transformed feature scatter matrices.\n        \"\"\"\n",
        "input": "",
        "output": "        if not isinstance(data_statistics, dict):\n            raise ValueError('Fisher-Rao distance requires class statistics dictionary as input')\n        feature_means = self.transform(data_statistics['means'])\n        feature_covariances = self.transform_scatters(data_statistics['covariances'])\n        if regularized:\n            feature_covariances = feature_covariances + self.diagonal_noise[None, :, :]\n        distances = self.distance_fun(feature_means, feature_covariances)\n        return distances\n    \n",
        "idx": "270"
    },
    {
        "instruction": "## src/sqfa/constraints.py\nimport torch.nn as nn\n\nclass Sphere(nn.Module):\n    \"\"\"Constrains the input tensor to lie on the sphere.\"\"\"\n\n    def forward(self, X):\n        \"\"\"\n        Normalize the input tensor so that it lies on the sphere.\n    \n        The norm pooled across channels is computed and used to normalize the tensor.\n    \n        Parameters\n        ----------\n        X : torch.Tensor\n        Input tensor in Euclidean space with shape (n_filters, n_dim).\n    \n        Returns\n        -------\n        torch.Tensor\n        Normalized tensor lying on the sphere with shape\n        (n_filters, n_dim).\n        \"\"\"\n",
        "input": "",
        "output": "        X_normalized = X / X.norm(dim=-1, keepdim=True)\n        return X_normalized\n    \n",
        "idx": "271"
    },
    {
        "instruction": "## src/sqfa/constraints.py\nimport torch.nn as nn\n\nclass Sphere(nn.Module):\n    \"\"\"Constrains the input tensor to lie on the sphere.\"\"\"\n\n    def forward(self, X):\n        \"\"\"\n        Normalize the input tensor so that it lies on the sphere.\n\n        The norm pooled across channels is computed and used to normalize the tensor.\n\n        Parameters\n        ----------\n        X : torch.Tensor\n            Input tensor in Euclidean space with shape (n_filters, n_dim).\n\n        Returns\n        -------\n        torch.Tensor\n            Normalized tensor lying on the sphere with shape\n            (n_filters, n_dim).\n        \"\"\"\n        X_normalized = X / X.norm(dim=-1, keepdim=True)\n        return X_normalized\n\n    def right_inverse(self, S):\n        \"\"\"\n        Identity function to assign to parametrization.\n    \n        Parameters\n        ----------\n        S : torch.Tensor\n        Input tensor. Should be different from zero.\n    \n        Returns\n        -------\n        torch.Tensor\n        Returns the input tensor `S`.\n        \"\"\"\n",
        "input": "",
        "output": "        return S\n    \n",
        "idx": "272"
    },
    {
        "instruction": "## src/sqfa/constraints.py\nimport torch.nn as nn\n\nclass Identity(nn.Module):\n    \"\"\"Leaves the input tensor unconstrained. Used for consistency.\"\"\"\n\n    def forward(self, X):\n        \"\"\"\n        Return the input tensor as is.\n\n        Parameters\n        ----------\n        X : torch.Tensor\n            Input tensor (n_filters, n_dim).\n\n        Returns\n        -------\n        torch.Tensor\n            Normalized tensor lying on the sphere with shape\n            (n_filters, n_dim).\n        \"\"\"\n        return X\n\n    def right_inverse(self, S):\n        \"\"\"\n        Identity function.\n    \n        Parameters\n        ----------\n        S : torch.Tensor\n        Input tensor.\n    \n        Returns\n        -------\n        torch.Tensor\n        Returns the input tensor.\n        \"\"\"\n",
        "input": "",
        "output": "        return S\n    \n",
        "idx": "274"
    },
    {
        "instruction": "## uscodekit/zip_code.py\nimport re\n\nfrom typing import Optional, List, Dict, Any\n\ndef extract_all_zip_codes(text: str) -> List[str]:\n    \"\"\"\n    Extracts all US ZIP codes from the given text.\n    \n    This function uses a regular expression to find all US ZIP codes in the\n    provided text. It supports both the 5-digit format and the ZIP+4 format.\n    \n    Args:\n    text (str): The text from which to extract the ZIP codes.\n    \n    Returns:\n    List[str]: A list of extracted ZIP codes (empty if none found).\n    \"\"\"\n",
        "input": "",
        "output": "    zip_code_pattern = r\"\\b\\d{5}(?:-\\d{4})?\\b\"\n\n    return re.findall(zip_code_pattern, text)\n\n",
        "idx": "301"
    },
    {
        "instruction": "## uscodekit/services/naics.py\nimport os\n\nfrom functools import lru_cache\n\nfrom typing import List, Optional, Dict\n\nfrom uscodekit.configs import NAICS2022Config, Config\n\nfrom uscodekit.shared.jsonfile import decrypt\n\nclass NAICS2022Service:\n\n    def __init__(self):\n        if os.path.isfile(Config.encryption_key_fp) and os.path.isfile(\n            NAICS2022Config.encrypted_database_fp\n        ):\n            self.data = self.search_database\n        else:\n            print(Config.file_missing_message)\n            self.data = []\n\n    @property\n    @lru_cache(maxsize=1)\n    def search_database(self) -> List[Dict]:\n        \"\"\"\n        Property that returns a cached list of dictionaries representing the search database.\n\n        This method reads data from the file path specified in the NAICS2022Config.search_data_fp\n        and caches the result to improve performance on subsequent accesses.\n\n        Returns:\n            list[dict]: A list of dictionaries containing the search database data.\n        \"\"\"\n\n        if os.path.isfile(Config.encryption_key_fp) and os.path.isfile(\n            NAICS2022Config.encrypted_database_fp\n        ):\n            return decrypt(NAICS2022Config.encrypted_database_fp)\n        else:\n            print(Config.file_missing_message)\n            return []\n\n    def get(self, code: str) -> Optional[Dict]:\n        \"\"\"\n        Retrieve a dictionary from the search database that matches the given code.\n\n        Args:\n            code (str): The code to search for in the database.\n\n        Returns:\n            dict | None: The dictionary that matches the given code if found, otherwise None.\n        \"\"\"\n        res = list(filter(lambda x: x[\"code\"] == code, self.data))\n        return res[0] if res else None\n\n    def industry_name(self, code: str) -> Optional[str]:\n        \"\"\"\n        Retrieve the industry name from the search database that matches the given code.\n\n        Args:\n            code (str): The code to search for in the database.\n\n        Returns:\n            dict | None: The dictionary that matches the given code if found, otherwise None.\n        \"\"\"\n        try:\n            return self.get(code)[\"title\"]\n        except Exception as e:\n            return None\n\n    def search(self, query: str, top_n: int = 10) -> List[Dict]:\n        \"\"\"\n        Searches the database for matches on both 'code' and 'title' fields,\n        prioritizing exact matches, prefix matches, and then partial matches.\n\n        Parameters:\n            query (str): The search query to match against both 'code' and 'title'.\n\n        Returns:\n            list: A sorted list of dictionaries matching the query, ranked by relevance.\n\n        Example:\n        >>> search('Public Finance') =>\n        [\n            {'code': '92113', 'title': 'Public Finance Activities'},\n            {'code': '921130', 'title': 'Public Finance Activities'}\n        ]\n        \"\"\"\n        # Normalize the query\n        query = query.strip().lower()\n\n        # Define scoring criteria\n        results = []\n\n        for entry in self.data:\n            code = entry[\"code\"]\n            title = entry[\"title\"].lower()\n\n            # Initialize relevance score\n            relevance_score = 0\n\n            # Check for exact matches in code or title (highest relevance)\n            if query == code or query == title:\n                relevance_score = 3\n            # Check for prefix match in code (high relevance)\n            elif code.startswith(query):\n                relevance_score = 2\n            # Check for partial match in title (medium relevance)\n            elif query in title:\n                relevance_score = 1\n\n            # If there's a match, add to results with relevance score\n            if relevance_score > 0:\n                results.append((relevance_score, entry))\n\n        # Sort results by relevance score in descending order\n        results.sort(key=lambda x: x[0], reverse=True)\n\n        # Return only the matched entries, without scores\n        return [entry for _, entry in results[:top_n]]\n\n    def industry_hierarchy(self, code: str) -> Optional[Dict]:\n        \"\"\"\n        Generates a hierarchical representation of NAICS code data based on the given code,\n        handling different lengths (2, 3, 4, 5, or 6 digits).\n    \n        Parameters:\n        code (str): The NAICS code for which to generate the hierarchy.\n    \n        Returns:\n        dict: A hierarchical dictionary with details up to the specified code length.\n        \"\"\"\n",
        "input": "",
        "output": "        rec = self.get(code)\n        if rec is None:\n            return None\n\n        # Initialize the hierarchy dictionary\n        hierarchy = {\n            \"sector\": None,\n            \"subsector\": None,\n            \"industry_group\": None,\n            \"naics_industry\": None,\n            \"national_industry\": None,\n        }\n\n        # Determine hierarchy based on the length of the code\n        if len(code) >= 2:\n            hierarchy[\"sector\"] = self.get(code[:2])\n        if len(code) >= 3:\n            hierarchy[\"subsector\"] = self.get(code[:3])\n        if len(code) >= 4:\n            hierarchy[\"industry_group\"] = self.get(code[:4])\n        if len(code) >= 5:\n            hierarchy[\"naics_industry\"] = self.get(code[:5])\n        if len(code) == 6:\n            hierarchy[\"national_industry\"] = self.get(code)\n\n        # Build the final record with available levels\n        record = {\n            \"code\": code,\n            \"title\": rec.get(\"title\"),\n            \"sector\": hierarchy[\"sector\"],\n            \"subsector\": hierarchy[\"subsector\"],\n            \"industry_group\": hierarchy[\"industry_group\"],\n            \"naics_industry\": hierarchy[\"naics_industry\"],\n            \"national_industry\": hierarchy[\"national_industry\"],\n        }\n\n        # Remove None entries for levels not included based on code length\n        return {k: v for k, v in record.items() if v is not None}\n    \n",
        "idx": "305"
    },
    {
        "instruction": "## item_manager.py\nfrom typing import Dict, List, Optional, Set, Tuple\n\nimport logging\n\nimport config\n\nclass ItemManager:\n    def __init__(self):\n        self.inventory: List[str] = []\n        self.newspaper_pieces: int = config.INITIAL_GAME_STATE.get(\"newspaper_pieces\", 0)\n        self.discovered_combinations: Set[str] = set()\n        self.removed_items: Set[str] = set()\n           \n             \n    def take_item(self, item: str, location_items: List[str], game_state: Dict) -> bool:\n        \"\"\"Pick up an item from the current location.\"\"\"\n        try:\n            if item not in location_items:\n                print(f\"There is no {item} here.\")\n                return False\n        \n            self.inventory.append(item)\n            self.removed_items.add(item)  # Track that this item has been removed\n        \n            # Handle special items first\n            if item == \"badge\":\n                game_state[\"has_badge\"] = True\n                print(\"You clip the badge to your belt. Its familiar weight is reassuring.\")\n                logging.info(\"Badge taken and has_badge state set to True\")\n                return True\n            \n            # Then handle newspaper pieces\n            if item.startswith(\"newspaper_piece_\"):\n                self.newspaper_pieces += 1\n                print(f\"You've found piece {self.newspaper_pieces} of 8 of the newspaper story.\")\n                if self.newspaper_pieces == 8:\n                    game_state[\"found_all_newspaper_pieces\"] = True\n                    print(\"\\nYou've collected all newspaper pieces!\")\n                    self.show_newspaper_story()\n                return True\n            \n            # Generic message for all other items\n            print(f\"You take the {item}.\")\n            return True\n        \n        except Exception as e:\n            logging.error(f\"Error taking item {item}: {e}\")\n            print(\"There was a problem picking up the item.\")\n            return False\n       \n    def examine_item(self, item: str, location_items: List[str], game_state: Dict) -> None:\n        \"\"\"Examine an item in inventory or in the current location.\"\"\"\n        try:\n            if item in self.inventory:\n                if item in config.ITEM_DESCRIPTIONS:\n                    print(\"\\n\" + config.ITEM_DESCRIPTIONS[item][\"detailed\"])\n                    if item == \"wallet\" and not game_state.get(\"discovered_clue\", False):\n                        game_state[\"discovered_clue\"] = True\n                        print(\"\\nThe business card seems suspicious. This could be a valuable lead.\")\n                    elif item == \"coded_message\" and not game_state.get(\"examined_code\", False):\n                        game_state[\"examined_code\"] = True\n                        print(\"\\nThe code looks like it might be decipherable with the right tools...\")\n                else:\n                    print(f\"You examine the {item} closely but find nothing unusual.\")\n            elif item in location_items:\n                print(f\"You'll need to take the {item} first to examine it closely.\")\n            else:\n                print(f\"You don't see any {item} here.\")\n            \n        except Exception as e:\n            logging.error(f\"Error examining item {item}: {e}\")\n            print(\"There was a problem examining the item.\")\n\n    def use_item(self, item: str, current_location: str, game_state: Dict) -> None:\n        \"\"\"Use an item from the inventory.\"\"\"\n        try:\n            if item not in self.inventory:\n                print(\"You don't have that item.\")\n                return\n           \n            item_data = config.ITEM_DESCRIPTIONS.get(item, {})\n            use_effects = item_data.get(\"use_effects\", {})\n            valid_locations = item_data.get(\"use_locations\", [])\n       \n            if current_location in use_effects or (\"all\" in use_effects and current_location in valid_locations):\n                effect = use_effects.get(current_location, use_effects.get(\"all\"))\n                print(\"\\n\" + effect)\n           \n                if item_data.get(\"consumable\", False):\n                    self.inventory.remove(item)\n                    print(f\"You no longer have the {item}.\")\n           \n                self._handle_special_item_effects(item, current_location, game_state)\n            else:\n                print(f\"You can't use the {item} here effectively.\")\n           \n        except Exception as e:\n            logging.error(f\"Error using item {item}: {e}\")\n            print(\"There was a problem using the item.\")\n\n    def _handle_special_item_effects(self, item: str, location: str, game_state: Dict) -> None:\n        \"\"\"\n        Handle special effects when using certain items in specific locations.\n        \"\"\"\n",
        "input": "",
        "output": "        try:\n            special_effects = {\n                (\"badge\", \"smith_tower\"): lambda: game_state.update({\"has_badge_shown\": True}),\n                (\"binoculars\", \"observation_deck\"): lambda: game_state.update({\"observed_suspicious_activity\": True}),\n                (\"old_key\", \"suspicious_warehouse\"): lambda: game_state.update({\"warehouse_unlocked\": True}),\n                (\"radio_manual\", \"warehouse_office\"): lambda: game_state.update({\"understood_radio\": True})\n        }\n       \n            effect = special_effects.get((item, location))\n            if effect:\n                effect()\n           \n        except Exception as e:\n            logging.error(f\"Error handling special effect for {item} at {location}: {e}\")\n    \n",
        "idx": "311"
    },
    {
        "instruction": "## input_validator.py\nfrom typing import Set, Dict, Optional, Any\n\nimport logging\n\nclass InputValidator:\n    \"\"\"Centralized input validation functionality.\"\"\"\n    \n    def __init__(self):\n        self.logger = logging.getLogger(__name__)\n    \n    @staticmethod\n    def validate_puzzle_input(input_str: str, \n                            valid_chars: str = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\",\n                            min_length: int = 1,\n                            max_length: int = 50) -> bool:\n        \"\"\"\n        Validate input string for puzzles.\n        \n        Args:\n            input_str: Input to validate\n            valid_chars: String of allowed characters\n            min_length: Minimum input length\n            max_length: Maximum input length\n            \n        Returns:\n            bool: True if input is valid\n        \"\"\"\n        if not input_str:\n            return False\n            \n        if not min_length <= len(input_str) <= max_length:\n            return False\n            \n        return all(char in valid_chars for char in input_str.upper())\n    \n    @staticmethod\n    def validate_direction(direction: str, valid_directions: Set[str]) -> bool:\n        \"\"\"\n        Validate movement direction.\n        \n        Args:\n            direction: Direction to validate\n            valid_directions: Set of valid directions\n            \n        Returns:\n            bool: True if direction is valid\n        \"\"\"\n        return direction.lower().strip() in {d.lower() for d in valid_directions}\n    \n    @staticmethod\n    def validate_command(command: str, valid_commands: Set[str]) -> bool:\n        \"\"\"\n        Validate game command.\n        \n        Args:\n            command: Command to validate\n            valid_commands: Set of valid commands\n            \n        Returns:\n            bool: True if command is valid\n        \"\"\"\n        return command.lower().strip() in valid_commands\n    \n    @staticmethod\n    def validate_item_name(item: str, max_length: int=50) -> bool:\n        \"\"\"\n        Validate item name.\n    \n        Args:\n        item: Item name to validate\n        max_length: Maximum allowed length\n    \n        Returns:\n        bool: True if item name is valid\n        \"\"\"\n",
        "input": "",
        "output": "        if not item or not isinstance(item, str):\n            return False\n            \n        if len(item) > max_length:\n            return False\n            \n        return item.replace('_', '').isalnum()\n    \n",
        "idx": "312"
    },
    {
        "instruction": "# Here are some relevant code fragments from other files of the repo:\n# --------------------------------------------------\n# the below code fragment can be found in:\n# puzzles/base_puzzle.py\n# --------------------------------------------------\n# from abc import ABC, abstractmethod\n# \n# from typing import Dict, List, Optional, Any\n# \n# import logging\n# \n# from contextlib import contextmanager\n# \n# class BasePuzzle(ABC):\n#     \"\"\"Abstract base class for all puzzles.\"\"\"\n#     \n#     def __init__(self):\n#         self.logger = logging.getLogger(self.__class__.__name__)\n#         self.attempts = 0\n#         self.max_attempts = 5  # Default value, can be overridden\n#         self.solved = False\n# \n#     @abstractmethod\n#     def solve(self, inventory: List[str], game_state: Dict) -> bool:\n#         \"\"\"\n#         Attempt to solve the puzzle.\n#         \n#         Args:\n#             inventory: List of items the player has\n#             game_state: Current game state dictionary\n#             \n#         Returns:\n#             bool: True if puzzle was solved, False otherwise\n#         \"\"\"\n#         pass\n#     \n#     @abstractmethod\n#     def get_state(self) -> Dict:\n#         \"\"\"\n#         Get current puzzle state for saving.\n#         \n#         Returns:\n#             Dict containing the puzzle's current state\n#         \"\"\"\n#         return {\n#             \"attempts\": self.attempts,\n#             \"max_attempts\": self.max_attempts,\n#             \"solved\": self.solved,\n#             # Add any additional common state here\n#         }\n#     \n#     @abstractmethod\n#     def restore_state(self, state: Dict) -> None:\n#         \"\"\"\n#         Restore puzzle state from saved game.\n#         \n#         Args:\n#             state: Dictionary containing puzzle state\n#         \"\"\"\n#         self.attempts = state.get(\"attempts\", 0)\n#         self.max_attempts = state.get(\"max_attempts\", 5)\n#         self.solved = state.get(\"solved\", False)\n#     \n#     @property\n#     @abstractmethod\n#     def requirements(self) -> List[str]:\n#         \"\"\"Required items for this puzzle.\"\"\"\n#         pass\n#     \n#     def validate_input(self, user_input: str, \n#                       valid_chars: str = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\") -> bool:\n#         \"\"\"\n#         Validate user input.\n#         \n#         Args:\n#             user_input: String to validate\n#             valid_chars: String of valid characters\n#             \n#         Returns:\n#             bool: True if input is valid\n#         \"\"\"\n#         if not user_input:\n#             return False\n#         return all(char in valid_chars for char in user_input.upper())\n#     @contextmanager\n#     def error_handler(self, operation: str):\n#         \"\"\"\n#         Context manager for standardized error handling.\n#         \n#         Args:\n#             operation: Name of the operation being performed\n#             \n#         Yields:\n#             None\n#         \"\"\"\n#         try:\n#             yield\n#         except Exception as e:\n#             self.logger.error(f\"Error in {operation}: {e}\")\n#             print(f\"\\nThere was a problem with {operation}. Please try again.\")\n#     \n#     def increment_attempts(self) -> bool:\n#         \"\"\"\n#         Increment attempt counter and check if max attempts reached.\n#         \n#         Returns:\n#             bool: True if more attempts available, False if max reached\n#         \"\"\"\n#         self.attempts += 1\n#         remaining = self.max_attempts - self.attempts\n#         \n#         if remaining <= 0:\n#             print(\"\\nYou've run out of attempts. Try again later.\")\n#             return False\n#             \n#         print(f\"\\n{remaining} attempts remaining.\")\n#         return True\n#     \n#     def reset_attempts(self) -> None:\n#         \"\"\"Reset attempt counter.\"\"\"\n#         self.attempts = 0\n# \n# --------------------------------------------------\n# the below code fragment can be found in:\n# utils.py\n# --------------------------------------------------\n# import os\n# \n# import sys\n# \n# import time\n# \n# import logging\n# \n# import shutil\n# \n# import textwrap\n# \n# from typing import Tuple, Optional, Dict, Any, List\n# \n# import config\n# \n# class DisplayManager:\n#     \"\"\"Handles all display-related functionality in a centralized way.\"\"\"\n#     \n#     @staticmethod\n#     def get_terminal_size() -> tuple[int, int]:\n#         \"\"\"Get current terminal size with fallback values.\"\"\"\n#         try:\n#             width, height = shutil.get_terminal_size()\n#             width = max(config.MIN_TERMINAL_WIDTH, \n#                        min(width, config.MAX_TERMINAL_WIDTH))\n#             return width, height\n#         except Exception:\n#             return config.DEFAULT_TERMINAL_WIDTH, config.DEFAULT_TERMINAL_HEIGHT\n#     \n#     @staticmethod\n#     def wrap_text(text: str, width: Optional[int] = None, indent: int = 0) -> str:\n#         \"\"\"Wrap text to fit terminal width with proper indentation.\"\"\"\n#         if width is None:\n#             width, _ = DisplayManager.get_terminal_size()\n#         \n#         # Adjust width for indent\n#         effective_width = width - indent\n#         \n#         # Split into paragraphs\n#         paragraphs = [p.strip() for p in text.strip().split('\\n\\n')]\n#         wrapped_paragraphs = []\n#         \n#         for paragraph in paragraphs:\n#             # Normalize spaces\n#             paragraph = ' '.join(paragraph.split())\n#             \n#             # Wrap the paragraph\n#             wrapped = textwrap.fill(\n#                 paragraph,\n#                 width=effective_width,\n#                 expand_tabs=True,\n#                 replace_whitespace=True,\n#                 break_long_words=False,\n#                 break_on_hyphens=True,\n#                 initial_indent=' ' * indent,\n#                 subsequent_indent=' ' * indent\n#             )\n#             \n#             wrapped_paragraphs.append(wrapped)\n#         \n#         return '\\n\\n'.join(wrapped_paragraphs)\n#     \n#     @staticmethod\n#     def print_text(text: str, delay: Optional[float] = None, \n#                   indent: int = 0, wrap: bool = True) -> None:\n#         \"\"\"\n#         Print text with optional wrapping and slow printing effect.\n#         \n#         Args:\n#             text: Text to display\n#             delay: Delay between characters for slow printing\n#             indent: Number of spaces to indent text\n#             wrap: Whether to wrap text to terminal width\n#         \"\"\"\n#         try:\n#             # Prepare the text\n#             display_text = DisplayManager.wrap_text(text, indent=indent) if wrap else text\n#             \n#             # Print with or without delay\n#             if delay:\n#                 for char in display_text:\n#                     sys.stdout.write(char)\n#                     sys.stdout.flush()\n#                     time.sleep(delay)\n#                 print()  # Add final newline\n#             else:\n#                 print(display_text)\n#                 \n#         except KeyboardInterrupt:\n#             print(\"\\nDisplay interrupted.\")\n#         except Exception as e:\n#             logging.error(f\"Error displaying text: {e}\")\n#             print(\"\\nError displaying text.\")\n#     \n#     @staticmethod\n#     def clear_screen() -> None:\n#         \"\"\"Clear the terminal screen.\"\"\"\n#         try:\n#             # Check if running in IDLE\n#             if 'idlelib.run' in sys.modules:\n#                 print(\"\\n\" * 100)\n#                 return\n#             \n#             # Use appropriate clear command based on OS\n#             os.system('cls' if os.name == 'nt' else 'clear')\n#         except Exception as e:\n#             logging.error(f\"Error clearing screen: {e}\")\n#             print(\"\\n\" * 100)  # Fallback\n#     \n#     @staticmethod\n#     def format_location_description(description: str, \n#                                   exits: list[str], \n#                                   items: list[str]) -> str:\n#         \"\"\"Format a location description with exits and items.\"\"\"\n#         try:\n#             if not description:\n#                 raise ValueError(\"Invalid description\")\n#             \n#             formatted = description.strip()\n#             \n#             if exits:\n#                 formatted += f\"\\n\\nExits: {', '.join(exits)}\"\n#             \n#             if items:\n#                 formatted += f\"\\n\\nYou can see: {', '.join(items)}\"\n#             \n#             return formatted\n#             \n#         except Exception as e:\n#             logging.error(f\"Error formatting location description: {e}\")\n#             return description\n# \n# def print_text(text: str, delay: Optional[float] = None, \n#               indent: int = 0, wrap: bool = True) -> None:\n#     \"\"\"Print text using DisplayManager.\"\"\"\n#     DisplayManager.print_text(text, delay, indent, wrap)\n# \n# --------------------------------------------------\n\n\n## puzzles/radio_puzzle.py\nfrom typing import Dict, List, Set, Tuple\n\nimport random\n\nfrom .base_puzzle import BasePuzzle\n\nfrom utils import print_text\n\nclass RadioPuzzle(BasePuzzle):\n    \"\"\"\n    Enhanced radio frequency puzzle implementation.\n    Players must tune to correct frequencies to intercept suspicious transmissions.\n    \"\"\"\n\n    def __init__(self):\n        # Initialize base puzzle features\n        super().__init__()\n        \n        # Define frequency ranges for different radio bands\n        self.RADIO_RANGES = {\n            \"emergency\": (1400, 1500),\n            \"police\": (1200, 1300),\n            \"civilian\": (1000, 1100)\n        }\n        \n        # Define possible messages for each band\n        self.RADIO_MESSAGES = {\n            \"emergency\": [\n                (\"...urgent shipment tonight... dock 7... look for red star...\",\n                 \"Emergency broadcast about suspicious shipment\"),\n                (\"...medical supplies... warehouse district... midnight...\",\n                 \"Emergency alert about medical supplies\"),\n            ],\n            \"police\": [\n                (\"...patrol units report to waterfront... suspicious activity...\",\n                 \"Police dispatch about waterfront\"),\n                (\"...all units... warehouse district... maintain surveillance...\",\n                 \"Police alert about warehouse\"),\n            ],\n            \"civilian\": [\n                (\"...weather forecast: heavy rain expected... port closing early...\",\n                 \"Civilian broadcast about weather\"),\n                (\"...dock workers union meeting... discussing night shifts...\",\n                 \"Civilian broadcast about dock workers\"),\n            ]\n        }\n        \n        # Puzzle state variables\n        self.active_frequencies = self._generate_frequencies()\n        self.found_frequencies: Set[str] = set()\n        \n        # Override base puzzle settings\n        self.max_attempts = 8  # More attempts for this puzzle due to its nature\n\n    @property\n    def requirements(self) -> List[str]:\n        \"\"\"Required items for this puzzle.\"\"\"\n        return [\"radio_manual\"]\n\n    def _generate_frequencies(self) -> Dict[str, Tuple[int, str]]:\n        \"\"\"\n        Generate random target frequencies within each range with messages.\n        Each band gets a random frequency and message.\n        \"\"\"\n",
        "input": "",
        "output": "        active = {}\n        with self.error_handler(\"frequency generation\"):\n            for band, (min_freq, max_freq) in self.RADIO_RANGES.items():\n                frequency = random.randint(min_freq, max_freq)\n                message, _ = random.choice(self.RADIO_MESSAGES[band])\n                active[band] = (frequency, message)\n            return active\n    \n",
        "idx": "314"
    },
    {
        "instruction": "## input_validator.py\nfrom typing import Set, Dict, Optional, Any\n\nimport logging\n\nclass InputValidator:\n    \"\"\"Centralized input validation functionality.\"\"\"\n    \n    def __init__(self):\n        self.logger = logging.getLogger(__name__)\n    \n    @staticmethod\n    def validate_puzzle_input(input_str: str, valid_chars: str='ABCDEFGHIJKLMNOPQRSTUVWXYZ', min_length: int=1, max_length: int=50) -> bool:\n        \"\"\"\n                            Validate input string for puzzles.\n                        \n                            Args:\n                            input_str: Input to validate\n                            valid_chars: String of allowed characters\n                            min_length: Minimum input length\n                            max_length: Maximum input length\n                        \n                            Returns:\n                            bool: True if input is valid\n                            \"\"\"\n",
        "input": "",
        "output": "        if not input_str:\n            return False\n            \n        if not min_length <= len(input_str) <= max_length:\n            return False\n            \n        return all(char in valid_chars for char in input_str.upper())\n    \n",
        "idx": "317"
    },
    {
        "instruction": "## puzzles/base_puzzle.py\nfrom abc import ABC, abstractmethod\n\nfrom typing import Dict, List, Optional, Any\n\nimport logging\n\nfrom contextlib import contextmanager\n\nclass BasePuzzle(ABC):\n    \"\"\"Abstract base class for all puzzles.\"\"\"\n    \n    def __init__(self):\n        self.logger = logging.getLogger(self.__class__.__name__)\n        self.attempts = 0\n        self.max_attempts = 5  # Default value, can be overridden\n        self.solved = False\n\n    @abstractmethod\n    def solve(self, inventory: List[str], game_state: Dict) -> bool:\n        \"\"\"\n        Attempt to solve the puzzle.\n        \n        Args:\n            inventory: List of items the player has\n            game_state: Current game state dictionary\n            \n        Returns:\n            bool: True if puzzle was solved, False otherwise\n        \"\"\"\n        pass\n    \n    @abstractmethod\n    def get_state(self) -> Dict:\n        \"\"\"\n        Get current puzzle state for saving.\n        \n        Returns:\n            Dict containing the puzzle's current state\n        \"\"\"\n        return {\n            \"attempts\": self.attempts,\n            \"max_attempts\": self.max_attempts,\n            \"solved\": self.solved,\n            # Add any additional common state here\n        }\n    \n    @abstractmethod\n    def restore_state(self, state: Dict) -> None:\n        \"\"\"\n        Restore puzzle state from saved game.\n        \n        Args:\n            state: Dictionary containing puzzle state\n        \"\"\"\n        self.attempts = state.get(\"attempts\", 0)\n        self.max_attempts = state.get(\"max_attempts\", 5)\n        self.solved = state.get(\"solved\", False)\n    \n    @property\n    @abstractmethod\n    def requirements(self) -> List[str]:\n        \"\"\"Required items for this puzzle.\"\"\"\n        pass\n    \n    def validate_input(self, user_input: str, valid_chars: str='ABCDEFGHIJKLMNOPQRSTUVWXYZ') -> bool:\n        \"\"\"\n                      Validate user input.\n                  \n                      Args:\n                      user_input: String to validate\n                      valid_chars: String of valid characters\n                  \n                      Returns:\n                      bool: True if input is valid\n                      \"\"\"\n",
        "input": "",
        "output": "        if not user_input:\n            return False\n        return all(char in valid_chars for char in user_input.upper())\n    \n",
        "idx": "318"
    },
    {
        "instruction": "## utils.py\nimport os\n\nimport sys\n\nimport time\n\nimport logging\n\nimport shutil\n\nimport textwrap\n\nfrom typing import Tuple, Optional, Dict, Any, List\n\nimport config\n\nclass DisplayManager:\n    \"\"\"Handles all display-related functionality in a centralized way.\"\"\"\n    \n    @staticmethod\n    def get_terminal_size() -> tuple[int, int]:\n        \"\"\"Get current terminal size with fallback values.\"\"\"\n        try:\n            width, height = shutil.get_terminal_size()\n            width = max(config.MIN_TERMINAL_WIDTH, \n                       min(width, config.MAX_TERMINAL_WIDTH))\n            return width, height\n        except Exception:\n            return config.DEFAULT_TERMINAL_WIDTH, config.DEFAULT_TERMINAL_HEIGHT\n    \n    @staticmethod\n    def wrap_text(text: str, width: Optional[int]=None, indent: int=0) -> str:\n        \"\"\"\n        Wrap text to fit terminal width with proper indentation.\n        \"\"\"\n",
        "input": "",
        "output": "        if width is None:\n            width, _ = DisplayManager.get_terminal_size()\n        \n        # Adjust width for indent\n        effective_width = width - indent\n        \n        # Split into paragraphs\n        paragraphs = [p.strip() for p in text.strip().split('\\n\\n')]\n        wrapped_paragraphs = []\n        \n        for paragraph in paragraphs:\n            # Normalize spaces\n            paragraph = ' '.join(paragraph.split())\n            \n            # Wrap the paragraph\n            wrapped = textwrap.fill(\n                paragraph,\n                width=effective_width,\n                expand_tabs=True,\n                replace_whitespace=True,\n                break_long_words=False,\n                break_on_hyphens=True,\n                initial_indent=' ' * indent,\n                subsequent_indent=' ' * indent\n            )\n            \n            wrapped_paragraphs.append(wrapped)\n        \n        return '\\n\\n'.join(wrapped_paragraphs)\n    \n",
        "idx": "319"
    },
    {
        "instruction": "## utils.py\nimport os\n\nimport sys\n\nimport time\n\nimport logging\n\nimport shutil\n\nimport textwrap\n\nfrom typing import Tuple, Optional, Dict, Any, List\n\nimport config\n\nclass DisplayManager:\n    \"\"\"Handles all display-related functionality in a centralized way.\"\"\"\n    \n    @staticmethod\n    def get_terminal_size() -> tuple[int, int]:\n        \"\"\"\n        Get current terminal size with fallback values.\n        \"\"\"\n",
        "input": "",
        "output": "        try:\n            width, height = shutil.get_terminal_size()\n            width = max(config.MIN_TERMINAL_WIDTH, \n                       min(width, config.MAX_TERMINAL_WIDTH))\n            return width, height\n        except Exception:\n            return config.DEFAULT_TERMINAL_WIDTH, config.DEFAULT_TERMINAL_HEIGHT\n    \n",
        "idx": "322"
    },
    {
        "instruction": "## sync/callback_func.py\nimport pandas as pd\n\nimport numpy as np\n\ndef trans_table_to_json(__data: pd.DataFrame) -> dict:\n    \"\"\"\n    \u5c06\u8868\u683c\u8f6c\u6362\u6210\u5b57\u5178\n    \"\"\"\n",
        "input": "",
        "output": "    __data.replace({pd.NaT: None, np.nan: None}, inplace=True)\n    return __data.to_dict(orient='records')\n\n",
        "idx": "324"
    },
    {
        "instruction": "\ndef compose(f, g):\n    \"\"\"\n    \u62fc\u63a5\u51fd\u6570\n    \"\"\"\n",
        "input": "",
        "output": "    def h(x):\n        return f(g(x))\n    return h\n\n",
        "idx": "325"
    },
    {
        "instruction": "## scheduler/general.py\nimport os\n\nimport toml\n\nimport pymongo\n\nimport datetime\n\nCONNECT_CONFIG = toml.load(os.path.join(os.path.dirname(os.path.abspath(__file__)), \"..\", \"source\", \"config\", \"connect.toml\"))[\"\u6570\u636e\u5904\u7406\u670d\u52a1\u5b58\u50a8\"]\n\nurl = \"mongodb://\" + CONNECT_CONFIG[\"ip\"] + \":\" + str(CONNECT_CONFIG[\"port\"])\n\nMONGO_CLIENT = pymongo.MongoClient(url)\n\nclass pipeline:\n    '''\u7ba1\u9053\u7684\u62bd\u8c61\uff0c\u8d1f\u8d23\u53d1\u9001\u548c\u7ef4\u62a4\u5728mongo\u4e2d\u5b9e\u73b0\u7684\u6d88\u606f\u961f\u5217'''\n    def __init__(self) -> None:\n        database = MONGO_CLIENT[\"public\"]\n        coll_list = database.list_collection_names()\n        if \"mq_send\" not in coll_list:\n            self.coll_send = database.create_collection(\"mq_send\")\n        else:\n            self.coll_send = database[\"mq_send\"]\n        if \"mq_recv\" not in coll_list:\n            self.coll_recv = database.create_collection(\"mq_recv\")\n        else:\n            self.coll_recv = database[\"mq_recv\"]\n            \n    def send(self, node_name: str) -> None:\n        self.coll_send.insert_one({\n            \"timestamp\": datetime.datetime.now(),\n            \"node_name\": node_name,\n            \"is_process\": False\n        })\n        \n    def clean_send_history(self, request_time: datetime.datetime) -> int:\n        '''\u6e05\u9664\u5bf9\u5e94\u65f6\u95f4\u4e4b\u524d\u7684\u6d88\u606f'''\n        return self.coll_send.delete_many({'timestamp': {'$lt': request_time}}).deleted_count\n        \n    def clean_recv_history(self, request_time: datetime.datetime) -> int:\n        '''\u6e05\u9664\u5bf9\u5e94\u65f6\u95f4\u4e4b\u524d\u7684\u6d88\u606f'''\n        return self.coll_recv.delete_many({'timestamp': {'$lt': request_time}}).deleted_count\n    \n    def recv(self, node_name: str) -> list:\n        \"\"\"\n        \u83b7\u53d6\u5bf9\u5e94\u8282\u70b9\u7684\u6d88\u606f\n        \"\"\"\n",
        "input": "",
        "output": "        temp_doc_list = self.coll_recv.find({\"node_name\": node_name, \"is_process\":False}).to_list()\n        for tdoc in temp_doc_list:\n            self.coll_recv.update_one({\"_id\":tdoc[\"_id\"]}, {\"$set\": {\"is_process\":True}})\n        return temp_doc_list\n    \n",
        "idx": "326"
    },
    {
        "instruction": "\ndef extract_coords(coords):\n    \"\"\"\n    Convert coordinates from string format to row and column indices.\n    \"\"\"\n",
        "input": "",
        "output": "    row = int(coords[1]) - 1\n    col = ord(coords[0].upper()) - 65\n    return row, col\n\n",
        "idx": "330"
    },
    {
        "instruction": "## server.py\nimport logging\n\nclass GameServer:\n    def __init__(self):\n        self.players = {}  # Stores player boards and hits\n        self.turn = None  # Tracks whose turn it is\n        self.game_over = False  # Indicates if the game is over\n\n    def register_player(self, player_name, board_data):\n        \"\"\"Registers a new player with their board.\"\"\"\n        if player_name in self.players:\n            logging.warning(f\"Player {player_name} already registered.\")\n            return \"Player already registered.\"\n\n        if len(self.players) >= 2:\n            logging.warning(f\"Player {player_name} failed to register. Game is full.\")\n            return \"Game is already full.\"\n\n        self.players[player_name] = {\"board\": board_data, \"hits\": 0}\n        logging.info(f\"Player {player_name} successfully registered.\")\n\n        # Assign the first turn to the first player\n        if len(self.players) == 1:\n            self.turn = player_name\n            logging.info(f\"Player {player_name} gets the first turn.\")\n\n        return \"Player registered successfully.\"\n\n    def is_game_ready(self):\n        \"\"\"\n        Checks if the game has two players ready to play.\n        \"\"\"\n",
        "input": "",
        "output": "        is_ready = len(self.players) == 2\n        logging.info(f\"Game ready status: {is_ready}\")\n        return is_ready\n    \n",
        "idx": "332"
    },
    {
        "instruction": "## server.py\nimport logging\n\nclass GameServer:\n    def __init__(self):\n        self.players = {}  # Stores player boards and hits\n        self.turn = None  # Tracks whose turn it is\n        self.game_over = False  # Indicates if the game is over\n\n    def register_player(self, player_name, board_data):\n        \"\"\"Registers a new player with their board.\"\"\"\n        if player_name in self.players:\n            logging.warning(f\"Player {player_name} already registered.\")\n            return \"Player already registered.\"\n\n        if len(self.players) >= 2:\n            logging.warning(f\"Player {player_name} failed to register. Game is full.\")\n            return \"Game is already full.\"\n\n        self.players[player_name] = {\"board\": board_data, \"hits\": 0}\n        logging.info(f\"Player {player_name} successfully registered.\")\n\n        # Assign the first turn to the first player\n        if len(self.players) == 1:\n            self.turn = player_name\n            logging.info(f\"Player {player_name} gets the first turn.\")\n\n        return \"Player registered successfully.\"\n\n    def is_game_ready(self):\n        \"\"\"Checks if the game has two players ready to play.\"\"\"\n        is_ready = len(self.players) == 2\n        logging.info(f\"Game ready status: {is_ready}\")\n        return is_ready\n\n    def whose_turn(self):\n        \"\"\"Returns the name of the player whose turn it is.\"\"\"\n        logging.info(f\"It is {self.turn}'s turn.\")\n        return self.turn\n\n    def make_guess(self, player_name, x, y):\n        \"\"\"Handles a player's guess.\"\"\"\n        if not self.is_game_ready():\n            logging.warning(\n                f\"Player {player_name} tried to guess before the game was ready.\"\n            )\n            return \"Game is not ready yet.\"\n\n        if self.turn != player_name:\n            logging.warning(f\"Player {player_name} tried to guess out of turn.\")\n            return \"Not your turn.\"\n\n        if not (0 <= x < 5 and 0 <= y < 5):\n            logging.warning(\n                f\"Player {player_name} made an invalid guess at ({x}, {y}).\"\n            )\n            return \"Invalid move: Out of bounds.\"\n\n        opponent = self.get_opponent(player_name)\n        opponent_board = self.players[opponent][\"board\"]\n\n        if opponent_board[x][y] == \"1\":\n            opponent_board[x][y] = \"H\"  # Mark as hit\n            self.players[player_name][\"hits\"] += 1\n            self.turn = opponent  # Switch turn\n            logging.info(f\"Player {player_name} hit a ship at ({x}, {y}).\")\n            return \"Hit\"\n\n        elif opponent_board[x][y] == \"0\":\n            opponent_board[x][y] = \"M\"  # Mark as miss\n            self.turn = opponent  # Switch turn\n            logging.info(f\"Player {player_name} missed at ({x}, {y}).\")\n            return \"Miss\"\n\n        logging.warning(f\"Player {player_name} made an invalid move at ({x}, {y}).\")\n        return \"Invalid move: Position already guessed.\"\n\n    def is_game_over(self):\n        \"\"\"Checks if the game is over and declares the winner.\"\"\"\n        for player_name, data in self.players.items():\n            if data[\"hits\"] >= 9:  # Assuming 9 hits to win\n                logging.info(f\"Game over. {player_name} wins!\")\n                if self.game_over:\n                    self._reset_game()\n                self.game_over = True\n                return True\n        return False\n\n    def get_board(self, player_name):\n        \"\"\"\n        Returns the board of the given player.\n        \"\"\"\n",
        "input": "",
        "output": "        if player_name in self.players:\n            logging.info(f\"Player {player_name} requested their board.\")\n            return (self.players[player_name][\"board\"],)\n        logging.warning(\n            f\"Player {player_name} requested a board but is not registered.\"\n        )\n        return {\n            \"status\": \"error\",\n            \"message\": \"Player not found.\",\n        }\n    \n",
        "idx": "333"
    },
    {
        "instruction": "## server.py\nimport logging\n\nclass GameServer:\n    def __init__(self):\n        self.players = {}  # Stores player boards and hits\n        self.turn = None  # Tracks whose turn it is\n        self.game_over = False  # Indicates if the game is over\n\n    def register_player(self, player_name, board_data):\n        \"\"\"Registers a new player with their board.\"\"\"\n        if player_name in self.players:\n            logging.warning(f\"Player {player_name} already registered.\")\n            return \"Player already registered.\"\n\n        if len(self.players) >= 2:\n            logging.warning(f\"Player {player_name} failed to register. Game is full.\")\n            return \"Game is already full.\"\n\n        self.players[player_name] = {\"board\": board_data, \"hits\": 0}\n        logging.info(f\"Player {player_name} successfully registered.\")\n\n        # Assign the first turn to the first player\n        if len(self.players) == 1:\n            self.turn = player_name\n            logging.info(f\"Player {player_name} gets the first turn.\")\n\n        return \"Player registered successfully.\"\n\n    def is_game_ready(self):\n        \"\"\"Checks if the game has two players ready to play.\"\"\"\n        is_ready = len(self.players) == 2\n        logging.info(f\"Game ready status: {is_ready}\")\n        return is_ready\n\n    def whose_turn(self):\n        \"\"\"Returns the name of the player whose turn it is.\"\"\"\n        logging.info(f\"It is {self.turn}'s turn.\")\n        return self.turn\n\n    def make_guess(self, player_name, x, y):\n        \"\"\"Handles a player's guess.\"\"\"\n        if not self.is_game_ready():\n            logging.warning(\n                f\"Player {player_name} tried to guess before the game was ready.\"\n            )\n            return \"Game is not ready yet.\"\n\n        if self.turn != player_name:\n            logging.warning(f\"Player {player_name} tried to guess out of turn.\")\n            return \"Not your turn.\"\n\n        if not (0 <= x < 5 and 0 <= y < 5):\n            logging.warning(\n                f\"Player {player_name} made an invalid guess at ({x}, {y}).\"\n            )\n            return \"Invalid move: Out of bounds.\"\n\n        opponent = self.get_opponent(player_name)\n        opponent_board = self.players[opponent][\"board\"]\n\n        if opponent_board[x][y] == \"1\":\n            opponent_board[x][y] = \"H\"  # Mark as hit\n            self.players[player_name][\"hits\"] += 1\n            self.turn = opponent  # Switch turn\n            logging.info(f\"Player {player_name} hit a ship at ({x}, {y}).\")\n            return \"Hit\"\n\n        elif opponent_board[x][y] == \"0\":\n            opponent_board[x][y] = \"M\"  # Mark as miss\n            self.turn = opponent  # Switch turn\n            logging.info(f\"Player {player_name} missed at ({x}, {y}).\")\n            return \"Miss\"\n\n        logging.warning(f\"Player {player_name} made an invalid move at ({x}, {y}).\")\n        return \"Invalid move: Position already guessed.\"\n\n    def is_game_over(self):\n        \"\"\"Checks if the game is over and declares the winner.\"\"\"\n        for player_name, data in self.players.items():\n            if data[\"hits\"] >= 9:  # Assuming 9 hits to win\n                logging.info(f\"Game over. {player_name} wins!\")\n                if self.game_over:\n                    self._reset_game()\n                self.game_over = True\n                return True\n        return False\n\n    def get_board(self, player_name):\n        \"\"\"Returns the board of the given player.\"\"\"\n        if player_name in self.players:\n            logging.info(f\"Player {player_name} requested their board.\")\n            return (self.players[player_name][\"board\"],)\n        logging.warning(\n            f\"Player {player_name} requested a board but is not registered.\"\n        )\n        return {\n            \"status\": \"error\",\n            \"message\": \"Player not found.\",\n        }\n\n    def get_opponent(self, player_name):\n        \"\"\"Helper method to find the opponent of the given player.\"\"\"\n        return [p for p in self.players if p != player_name][0]\n\n    def _reset_game(self):\n        \"\"\"\n        Resets the game state.\n        \"\"\"\n",
        "input": "",
        "output": "        self.players = {}\n        self.turn = None\n        self.game_over = False\n        logging.info(\"Game state reset.\")\n        logging.info(\"Battleship server started and awaiting connections...\")\n    \n",
        "idx": "334"
    },
    {
        "instruction": "## simpler_whisper/whisper.py\nimport numpy as np\n\nfrom typing import Callable, List, Union\n\nfrom . import _whisper_cpp\n\nfrom dataclasses import dataclass\n\nclass WhisperToken:\n    \"\"\"A token from the Whisper model with timing and probability information.\"\"\"\n\n    id: int\n    p: float\n    t0: int  # Start time in milliseconds\n    t1: int  # End time in milliseconds\n    text: str\n\nclass WhisperSegment:\n    \"\"\"A segment of transcribed text with timing information and token details.\"\"\"\n\n    text: str\n    start: int  # Start time in milliseconds\n    end: int  # End time in milliseconds\n    tokens: List[WhisperToken]\n\nclass ThreadedWhisperModel:\n    def __init__(\n        self,\n        model_path: str,\n        callback: Callable[[int, List[WhisperSegment], bool], None],\n        use_gpu=False,\n        max_duration_sec=10.0,\n        sample_rate=16000,\n    ):\n        \"\"\"\n        Initialize a threaded Whisper model for continuous audio processing.\n\n        Args:\n            model_path (str): Path to the Whisper model file\n            use_gpu (bool): Whether to use GPU acceleration\n            max_duration_sec (float): Maximum duration in seconds before finalizing a segment\n            sample_rate (int): Audio sample rate (default: 16000)\n            callback: Function that takes three arguments:\n                     - chunk_id (int): Unique identifier for the audio chunk\n                     - segments (List[WhisperSegment]): Transcribed text for the audio chunk\n                     - is_partial (bool): Whether this is a partial result\n        \"\"\"\n        self.model = _whisper_cpp.ThreadedWhisperModel(\n            model_path, use_gpu, max_duration_sec, sample_rate\n        )\n        self._is_running = False\n        self.callback = callback\n\n    def handle_result(\n        self, chunk_id: int, segments: List[WhisperSegment], is_partial: bool\n    ):\n        if self.callback is not None:\n            self.callback(chunk_id, segments, is_partial)\n\n    def start(self, result_check_interval_ms=100):\n        \"\"\"\n        Start the processing threads with a callback for results.\n\n        Args:\n            callback: Function that takes three arguments:\n                     - chunk_id (int): Unique identifier for the audio chunk\n                     - segments (WhisperSegment): Transcribed text for the audio chunk\n                     - is_partial (bool): Whether this is a partial result\n            result_check_interval_ms (int): How often to check for results\n        \"\"\"\n        if self._is_running:\n            return\n\n        self.model.start(self.handle_result, result_check_interval_ms)\n        self._is_running = True\n\n    def stop(self):\n        \"\"\"\n        Stop processing and clean up resources.\n        Any remaining audio will be processed as a final segment.\n        \"\"\"\n",
        "input": "",
        "output": "        if not self._is_running:\n            return\n\n        self.model.stop()\n        self._is_running = False\n    \n",
        "idx": "342"
    },
    {
        "instruction": "## simpler_whisper/whisper.py\nimport numpy as np\n\nfrom typing import Callable, List, Union\n\nfrom . import _whisper_cpp\n\nfrom dataclasses import dataclass\n\nclass WhisperToken:\n    \"\"\"A token from the Whisper model with timing and probability information.\"\"\"\n\n    id: int\n    p: float\n    t0: int  # Start time in milliseconds\n    t1: int  # End time in milliseconds\n    text: str\n\nclass WhisperSegment:\n    \"\"\"A segment of transcribed text with timing information and token details.\"\"\"\n\n    text: str\n    start: int  # Start time in milliseconds\n    end: int  # End time in milliseconds\n    tokens: List[WhisperToken]\n\nclass ThreadedWhisperModel:\n    def __init__(\n        self,\n        model_path: str,\n        callback: Callable[[int, List[WhisperSegment], bool], None],\n        use_gpu=False,\n        max_duration_sec=10.0,\n        sample_rate=16000,\n    ):\n        \"\"\"\n        Initialize a threaded Whisper model for continuous audio processing.\n\n        Args:\n            model_path (str): Path to the Whisper model file\n            use_gpu (bool): Whether to use GPU acceleration\n            max_duration_sec (float): Maximum duration in seconds before finalizing a segment\n            sample_rate (int): Audio sample rate (default: 16000)\n            callback: Function that takes three arguments:\n                     - chunk_id (int): Unique identifier for the audio chunk\n                     - segments (List[WhisperSegment]): Transcribed text for the audio chunk\n                     - is_partial (bool): Whether this is a partial result\n        \"\"\"\n        self.model = _whisper_cpp.ThreadedWhisperModel(\n            model_path, use_gpu, max_duration_sec, sample_rate\n        )\n        self._is_running = False\n        self.callback = callback\n\n    def handle_result(\n        self, chunk_id: int, segments: List[WhisperSegment], is_partial: bool\n    ):\n        if self.callback is not None:\n            self.callback(chunk_id, segments, is_partial)\n\n    def start(self, result_check_interval_ms=100):\n        \"\"\"\n        Start the processing threads with a callback for results.\n\n        Args:\n            callback: Function that takes three arguments:\n                     - chunk_id (int): Unique identifier for the audio chunk\n                     - segments (WhisperSegment): Transcribed text for the audio chunk\n                     - is_partial (bool): Whether this is a partial result\n            result_check_interval_ms (int): How often to check for results\n        \"\"\"\n        if self._is_running:\n            return\n\n        self.model.start(self.handle_result, result_check_interval_ms)\n        self._is_running = True\n\n    def stop(self):\n        \"\"\"\n        Stop processing and clean up resources.\n        Any remaining audio will be processed as a final segment.\n        \"\"\"\n        if not self._is_running:\n            return\n\n        self.model.stop()\n        self._is_running = False\n\n    def queue_audio(self, audio):\n        \"\"\"\n        Queue audio for processing.\n    \n        Args:\n        audio: Audio samples as numpy array or array-like object.\n        Will be converted to float32.\n    \n        Returns:\n        chunk_id (int): Unique identifier for this audio chunk\n        \"\"\"\n",
        "input": "",
        "output": "        audio = np.array(audio, dtype=np.float32)\n        return self.model.queue_audio(audio)\n    \n",
        "idx": "343"
    },
    {
        "instruction": "## scrapi/rfc9290.py\nimport cbor2\n\nDEFINED_FIELDS = {\n    \"title\": -1,\n    \"detail\": -2,\n    \"instance\": -3,\n    \"response-code\": -4,\n    \"base-uri\": -5,\n    \"base-lang\": -6,\n    \"base-rtl\": -7,\n}\n\ndef encode_problem_details(data):\n    \"\"\"\n    Encodes a dictionary into a CBOR object according to RFC 9290 using numeric keys.\n    \n    Parameters:\n    data (dict): Dictionary containing RFC 9290 problem details.\n    \n    Returns:\n    bytes: CBOR-encoded bytes representing the problem details.\n    \"\"\"\n",
        "input": "",
        "output": "    numeric_key_data = {\n        DEFINED_FIELDS[k]: v for k, v in data.items() if k in DEFINED_FIELDS\n    }\n    return cbor2.dumps(numeric_key_data)\n\n",
        "idx": "346"
    },
    {
        "instruction": "# Here are some relevant code fragments from other files of the repo:\n# --------------------------------------------------\n# the below code fragment can be found in:\n# scrapi/scrapi_exception.py\n# --------------------------------------------------\n# class ScrapiException(Exception):\n#     \"\"\"Indicate SCRAPI-specific errors\"\"\"\n# \n# --------------------------------------------------\n# the below code fragment can be found in:\n# scrapi/scrapi_engine.py\n# --------------------------------------------------\n# from abc import ABC\n# \n# from abc import abstractmethod\n# \n# class ScrapiEngine(ABC):\n#     \"\"\"Virtual base class for all SCRAPI providers\"\"\"\n# \n#     @abstractmethod\n#     def initialized(self):\n#         \"\"\"Pure virtual. Use a derived class\"\"\"\n#         pass\n# \n#     @abstractmethod\n#     def get_configuration(self):\n#         \"\"\"Pure virtual. Use a derived class\"\"\"\n#         pass\n# \n#     @abstractmethod\n#     def register_signed_statement(self, statement):\n#         \"\"\"Pure virtual. Use a derived class\"\"\"\n#         pass\n# \n#     @abstractmethod\n#     def check_registration(self, registration_id):\n#         \"\"\"Pure virtual. Use a derived class\"\"\"\n#         pass\n# \n#     @abstractmethod\n#     def resolve_receipt(self, entry_id):\n#         \"\"\"Pure virtual. Use a derived class\"\"\"\n#         pass\n# \n#     @abstractmethod\n#     def resolve_signed_statement(self, entry_id):\n#         \"\"\"Pure virtual. Use a derived class\"\"\"\n#         pass\n# \n#     @abstractmethod\n#     def issue_signed_statement(self, statement):\n#         \"\"\"Pure virtual. Use a derived class\"\"\"\n#         pass\n# \n# --------------------------------------------------\n# the below code fragment can be found in:\n# scrapi/datatrails_engine.py\n# --------------------------------------------------\n# import logging\n# \n# from pprint import pprint\n# \n# from archivist.archivist import Archivist\n# \n# from archivist.logger import set_logger\n# \n# import cbor2\n# \n# from pycose.messages import Sign1Message\n# \n# import requests\n# \n# from scrapi_engine import ScrapiEngine\n# \n# from scrapi_exception import ScrapiException\n# \n# class DatatrailsEngine(ScrapiEngine):\n#     \"\"\"DataTrails SCRAPI Engine implementation\"\"\"\n# \n#     def __init__(self, ts_args):\n#         self._url = ts_args[\"url\"]\n#         self._client_id = ts_args[\"client_id\"]\n#         self._client_secret = ts_args[\"client_secret\"]\n# \n#         self._archivist = Archivist(self._url, (self._client_id, self._client_secret))\n#         set_logger(ts_args[\"log_level\"] or \"INFO\")\n# \n#         self._initialized = True\n# \n#     def __str__(self) -> str:\n#         return f\"DataTrails Scrapi Engine ({self._url})\"\n# \n#     def initialized(self):\n#         # TODO: need to check more status for emergent errors. Maybe send a NoOp?\n#         return self._initialized\n# \n#     def get_configuration(self):\n#         raise NotImplementedError(\"get_configuration\")\n# \n#     def register_signed_statement(self, statement):\n#         # DataTrails SDK doesn't have native SCITT support yet\n#         # but we can still use the Archivist object to look after our\n#         # authenticated connection to the server\n#         # When the SCRAPI standard settles this code will migrate to the\n#         # core DataTrails SDK\n#         headers = self._archivist._add_headers({})\n#         response = requests.post(\n#             f\"{self._url}/archivist/v1/publicscitt/entries\",\n#             data=statement,\n#             headers=headers,\n#             timeout=20000,\n#         )\n# \n#         # Three main failure modes:\n#         # - General network or API error: non-200 return\n#         # - Malformed statement or general errors will not return an operation ID\n#         # - Failure of registration policy or somesuch will return a failed operation\n#         if response.status_code != 200:\n#             logging.debug(\"%s\", str(response))\n#             raise ScrapiException(f\"Failed to register statement: {response}\")\n# \n#         # The DataTrails implementation currently returns JSON.\n#         # Fake up CBOR response here so that common code doesn't need to change\n#         return None, cbor2.dumps(response.json())\n# \n#     def check_registration(self, registration_id):\n#         logging.debug(\"checking on operation %s\", registration_id)\n#         # DataTrails SDK doesn't have native SCITT support yet\n#         # but we can still use the general robust machinery to submit\n#         # calls to the REST endpoint.\n#         # When the SCRAPI standard settles this code will migrate to the\n#         # core DataTrails SDK.\n#         # Worth using the DataTrails SDK rather than raw requests for\n#         # this one because it includes generic error handling like 429s\n#         # internally\n#         headers = headers = self._archivist._add_headers({})\n#         response = requests.get(\n#             f\"{self._url}/archivist/v1/publicscitt/operations/{registration_id}\",\n#             headers=headers,\n#             timeout=20000,\n#         )\n#         if response.status_code == 400:\n#             # Note: The Public SCITT endpoint returns 400 for Events that have not\n#             # made it across the sharing boundary yet. Bodge in a non-fatal fix\n#             # here but this needs to be made better.\n#             # We're not in any position to know if this is just running or a\n#             # permanent problem, so return 'unspecified' and let the client app\n#             # sort it out for now.\n#             logging.debug(\"Suspected temporary propagation 400 error\")\n#             return None, cbor2.dumps(\n#                 {\"operationID\": registration_id, \"status\": \"running\"}\n#             )\n# \n#         if response.status_code not in [200, 202]:\n#             logging.debug(\"FAILED to get operation status: %s\", response.status_code)\n#             return response.content, None\n# \n#         # As things stand DataTrails returns JSON. This will change in future releases.\n#         # Fake up CBOR response here so that common code doesn't need to change\n#         return None, cbor2.dumps(response.json())\n# \n#     def resolve_receipt(self, entry_id):\n#         logging.debug(\"resolving receipt %s\", entry_id)\n#         # DataTrails SDK can't process non-JSON responses yet\n#         # but we can still use the Archivist object to look after our\n#         # authenticated connection to the server then call out to requests\n#         # When the SCRAPI standard settles this code will migrate to the\n#         # core DataTrails SDK\n#         headers = headers = self._archivist._add_headers({})\n#         response = requests.get(\n#             f\"{self._url}/archivist/v1/publicscitt/entries/{entry_id}/receipt\",\n#             headers=headers,\n#             timeout=20000,\n#         )\n#         if response.status_code != 200:\n#             logging.debug(\"FAILED to get receipt: %s\", response.status_code)\n#             return response.content, None\n# \n#         return None, response.content\n# \n#     def resolve_signed_statement(self, entry_id):\n#         logging.debug(\"resolving entry %s\", entry_id)\n#         # DataTrails SDK can't process non-JSON responses yet\n#         # but we can still use the Archivist object to look after our\n#         # authenticated connection to the server then call out to requests\n#         # When the SCRAPI standard settles this code will migrate to the\n#         # core DataTrails SDK\n#         headers = headers = self._archivist._add_headers({})\n#         response = requests.get(\n#             f\"{self._url}/archivist/v1/publicscitt/entries/{entry_id}\",\n#             headers=headers,\n#             timeout=20000,\n#         )\n#         if response.status_code != 200:\n#             logging.debug(\"FAILED to get entry: %s\", response.status_code)\n#             return response.content, None\n# \n#         # Note: DataTrails currently returns the _counter_SignedStatement\n#         # but SCRAPI wants the original SignedStatement exactly as submitted\n#         # by the Issuer, so strip off the outer envelope\n#         decoded_statement = Sign1Message.decode(response.content)\n#         inner_statement = Sign1Message.decode(decoded_statement.payload)\n# \n#         print(\"\\ncbor decoded cose sign1 statement:\\n\")\n#         print(\"protected headers:\")\n#         pprint(inner_statement.phdr)\n#         print(\"\\nunprotected headers: \")\n#         pprint(inner_statement.uhdr)\n#         print(\"\\npayload: \", inner_statement.payload)\n#         print(\"payload hex: \", inner_statement.payload.hex())\n# \n#         return None, inner_statement\n# \n#     def issue_signed_statement(self, statement):\n#         return (None, None)\n# \n# --------------------------------------------------\n# the below code fragment can be found in:\n# scrapi/rfc9290.py\n# --------------------------------------------------\n# import cbor2\n# \n# DEFINED_FIELDS = {\n#     \"title\": -1,\n#     \"detail\": -2,\n#     \"instance\": -3,\n#     \"response-code\": -4,\n#     \"base-uri\": -5,\n#     \"base-lang\": -6,\n#     \"base-rtl\": -7,\n# }\n# \n# def decode_problem_details(cbor_data):\n#     \"\"\"\n#     Decodes a CBOR-encoded problem details object with numeric keys into a dictionary.\n# \n#     Parameters:\n#         cbor_data (bytes): CBOR-encoded bytes representing the problem details.\n# \n#     Returns:\n#         dict: Dictionary containing RFC 9290 problem details with textual keys.\n#     \"\"\"\n#     # Decode the CBOR data\n#     decoded_data = cbor2.loads(cbor_data)\n#     # Convert numeric keys back to their textual representation\n#     text_key_data = {\n#         key: decoded_data.get(DEFINED_FIELDS[key])\n#         for key in DEFINED_FIELDS\n#         if DEFINED_FIELDS[key] in decoded_data\n#     }\n#     return text_key_data\n# \n# --------------------------------------------------\n\n\n## scrapi/scrapi.py\nimport logging\n\nfrom time import time\n\nimport cbor2\n\nfrom datatrails_engine import DatatrailsEngine\n\nfrom scrapi_exception import ScrapiException\n\nfrom rfc9290 import decode_problem_details, encode_problem_details\n\nclass Scrapi:  # pylint: disable=too-many-instance-attributes\n    \"\"\"Portable class for all Scrapi implementations.\n\n    args:\n        ts_type (str): Type of transparency service\n        ts_args (dict): TS-specific initialization params\n\n    \"\"\"\n\n    def __init__(self, ts_type: str, ts_args: dict):\n        match ts_type:\n            case \"DataTrails\":\n                self.engine = DatatrailsEngine(ts_args)\n\n            case _:\n                raise ScrapiException(f\"Unknown engine type: {ts_type}'\")\n\n    def __str__(self) -> str:\n        if self.engine:\n            return self.engine.__str__()\n\n        return \"Scrapi (uninitialized)\"\n\n    # The following methods require a Transparency Service and so require the\n    # engine to be initialized\n\n    def check_engine(self):\n        \"\"\"Helper to protect all calls that need a valid TS connection\"\"\"\n\n        logging.debug(\"Scrapi checking engine liveness...\")\n\n        if not self.engine:\n            raise ScrapiException(\"No Transparency Service engine specified\")\n\n        if not self.engine.initialized():\n            raise ScrapiException(\"Transparency Service engine malfunction\")\n\n        logging.debug(\"Scrapi engine check SUCCESS\")\n\n    def get_configuration(self):\n        \"\"\"Wrapper for SCRAPI Transparency Configuration call\n\n        args:\n            none\n\n        returns:\n            application/json\n        \"\"\"\n\n        self.check_engine()\n\n        return self.engine.get_configuration()\n\n    def register_signed_statement(self, statement):\n        \"\"\"\n        Wrapper for SCRAPI Register Signed Statement call\n    \n        args:\n        Content-Type: application/cose\n    \n        18([                            / COSE Sign1         /\n        h'a1013822',                  / Protected Header   /\n        {},                           / Unprotected Header /\n        null,                         / Detached Payload   /\n        h'269cd68f4211dffc...0dcb29c' / Signature          /\n        ])\n    \n        returns:\n        application/json\n        \"\"\"\n",
        "input": "",
        "output": "        self.check_engine()\n\n        err, result = self.engine.register_signed_statement(statement)\n        if err:\n            # Decode and log the RFC9290 Problem Details.\n            problem_details = decode_problem_details(result)\n            print(problem_details)\n            return None\n\n        # Pull the registration ID out\n        operation = cbor2.loads(result)\n\n        # Check for common errors\n        if not \"status\" in operation or operation[\"status\"] == \"failed\":\n            raise ScrapiException(\"Statement Registration Failed\")\n\n        if not \"operationID\" in operation:\n            raise ScrapiException(\"No Operation ID for Statement\")\n\n        # Seems legit, send it back\n        return operation[\"operationID\"]\n    \n",
        "idx": "349"
    },
    {
        "instruction": "\ndef format_file_size(size_bytes: int) -> str:\n    \"\"\"\n    Format file size in bytes to human readable format\n    \"\"\"\n",
        "input": "",
        "output": "    for unit in ['B', 'KB', 'MB', 'GB']:\n        if size_bytes < 1024:\n            return f\"{size_bytes:.2f} {unit}\"\n        size_bytes /= 1024\n    return f\"{size_bytes:.2f} TB\"\n\n",
        "idx": "365"
    },
    {
        "instruction": "\ndef duration_to_seconds(duration: str) -> int:\n    \"\"\"\n    \u041f\u0435\u0440\u0435\u0432\u043e\u0434 \u0447\u0430\u0441\u0443 \u0432 \u0441\u0435\u043a\u0443\u043d\u0434\u0438\n    \"\"\"\n",
        "input": "",
        "output": "    times = duration.split(\":\")\n    return (int(times[0]) * 3600) + (int(times[1]) * 60) + int(times[2])\n\n",
        "idx": "370"
    },
    {
        "instruction": "## logic/command_go.py\nfrom logic.log import LOG\n\nWIDGET_WIDTH_OPTIONS = ['w-min', 'w-24', 'w-32', 'w-40', 'w-48', 'w-64', 'w-72', 'w-90', 'w-96', 'w-full']\n\nWIDGET_HEIGHT_OPTIONS = ['h-min', 'h-24', 'h-32', 'h-40', 'h-48', 'h-64', 'h-72', 'h-90', 'h-96', 'h-full']\n\nCOLOR_VALUE_OPTIONS = ['50', '100', '200', '300', '400', '500', '600', '700', '800', '900']\n\nROUNDED_OPTIONS = ['rounded-none', 'rounded-sm', 'rounded', 'rounded-md', 'rounded-lg', 'rounded-xl', 'rounded-2xl', 'rounded-full']\n\nWIDGET_MARGIN_OPTIONS = ['m-0', 'm-2', 'm-4', 'm-6', 'm-8', 'm-12', 'm-16', 'm-24', 'm-32']\n\nBOLD_OPTIONS = ['', 'font-thin', 'font-normal', 'font-medium', 'font-semibold', 'font-bold', 'font-extrabold', 'font-black']\n\nTEXT_ALIGNMENT_OPTIONS = ['text-left', 'text-left', 'text-center', 'text-justify', 'text-right']\n\nTEXT_SIZE_OPTIONS = ['text-xs', 'text-sm', 'text-base', 'text-lg', 'text-xl', 'text-2xl', 'text-3xl', 'text-4xl', 'text-5xl', 'text-6xl', 'text-7xl', 'text-8xl', 'text-9xl']\n\nDEFAULT_COLOR_VALUE = 50\n\ndef ProcessInput_SpecificType(config, input, widget_id, spec_item, target_dict, depth=0):\n  \"\"\"`input_type_record` is a single spec item, with no children, that results in a single value set by `key_full` into `target_dict`\n  \n  `target_dict` is actually the input we are processing, thus ultimately it is our \"output\"\n  \"\"\"\n  # key = widget_spec_key\n\n  # LOG.info(f'Input: {input}')\n  # LOG.debug(f'For Widget: {widget_id}  Spec Item: {spec_item}')\n\n  # widget_edit_key = f'''__edit.{spec_item['key_full']}'''\n  widget_spec_key = f'''{widget_id}.{spec_item['key_full']}'''\n\n  # Set the raw input value in 1 place, because we need to set the default too\n  raw_input_value = input.get(widget_spec_key, spec_item.get('default', ''))\n\n  # Text\n  if spec_item['type'] == 'text':\n    target_dict[widget_spec_key] = raw_input_value\n\n  # Int\n  elif spec_item['type'] == 'int':\n    # Lookup: Width\n    if 'lookup' in spec_item and spec_item['lookup'] == 'width':\n      target_dict[widget_spec_key] = GetOptionByPercent(widget_spec_key, WIDGET_WIDTH_OPTIONS, int(raw_input_value))\n    \n    # Lookup: Height\n    elif 'lookup' in spec_item and spec_item['lookup'] == 'height':\n      target_dict[widget_spec_key] = GetOptionByPercent(widget_spec_key, WIDGET_HEIGHT_OPTIONS, int(raw_input_value))\n    \n    # Lookup: Rounded\n    elif 'lookup' in spec_item and spec_item['lookup'] == 'rounded':\n      target_dict[widget_spec_key] = GetOptionByPercent(widget_spec_key, ROUNDED_OPTIONS, int(raw_input_value))\n    \n    # Lookup: Margin\n    elif 'lookup' in spec_item and spec_item['lookup'] == 'margin':\n      target_dict[widget_spec_key] = GetOptionByPercent(widget_spec_key, WIDGET_MARGIN_OPTIONS, int(raw_input_value))\n\n    # Lookup: Bold\n    elif 'lookup' in spec_item and spec_item['lookup'] == 'bold':\n      target_dict[widget_spec_key] = GetOptionByPercent(widget_spec_key, BOLD_OPTIONS, int(raw_input_value))\n\n    # Lookup: Align\n    elif 'lookup' in spec_item and spec_item['lookup'] == 'text_align':\n      target_dict[widget_spec_key] = GetOptionByPercent(widget_spec_key, TEXT_ALIGNMENT_OPTIONS, int(raw_input_value))\n\n    # Lookup: Align\n    elif 'lookup' in spec_item and spec_item['lookup'] == 'text_size':\n      target_dict[widget_spec_key] = GetOptionByPercent(widget_spec_key, TEXT_SIZE_OPTIONS, int(raw_input_value))\n\n    # Else, just direct assignment\n    else:\n      target_dict[widget_spec_key] = int(raw_input_value)\n\n  # Checkbox\n  elif spec_item['type'] == 'checkbox':\n    # LOG.info(f'For Widget Checkbox: {widget_id}  Spec Item: {spec_item}')\n\n    if raw_input_value == 'true':\n      if 'value_if_true' in spec_item:\n        target_dict[widget_spec_key] = spec_item['value_if_true']\n      else:\n        target_dict[widget_spec_key] = True\n    else:\n      if 'value_if_false' in spec_item:\n        target_dict[widget_spec_key] = spec_item['value_if_false']\n      else:\n        target_dict[widget_spec_key] = False\n\n  # Color\n  elif spec_item['type'] == 'color':\n    value_key = f'''{widget_spec_key}_value'''\n\n    # Get the raw value color value, or default back to 50\n    raw_color_value = input.get(value_key, DEFAULT_COLOR_VALUE)\n\n    color_value = GetOptionByPercent(value_key, COLOR_VALUE_OPTIONS, int(raw_color_value))\n    target_dict[widget_spec_key] = f'''text-{raw_input_value}-{color_value} raw-color-{raw_color_value} value-key-{value_key}'''\n\n  # Color Background\n  elif spec_item['type'] == 'color_background':\n    value_key = f'''{widget_spec_key}_value'''\n\n    # Get the raw value color value, or default back to 50\n    raw_color_value = input.get(value_key, DEFAULT_COLOR_VALUE)\n\n    color_value = GetOptionByPercent(value_key, COLOR_VALUE_OPTIONS, int(raw_color_value))\n    target_dict[widget_spec_key] = f'''bg-{raw_input_value}-{color_value}'''\n\n  # Icon\n  elif spec_item['type'] == 'icon':\n    target_dict[widget_spec_key] = raw_input_value\n\n  # Unknown: Error\n  else:\n    LOG.error(f'''ProcessInput_SpecificType: Unknown type: {spec_item['type']}  Spec Item: {spec_item}''')\n\ndef Clamp(value, clamp_min, clamp_max):\n  \"\"\"Clamp value between min and max values\"\"\"\n  return min(clamp_max, max(clamp_min, value))\n\ndef GetOptionByPercent(name_for_error, options, value_0_100):\n  \"\"\"\"\"\"\n  try:\n    percent = value_0_100 / 100.0\n\n    index = int(len(options) * percent)\n    index = Clamp(index, 0, len(options) - 1)\n\n    return options[index]\n  except ValueError as e:\n    LOG.error(f'''Site Editor: {name_for_error} input is not an integer: {value_0_100}''')\n    return None\n\ndef ProcessInputFromSpec(config, input, widget_id, spec, depth=0):\n    \"\"\"\n  We are given input, and we match it to the spec, so we can organize it into output\n  \"\"\"\n",
        "input": "",
        "output": "  result = {}\n\n  # LOG.debug(f'Widget: {widget_id}')\n  # LOG.debug(f'Input: {pprint.pformat(input)}')\n  # LOG.debug(f'Spec: {pprint.pformat(spec)}')\n\n  for spec_item in spec:\n    # If this is an include of some type, then we recurse with this data as the new root item\n    if 'import_data' in spec_item:\n      sub_result = ProcessInputFromSpec(config, input, widget_id, spec_item['import_data'], depth=depth+1)\n\n      result.update(sub_result)\n    elif 'list_data' in spec_item:\n      sub_result = ProcessInputFromSpec(config, input, widget_id, spec_item['list_data'], depth=depth+1)\n      result.update(sub_result)\n\n    # Else, this is a specific type, we process it here\n    else:\n      ProcessInput_SpecificType(config, input, widget_id, spec_item, result)\n\n  return result\n\n",
        "idx": "378"
    },
    {
        "instruction": "\ndef Site_Content_Admin(config):\n    \"\"\"\n  This is the data for ALL the content, and it edits data fields, or adds/removes, whatever.  Label management as well, since `limit` must be upheld\n  \n  `limit` and `limit_queue`, where we insert new elements into the front of the queue, so it bumps the old.  `limit` causes additions to fail until 1 is removed.  Make that easy, viewer-select\n  \"\"\"\n",
        "input": "",
        "output": "  result = config.input['existing']\n  \n  return result\n\n",
        "idx": "381"
    },
    {
        "instruction": "\ndef GetLinkHtml(url, name=None):\n    \"\"\"\n  Create an HTML URL\n  \"\"\"\n",
        "input": "",
        "output": "  if not name:\n    name = url\n\n  link = f'''<a href=\"{url}\" class=\"font-medium text-blue-600 dark:text-blue-500 hover:underline\">{name}</a>'''\n  \n  return link\n\n",
        "idx": "382"
    },
    {
        "instruction": "## logic/utility.py\nimport json\n\ndef IsDataEqual(a, b):\n    \"\"\"\n  Uses JSON to ensure any data type that is serializable can be compared\n  \"\"\"\n",
        "input": "",
        "output": "  a_json = json.dumps(a)\n  b_json = json.dumps(b)\n\n  # Return if they are equal\n  return a_json == b_json\n\n",
        "idx": "383"
    },
    {
        "instruction": "\ndef CloseDifference(value, test_value, tolerance=0.04):\n",
        "input": "",
        "output": "  diff = value - test_value\n  \n  return abs(diff) < tolerance\n\n",
        "idx": "384"
    },
    {
        "instruction": "## logic/command_go.py\nimport pprint\n\nfrom logic import utility\n\nfrom logic.log import LOG\n\ndef Space_Content_Derived(config):\n    \"\"\"\n  Register content\n  \"\"\"\n",
        "input": "",
        "output": "  request_input = utility.LoadJsonFromString(config.input['request']['request_input'])\n\n  LOG.info(f'Input request: {pprint.pformat(request_input)}')\n\n  # Start with the pass through and mutate\n  result = config.input.get('existing', {})\n  if not result: result = {}\n\n  # Pass this through\n  result['request_input'] = request_input\n\n  return result\n\n",
        "idx": "385"
    },
    {
        "instruction": "\ndef CreateNewDomain(new_uuid, domain_name):\n",
        "input": "",
        "output": "  data = {'uuid': new_uuid, 'name': domain_name, 'theme': 'default', 'paths': ['/', '/404']}\n\n  return data\n\n",
        "idx": "387"
    },
    {
        "instruction": "\ndef CreateNewProductStock(new_uuid, product_stock_name):\n",
        "input": "",
        "output": "  data = {'uuid': new_uuid, 'name': product_stock_name, 'theme': 'default', 'details': [], 'parent_uuid': None}\n\n  return data\n\n",
        "idx": "388"
    },
    {
        "instruction": "\ndef CreateNewPurchaseUsage(new_uuid, purchase_usage_name):\n",
        "input": "",
        "output": "  data = {'uuid': new_uuid, 'name': purchase_usage_name, 'theme': 'default', 'details': [], 'parent_uuid': None}\n\n  return data\n\n",
        "idx": "390"
    },
    {
        "instruction": "\ndef CreateNewUser(new_uuid, user_name):\n",
        "input": "",
        "output": "  data = {'uuid': new_uuid, 'name': user_name, 'theme': 'default', 'details': [], 'parent_uuid': None}\n\n  return data\n\n",
        "idx": "391"
    },
    {
        "instruction": "\ndef bytes_num(n: int) -> int:\n    \"\"\"\n    Returns the number of bytes required to represent n as bytes\n    \"\"\"\n",
        "input": "",
        "output": "    if n == 0:\n        return 1\n    return (n.bit_length() + 7) // 8\n\n",
        "idx": "395"
    },
    {
        "instruction": "## examples/utils.py\nfrom bitcoinutils.script import Script\n\nRAFFLE_VERSION = b'\\x00'\n\ndef bytes_num(n: int) -> int:\n    \"\"\"\n    Returns the number of bytes required to represent n as bytes\n    \"\"\"\n    if n == 0:\n        return 1\n    return (n.bit_length() + 7) // 8\n\ndef op_return_script(blockheight: int) -> Script:\n    \"\"\"\n    The OP_RETURN Script to be appended to the OP_RETURN output.\n    \n    It's a raffle version number followed by more data.\n    For version 0x00, what follows is a block height number represented as a big endian byte sequence.\n    The data is returned as a hex string because that's what the bitcoinutils library expects.\n    \"\"\"\n",
        "input": "",
        "output": "    payload = (RAFFLE_VERSION + blockheight.to_bytes(bytes_num(blockheight), 'big')).hex()\n    return Script(['OP_RETURN', payload])\n\n",
        "idx": "396"
    },
    {
        "instruction": "\ndef canonize_outpoint(outpoint: tuple[str, int]) -> bytes:\n    \"\"\"\n    Returns an outpoint in its canonical form.\n    The canonical form is defined as the serialization format in a real bitcoin transaction.\n    \n    It consists of 32 bytes of the txid in little endian, followed by 4 bytes for the vout, also in little endian.\n    \"\"\"\n",
        "input": "",
        "output": "    canonical_txid = bytes.fromhex(outpoint[0])[::-1]\n    canonical_vout = outpoint[1].to_bytes(4, 'little')\n\n    assert len(canonical_txid) == 32\n    return canonical_txid + canonical_vout\n\n",
        "idx": "397"
    },
    {
        "instruction": "## examples/utils.py\nimport hashlib\n\ndef canonize_outpoint(outpoint: tuple[str, int]) -> bytes:\n    \"\"\"\n    Returns an outpoint in its canonical form.\n    The canonical form is defined as the serialization format in a real bitcoin transaction.\n\n    It consists of 32 bytes of the txid in little endian, followed by 4 bytes for the vout, also in little endian.\n    \"\"\"\n    canonical_txid = bytes.fromhex(outpoint[0])[::-1]\n    canonical_vout = outpoint[1].to_bytes(4, 'little')\n\n    assert len(canonical_txid) == 32\n    return canonical_txid + canonical_vout\n\ndef outpoints_merkle_root(sorted_outpoints: list[tuple[str, int]]) -> bytes:\n    \"\"\"\n    Calculates the Merkle Root Hash of a list of outpoints.\n    \n    Pre: The list of outpoints is not empty\n    Pre: The outpoints are sorted according to their canonical representation\n    \"\"\"\n",
        "input": "",
        "output": "    assert len(sorted_outpoints) > 0\n    assert sorted(sorted_outpoints, key=canonize_outpoint) == sorted_outpoints\n\n    hashes = [hashlib.sha256(leaf).digest() for leaf in\n              [canonize_outpoint(outpoint) for outpoint in sorted_outpoints]]\n\n    while len(hashes) > 1:\n        if len(hashes) % 2 == 1:\n            hashes.append(hashes[-1])\n\n        next_hashes: list[bytes] = []\n        for i in range(0, len(hashes), 2):\n            next_hashes.append(hashlib.sha256(hashes[i] + hashes[i + 1]).digest())\n\n        hashes = next_hashes\n    return hashes[0]\n\n",
        "idx": "398"
    },
    {
        "instruction": "## derapi/client.py\nimport ssl\n\nfrom typing import Any, Dict, Optional, Union\n\nimport httpx\n\nfrom attrs import define, evolve, field\n\nclass Client:\n    \"\"\"A class for keeping track of data related to the API\n\n    The following are accepted as keyword arguments and will be used to construct httpx Clients internally:\n\n        ``base_url``: The base URL for the API, all requests are made to a relative path to this URL\n\n        ``cookies``: A dictionary of cookies to be sent with every request\n\n        ``headers``: A dictionary of headers to be sent with every request\n\n        ``timeout``: The maximum amount of a time a request can take. API functions will raise\n        httpx.TimeoutException if this is exceeded.\n\n        ``verify_ssl``: Whether or not to verify the SSL certificate of the API server. This should be True in production,\n        but can be set to False for testing purposes.\n\n        ``follow_redirects``: Whether or not to follow redirects. Default value is False.\n\n        ``httpx_args``: A dictionary of additional arguments to be passed to the ``httpx.Client`` and ``httpx.AsyncClient`` constructor.\n\n\n    Attributes:\n        raise_on_unexpected_status: Whether or not to raise an errors.UnexpectedStatus if the API returns a\n            status code that was not documented in the source OpenAPI document. Can also be provided as a keyword\n            argument to the constructor.\n    \"\"\"\n\n    raise_on_unexpected_status: bool = field(default=False, kw_only=True)\n    _base_url: str = field(alias=\"base_url\")\n    _cookies: Dict[str, str] = field(factory=dict, kw_only=True, alias=\"cookies\")\n    _headers: Dict[str, str] = field(factory=dict, kw_only=True, alias=\"headers\")\n    _timeout: Optional[httpx.Timeout] = field(default=None, kw_only=True, alias=\"timeout\")\n    _verify_ssl: Union[str, bool, ssl.SSLContext] = field(default=True, kw_only=True, alias=\"verify_ssl\")\n    _follow_redirects: bool = field(default=False, kw_only=True, alias=\"follow_redirects\")\n    _httpx_args: Dict[str, Any] = field(factory=dict, kw_only=True, alias=\"httpx_args\")\n    _client: Optional[httpx.Client] = field(default=None, init=False)\n    _async_client: Optional[httpx.AsyncClient] = field(default=None, init=False)\n\n    def with_headers(self, headers: Dict[str, str]) -> 'Client':\n        \"\"\"\n        Get a new client matching this one with additional headers\n        \"\"\"\n",
        "input": "",
        "output": "        if self._client is not None:\n            self._client.headers.update(headers)\n        if self._async_client is not None:\n            self._async_client.headers.update(headers)\n        return evolve(self, headers={**self._headers, **headers})\n    \n",
        "idx": "417"
    },
    {
        "instruction": "## derapi/client.py\nimport ssl\n\nfrom typing import Any, Dict, Optional, Union\n\nimport httpx\n\nfrom attrs import define, evolve, field\n\nclass Client:\n    \"\"\"A class for keeping track of data related to the API\n\n    The following are accepted as keyword arguments and will be used to construct httpx Clients internally:\n\n        ``base_url``: The base URL for the API, all requests are made to a relative path to this URL\n\n        ``cookies``: A dictionary of cookies to be sent with every request\n\n        ``headers``: A dictionary of headers to be sent with every request\n\n        ``timeout``: The maximum amount of a time a request can take. API functions will raise\n        httpx.TimeoutException if this is exceeded.\n\n        ``verify_ssl``: Whether or not to verify the SSL certificate of the API server. This should be True in production,\n        but can be set to False for testing purposes.\n\n        ``follow_redirects``: Whether or not to follow redirects. Default value is False.\n\n        ``httpx_args``: A dictionary of additional arguments to be passed to the ``httpx.Client`` and ``httpx.AsyncClient`` constructor.\n\n\n    Attributes:\n        raise_on_unexpected_status: Whether or not to raise an errors.UnexpectedStatus if the API returns a\n            status code that was not documented in the source OpenAPI document. Can also be provided as a keyword\n            argument to the constructor.\n    \"\"\"\n\n    raise_on_unexpected_status: bool = field(default=False, kw_only=True)\n    _base_url: str = field(alias=\"base_url\")\n    _cookies: Dict[str, str] = field(factory=dict, kw_only=True, alias=\"cookies\")\n    _headers: Dict[str, str] = field(factory=dict, kw_only=True, alias=\"headers\")\n    _timeout: Optional[httpx.Timeout] = field(default=None, kw_only=True, alias=\"timeout\")\n    _verify_ssl: Union[str, bool, ssl.SSLContext] = field(default=True, kw_only=True, alias=\"verify_ssl\")\n    _follow_redirects: bool = field(default=False, kw_only=True, alias=\"follow_redirects\")\n    _httpx_args: Dict[str, Any] = field(factory=dict, kw_only=True, alias=\"httpx_args\")\n    _client: Optional[httpx.Client] = field(default=None, init=False)\n    _async_client: Optional[httpx.AsyncClient] = field(default=None, init=False)\n\n    def with_headers(self, headers: Dict[str, str]) -> \"Client\":\n        \"\"\"Get a new client matching this one with additional headers\"\"\"\n        if self._client is not None:\n            self._client.headers.update(headers)\n        if self._async_client is not None:\n            self._async_client.headers.update(headers)\n        return evolve(self, headers={**self._headers, **headers})\n\n    def with_cookies(self, cookies: Dict[str, str]) -> \"Client\":\n        \"\"\"Get a new client matching this one with additional cookies\"\"\"\n        if self._client is not None:\n            self._client.cookies.update(cookies)\n        if self._async_client is not None:\n            self._async_client.cookies.update(cookies)\n        return evolve(self, cookies={**self._cookies, **cookies})\n\n    def with_timeout(self, timeout: httpx.Timeout) -> 'Client':\n        \"\"\"\n        Get a new client matching this one with a new timeout (in seconds)\n        \"\"\"\n",
        "input": "",
        "output": "        if self._client is not None:\n            self._client.timeout = timeout\n        if self._async_client is not None:\n            self._async_client.timeout = timeout\n        return evolve(self, timeout=timeout)\n    \n",
        "idx": "419"
    },
    {
        "instruction": "## game/darkhex.py\nimport logging\n\nfrom scipy.cluster.hierarchy import DisjointSet\n\nimport game.util as util\n\nclass AbstractDarkHex:\n    \"\"\"\n    Class that can run a game of Dark Hex. \n    \n    Initialise with the dimensions and an empty board will be created. \n    \n    By default, white moves first.\n    \n    Assume that position (1,1) is the top left cell, and (2,1) is the top row, 2nd column etc.\n    \n    We have black \"goals\" at the top and bottom, and white \"goals\" at the left and right.\n    \"\"\"\n\n    def __init__(self, _cols : int, _rows : int, _first_turn=\"w\"):\n        self.cols = _cols\n        self.rows = _rows\n        self.board = []\n        self.black_board = []\n        self.white_board = []\n        self.black_components = DisjointSet([])\n        self.white_components = DisjointSet([])\n        self.turn = _first_turn  # for now, default first turn is white's\n        self.first_turn = _first_turn  # save in case of reset\n        logging.info(\"Board parameters defined\")\n        self.reset_board()  # set starting state of board and components\n\n    def move(self, row : int, col : int, colour : str) -> str:\n        \"\"\"\n        Attempt to place a piece of a given colour into a given cell\n        Parameters:\n            colour: \"b\" or \"w\" representing black and white respectively\n            row: The row to insert on, with 1 being at the top\n            col: The column to insert on, with 1 being at the left\n        Returns:\n            \"black_win\" if the cell is placed and this wins the game for black\n            \"white_win\" if the cell is placed and this wins the game for white\n            \"placed\" if the cell is placed and the game continues\n            \"full_white\" if the cell is occupied with a white tile\n            \"full_black\" if the cell is occupied with a black tile\n        \"\"\"\n        # check that this player is allowed to move\n        assert colour == self.turn\n\n        cell = self.board[row][col]\n        if cell != \"e\":  # if the chosen cell is not empty\n            logging.info(\"Non-empty cell %s at (%s, %s)\", cell, col, row)\n            # update our view, since we know where their piece is now\n            self._get_board(colour)[row][col] = self.board[row][col]  # view update\n            return \"full_\" + util.colour_map[self.board[row][col]]\n        else:\n            # update global board and our view\n            self.board[row][col] = colour\n            self._get_board(colour)[row][col] = colour\n            self.turn = util.swap_colour(colour)  # swap turn\n            self.update_components(row, col, colour)  # update components\n            logging.info(\"%s played at (%s, %s)\",\n                         util.colour_map[colour], col, row)\n            win_check = self.win_check()\n            logging.info(\"Result of win_check is: %s\", win_check)\n            if win_check != \"none\":\n                return win_check\n            else:\n                return \"placed\"\n    #TODO bug where black wins but it isnt registered. shape like <\n\n    def win_check(self) -> str:\n        \"\"\"\n        Check if the board is in a winning position for some player.\n        Returns:\n        \"black_win\" if black has won\n        \"white_win\" if white has won\n        \"none\" if nobody has won\n        \"\"\"\n",
        "input": "",
        "output": "        logging.info(\"Performing a win check\")\n        if self.black_components.connected((1, 0), (1, self.rows+1)):\n            return \"black_win\"\n        elif self.white_components.connected((0, 1), (self.cols+1, 1)):\n            return \"white_win\"\n        else:\n            return \"none\"\n    \n",
        "idx": "435"
    },
    {
        "instruction": "## game/darkhex.py\nimport logging\n\nfrom scipy.cluster.hierarchy import DisjointSet\n\nimport game.util as util\n\nclass AbstractDarkHex:\n    \"\"\"\n    Class that can run a game of Dark Hex. \n    \n    Initialise with the dimensions and an empty board will be created. \n    \n    By default, white moves first.\n    \n    Assume that position (1,1) is the top left cell, and (2,1) is the top row, 2nd column etc.\n    \n    We have black \"goals\" at the top and bottom, and white \"goals\" at the left and right.\n    \"\"\"\n\n    def __init__(self, _cols : int, _rows : int, _first_turn=\"w\"):\n        self.cols = _cols\n        self.rows = _rows\n        self.board = []\n        self.black_board = []\n        self.white_board = []\n        self.black_components = DisjointSet([])\n        self.white_components = DisjointSet([])\n        self.turn = _first_turn  # for now, default first turn is white's\n        self.first_turn = _first_turn  # save in case of reset\n        logging.info(\"Board parameters defined\")\n        self.reset_board()  # set starting state of board and components\n\n    def move(self, row : int, col : int, colour : str) -> str:\n        \"\"\"\n        Attempt to place a piece of a given colour into a given cell\n        Parameters:\n            colour: \"b\" or \"w\" representing black and white respectively\n            row: The row to insert on, with 1 being at the top\n            col: The column to insert on, with 1 being at the left\n        Returns:\n            \"black_win\" if the cell is placed and this wins the game for black\n            \"white_win\" if the cell is placed and this wins the game for white\n            \"placed\" if the cell is placed and the game continues\n            \"full_white\" if the cell is occupied with a white tile\n            \"full_black\" if the cell is occupied with a black tile\n        \"\"\"\n        # check that this player is allowed to move\n        assert colour == self.turn\n\n        cell = self.board[row][col]\n        if cell != \"e\":  # if the chosen cell is not empty\n            logging.info(\"Non-empty cell %s at (%s, %s)\", cell, col, row)\n            # update our view, since we know where their piece is now\n            self._get_board(colour)[row][col] = self.board[row][col]  # view update\n            return \"full_\" + util.colour_map[self.board[row][col]]\n        else:\n            # update global board and our view\n            self.board[row][col] = colour\n            self._get_board(colour)[row][col] = colour\n            self.turn = util.swap_colour(colour)  # swap turn\n            self.update_components(row, col, colour)  # update components\n            logging.info(\"%s played at (%s, %s)\",\n                         util.colour_map[colour], col, row)\n            win_check = self.win_check()\n            logging.info(\"Result of win_check is: %s\", win_check)\n            if win_check != \"none\":\n                return win_check\n            else:\n                return \"placed\"\n    #TODO bug where black wins but it isnt registered. shape like <\n\n    def win_check(self) -> str:\n        \"\"\"\n        Check if the board is in a winning position for some player.\n        Returns:\n            \"black_win\" if black has won\n            \"white_win\" if white has won\n            \"none\" if nobody has won\n        \"\"\"\n        #check if the two black rows are connected or the two white columns are connected\n        logging.info(\"Performing a win check\")\n        if self.black_components.connected((1, 0), (1, self.rows+1)):\n            return \"black_win\"\n        elif self.white_components.connected((0, 1), (self.cols+1, 1)):\n            return \"white_win\"\n        else:\n            return \"none\"\n\n    def update_components(self, row : int, col : int, colour : str) -> None:\n        \"\"\"\n        Update the connected components of the given colour to include the new cell (col,row)\n        \"\"\"\n        logging.debug(\"Attempting to merge components surrounding (%s, %s)\", col, row)\n        match colour:\n            case \"w\":\n                components = self.white_components\n            case \"b\":\n                components = self.black_components\n            case _:\n                raise ValueError(\"Invalid colour given to update_components\")\n\n        components.add((col,row))\n        # attempt to connect to each matching colour in surrounding hex\n        adj = [\n            (col-1, row), (col, row-1), (col+1, row-1),\n            (col+1, row), (col, row+1), (col-1,row+1)\n        ]\n        for cell in adj:\n            # if adjacent cell is of the same colour\n            if self.board[cell[1]][cell[0]] == colour:\n                # connect the components\n                components.merge((col,row),cell)\n                logging.debug(\"(%s, %s) and %s %s components merged\", \n                              col, row, cell, util.colour_map[colour])\n\n\n    def reset_board(self) -> None:\n        \"\"\"\n        Restart the game with the same board dimensions\n        \"\"\"\n",
        "input": "",
        "output": "        self.board = self._create_board()\n        self.black_board = self._create_board()\n        self.white_board = self._create_board()\n\n        # revert to correct first turn\n        self.turn = self.first_turn\n\n        # set starting components\n        self.black_components = DisjointSet([])\n        self.white_components = DisjointSet([])\n        # initial black components are top and bottom rows\n        for x in range(1,self.cols+1):\n            self.black_components.add((x, 0))\n            self.black_components.merge((1,0), (x,0))\n            self.black_components.add((x, self.rows+1))\n            self.black_components.merge((1, self.rows+1), (x, self.rows+1))\n\n        # initial white components are left and right columns\n        for y in range(self.rows+2):\n            self.white_components.add((0,y))\n            self.white_components.merge((0,0), (0,y))\n            self.white_components.add((self.cols+1, y))\n            self.white_components.merge((self.cols+1,0), (self.cols+1, y))\n\n        logging.info(\"Board reset\")\n    \n",
        "idx": "437"
    },
    {
        "instruction": "## ultrasonic.py\nimport RPi.GPIO as GPIO\n\nfrom time import sleep, time\n\nTRIG_PIN = 23\n\nECHO_PIN = 24\n\ndef measure_distance():\n    \"\"\"Measure the distance using the ultrasonic sensor.\"\"\"\n    # Send pulse\n    GPIO.output(TRIG_PIN, GPIO.LOW)\n    sleep(0.1)\n    GPIO.output(TRIG_PIN, GPIO.HIGH)\n    sleep(0.00001)\n    GPIO.output(TRIG_PIN, GPIO.LOW)\n\n    # Wait for echo response\n    pulse_start = time()\n    while GPIO.input(ECHO_PIN) == GPIO.LOW:\n        pulse_start = time()\n\n    pulse_end = time()\n    while GPIO.input(ECHO_PIN) == GPIO.HIGH:\n        pulse_end = time()\n\n    pulse_duration = pulse_end - pulse_start\n    distance = pulse_duration * 17150  # Calculate distance in cm\n    return distance\n\ndef is_object_detected(threshold=10):\n    \"\"\"\n    Check if an object is within the threshold distance.\n    \"\"\"\n",
        "input": "",
        "output": "    distance = measure_distance()\n    return distance < threshold\n\n",
        "idx": "442"
    },
    {
        "instruction": "\ndef skip_submodules(app, what, name, obj, skip, options):\n    \"\"\"\n    Function used by ``autoapi-skip-member`` event to skip submodules.\n    \n    Parameters\n    ----------\n    app : Sphinx\n    The Sphinx application object.\n    what : str\n    The type of the member.\n    name : str\n    The name of the member (like ``module.Class.attribute`` for instance).\n    obj : object\n    The Sphinx object representing the member.\n    skip : bool\n    Whether the member should be skipped (at this point, from the configuration).\n    options : list[str]\n    The options passed to the directive from ``conf.py``.\n    \n    Returns\n    -------\n    bool\n    Whether the member should be skipped.\n    \"\"\"\n",
        "input": "",
        "output": "    if what == \"attribute\":\n        if obj.is_undoc_member:\n            print(f\"  \u2022 Skipping {what} {name} because it is not documented.\")\n            return True\n    return skip\n\n",
        "idx": "444"
    },
    {
        "instruction": "\ndef skip_submodules(app, what, name, obj, skip, options):\n    \"\"\"\n    Function used by ``autoapi-skip-member`` event to skip submodules.\n    \n    Parameters\n    ----------\n    app : Sphinx\n    The Sphinx application object.\n    what : str\n    The type of the member.\n    name : str\n    The name of the member (like ``module.Class.attribute`` for instance).\n    obj : object\n    The Sphinx object representing the member.\n    skip : bool\n    Whether the member should be skipped (at this point, from the configuration).\n    options : list[str]\n    The options passed to the directive from ``conf.py``.\n    \n    Returns\n    -------\n    bool\n    Whether the member should be skipped.\n    \"\"\"\n",
        "input": "",
        "output": "    if what == \"attribute\":\n        if obj.is_undoc_member:\n            print(f\"  \u2022 Skipping {what} {name} because it is not documented.\")\n            return True\n    return skip\n\n",
        "idx": "445"
    },
    {
        "instruction": "# Here are some relevant code fragments from other files of the repo:\n# --------------------------------------------------\n# the below code fragment can be found in:\n# src/entaldocs/logger.py\n# --------------------------------------------------\n# import sys\n# \n# from datetime import datetime\n# \n# class BaseLogger:\n#     \"\"\"A dummy class for documentation purposes\"\"\"\n# \n#     ...\n# \n# class Logger(BaseLogger):\n#     \"\"\"A class to log messages to the console.\"\"\"\n# \n#     def __init__(self, name: str, with_time: bool = True):\n#         \"\"\"Initialize the Logger.\n# \n#         Parameters\n#         ----------\n#         name : str\n#             The name of the logger.\n#         with_time : bool, optional\n#             Whether to include the time in the log messages, by default True.\n#         \"\"\"\n#         self.name = name\n#         self.with_time = with_time\n# \n#     def now(self):\n#         \"\"\"Get the current time.\n# \n#         Returns:\n#         --------\n#         str\n#             The current time.\n#         \"\"\"\n#         return datetime.now().strftime(\"%H:%M:%S\")\n# \n#     @property\n#     def prefix(self):\n#         \"\"\"Get the prefix for the log messages.\n# \n#         The prefix includes the name of the logger and the current time.\n# \n#         Returns:\n#         --------\n#         str\n#             The prefix.\n#         \"\"\"\n#         prefix = \"\"\n#         if self.name:\n#             prefix += f\"{self.name}\"\n#             if self.with_time:\n#                 prefix += f\" | {self.now()}\"\n#         else:\n#             prefix += self.now()\n#         if prefix:\n#             return f\"[grey50 bold]\\\\[{prefix}][/grey50 bold] \"\n#         return prefix\n# \n#     def prompt(self, message: str, default: str = None) -> str:\n#         \"\"\"Prompt the user for a value.\n# \n#         Parameters\n#         ----------\n#         message : str\n#             The message to prompt the user with.\n#         default : str, optional\n#             The default value, by default None.\n# \n#         Returns:\n#         --------\n#         str\n#             The value entered by the user.\n#         \"\"\"\n#         text = (\n#             f\"{self.prefix}{message} \\\\[default: {default}]\"\n#             if default\n#             else f\"{self.prefix}{message}\"\n#         )\n#         print(text, end=\"\")\n#         return input(\":\").strip() or default\n# \n#     def confirm(self, message: str) -> bool:\n#         \"\"\"Confirm a message with the user.\n# \n#         Parameters\n#         ----------\n#         message : str\n#             The message to confirm.\n# \n#         Returns:\n#         --------\n#         bool\n#             Whether the user confirmed the message.\n#         \"\"\"\n#         return self.prompt(f\"{message} (y/N)\", \"N\").lower() == \"y\"\n# \n#     def abort(self, message: str, exit=1):\n#         \"\"\"Abort the program with a message.\n# \n#         Parameters\n#         ----------\n#         message : str\n#             The message to print before aborting.\n#         \"\"\"\n#         print(f\"{self.prefix}[red]{message}[/red]\")\n#         sys.exit(exit)\n# \n#     def success(self, message: str):\n#         \"\"\"Print a success message.\n# \n#         Parameters\n#         ----------\n#         message : str\n#             The message to print.\n#         \"\"\"\n#         print(f\"{self.prefix}[green]{message}[/green]\")\n# \n#     def warning(self, message: str):\n#         \"\"\"Print a warning message.\n# \n#         Parameters\n#         ----------\n#         message : str\n#             The message to print.\n#         \"\"\"\n#         print(f\"{self.prefix}[yellow]{message}[/yellow]\")\n# \n#     def error(self, message: str):\n#         \"\"\"Print an error message.\n# \n#         Parameters\n#         ----------\n#         message : str\n#             The message to print.\n#         \"\"\"\n#         print(f\"{self.prefix}[red]{message}[/red]\")\n# \n#     def info(self, message: str):\n#         \"\"\"Print an info message.\n# \n#         Parameters\n#         ----------\n#         message : str\n#             The message to print.\n#         \"\"\"\n#         print(f\"{self.prefix}[blue]{message}[/blue]\")\n# \n#     def clear_line(self):\n#         \"\"\"Clear the current line.\"\"\"\n#         import shutil\n# \n#         cols = shutil.get_terminal_size().columns\n#         print(\" \" * cols, end=\"\\r\")\n#         print(\" \" * cols, end=\"\\r\")\n# \n# --------------------------------------------------\n\n\n## src/entaldocs/utils.py\nfrom os.path import expandvars, relpath\n\nfrom pathlib import Path\n\nfrom entaldocs.logger import Logger\n\nlogger = Logger(\"entaldocs\")\n\ndef resolve_path(path: str | Path) -> Path:\n    \"\"\"Resolve a path and expand environment variables.\n\n    Parameters\n    ----------\n    path : str | Path\n        The path to resolve.\n\n    Returns:\n    --------\n    Path\n        The resolved path.\n    \"\"\"\n    return Path(expandvars(path)).expanduser().resolve()\n\ndef get_project_name(with_defaults) -> str:\n    \"\"\"\n    Get the current project's name from the user.\n    \n    Prompts the user for the project name, with the default being the current\n    directory's name.\n    \n    Parameters\n    ----------\n    with_defaults : bool\n    Whether to trust the defaults and skip all prompts.\n    \n    Returns\n    -------\n    str\n    The project name.\n    \"\"\"\n",
        "input": "",
        "output": "    default = resolve_path(\".\").name\n    return default if with_defaults else logger.prompt(\"Project name\", default=default)\n\n",
        "idx": "448"
    },
    {
        "instruction": "## src/entaldocs/logger.py\nimport sys\n\nfrom datetime import datetime\n\nclass BaseLogger:\n    \"\"\"A dummy class for documentation purposes\"\"\"\n\n    ...\n\nclass Logger(BaseLogger):\n    \"\"\"A class to log messages to the console.\"\"\"\n\n    def __init__(self, name: str, with_time: bool = True):\n        \"\"\"Initialize the Logger.\n\n        Parameters\n        ----------\n        name : str\n            The name of the logger.\n        with_time : bool, optional\n            Whether to include the time in the log messages, by default True.\n        \"\"\"\n        self.name = name\n        self.with_time = with_time\n\n    def now(self):\n        \"\"\"\n        Get the current time.\n    \n        Returns:\n        --------\n        str\n        The current time.\n        \"\"\"\n",
        "input": "",
        "output": "        return datetime.now().strftime(\"%H:%M:%S\")\n    \n",
        "idx": "450"
    },
    {
        "instruction": "## src/entaldocs/logger.py\nimport sys\n\nfrom datetime import datetime\n\nclass BaseLogger:\n    \"\"\"A dummy class for documentation purposes\"\"\"\n\n    ...\n\nclass Logger(BaseLogger):\n    \"\"\"A class to log messages to the console.\"\"\"\n\n    def __init__(self, name: str, with_time: bool = True):\n        \"\"\"Initialize the Logger.\n\n        Parameters\n        ----------\n        name : str\n            The name of the logger.\n        with_time : bool, optional\n            Whether to include the time in the log messages, by default True.\n        \"\"\"\n        self.name = name\n        self.with_time = with_time\n\n    def now(self):\n        \"\"\"Get the current time.\n\n        Returns:\n        --------\n        str\n            The current time.\n        \"\"\"\n        return datetime.now().strftime(\"%H:%M:%S\")\n\n    @property\n    def prefix(self):\n        \"\"\"Get the prefix for the log messages.\n\n        The prefix includes the name of the logger and the current time.\n\n        Returns:\n        --------\n        str\n            The prefix.\n        \"\"\"\n        prefix = \"\"\n        if self.name:\n            prefix += f\"{self.name}\"\n            if self.with_time:\n                prefix += f\" | {self.now()}\"\n        else:\n            prefix += self.now()\n        if prefix:\n            return f\"[grey50 bold]\\\\[{prefix}][/grey50 bold] \"\n        return prefix\n\n    def prompt(self, message: str, default: str=None) -> str:\n        \"\"\"\n        Prompt the user for a value.\n    \n        Parameters\n        ----------\n        message : str\n        The message to prompt the user with.\n        default : str, optional\n        The default value, by default None.\n    \n        Returns:\n        --------\n        str\n        The value entered by the user.\n        \"\"\"\n",
        "input": "",
        "output": "        text = (\n            f\"{self.prefix}{message} \\\\[default: {default}]\"\n            if default\n            else f\"{self.prefix}{message}\"\n        )\n        print(text, end=\"\")\n        return input(\":\").strip() or default\n    \n",
        "idx": "451"
    },
    {
        "instruction": "\ndef supports_isinstance(type_: type) -> bool:\n    \"\"\"\n    Check if a type supports isinstance checks.\n    \n    This is used for checking if a type supports isinstance checks, like checking\n    if a tool's params_type supports isinstance checks.\n    \n    Args:\n    type_: The type to check.\n    \n    Returns:\n    True if the type supports isinstance checks.\n    \"\"\"\n",
        "input": "",
        "output": "    metaclass = type(type_)\n    return hasattr(metaclass, \"__instancecheck__\") or hasattr(metaclass, \"__subclasscheck__\")\n\n",
        "idx": "455"
    },
    {
        "instruction": "# Here are some relevant code fragments from other files of the repo:\n# --------------------------------------------------\n# the below code fragment can be found in:\n# liteswarm/utils/misc.py\n# --------------------------------------------------\n# from typing import Any, Concatenate, ParamSpec, TypeVar, cast, overload\n# \n# _AttributeType = TypeVar(\"_AttributeType\")\n# \n# _AttributeDefaultType = TypeVar(\"_AttributeDefaultType\")\n# \n# def safe_get_attr(\n#     obj: Any,\n#     attr: str,\n#     expected_type: type[_AttributeType],\n#     default: _AttributeDefaultType = None,  # type: ignore\n# ) -> _AttributeType | _AttributeDefaultType:\n#     \"\"\"Safely retrieves and validates an attribute of an object.\n# \n#     This function attempts to access the specified attribute from the given object.\n#     If the attribute exists and its value matches the expected type, the value is returned.\n#     Otherwise, the `default` value is returned.\n# \n#     If the `default` is not provided, it defaults to `None`. The return type will be inferred\n#     as a union of the expected type and the type of the default value.\n# \n#     Args:\n#         obj: The object from which to retrieve the attribute.\n#         attr: The name of the attribute to retrieve.\n#         expected_type: The expected type of the attribute's value.\n#         default: The value to return if the attribute does not exist\n#             or its value does not match the expected type. Defaults to `None`.\n# \n#     Returns:\n#         The attribute's value if it exists and matches the expected type,\n#         or the `default` value otherwise.\n# \n#     Examples:\n#         Basic usage:\n#             ```python\n#             class Example:\n#                 attribute: int = 42\n# \n# \n#             instance = Example()\n# \n#             # Attribute exists and matches expected type\n#             value1: int = safe_get_attr(instance, \"attribute\", int, default=0)\n#             print(value1)  # Output: 42\n# \n#             # Attribute exists but does not match expected type\n#             value2: str = safe_get_attr(instance, \"attribute\", str, default=\"default_value\")\n#             print(value2)  # Output: \"default_value\"\n# \n#             # Attribute does not exist, returns default\n#             value3: int = safe_get_attr(instance, \"nonexistent\", int, default=100)\n#             print(value3)  # Output: 100\n# \n#             # Attribute does not exist, no default provided\n#             value4: int | None = safe_get_attr(instance, \"nonexistent\", int, default=100)\n#             print(value4)  # Output: 100\n#             ```\n#     \"\"\"\n#     value = getattr(obj, attr, default)\n#     if isinstance(value, expected_type):\n#         return value\n# \n#     return default\n# \n# --------------------------------------------------\n\n\n## liteswarm/utils/usage.py\nfrom numbers import Number\n\nfrom typing import Any\n\nfrom litellm import Usage\n\nfrom liteswarm.utils.misc import safe_get_attr\n\ndef combine_dicts(\n    left: dict[str, Any] | None,\n    right: dict[str, Any] | None,\n) -> dict[str, Any] | None:\n    \"\"\"Merge dictionaries with special handling for numbers.\n\n    Creates a new dictionary by combining two input dictionaries:\n    - Adds numeric values when keys overlap\n    - Preserves non-numeric values from left dictionary\n    - Includes unique keys from both dictionaries\n\n    Args:\n        left: First dictionary to merge.\n        right: Second dictionary to merge.\n\n    Returns:\n        Combined dictionary or None if both inputs are None.\n\n    Examples:\n        Basic merge:\n            ```python\n            result = combine_dicts(\n                {\"a\": 1, \"b\": \"text\"},\n                {\"a\": 2, \"c\": 3},\n            )\n            assert result == {\n                \"a\": 3,  # Numbers added\n                \"b\": \"text\",  # Non-numeric preserved\n                \"c\": 3,  # Unique key included\n            }\n            ```\n\n        None handling:\n            ```python\n            assert combine_dicts(None, None) is None\n            assert combine_dicts({\"a\": 1}, None) == {\"a\": 1}\n            assert combine_dicts(None, {\"b\": 2}) == {\"b\": 2}\n            ```\n\n        Mixed types:\n            ```python\n            result = combine_dicts(\n                {\"count\": 1, \"name\": \"test\"},\n                {\"count\": 2, \"name\": \"other\"},\n            )\n            assert result == {\n                \"count\": 3,  # Numbers added\n                \"name\": \"test\",  # Left value preserved\n            }\n            ```\n    \"\"\"\n    if left is None:\n        return right\n\n    if right is None:\n        return left\n\n    result = {}\n\n    all_keys = set(left) | set(right)\n\n    for key in all_keys:\n        left_value = left.get(key)\n        right_value = right.get(key)\n\n        if isinstance(left_value, Number) and isinstance(right_value, Number):\n            result[key] = left_value + right_value  # type: ignore\n        elif key in left:\n            result[key] = left_value\n        else:\n            result[key] = right_value\n\n    return result\n\ndef combine_usage(left: Usage | None, right: Usage | None) -> Usage | None:\n    \"\"\"\n    Merge two LiteLLM usage statistics.\n    \n    Combines token counts and details from two Usage objects:\n    - Adds all token counts (prompt, completion, total)\n    - Merges token details dictionaries\n    - Handles optional fields and None values\n    \n    Args:\n    left: First Usage object to merge.\n    right: Second Usage object to merge.\n    \n    Returns:\n    Combined Usage object or None if both inputs are None.\n    \n    Examples:\n    Basic merge:\n    ```python\n    usage1 = Usage(\n    prompt_tokens=10,\n    completion_tokens=5,\n    total_tokens=15,\n    )\n    usage2 = Usage(\n    prompt_tokens=20,\n    completion_tokens=10,\n    total_tokens=30,\n    )\n    total = combine_usage(usage1, usage2)\n    assert total.prompt_tokens == 30\n    assert total.completion_tokens == 15\n    assert total.total_tokens == 45\n    ```\n    \n    With details:\n    ```python\n    usage1 = Usage(\n    prompt_tokens=10,\n    completion_tokens=5,\n    prompt_tokens_details={\"system\": 3, \"user\": 7},\n    )\n    usage2 = Usage(\n    prompt_tokens=15,\n    completion_tokens=8,\n    prompt_tokens_details={\"system\": 5, \"user\": 10},\n    )\n    total = combine_usage(usage1, usage2)\n    assert total.prompt_tokens_details == {\"system\": 8, \"user\": 17}\n    ```\n    \"\"\"\n",
        "input": "",
        "output": "    if left is None:\n        return right\n\n    if right is None:\n        return left\n\n    prompt_tokens = (left.prompt_tokens or 0) + (right.prompt_tokens or 0)\n    completion_tokens = (left.completion_tokens or 0) + (right.completion_tokens or 0)\n    total_tokens = (left.total_tokens or 0) + (right.total_tokens or 0)\n\n    lhs_reasoning_tokens = safe_get_attr(left, \"reasoning_tokens\", int, default=0)\n    rhs_reasoning_tokens = safe_get_attr(right, \"reasoning_tokens\", int, default=0)\n    reasoning_tokens = lhs_reasoning_tokens + rhs_reasoning_tokens\n\n    lhs_completion_tokens_details = safe_get_attr(left, \"completion_tokens_details\", dict)\n    rhs_completion_tokens_details = safe_get_attr(right, \"completion_tokens_details\", dict)\n    completion_tokens_details = combine_dicts(\n        lhs_completion_tokens_details,\n        rhs_completion_tokens_details,\n    )\n\n    lhs_prompt_tokens_details = safe_get_attr(left, \"prompt_tokens_details\", dict)\n    rhs_prompt_tokens_details = safe_get_attr(right, \"prompt_tokens_details\", dict)\n    prompt_tokens_details = combine_dicts(\n        lhs_prompt_tokens_details,\n        rhs_prompt_tokens_details,\n    )\n\n    return Usage(\n        prompt_tokens=prompt_tokens,\n        completion_tokens=completion_tokens,\n        total_tokens=total_tokens,\n        reasoning_tokens=reasoning_tokens,\n        completion_tokens_details=completion_tokens_details,\n        prompt_tokens_details=prompt_tokens_details,\n    )\n\n",
        "idx": "457"
    },
    {
        "instruction": "## examples/advanced/structured_outputs/strategies/openai_pydantic.py\nfrom collections.abc import Callable\n\nfrom typing import Literal, TypeAlias, TypeVar, get_args\n\nfrom pydantic import BaseModel\n\nfrom liteswarm import LLM, Agent, ContextVariables\n\nfrom liteswarm.utils.pydantic import (\n    remove_default_values,\n    replace_default_values,\n    restore_default_values,\n)\n\nT = TypeVar(\"T\", bound=BaseModel)\n\ndef create_response_parser(response_format: type[T], patched_response_format: type[BaseModel]) -> Callable[[str, ContextVariables], T]:\n    \"\"\"\n    Create a response parser for OpenAI models.\n    \n    Args:\n    response_format: Original response format type.\n    patched_response_format: Modified response format with defaults removed.\n    \n    Returns:\n    A callable that parses OpenAI responses into the specified format.\n    \n    Notes:\n    The parser handles OpenAI's response format and restores default values\n    that were removed to improve response accuracy.\n    \"\"\"\n",
        "input": "",
        "output": "    def response_parser(response: str, _: ContextVariables) -> T:\n        patched_response_content = patched_response_format.model_validate_json(response)\n        return restore_default_values(patched_response_content, response_format)\n\n    return response_parser\n\n",
        "idx": "461"
    },
    {
        "instruction": "## examples/advanced/structured_outputs/strategies/llm_json_tags.py\nimport re\n\ndef find_tag(text: str, tag: str) -> str | None:\n    \"\"\"\n    Find and extract content from a tagged section.\n    \n    Args:\n    text: Text containing tagged sections.\n    tag: Name of the tag to find.\n    \n    Returns:\n    Content between the specified tags, or None if not found.\n    \"\"\"\n",
        "input": "",
        "output": "    pattern = re.compile(rf\"<{tag}>(.*?)</{tag}>\", re.DOTALL)\n    match = pattern.search(text)\n    return match.group(1) if match else None\n\n",
        "idx": "462"
    },
    {
        "instruction": "## examples/advanced/chat_app_server/app.py\nfrom dataclasses import dataclass, field\n\nfrom typing import Annotated, Any\n\nfrom uuid import uuid4\n\nfrom pydantic import BaseModel, ConfigDict\n\nfrom liteswarm import SwarmChat, set_verbose\n\nclass ChatSession:\n    \"\"\"Chat session container.\"\"\"\n\n    session_id: str\n    user_id: str\n    chat: SwarmChat\n    last_agent_id: str | None = None\n\nclass ChatState:\n    \"\"\"State container for chat components.\"\"\"\n\n    user_store: \"UserStore\"\n    sessions: dict[str, ChatSession] = field(default_factory=dict)\n\n    async def create_session(self, user_id: str) -> ChatSession:\n        \"\"\"Create a new chat session.\n\n        Args:\n            user_id: ID of the user creating the session.\n\n        Returns:\n            New chat session.\n        \"\"\"\n        chat = SwarmChat()\n        session_id = str(uuid4())\n        session = ChatSession(\n            session_id=session_id,\n            user_id=user_id,\n            chat=chat,\n        )\n\n        self.sessions[session_id] = session\n        return session\n\n    async def get_session(self, session_id: str) -> ChatSession | None:\n        \"\"\"Get a chat session by ID.\n\n        Args:\n            session_id: ID of the session to get.\n\n        Returns:\n            Chat session if found, None otherwise.\n        \"\"\"\n        return self.sessions.get(session_id)\n\n    async def delete_session(self, session_id: str) -> None:\n        \"\"\"Delete a chat session.\n\n        Args:\n            session_id: ID of the session to delete.\n        \"\"\"\n        if session_id in self.sessions:\n            self.sessions.pop(session_id)\n\n    async def get_user_sessions(self, user_id: str) -> list[ChatSession]:\n        \"\"\"Get all sessions for a user.\n\n        Args:\n            user_id: ID of the user to get sessions for.\n\n        Returns:\n            List of user's chat sessions.\n        \"\"\"\n        return [s for s in self.sessions.values() if s.user_id == user_id]\n\n    async def delete_user_sessions(self, user_id: str) -> None:\n        \"\"\"Delete all sessions for a user.\n\n        Args:\n            user_id: ID of the user to delete sessions for.\n        \"\"\"\n        session_ids = [s.session_id for s in self.sessions.values() if s.user_id == user_id]\n        for session_id in session_ids:\n            await self.delete_session(session_id)\n\nclass UserStore:\n    \"\"\"In-memory user management for chat server.\"\"\"\n\n    _users: dict[str, \"User\"] = field(default_factory=dict)\n\n    async def add_user(\n        self,\n        user_id: str,\n        name: str | None = None,\n        metadata: dict[str, Any] | None = None,\n    ) -> None:\n        \"\"\"Add new user.\"\"\"\n        if user_id in self._users:\n            raise ValueError(\"User already exists\")\n\n        self._users[user_id] = User(\n            user_id=user_id,\n            name=name,\n            metadata=metadata,\n        )\n\n    async def get_user(self, user_id: str) -> \"User | None\":\n        \"\"\"Get user by ID.\"\"\"\n        return self._users.get(user_id)\n\n    async def list_users(self) -> dict[str, \"User\"]:\n        \"\"\"Get all users.\"\"\"\n        return self._users.copy()\n\n    async def delete_user(self, user_id: str) -> None:\n        \"\"\"Delete user.\"\"\"\n        if user_id not in self._users:\n            return\n        self._users.pop(user_id)\n\nclass PydanticModel(BaseModel):\n    \"\"\"Base model for Pydantic models.\"\"\"\n\n    model_config = ConfigDict(\n        arbitrary_types_allowed=True,\n        use_attribute_docstrings=True,\n        extra=\"forbid\",\n    )\n\nclass User(PydanticModel):\n    \"\"\"User model for chat server.\"\"\"\n\n    user_id: str\n    name: str | None = None\n    metadata: dict[str, Any] | None = None\n\nclass StateManager:\n    \"\"\"Singleton manager for application state.\"\"\"\n\n    _chat_state: ChatState | None = None\n\n    @classmethod\n    def get_chat_state(cls) -> ChatState:\n        \"\"\"\n        Get or create chat state.\n        \"\"\"\n",
        "input": "",
        "output": "        if cls._chat_state is None:\n            cls._chat_state = ChatState(user_store=UserStore())\n        return cls._chat_state\n    \n",
        "idx": "469"
    },
    {
        "instruction": "## examples/advanced/agent_team/run.py\nfrom typing import Any, Literal, get_args, get_origin\n\nfrom pydantic import BaseModel\n\nclass TaskBase(BaseModel):\n    \"\"\"Base class for all task types.\"\"\"\n\n    type: str\n    id: str\n    title: str\n    description: str\n\n    @classmethod\n    def task_type(cls) -> str:\n        \"\"\"Get the task type.\"\"\"\n        type_field = cls.model_fields[\"type\"]\n        origin = get_origin(type_field.annotation)\n        if origin is Literal:\n            return get_args(type_field.annotation)[0]\n\n        raise ValueError(\"Task type is not set\")\n\n    def build_prompt(self) -> str:\n        \"\"\"\n        Build a prompt for this task.\n        \"\"\"\n",
        "input": "",
        "output": "        raise NotImplementedError(\"Subclasses must implement build_prompt\")\n    \n",
        "idx": "471"
    },
    {
        "instruction": "# Here are some relevant code fragments from other files of the repo:\n# --------------------------------------------------\n# the below code fragment can be found in:\n# liteswarm/types/typing.py\n# --------------------------------------------------\n# from typing import TYPE_CHECKING, Any, TypeAlias, TypeGuard, TypeVar, Union, get_args, get_origin\n# \n# --------------------------------------------------\n# the below code fragment can be found in:\n# liteswarm/types/base.py\n# --------------------------------------------------\n# from pydantic import BaseModel, ConfigDict\n# \n# class SwarmBaseModel(BaseModel):\n#     \"\"\"Base model configuration for Swarm types.\n# \n#     Enables arbitrary types, docstrings as descriptions, and strict field checking.\n#     \"\"\"\n# \n#     model_config = ConfigDict(\n#         arbitrary_types_allowed=True,\n#         use_attribute_docstrings=True,\n#         extra=\"forbid\",\n#     )\n# \n# --------------------------------------------------\n\n\n## liteswarm/types/llm.py\nfrom typing import Any, Generic, Literal, Self, TypeAlias\n\nfrom litellm.types.utils import ChatCompletionAudioResponse, ChatCompletionDeltaToolCall, FunctionCall\n\nfrom litellm.types.utils import Delta as LiteDelta\n\nfrom liteswarm.types.base import SwarmBaseModel\n\nMessageRole: TypeAlias = Literal[\"assistant\", \"user\", \"system\", \"tool\", \"function\", \"developer\"]\n\nToolCall: TypeAlias = ChatCompletionDeltaToolCall\n\nAudioResponse: TypeAlias = ChatCompletionAudioResponse\n\nclass Delta(SwarmBaseModel):\n    \"\"\"Streaming update from language model generation.\n\n    Contains new content and changes since the last update during\n    streaming. Updates can include text content, role changes,\n    tool calls, or audio responses.\n\n    Note:\n        Any field may be empty or partially complete.\n    \"\"\"\n\n    content: str | None = None\n    \"\"\"New text content.\"\"\"\n\n    role: MessageRole | None = None\n    \"\"\"Role of the message author.\"\"\"\n\n    function_call: FunctionCall | None = None\n    \"\"\"Function call update (deprecated).\"\"\"\n\n    tool_calls: list[ToolCall] | None = None\n    \"\"\"Tool calls being made.\"\"\"\n\n    audio: AudioResponse | None = None\n    \"\"\"Audio response if available.\"\"\"\n\n    @property\n    def is_empty(self) -> bool:\n        \"\"\"Check if the delta is empty.\n\n        Returns:\n            True if the delta is empty, False otherwise.\n        \"\"\"\n        return all(not getattr(self, attr) for attr in self.model_fields)\n\n    @classmethod\n    def from_delta(cls, delta: LiteDelta) -> 'Delta':\n        \"\"\"\n        Create a Delta from a LiteLLM delta object.\n    \n        Args:\n        delta: LiteLLM delta to convert.\n    \n        Returns:\n        New Delta instance with copied attributes.\n        \"\"\"\n",
        "input": "",
        "output": "        return cls(\n            content=delta.content,\n            role=delta.role,\n            function_call=delta.function_call,\n            tool_calls=delta.tool_calls,\n            audio=delta.audio,\n        )\n    \n",
        "idx": "474"
    },
    {
        "instruction": "# Here are some relevant code fragments from other files of the repo:\n# --------------------------------------------------\n# the below code fragment can be found in:\n# liteswarm/types/typing.py\n# --------------------------------------------------\n# from typing import TYPE_CHECKING, Any, TypeAlias, TypeGuard, TypeVar, Union, get_args, get_origin\n# \n# --------------------------------------------------\n# the below code fragment can be found in:\n# liteswarm/types/base.py\n# --------------------------------------------------\n# from pydantic import BaseModel, ConfigDict\n# \n# class SwarmBaseModel(BaseModel):\n#     \"\"\"Base model configuration for Swarm types.\n# \n#     Enables arbitrary types, docstrings as descriptions, and strict field checking.\n#     \"\"\"\n# \n#     model_config = ConfigDict(\n#         arbitrary_types_allowed=True,\n#         use_attribute_docstrings=True,\n#         extra=\"forbid\",\n#     )\n# \n# --------------------------------------------------\n# the below code fragment can be found in:\n# liteswarm/types/llm.py\n# --------------------------------------------------\n# from typing import Any, Generic, Literal, Self, TypeAlias\n# \n# from litellm.types.utils import ChatCompletionAudioResponse, ChatCompletionDeltaToolCall, FunctionCall\n# \n# from liteswarm.types.base import SwarmBaseModel\n# \n# MessageRole: TypeAlias = Literal[\"assistant\", \"user\", \"system\", \"tool\", \"function\", \"developer\"]\n# \n# ToolCall: TypeAlias = ChatCompletionDeltaToolCall\n# \n# AudioResponse: TypeAlias = ChatCompletionAudioResponse\n# \n# class Message(SwarmBaseModel):\n#     \"\"\"Message in a conversation between user, assistant, and tools.\n# \n#     Represents a message in a conversation between participants\n#     with content and optional tool interactions. Each message has\n#     a specific role and may include tool calls or responses.\n# \n#     Examples:\n#         System message:\n#             ```python\n#             system_msg = Message(\n#                 role=\"system\",\n#                 content=\"You are a helpful assistant.\",\n#             )\n#             ```\n# \n#         Assistant with tool:\n#             ```python\n#             assistant_msg = Message(\n#                 role=\"assistant\",\n#                 content=\"Let me calculate that.\",\n#                 tool_calls=[\n#                     ToolCall(\n#                         id=\"calc_1\",\n#                         function={\"name\": \"add\", \"arguments\": '{\"a\": 2, \"b\": 2}'},\n#                         type=\"function\",\n#                         index=0,\n#                     )\n#                 ],\n#             )\n#             ```\n# \n#         Tool response:\n#             ```python\n#             tool_msg = Message(\n#                 role=\"tool\",\n#                 content=\"4\",\n#                 tool_call_id=\"calc_1\",\n#             )\n#             ```\n#     \"\"\"\n# \n#     role: MessageRole\n#     \"\"\"Role of the message author.\"\"\"\n# \n#     content: str | None = None\n#     \"\"\"Text content of the message.\"\"\"\n# \n#     tool_calls: list[ToolCall] | None = None\n#     \"\"\"Tool calls made in this message.\"\"\"\n# \n#     tool_call_id: str | None = None\n#     \"\"\"ID of the tool call this message responds to.\"\"\"\n# \n#     audio: AudioResponse | None = None\n#     \"\"\"Audio response data if available.\"\"\"\n# \n# --------------------------------------------------\n\n\n## liteswarm/types/chat.py\nimport uuid\n\nfrom datetime import datetime\n\nfrom typing import Annotated, Any, Generic, Literal\n\nfrom pydantic import BaseModel, ConfigDict, Discriminator, field_serializer\n\nfrom liteswarm.types.llm import AudioResponse, Message, MessageRole, ToolCall\n\nclass ChatMessage(BaseModel):\n    \"\"\"Message type for chat applications with metadata support.\n\n    Extends the base Message type with fields for identification, timestamps,\n    and application-specific metadata. Maintains compatibility with base Message\n    while adding features needed for chat applications.\n\n    Examples:\n        ```python\n        # Create from scratch\n        message = ChatMessage(\n            id=\"msg_123\",\n            role=\"user\",\n            content=\"Hello!\",\n            metadata={\"client_id\": \"web_1\"},\n        )\n\n        # Convert from base Message\n        base_msg = Message(role=\"assistant\", content=\"Hi!\")\n        chat_msg = ChatMessage.from_message(\n            base_msg,\n            metadata={\"source\": \"chat\"},\n        )\n        ```\n    \"\"\"\n\n    id: str\n    \"\"\"Unique message identifier.\"\"\"\n\n    role: MessageRole\n    \"\"\"Role of the message author.\"\"\"\n\n    content: str | None = None\n    \"\"\"Text content of the message.\"\"\"\n\n    tool_calls: list[ToolCall] | None = None\n    \"\"\"Tool calls made in this message.\"\"\"\n\n    tool_call_id: str | None = None\n    \"\"\"ID of the tool call this message responds to.\"\"\"\n\n    audio: AudioResponse | None = None\n    \"\"\"Audio response data if available.\"\"\"\n\n    created_at: datetime = datetime.now()\n    \"\"\"Message creation timestamp.\"\"\"\n\n    metadata: dict[str, Any] | None = None\n    \"\"\"Application-specific message data.\"\"\"\n\n    model_config = ConfigDict(\n        arbitrary_types_allowed=True,\n        use_attribute_docstrings=True,\n        extra=\"forbid\",\n    )\n\n    @classmethod\n    def from_message(cls, message: Message, *, id: str | None=None, created_at: datetime | None=None, metadata: dict[str, Any] | None=None) -> 'ChatMessage':\n        \"\"\"\n        Create a ChatMessage from a base Message.\n    \n        Args:\n        message: Base Message to convert.\n        id: Optional message identifier.\n        created_at: Optional creation timestamp.\n        metadata: Optional message metadata.\n    \n        Returns:\n        New ChatMessage with added fields.\n        \"\"\"\n",
        "input": "",
        "output": "        return cls(\n            id=id or str(uuid.uuid4()),\n            role=message.role,\n            content=message.content,\n            tool_calls=message.tool_calls,\n            tool_call_id=message.tool_call_id,\n            audio=message.audio,\n            created_at=created_at or datetime.now(),\n            metadata=metadata,\n        )\n    \n",
        "idx": "477"
    },
    {
        "instruction": "\ndef convert_to_dict(sql_result):\n    \"\"\"\n    Converts the results of a query to a JSON format.\n    \n    Parameters:\n    results (ResultProxy): The result of a query.\n    \n    Returns:\n    list: A list of dictionaries, where each dictionary represents a row in the query result.\n    \"\"\"\n",
        "input": "",
        "output": "    raw_results = sql_result.all()\n\n    # Convert each row to a dictionary\n    return [dict(row._mapping) for row in raw_results]\n\n",
        "idx": "484"
    },
    {
        "instruction": "## models/features.py\nfrom sklearn.preprocessing import StandardScaler, OneHotEncoder, LabelEncoder\n\ndef family_feat_eng(data):\n    \"\"\"\n    Add family-related features to the dataset: Family_Size and Family_category.\n    \"\"\"\n",
        "input": "",
        "output": "    data[\"Family_Size\"] = data[\"Parch\"] + data[\"SibSp\"]\n\n    # categorize 'Family_size' into 'family_category'\n    def categorize_family_size(size):\n        if size == 0:\n            return \"no family\"\n        elif size <= 3:\n            return \"small family\"\n        else:\n            return \"large family\"\n\n    data[\"Family_category\"] = data[\"Family_Size\"].apply(categorize_family_size)\n\n    # encode family_category with numbers\n    family_encoder = LabelEncoder()\n    data[\"Family_category\"] = family_encoder.fit_transform(data[\"Family_category\"])\n\n    return data\n\n",
        "idx": "486"
    },
    {
        "instruction": "## models/features.py\nimport pandas as pd\n\nfrom sklearn.preprocessing import StandardScaler, OneHotEncoder, LabelEncoder\n\ndef age_feat_eng(data):\n    \"\"\"\n    Add age-related categories to the dataset: Age_band.\n    \"\"\"\n",
        "input": "",
        "output": "    bins = [-float(\"inf\"), 2, 4, 12, 18, 30, 45, 60, float(\"inf\")]\n    labels = [\n        \"baby\",\n        \"infant\",\n        \"child\",\n        \"teenager\",\n        \"youngadult\",\n        \"adult\",\n        \"oldadult\",\n        \"elder\",\n    ]\n\n    # Cut the 'Age' column into bins and add 'Age_band'\n    data[\"Age_band\"] = pd.cut(data[\"Age\"], bins=bins, labels=labels)\n\n    # encode Age_band with numbers\n    age_band_encoder = LabelEncoder()\n    data[\"Age_band\"] = age_band_encoder.fit_transform(data[\"Age_band\"])\n\n    return data\n\n",
        "idx": "487"
    },
    {
        "instruction": "## models/features.py\nfrom sklearn.impute import SimpleImputer\n\nfrom sklearn.preprocessing import StandardScaler, OneHotEncoder, LabelEncoder\n\nfrom sklearn.compose import ColumnTransformer\n\nfrom sklearn.pipeline import Pipeline\n\npreprocessor = ColumnTransformer(\n    transformers=[\n        # Pipeline for numerical features\n        (\n            \"num\",\n            Pipeline(\n                steps=[\n                    (\n                        \"imputer\",\n                        SimpleImputer(strategy=\"median\"),\n                    ),  # Impute missing values for numerical features\n                    (\"scaler\", StandardScaler()),\n                ]\n            ),\n            [\n                \"Fare\",\n            ],\n        ),\n        # Pipeline for categorical features\n        (\n            \"cat\",\n            Pipeline(\n                steps=[\n                    (\n                        \"imputer\",\n                        SimpleImputer(strategy=\"most_frequent\"),\n                    ),  # Impute missing values for categorical features\n                    (\n                        \"onehot\",\n                        OneHotEncoder(sparse_output=False, handle_unknown=\"ignore\"),\n                    ),\n                ]\n            ),\n            [\"Pclass\", \"Age_band\", \"Family_category\", \"Sex\", \"Embarked\"],\n        ),\n    ],\n    remainder=\"passthrough\",\n)\n\ndef preprocess_feat(X, fit=False):\n    \"\"\"\n    Apply the preprocessor to the dataset.\n    Parameters:\n    - X: Feature dataset to process\n    - fit: If True, fit and transform (use for training data)\n    If False, just transform (use for test/validation data)\n    \"\"\"\n",
        "input": "",
        "output": "    if fit:\n        X_transformed = preprocessor.fit_transform(X)\n    else:\n        X_transformed = preprocessor.transform(X)\n\n    return X_transformed\n\n",
        "idx": "490"
    },
    {
        "instruction": "## sra_dispatch/read_config.py\nimport json\n\ndef load_config(json_file) -> dict:\n    \"\"\"\n    Reads a JSON config file and returns a dictionary object.\n    \"\"\"\n",
        "input": "",
        "output": "    with open(json_file) as file:\n        config = json.load(file)\n    return config\n\n",
        "idx": "492"
    },
    {
        "instruction": "\ndef get_nt_indels(col_reads):\n    \"\"\"\n    Called to collect indels if amino acid reporting is disabled\n    Parameters:\n    col_reads - dict of unique variant sequences\n    Functionality: goes through unique sequences looking for indels and adds them to a new dict\n    Returns the new indel dict\n    \"\"\"\n",
        "input": "",
        "output": "    indel_dict = {}\n    for SNP_sequence in col_reads:\n        if \"del\" in SNP_sequence or \"insert\" in SNP_sequence:\n            for mut in SNP_sequence.split(\" \"):\n                if \"del\" in mut or \"ins\" in mut:\n                    try:\n                        indel_dict[mut] += sum(col_reads[SNP_sequence].values())\n                    except:\n                        indel_dict[mut] = sum(col_reads[SNP_sequence].values())\n    return(indel_dict)\n\n",
        "idx": "496"
    },
    {
        "instruction": "## knnreg.py\nimport numpy as np\n\nimport pandas as pd\n\nX = pd.DataFrame(X)\n\ny = pd.Series(y)\n\nX.columns = [f'col_{col}' for col in X.columns]\n\nclass MyKNNReg:\n    \"\"\"\n    \u041a\u043b\u0430\u0441\u0441 \u0434\u043b\u044f \u0440\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u0438 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u0430 k-\u0431\u043b\u0438\u0436\u0430\u0439\u0448\u0438\u0445 \u0441\u043e\u0441\u0435\u0434\u0435\u0439 \u0434\u043b\u044f \u0440\u0435\u0433\u0440\u0435\u0441\u0441\u0438\u0438.\n\n    Attributes:\n        k (int): \u041a\u043e\u043b\u0438\u0447\u0435\u0441\u0442\u0432\u043e \u0431\u043b\u0438\u0436\u0430\u0439\u0448\u0438\u0445 \u0441\u043e\u0441\u0435\u0434\u0435\u0439.\n        metric (str): \u041c\u0435\u0442\u0440\u0438\u043a\u0430 \u0434\u043b\u044f \u0440\u0430\u0441\u0447\u0435\u0442\u0430 \u0440\u0430\u0441\u0441\u0442\u043e\u044f\u043d\u0438\u044f.\n        weight (str): \u0422\u0438\u043f \u0432\u0435\u0441\u043e\u0432 \u0434\u043b\u044f \u043f\u0440\u0435\u0434\u0441\u043a\u0430\u0437\u0430\u043d\u0438\u044f.\n        X_train (pd.DataFrame): \u041e\u0431\u0443\u0447\u0430\u044e\u0449\u0430\u044f \u0432\u044b\u0431\u043e\u0440\u043a\u0430.\n        y_train (pd.Series): \u0426\u0435\u043b\u0435\u0432\u0430\u044f \u043f\u0435\u0440\u0435\u043c\u0435\u043d\u043d\u0430\u044f \u043e\u0431\u0443\u0447\u0430\u044e\u0449\u0435\u0439 \u0432\u044b\u0431\u043e\u0440\u043a\u0438.\n    \"\"\"\n\n    def __init__(self, k=3, metric='euclidean', weight='uniform'):\n        \"\"\"\n        \u0418\u043d\u0438\u0446\u0438\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f \u043a\u043b\u0430\u0441\u0441\u0430.\n\n        Args:\n            k (int): \u041a\u043e\u043b\u0438\u0447\u0435\u0441\u0442\u0432\u043e \u0431\u043b\u0438\u0436\u0430\u0439\u0448\u0438\u0445 \u0441\u043e\u0441\u0435\u0434\u0435\u0439.\n            metric (str): \u041c\u0435\u0442\u0440\u0438\u043a\u0430 \u0434\u043b\u044f \u0440\u0430\u0441\u0447\u0435\u0442\u0430 \u0440\u0430\u0441\u0441\u0442\u043e\u044f\u043d\u0438\u044f.\n            weight (str): \u0422\u0438\u043f \u0432\u0435\u0441\u043e\u0432 \u0434\u043b\u044f \u043f\u0440\u0435\u0434\u0441\u043a\u0430\u0437\u0430\u043d\u0438\u044f.\n        \"\"\"\n        self.k = k\n        self.metric = metric\n        self.weight = weight\n        self.X_train = None\n        self.y_train = None\n\n    def __repr__(self):\n        return f'MyKNNReg class: k={self.k}'\n\n    def fit(self, X, y):\n        \"\"\"\n        \u041e\u0431\u0443\u0447\u0435\u043d\u0438\u0435 \u043c\u043e\u0434\u0435\u043b\u0438.\n    \n        Args:\n        X (pd.DataFrame): \u041e\u0431\u0443\u0447\u0430\u044e\u0449\u0430\u044f \u0432\u044b\u0431\u043e\u0440\u043a\u0430.\n        y (pd.Series): \u0426\u0435\u043b\u0435\u0432\u0430\u044f \u043f\u0435\u0440\u0435\u043c\u0435\u043d\u043d\u0430\u044f \u043e\u0431\u0443\u0447\u0430\u044e\u0449\u0435\u0439 \u0432\u044b\u0431\u043e\u0440\u043a\u0438.\n        \"\"\"\n",
        "input": "",
        "output": "        self.X_train = X.copy()\n        self.y_train = y.copy()\n    \n",
        "idx": "499"
    },
    {
        "instruction": "## knnreg.py\nimport numpy as np\n\nimport pandas as pd\n\nX = pd.DataFrame(X)\n\ny = pd.Series(y)\n\nX.columns = [f'col_{col}' for col in X.columns]\n\nclass MyKNNReg:\n    \"\"\"\n    \u041a\u043b\u0430\u0441\u0441 \u0434\u043b\u044f \u0440\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u0438 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u0430 k-\u0431\u043b\u0438\u0436\u0430\u0439\u0448\u0438\u0445 \u0441\u043e\u0441\u0435\u0434\u0435\u0439 \u0434\u043b\u044f \u0440\u0435\u0433\u0440\u0435\u0441\u0441\u0438\u0438.\n\n    Attributes:\n        k (int): \u041a\u043e\u043b\u0438\u0447\u0435\u0441\u0442\u0432\u043e \u0431\u043b\u0438\u0436\u0430\u0439\u0448\u0438\u0445 \u0441\u043e\u0441\u0435\u0434\u0435\u0439.\n        metric (str): \u041c\u0435\u0442\u0440\u0438\u043a\u0430 \u0434\u043b\u044f \u0440\u0430\u0441\u0447\u0435\u0442\u0430 \u0440\u0430\u0441\u0441\u0442\u043e\u044f\u043d\u0438\u044f.\n        weight (str): \u0422\u0438\u043f \u0432\u0435\u0441\u043e\u0432 \u0434\u043b\u044f \u043f\u0440\u0435\u0434\u0441\u043a\u0430\u0437\u0430\u043d\u0438\u044f.\n        X_train (pd.DataFrame): \u041e\u0431\u0443\u0447\u0430\u044e\u0449\u0430\u044f \u0432\u044b\u0431\u043e\u0440\u043a\u0430.\n        y_train (pd.Series): \u0426\u0435\u043b\u0435\u0432\u0430\u044f \u043f\u0435\u0440\u0435\u043c\u0435\u043d\u043d\u0430\u044f \u043e\u0431\u0443\u0447\u0430\u044e\u0449\u0435\u0439 \u0432\u044b\u0431\u043e\u0440\u043a\u0438.\n    \"\"\"\n\n    def __init__(self, k=3, metric='euclidean', weight='uniform'):\n        \"\"\"\n        \u0418\u043d\u0438\u0446\u0438\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f \u043a\u043b\u0430\u0441\u0441\u0430.\n\n        Args:\n            k (int): \u041a\u043e\u043b\u0438\u0447\u0435\u0441\u0442\u0432\u043e \u0431\u043b\u0438\u0436\u0430\u0439\u0448\u0438\u0445 \u0441\u043e\u0441\u0435\u0434\u0435\u0439.\n            metric (str): \u041c\u0435\u0442\u0440\u0438\u043a\u0430 \u0434\u043b\u044f \u0440\u0430\u0441\u0447\u0435\u0442\u0430 \u0440\u0430\u0441\u0441\u0442\u043e\u044f\u043d\u0438\u044f.\n            weight (str): \u0422\u0438\u043f \u0432\u0435\u0441\u043e\u0432 \u0434\u043b\u044f \u043f\u0440\u0435\u0434\u0441\u043a\u0430\u0437\u0430\u043d\u0438\u044f.\n        \"\"\"\n        self.k = k\n        self.metric = metric\n        self.weight = weight\n        self.X_train = None\n        self.y_train = None\n\n    def __repr__(self):\n        return f'MyKNNReg class: k={self.k}'\n\n    def fit(self, X, y):\n        \"\"\"\n        \u041e\u0431\u0443\u0447\u0435\u043d\u0438\u0435 \u043c\u043e\u0434\u0435\u043b\u0438.\n\n        Args:\n            X (pd.DataFrame): \u041e\u0431\u0443\u0447\u0430\u044e\u0449\u0430\u044f \u0432\u044b\u0431\u043e\u0440\u043a\u0430.\n            y (pd.Series): \u0426\u0435\u043b\u0435\u0432\u0430\u044f \u043f\u0435\u0440\u0435\u043c\u0435\u043d\u043d\u0430\u044f \u043e\u0431\u0443\u0447\u0430\u044e\u0449\u0435\u0439 \u0432\u044b\u0431\u043e\u0440\u043a\u0438.\n        \"\"\"\n        self.X_train = X.copy()\n        self.y_train = y.copy()\n\n    def predict(self, X_test):\n        \"\"\"\n        \u041f\u0440\u0435\u0434\u0441\u043a\u0430\u0437\u0430\u043d\u0438\u0435 \u0437\u043d\u0430\u0447\u0435\u043d\u0438\u0439 \u0446\u0435\u043b\u0435\u0432\u043e\u0439 \u043f\u0435\u0440\u0435\u043c\u0435\u043d\u043d\u043e\u0439.\n\n        Args:\n            X_test (pd.DataFrame): \u0422\u0435\u0441\u0442\u043e\u0432\u0430\u044f \u0432\u044b\u0431\u043e\u0440\u043a\u0430.\n\n        Returns:\n            np.array: \u041f\u0440\u0435\u0434\u0441\u043a\u0430\u0437\u0430\u043d\u043d\u044b\u0435 \u0437\u043d\u0430\u0447\u0435\u043d\u0438\u044f \u0446\u0435\u043b\u0435\u0432\u043e\u0439 \u043f\u0435\u0440\u0435\u043c\u0435\u043d\u043d\u043e\u0439.\n        \"\"\"\n        predictions = []\n\n        for index, test_point in X_test.iterrows():\n            # \u0412\u044b\u0447\u0438\u0441\u043b\u044f\u0435\u043c \u0440\u0430\u0441\u0441\u0442\u043e\u044f\u043d\u0438\u0435 \u0434\u043e \u043a\u0430\u0436\u0434\u043e\u0433\u043e \u043e\u0431\u044a\u0435\u043a\u0442\u0430 \u0438\u0437 \u043e\u0431\u0443\u0447\u0430\u044e\u0449\u0435\u0439 \u0432\u044b\u0431\u043e\u0440\u043a\u0438\n            distances = self._calculate_distance(self.X_train, test_point)\n\n            # \u041d\u0430\u0445\u043e\u0434\u0438\u043c \u0438\u043d\u0434\u0435\u043a\u0441\u044b k \u0431\u043b\u0438\u0436\u0430\u0439\u0448\u0438\u0445 \u0441\u043e\u0441\u0435\u0434\u0435\u0439\n            k_indices = np.argsort(distances)[:self.k]\n\n            # \u0423\u0441\u0440\u0435\u0434\u043d\u044f\u0435\u043c \u0437\u043d\u0430\u0447\u0435\u043d\u0438\u044f \u0442\u0430\u0440\u0433\u0435\u0442\u0430 \u0431\u043b\u0438\u0436\u0430\u0439\u0448\u0438\u0445 k \u043e\u0431\u044a\u0435\u043a\u0442\u043e\u0432\n            k_nearest_targets = self.y_train.iloc[k_indices]\n            k_nearest_distances = distances[k_indices]\n\n            # \u0412\u044b\u0447\u0438\u0441\u043b\u044f\u0435\u043c \u0432\u0435\u0441\u0430\n            weight = self._calculate_weight(k_nearest_distances)\n\n            # \u041d\u043e\u0440\u043c\u0430\u043b\u0438\u0437\u0443\u0435\u043c \u0432\u0435\u0441\u0430\n            weight /= weight.sum()\n\n            # \u0412\u044b\u0447\u0438\u0441\u043b\u044f\u0435\u043c \u043f\u0440\u0435\u0434\u0441\u043a\u0430\u0437\u0430\u043d\u0438\u0435 \u0441 \u0443\u0447\u0435\u0442\u043e\u043c \u0432\u0435\u0441\u043e\u0432\n            prediction = np.dot(weight, k_nearest_targets)\n            predictions.append(prediction)\n\n        return np.array(predictions)\n\n    def _calculate_distance(self, x1, x2):\n        \"\"\"\n        \u0420\u0430\u0441\u0447\u0435\u0442 \u0440\u0430\u0441\u0441\u0442\u043e\u044f\u043d\u0438\u044f \u043c\u0435\u0436\u0434\u0443 \u0434\u0432\u0443\u043c\u044f \u0442\u043e\u0447\u043a\u0430\u043c\u0438.\n    \n        Args:\n        x1 (pd.DataFrame): \u041f\u0435\u0440\u0432\u0430\u044f \u0442\u043e\u0447\u043a\u0430.\n        x2 (pd.Series): \u0412\u0442\u043e\u0440\u0430\u044f \u0442\u043e\u0447\u043a\u0430.\n    \n        Returns:\n        np.array: \u0420\u0430\u0441\u0441\u0442\u043e\u044f\u043d\u0438\u0435 \u043c\u0435\u0436\u0434\u0443 \u0434\u0432\u0443\u043c\u044f \u0442\u043e\u0447\u043a\u0430\u043c\u0438.\n        \"\"\"\n",
        "input": "",
        "output": "        metric = {\n            'euclidean': lambda x1, x2: np.sqrt(((x1 - x2) ** 2).sum(axis=1)),\n            'chebyshev': lambda x1, x2: np.max(np.abs(x1 - x2), axis=1),\n            'manhattan': lambda x1, x2: np.sum(np.abs(x1 - x2), axis=1),\n            'cosine': lambda x1, x2: 1 - np.dot(x1, x2) / (np.linalg.norm(x1, axis=1) * np.linalg.norm(x2)),\n        }\n        return metric[self.metric](x1, x2)\n    \n",
        "idx": "501"
    },
    {
        "instruction": "## tree_clas.py\nimport numpy as np\n\nfrom graphviz import Digraph\n\nclass MyTreeClf:\n    \n    def __init__(self, max_depth=15, min_samples_split=2, max_leafs=20, bins=None, criterion='entropy'):\n        self.max_depth = max_depth\n        self.min_samples_split = min_samples_split\n        self.max_leafs = max_leafs\n        self.bins = bins\n        self.leafs_cnt = 0\n        self.tree = None\n        self.histograms = {}\n        self.criterion = criterion\n        self.fi = {col: 0 for col in X.columns}\n        # self.reserved_leaves = 0\n        \n\n    def entropy(self, y):\n",
        "input": "",
        "output": "        value_counts = y.value_counts(normalize=True)\n        return -np.sum(value_counts * np.log2(value_counts))\n    \n",
        "idx": "502"
    },
    {
        "instruction": "## tree_reg.py\nimport numpy as np\n\nfrom graphviz import Digraph\n\nclass MyTreeReg:\n    def __init__(self, max_depth=5, min_samples_split=2, max_leafs=20):\n        self.max_depth = max_depth\n        self.min_samples_split = min_samples_split\n        self.max_leafs = max_leafs - 1\n        self.leafs_cnt = 0\n        self.reserved_leaves = 0\n        \n    def __repr__(self):\n        return f'MyTreeReg class: max_depth={self.max_depth}, min_samples_split={self.min_samples_split}, max_leafs={self.max_leafs}'\n    \n    def get_best_split(self, X, y):\n        best_gain = -np.inf\n        best_col_name = None\n        best_split_value = None\n        \n        for col_name in X.columns:\n            unique_values = np.sort(X[col_name].unique())\n            \n            for i in range(len(unique_values) - 1):\n                split_value = (unique_values[i] + unique_values[i + 1]) / 2\n                gain = self._calculate_mse_gain(X, y, col_name, split_value)\n                \n                if gain > best_gain:\n                    best_gain = gain\n                    best_col_name = col_name\n                    best_split_value = split_value\n        \n        return best_col_name, best_split_value, best_gain\n    \n    def _calculate_mse_gain(self, X, y, col_name, split_value):\n        left_mask = X[col_name] <= split_value\n        right_mask = X[col_name] > split_value\n        \n        y_left = y[left_mask]\n        y_right = y[right_mask]\n        \n        if len(y_left) == 0 or len(y_right) == 0:\n            return -np.inf\n        \n        mse_left = np.mean((y_left - np.mean(y_left)) ** 2)\n        mse_right = np.mean((y_right - np.mean(y_right)) ** 2)\n        total_mse = (len(y_left) * mse_left + len(y_right) * mse_right) / (len(y_left) + len(y_right))\n        \n        total_mse_original = np.mean((y - np.mean(y)) ** 2)\n        gain = total_mse_original - total_mse\n        \n        return gain\n    \n    def fit(self, X, y, depth=0, node=None):\n",
        "input": "",
        "output": "        if node is None:\n            self.tree = {}\n            node = self.tree\n            is_root = True\n        else:\n            is_root = False\n\n        if (depth >= self.max_depth or len(y) < self.min_samples_split or len(set(y)) == 1 or \n            self.max_leafs - self.leafs_cnt <= 1) and not is_root:\n            node['leaf'] = np.mean(y)\n            self.leafs_cnt += 1\n            return\n\n        col_name, split_value, ig = self.get_best_split(X, y)\n\n        node[col_name] = {}\n        node[col_name][f'<= {split_value}'] = {}\n        node[col_name][f'> {split_value}'] = {}\n\n\n        left_mask = X[col_name] <= split_value\n        right_mask = X[col_name] > split_value\n\n        self.fit(X[left_mask], y[left_mask], depth + 1, node[col_name][f'<= {split_value}'])\n        self.fit(X[right_mask], y[right_mask], depth + 1, node[col_name][f'> {split_value}'])\n    \n",
        "idx": "503"
    },
    {
        "instruction": "## log_reg.py\nimport random\n\nimport numpy as np\n\nimport pandas as pd\n\nfrom sklearn.metrics import precision_score, recall_score, f1_score, roc_auc_score, accuracy_score\n\nclass MyLogReg:\n    def __init__(self, n_iter=100, learning_rate=0.1, weights=None, metric=None, reg=None, l1_coef=0, l2_coef=0, sgd_sample=None, random_state=42):\n        self.n_iter = n_iter \n        self.learning_rate = learning_rate \n        self.weights = weights\n        self.metric = metric\n        self.best_score = None\n        self.reg = reg\n        self.l1_coef = l1_coef\n        self.l2_coef = l2_coef\n        self.sgd_sample = sgd_sample\n        self.random_state = random_state\n\n        \n    def __str__(self):\n        return f\"MyLineReg class: n_iter={self.n_iter}, learning_rate={self.learning_rate}\"\n\n\n    def fit(self, X: pd.DataFrame, y: pd.Series, verbose=False):\n        random.seed(self.random_state)\n        X = np.hstack((np.ones((X.shape[0], 1)), X))  # \u0414\u043e\u0431\u0430\u0432\u043b\u044f\u0435\u043c \u0441\u0442\u043e\u043b\u0431\u0435\u0446 \u0435\u0434\u0438\u043d\u0438\u0446\n        self.weights = np.ones(X.shape[1])  # \u0418\u043d\u0438\u0446\u0438\u0430\u043b\u0438\u0437\u0438\u0440\u0443\u0435\u043c weights \u0441 \u043f\u0440\u0430\u0432\u0438\u043b\u044c\u043d\u043e\u0439 \u0440\u0430\u0437\u043c\u0435\u0440\u043d\u043e\u0441\u0442\u044c\u044e\n        \n        for i in range(1, self.n_iter + 1):\n            batch_X, batch_y = self._get_mini_batch(X, y)\n            y_pred, loss, gradient = self._data_calculations(batch_X, batch_y)\n            learning_rate = self.learning_rate(i) if callable(self.learning_rate) else self.learning_rate\n            self.weights -= learning_rate * gradient\n            metric_value = self._calculate_metric(batch_y, y_pred)\n            \n            if verbose and i % verbose == 0:\n                print(f\"{i} | loss: {loss} | {self.metric}: {metric_value}\")\n                \n        self.best_score = self._calculate_metric(y, self.predict_proba(X))\n        \n\n    def y_predict(self, X: np.ndarray):\n        z = np.dot(X, self.weights)\n        return 1 / (1 + np.exp(-z))\n\n    def get_coef(self):\n        return self.weights[1:]  # \u0412\u043e\u0437\u0432\u0440\u0430\u0449\u0430\u0435\u043c \u0432\u0435\u0441\u0430 \u0431\u0435\u0437 \u0441\u0432\u043e\u0431\u043e\u0434\u043d\u043e\u0433\u043e \u0447\u043b\u0435\u043d\u0430\n    \n\n    def _log_loss(self, y_true, y_pred):\n        eps = 1e-15\n        return -np.mean(y_true * np.log(y_pred + eps) + (1 - y_true) * np.log(1 - y_pred + eps))\n    \n    \n    def predict_proba(self, X: np.ndarray):\n        return self.y_predict(X)\n    \n    \n    def predict(self, X: np.ndarray):\n        proba = self.predict_proba(X)\n        return (proba >= 0.5).astype(int)\n    \n    \n    def _data_calculations(self, X, y):\n        regularization, regularization_gradient = self._calculate_regularization()\n        y_pred = self.y_predict(X)\n        loss = self._log_loss(y, y_pred) + regularization\n        gradient = np.dot(X.T, (y_pred - y)) / X.shape[0] + regularization_gradient\n        return y_pred, loss, gradient\n    \n    \n    def _calculate_metric(self, y_true, y_pred):\n        y_true, y_pred_binary = self._binary_labels(y_true, y_pred)\n\n        if self.metric == 'accuracy':\n            return accuracy_score(y_true, y_pred_binary)\n        elif self.metric == 'f1':\n            return f1_score(y_true, y_pred_binary)\n        elif self.metric == 'roc_auc':\n            if len(np.unique(y_true)) > 1:\n                roc_auc = roc_auc_score(y_true, y_pred)\n            else:\n                roc_auc = None\n            return roc_auc\n        elif self.metric == 'precision':\n            return precision_score(y_true, y_pred_binary)\n        elif self.metric == 'recall':\n            return recall_score(y_true, y_pred_binary)\n        else:\n            return None\n\n\n    def _binary_labels(self, y_true, y_pred):\n",
        "input": "",
        "output": "        median = np.median(y_true)\n        y_true = (y_true >= median).astype(int)\n        y_pred_binary = (y_pred >= 0.5).astype(int)\n        return y_true, y_pred_binary\n    \n",
        "idx": "504"
    },
    {
        "instruction": "## log_reg.py\nimport random\n\nimport numpy as np\n\nimport pandas as pd\n\nfrom sklearn.metrics import precision_score, recall_score, f1_score, roc_auc_score, accuracy_score\n\nclass MyLogReg:\n    def __init__(self, n_iter=100, learning_rate=0.1, weights=None, metric=None, reg=None, l1_coef=0, l2_coef=0, sgd_sample=None, random_state=42):\n        self.n_iter = n_iter \n        self.learning_rate = learning_rate \n        self.weights = weights\n        self.metric = metric\n        self.best_score = None\n        self.reg = reg\n        self.l1_coef = l1_coef\n        self.l2_coef = l2_coef\n        self.sgd_sample = sgd_sample\n        self.random_state = random_state\n\n        \n    def __str__(self):\n        return f\"MyLineReg class: n_iter={self.n_iter}, learning_rate={self.learning_rate}\"\n\n\n    def fit(self, X: pd.DataFrame, y: pd.Series, verbose=False):\n        random.seed(self.random_state)\n        X = np.hstack((np.ones((X.shape[0], 1)), X))  # \u0414\u043e\u0431\u0430\u0432\u043b\u044f\u0435\u043c \u0441\u0442\u043e\u043b\u0431\u0435\u0446 \u0435\u0434\u0438\u043d\u0438\u0446\n        self.weights = np.ones(X.shape[1])  # \u0418\u043d\u0438\u0446\u0438\u0430\u043b\u0438\u0437\u0438\u0440\u0443\u0435\u043c weights \u0441 \u043f\u0440\u0430\u0432\u0438\u043b\u044c\u043d\u043e\u0439 \u0440\u0430\u0437\u043c\u0435\u0440\u043d\u043e\u0441\u0442\u044c\u044e\n        \n        for i in range(1, self.n_iter + 1):\n            batch_X, batch_y = self._get_mini_batch(X, y)\n            y_pred, loss, gradient = self._data_calculations(batch_X, batch_y)\n            learning_rate = self.learning_rate(i) if callable(self.learning_rate) else self.learning_rate\n            self.weights -= learning_rate * gradient\n            metric_value = self._calculate_metric(batch_y, y_pred)\n            \n            if verbose and i % verbose == 0:\n                print(f\"{i} | loss: {loss} | {self.metric}: {metric_value}\")\n                \n        self.best_score = self._calculate_metric(y, self.predict_proba(X))\n        \n\n    def y_predict(self, X: np.ndarray):\n        z = np.dot(X, self.weights)\n        return 1 / (1 + np.exp(-z))\n\n    def get_coef(self):\n        return self.weights[1:]  # \u0412\u043e\u0437\u0432\u0440\u0430\u0449\u0430\u0435\u043c \u0432\u0435\u0441\u0430 \u0431\u0435\u0437 \u0441\u0432\u043e\u0431\u043e\u0434\u043d\u043e\u0433\u043e \u0447\u043b\u0435\u043d\u0430\n    \n\n    def _log_loss(self, y_true, y_pred):\n        eps = 1e-15\n        return -np.mean(y_true * np.log(y_pred + eps) + (1 - y_true) * np.log(1 - y_pred + eps))\n    \n    \n    def predict_proba(self, X: np.ndarray):\n        return self.y_predict(X)\n    \n    \n    def predict(self, X: np.ndarray):\n        proba = self.predict_proba(X)\n        return (proba >= 0.5).astype(int)\n    \n    \n    def _data_calculations(self, X, y):\n",
        "input": "",
        "output": "        regularization, regularization_gradient = self._calculate_regularization()\n        y_pred = self.y_predict(X)\n        loss = self._log_loss(y, y_pred) + regularization\n        gradient = np.dot(X.T, (y_pred - y)) / X.shape[0] + regularization_gradient\n        return y_pred, loss, gradient\n    \n",
        "idx": "506"
    },
    {
        "instruction": "## log_reg.py\nimport random\n\nimport numpy as np\n\nimport pandas as pd\n\nfrom sklearn.metrics import precision_score, recall_score, f1_score, roc_auc_score, accuracy_score\n\nclass MyLogReg:\n    def __init__(self, n_iter=100, learning_rate=0.1, weights=None, metric=None, reg=None, l1_coef=0, l2_coef=0, sgd_sample=None, random_state=42):\n        self.n_iter = n_iter \n        self.learning_rate = learning_rate \n        self.weights = weights\n        self.metric = metric\n        self.best_score = None\n        self.reg = reg\n        self.l1_coef = l1_coef\n        self.l2_coef = l2_coef\n        self.sgd_sample = sgd_sample\n        self.random_state = random_state\n\n        \n    def __str__(self):\n        return f\"MyLineReg class: n_iter={self.n_iter}, learning_rate={self.learning_rate}\"\n\n\n    def fit(self, X: pd.DataFrame, y: pd.Series, verbose=False):\n        random.seed(self.random_state)\n        X = np.hstack((np.ones((X.shape[0], 1)), X))  # \u0414\u043e\u0431\u0430\u0432\u043b\u044f\u0435\u043c \u0441\u0442\u043e\u043b\u0431\u0435\u0446 \u0435\u0434\u0438\u043d\u0438\u0446\n        self.weights = np.ones(X.shape[1])  # \u0418\u043d\u0438\u0446\u0438\u0430\u043b\u0438\u0437\u0438\u0440\u0443\u0435\u043c weights \u0441 \u043f\u0440\u0430\u0432\u0438\u043b\u044c\u043d\u043e\u0439 \u0440\u0430\u0437\u043c\u0435\u0440\u043d\u043e\u0441\u0442\u044c\u044e\n        \n        for i in range(1, self.n_iter + 1):\n            batch_X, batch_y = self._get_mini_batch(X, y)\n            y_pred, loss, gradient = self._data_calculations(batch_X, batch_y)\n            learning_rate = self.learning_rate(i) if callable(self.learning_rate) else self.learning_rate\n            self.weights -= learning_rate * gradient\n            metric_value = self._calculate_metric(batch_y, y_pred)\n            \n            if verbose and i % verbose == 0:\n                print(f\"{i} | loss: {loss} | {self.metric}: {metric_value}\")\n                \n        self.best_score = self._calculate_metric(y, self.predict_proba(X))\n        \n\n    def y_predict(self, X: np.ndarray):\n        z = np.dot(X, self.weights)\n        return 1 / (1 + np.exp(-z))\n\n    def get_coef(self):\n        return self.weights[1:]  # \u0412\u043e\u0437\u0432\u0440\u0430\u0449\u0430\u0435\u043c \u0432\u0435\u0441\u0430 \u0431\u0435\u0437 \u0441\u0432\u043e\u0431\u043e\u0434\u043d\u043e\u0433\u043e \u0447\u043b\u0435\u043d\u0430\n    \n\n    def _log_loss(self, y_true, y_pred):\n",
        "input": "",
        "output": "        eps = 1e-15\n        return -np.mean(y_true * np.log(y_pred + eps) + (1 - y_true) * np.log(1 - y_pred + eps))\n    \n",
        "idx": "507"
    },
    {
        "instruction": "## line_reg.py\nimport random\n\nfrom matplotlib import pyplot as plt\n\nimport numpy as np\n\nimport pandas as pd\n\nX = pd.DataFrame(X)\n\ny = pd.Series(y)\n\nX.columns = [f'col_{col}' for col in X.columns]\n\nclass MyLineReg:\n    def __init__(self, n_iter=100, learning_rate=0.1, weights=None, metric=None, reg=None, l1_coef=0, l2_coef=0, sgd_sample=None, random_state=42):\n        self.n_iter = n_iter\n        self.learning_rate = learning_rate\n        self.weights = weights\n        self.metric = metric\n        self.best_score = None \n        self.reg = reg\n        self.l1_coef = l1_coef\n        self.l2_coef = l2_coef\n        self.sgd_sample = sgd_sample\n        self.random_state = random_state\n        self.loss_history = []\n        \n        \n    def __str__(self) -> str:\n        return (\n            f\"MyLineReg(n_iter={self.n_iter}, learning_rate={self.learning_rate}, \"\n            f\"metric={self.metric}, reg={self.reg}, l1_coef={self.l1_coef}, \"\n            f\"l2_coef={self.l2_coef}, sgd_sample={self.sgd_sample}, \"\n            f\"random_state={self.random_state})\"\n        )\n\n    \n    def fit(self, X: pd.DataFrame, y: pd.Series, verbose: int=0) -> None:\n",
        "input": "",
        "output": "        random.seed(self.random_state)\n        X_with_intercept = np.hstack((np.ones((X.shape[0], 1)), X))\n        self.weights = np.ones(X_with_intercept.shape[1])\n        self.y = y\n        self.X = X_with_intercept\n        \n        for iteration in range(1, self.n_iter + 1):\n            batch_X, batch_y = self._get_mini_batch(X_with_intercept, y)\n            predictions = np.dot(batch_X, self.weights)\n            errors = predictions - batch_y\n            regularization, regularization_gradient = self._calculate_reg_and_grad()\n            loss = np.mean(errors ** 2) + regularization\n            self.loss_history.append(loss)\n            gradient = (2 / batch_X.shape[0] * np.dot(batch_X.T, errors)) + regularization_gradient\n            \n            \n            learning_rate = self.learning_rate(iteration) if callable(self.learning_rate) else self.learning_rate\n            self.weights -= learning_rate * gradient\n            \n            if self.metric and iteration % verbose == 0:\n                metric_value = self._calculate_metric(y, np.dot(X_with_intercept,    self.weights))\n                print(f\"Iteration {iteration} | Loss: {loss:.5f} | {self.metric}: {metric_value:.5f}\")\n        \n        self.best_score = self._calculate_metric(y, np.dot(X_with_intercept, self.weights)) if self.metric else None\n    \n",
        "idx": "512"
    },
    {
        "instruction": "# Here are some relevant code fragments from other files of the repo:\n# --------------------------------------------------\n# the below code fragment can be found in:\n# api/database.py\n# --------------------------------------------------\n# from datetime import datetime\n# \n# from sqlalchemy.orm import DeclarativeBase, sessionmaker\n# \n# from sqlalchemy import create_engine, Column, Integer, String, Text, text, DateTime\n# \n# USERNAME = \"root\"\n# \n# PASSWORD = \"Abdallah%402004\"\n# \n# HOST = \"localhost\"\n# \n# DATABASE = \"note_db\"\n# \n# class Base(DeclarativeBase):\n#     \"\"\"Base class for all models\"\"\"\n# \n# class UserDb(Base):\n#     \"\"\"This class represents the user table in the database.\"\"\"\n#     __tablename__ = 'users'\n# \n#     id = Column(Integer, autoincrement=True, primary_key=True)\n#     username = Column(String(50), unique=True, nullable=False)\n#     email = Column(String(100), unique=True, nullable=False)\n#     hashed_password = Column(String(255), nullable=False)\n#     session_id = Column(String(40), default=None)\n#     time_created = Column(DateTime, default=datetime.now)\n#     last_opened = Column(DateTime, default=datetime.now)\n#     date_of_birth = Column(Text, default=None)\n#     description = Column(String(500), default=None)\n# \n# def create_engine_and_connect():\n#     \"\"\"Creates the engine and connects to the database.\"\"\"\n#     return create_engine(\n#         f'mysql+mysqlconnector://{USERNAME}:{PASSWORD}@{HOST}/{DATABASE}'\n#     )\n# \n# def get_session():\n#     \"\"\"Return a new session.\"\"\"\n#     engine = create_engine_and_connect()\n#     session = sessionmaker(bind=engine)\n#     return session()\n# \n# --------------------------------------------------\n\n\n## api/models/users.py\nfrom typing import Union, Optional\n\nfrom sqlalchemy import or_, and_\n\nfrom sqlalchemy.exc import SQLAlchemyError\n\nfrom api.database import UserDb, get_session\n\nclass User():\n    \"\"\"User Class\"\"\"\n    def __init__(self):\n        self.sess = get_session()\n        # self.users_data = [\n        #     {\"id\": 1, \"username\": \"Ali\"},\n        #     {\"id\": 2, \"username\": \"John\"},\n        #     {\"id\": 3, \"username\": \"Jane\"},\n        #     {\"id\": 4, \"username\": \"Bob\"},\n        #     {\"id\": 5, \"username\": \"Alice\"},\n        #     {\"id\": 6, \"username\": \"Charlie\"},\n        #     {\"id\": 7, \"username\": \"Diana\"},\n        #     {\"id\": 8, \"username\": \"Eva\"},\n        #     {\"id\": 9, \"username\": \"Frank\"},\n        #     {\"id\": 10, \"username\": \"Gabriel\"},\n        #     {\"id\": 11, \"username\": \"Hannah\"},\n        #     {\"id\": 12, \"username\": \"Isaac\"},\n        #     {\"id\": 13, \"username\": \"Julia\"},\n        #     {\"id\": 14, \"username\": \"Kevin\"},\n        #     {\"id\": 15, \"username\": \"Lily\"}\n        # ]\n\n    def get_user_by_id(self, user_id):\n        \"\"\"Get user by id function\"\"\"\n        try:\n            user = self.sess.query(UserDb).filter(\n                UserDb.id == user_id\n            ).first()\n            return user\n        except SQLAlchemyError as e:\n            raise SQLAlchemyError(f\"Error getting user by id: {str(e)}\") from e\n        finally:\n            self.sess.close()\n\n    def get_user_by_session_id(self, session_id):\n        \"\"\"Get user by session id function\"\"\"\n        try:\n            user = self.sess.query(UserDb).filter(\n                UserDb.session_id == session_id\n            ).first()\n            return user\n        except SQLAlchemyError as e:\n            raise SQLAlchemyError(f\"Error getting user by session id: {str(e)}\") from e\n        finally:\n            self.sess.close()\n\n    def get_user_by_username(\n        self, name: str, skip: Optional[int] = 0, limit: Optional[int] = None\n    ) -> Union[list, dict, str]:\n        \"\"\"Get user by username function\"\"\"\n        try:\n            users_data = self.sess.query(UserDb).filter(\n                UserDb.username.like(f\"%{name.lower()}%\")\n            ).offset(skip).limit(limit).all()\n\n            if not users_data:\n                return f\"User with name {name} not found\"\n\n            return users_data\n        except SQLAlchemyError as e:\n            raise SQLAlchemyError(f\"Error getting user by username: {e}\") from e\n        finally:\n            self.sess.close()\n\n    def get_all_users_data(\n        self,\n        skip: Optional[int],\n        limit: Optional[int]\n    ) -> list:\n        \"\"\"Get all users in list of dict\"\"\"\n        try:\n            users = self.sess.query(UserDb)\n\n            if skip is not None and limit is not None:\n                users = users.offset(skip).limit(limit)\n            elif skip and limit is None:\n                users = users.offset(skip).limit(10)\n            elif skip is None and limit:\n                users = users.offset(0).limit(limit)\n\n            return users.all()\n        except SQLAlchemyError as e:\n            raise SQLAlchemyError(f\"Error getting all users: {str(e)}\") from e\n        finally:\n            self.sess.close()\n\n    def check_if_user_exists(self, username: str, email: str) -> Optional[UserDb]:\n        \"\"\"Check if user exists in database\"\"\"\n        try:\n            user_existed = self.sess.query(UserDb).filter(\n                or_(\n                    UserDb.username == username,\n                    UserDb.email == email\n                )\n            ).first()\n            if user_existed:\n                return user_existed\n            return None\n        except SQLAlchemyError as e:\n            raise SQLAlchemyError(f\"Error checking user existence: {str(e)}\") from e\n        finally:\n            self.sess.close()\n\n    # authenticate_user Not Used \u2b07\n    def authenticate_user(self, username: str, password: str) -> Union[dict, str]:\n        \"\"\"Authenticate user by username and password\"\"\"\n        try:\n            user = self.sess.query(UserDb).filter(\n                and_(\n                    or_(\n                        UserDb.username == username,\n                        UserDb.email == username\n                    )\n                    # UserDb.hashed_password == password\n                )\n            ).first()\n            if user:\n                if user.hashed_password == password:\n                    return self.convert_class_user_to_object(user)\n                return \"Invalid password. password not correct\"\n            return \"Invalid username. user not exists\"\n        except SQLAlchemyError as e:\n            raise SQLAlchemyError(f\"Error authenticating user: {e}\") from e\n        finally:\n            self.sess.close()\n\n    def insert_new_user(self, **kwargs: dict):\n        \"\"\"Insert new user into database\"\"\"\n        try:\n            new_user = UserDb(**kwargs)\n            self.sess.add(new_user)\n            self.sess.commit()\n            self.sess.refresh(new_user)\n            return new_user\n        except SQLAlchemyError as e:\n            self.sess.rollback()\n            raise SQLAlchemyError(f\"Error inserting new user: {e}\") from e\n        finally:\n            self.sess.close()\n\n    def update_user_account(self, kwargs: dict) -> dict:\n        \"\"\"Update user account information\"\"\"\n        try:\n            user = None\n\n            if kwargs['session_id']:\n                user = self.sess.query(UserDb).filter(\n                    UserDb.session_id == kwargs['session_id']\n                ).first()\n            elif kwargs['id']:\n                user = self.sess.query(UserDb).filter(\n                    UserDb.id == kwargs['id']\n                ).first()\n\n            if user:\n                for key, value in kwargs.items():\n                    if key not in ['id', 'session_id'] and value is not None:\n                        setattr(user, key, value)\n                self.sess.commit()\n                return True\n            return False\n        except SQLAlchemyError as e:\n            self.sess.rollback()\n            raise SQLAlchemyError(f\"Error updating user account: {e}\") from e\n        finally:\n            self.sess.close()\n\n    def delete_user(self, user_id: int) -> bool:\n        \"\"\"Delete user Account permanently from database\"\"\"\n        try:\n            user = self.sess.query(UserDb).filter(\n                UserDb.id == user_id\n            ).first()\n\n            if user:\n                self.sess.delete(user)\n                self.sess.commit()\n                return True\n\n            return False\n        except SQLAlchemyError as e:\n            self.sess.rollback()\n            raise SQLAlchemyError(f\"Error deleting user with id ({user_id}): {e}\") from e\n        finally:\n            self.sess.close()\n\n    @classmethod\n    def convert_class_user_to_object(cls, user: UserDb) -> dict:\n        \"\"\"\n        Convert a UserDb object to a User dict\n        \"\"\"\n",
        "input": "",
        "output": "        return {\n            \"id\": user.id,\n            \"username\": user.username,\n            \"email\": user.email,\n            \"hashed_password\": user.hashed_password,\n            \"session_id\": user.session_id,\n            \"time_created\": user.time_created,\n            \"last_opened\": user.last_opened,\n            \"date_of_birth\": user.date_of_birth,\n            \"description\": user.description,\n        }\n    \n",
        "idx": "545"
    },
    {
        "instruction": "## model/simulator/data_simulator.py\nimport numpy as np\n\ndef heranca(genotipo_pai, genotipo_mae):\n",
        "input": "",
        "output": "    genotipo_filho = {}\n    for g in genotipo_pai:\n        selecao_pai = np.random.randint(2)\n        selecao_mae = np.random.randint(2)\n        genotipo_filho[g] = (\n            genotipo_pai[g][selecao_pai],\n            genotipo_mae[g][selecao_mae],\n        )\n    return genotipo_filho\n\n",
        "idx": "548"
    },
    {
        "instruction": "## model/simulator/data_simulator.py\nimport numpy as np\n\nfrom tqdm import tqdm\n\nprob_alelos_dominantes = {\n    1: 0.01,   # Pulm\u00e3o\n    2: 0.005,  # Ov\u00e1rio\n    3: 0.008,  # Est\u00f4mago\n    4: 0.015,  # Pele\n    5: 0.012,  # Leucemia\n    6: 0.009,  # Intestino\n    7: 0.007,  # Cabe\u00e7a e Pesco\u00e7o\n    8: 0.006,  # Mama\n    9: 0.011,  # Pr\u00f3stata\n    10:0.013, # Tire\u00f3ide\n    11:0.014, # Cerebral/sistema nervoso central\n    12:0.018, # Bexiga\n    13:0.016, # Linfoma\n    14:0.02,  # Bra\u00e7os/pernas\n    15:0.017, # Outro\n}\n\nprob_cancer = {\n    'homem': {\n        1: (0.3, 0.02),  # Pulm\u00e3o\n        2: (0.2, 0.03),  # Ov\u00e1rio\n        3: (0.25, 0.015),# Est\u00f4mago\n        4: (0.2, 0.01),  # Pele\n        5: (0.3, 0.025), # Leucemia\n        6: (0.2, 0.015), # Intestino\n        7: (0.25, 0.02), # Cabe\u00e7a e Pesco\u00e7o\n        8: (0.15, 0.01), # Mama\n        9: (0.25, 0.015),# Pr\u00f3stata\n        10: (0.25, 0.02),# Tire\u00f3ide\n        11: (0.2, 0.015),# Cerebral/sistema nervoso central\n        12: (0.2, 0.015),# Bexiga\n        13: (0.3, 0.025),# Linfoma\n        14: (0.3, 0.02), # Bra\u00e7os/pernas\n        15: (0.15, 0.01) # Outro\n    },\n    'mulher': {\n        1: (0.3, 0.02),  # Pulm\u00e3o\n        2: (0.2, 0.03),  # Ov\u00e1rio\n        3: (0.25, 0.015),# Est\u00f4mago\n        4: (0.2, 0.01),  # Pele\n        5: (0.3, 0.025), # Leucemia\n        6: (0.2, 0.015), # Intestino\n        7: (0.25, 0.02), # Cabe\u00e7a e Pesco\u00e7o\n        8: (0.15, 0.01), # Mama\n        9: (0.25, 0.015),# Pr\u00f3stata\n        10: (0.25, 0.02),# Tire\u00f3ide\n        11: (0.2, 0.015),# Cerebral/sistema nervoso central\n        12: (0.2, 0.015),# Bexiga\n        13: (0.3, 0.025),# Linfoma\n        14: (0.3, 0.02), # Bra\u00e7os/pernas\n        15: (0.15, 0.01) # Outro\n    },\n}\n\ndef eh_alelo_dominante(prob_alelo_dominante):\n    return np.random.rand() < prob_alelo_dominante\n\ndef tem_cancer(prob_cancer):\n    return np.random.rand() < prob_cancer\n\ndef gene(prob_alelo_dominante):\n    return tuple(eh_alelo_dominante(prob_alelo_dominante) for _ in range(2))\n\ndef genotipo(prob_alelos_dominantes):\n    return {g: gene(p) for g, p in prob_alelos_dominantes.items()}\n\ndef fenotipo(genotipo_, genero, prob_cancer):\n    f = {}\n    for g, genes_ in genotipo_.items():\n        dominant = any(genes_)\n        pR, pr = prob_cancer[genero][g]\n        p_cancer = pR if dominant else pr\n        f[g] = tem_cancer(p_cancer)\n    return f\n\ndef heranca(genotipo_pai, genotipo_mae):\n    genotipo_filho = {}\n    for g in genotipo_pai:\n        selecao_pai = np.random.randint(2)\n        selecao_mae = np.random.randint(2)\n        genotipo_filho[g] = (\n            genotipo_pai[g][selecao_pai],\n            genotipo_mae[g][selecao_mae],\n        )\n    return genotipo_filho\n\ndef genero():\n    return 'homem' if np.random.randint(2) == 0 else 'mulher'\n\ndef heredograma(prob_alelos_dominantes, prob_cancer):\n\n    genotipo_avo_paterno = genotipo(prob_alelos_dominantes)\n    fenotipo_avo_paterno = fenotipo(genotipo_avo_paterno, 'homem', prob_cancer)\n\n    genotipo_avoh_paterna = genotipo(prob_alelos_dominantes)\n    fenotipo_avoh_paterna = fenotipo(genotipo_avoh_paterna, 'mulher', prob_cancer)\n\n    genotipo_avo_materno = genotipo(prob_alelos_dominantes)\n    fenotipo_avo_materno = fenotipo(genotipo_avo_materno, 'homem', prob_cancer)\n\n    genotipo_avoh_materna = genotipo(prob_alelos_dominantes)\n    fenotipo_avoh_materna = fenotipo(genotipo_avoh_materna, 'mulher', prob_cancer)\n\n    genotipo_pai = heranca(genotipo_avo_paterno, genotipo_avoh_paterna)\n    fenotipo_pai = fenotipo(genotipo_pai, 'homem', prob_cancer)\n\n    genotipo_mae = heranca(genotipo_avo_materno, genotipo_avoh_materna)\n    fenotipo_mae = fenotipo(genotipo_mae, 'mulher', prob_cancer)\n\n    genero_paciente = genero()\n    genotipo_paciente = heranca(genotipo_pai, genotipo_mae)\n    fenotipo_paciente = fenotipo(genotipo_paciente, genero_paciente, prob_cancer)\n\n    genotipo_esposo_esposa = genotipo(prob_alelos_dominantes)\n\n    genero_filho = genero()\n    genotipo_filho = heranca(genotipo_paciente, genotipo_esposo_esposa)\n    fenotipo_filho = fenotipo(genotipo_filho, genero_filho, prob_cancer)\n\n    return {\n        'fenotipo_avo_paterno': fenotipo_avo_paterno,\n        'fenotipo_avoh_paterna': fenotipo_avoh_paterna,\n        'fenotipo_avo_materno': fenotipo_avo_materno,\n        'fenotipo_avoh_materna': fenotipo_avoh_materna,\n        'fenotipo_pai': fenotipo_pai,\n        'fenotipo_mae': fenotipo_mae,\n        'fenotipo_paciente': fenotipo_paciente,\n        'fenotipo_filho': fenotipo_filho,\n        'genotipo_paciente': genotipo_paciente,\n        'genero_paciente': genero_paciente,\n        'genero_filho': genero_filho,\n    }\n\ndef simular_heredogramas(num_pacientes):\n",
        "input": "",
        "output": "    pacientes = []\n    for _ in tqdm(range(num_pacientes), desc=\"Simulando heredogramas\"):\n        pacientes.append(heredograma(prob_alelos_dominantes, prob_cancer))\n    return pacientes\n\n",
        "idx": "550"
    },
    {
        "instruction": "## model/train.py\nimport pandas as pd\n\nimport numpy as np\n\nfrom sklearn.base import TransformerMixin, BaseEstimator\n\nclass CustomCategoricalImputer(BaseEstimator, TransformerMixin):\n    \"\"\"Imputador personalizado para valores ausentes em colunas categ\u00f3ricas.\"\"\"\n    \n    def __init__(self, categorical_features):\n        self.categorical_features = categorical_features\n    \n    def fit(self, X, y=None):\n        \"\"\"\n        Ajusta o imputador aos dados de treinamento.\n        \"\"\"\n",
        "input": "",
        "output": "        return self\n    \n",
        "idx": "551"
    },
    {
        "instruction": "## model/mock_model.py\nimport pickle\n\nfrom abc import ABC, abstractmethod\n\nfrom sklearn.base import BaseEstimator\n\nfrom sklearn.linear_model import LogisticRegression\n\nclass Model(BaseEstimator, ABC):\n    \"\"\"Abstract class defining the behavior of a model.\"\"\"\n\n    @abstractmethod\n    def fit(self, X, y):\n        \"\"\"Abstract method to train the model.\"\"\"\n        raise NotImplementedError(\"The fit method must be implemented in subclasses.\")\n\n    @abstractmethod\n    def predict(self, X):\n        \"\"\"Abstract method to make predictions with the trained model.\"\"\"\n        raise NotImplementedError(\"The predict method must be implemented in subclasses.\")\n    \n    @abstractmethod\n    def predict_proba(self, X):\n        \"\"\"Abstract method to make probabilities predictions with the trained model.\"\"\"\n        raise NotImplementedError(\"The predict method must be implemented in subclasses.\")\n\nclass MockModel(Model):\n    \"\"\"Class implementing a RandomForestClassifier model.\"\"\"\n\n    def __init__(self):\n        \"\"\"Initializer of the class.\"\"\"\n        self.model = LogisticRegression(\n           C=0.01,\n           solver='newton-cg',\n           max_iter=100\n        )\n\n    def fit(self, X, y):\n        \"\"\"Trains the model with input data X and labels y.\"\"\"\n        self.model.fit(X, y)\n\n    def predict(self, X):\n        \"\"\"Makes predictions with the trained model using input data X.\"\"\"\n        return self.model.predict(X)\n    \n    def predict_proba(self, X):\n        \"\"\"Makes probabilities predictions with the trained model using input data X.\"\"\"\n        return self.model.predict_proba(X)\n\n    def save(self, filename):\n        \"\"\"\n        Saves the model to a file using pickle.\n        \"\"\"\n",
        "input": "",
        "output": "        with open(filename, 'wb') as file:\n            pickle.dump(self.model, file)\n        print(f\"Model saved successfully at {filename}\")\n    \n",
        "idx": "554"
    },
    {
        "instruction": "## model/mock_model.py\nimport pickle\n\nfrom abc import ABC, abstractmethod\n\nfrom sklearn.base import BaseEstimator\n\nfrom sklearn.linear_model import LogisticRegression\n\nclass Model(BaseEstimator, ABC):\n    \"\"\"Abstract class defining the behavior of a model.\"\"\"\n\n    @abstractmethod\n    def fit(self, X, y):\n        \"\"\"Abstract method to train the model.\"\"\"\n        raise NotImplementedError(\"The fit method must be implemented in subclasses.\")\n\n    @abstractmethod\n    def predict(self, X):\n        \"\"\"Abstract method to make predictions with the trained model.\"\"\"\n        raise NotImplementedError(\"The predict method must be implemented in subclasses.\")\n    \n    @abstractmethod\n    def predict_proba(self, X):\n        \"\"\"Abstract method to make probabilities predictions with the trained model.\"\"\"\n        raise NotImplementedError(\"The predict method must be implemented in subclasses.\")\n\nclass MockModel(Model):\n    \"\"\"Class implementing a RandomForestClassifier model.\"\"\"\n\n    def __init__(self):\n        \"\"\"Initializer of the class.\"\"\"\n        self.model = LogisticRegression(\n           C=0.01,\n           solver='newton-cg',\n           max_iter=100\n        )\n\n    def fit(self, X, y):\n        \"\"\"Trains the model with input data X and labels y.\"\"\"\n        self.model.fit(X, y)\n\n    def predict(self, X):\n        \"\"\"Makes predictions with the trained model using input data X.\"\"\"\n        return self.model.predict(X)\n    \n    def predict_proba(self, X):\n        \"\"\"Makes probabilities predictions with the trained model using input data X.\"\"\"\n        return self.model.predict_proba(X)\n\n    def save(self, filename):\n        \"\"\"Saves the model to a file using pickle.\"\"\"\n        with open(filename, 'wb') as file:\n            pickle.dump(self.model, file)\n        print(f\"Model saved successfully at {filename}\")\n\n    @classmethod\n    def load(cls, filename):\n        \"\"\"\n        Loads the model from a file using pickle.\n        \"\"\"\n",
        "input": "",
        "output": "        with open(filename, 'rb') as file:\n            model = pickle.load(file)\n        instance = cls()\n        instance.model = model\n        return instance\n    \n",
        "idx": "555"
    },
    {
        "instruction": "## TodoList.py\nfrom datetime import datetime\n\nclass TodoList:\n    \"\"\"A class to store and manage one list of tasks\n    \"\"\"\n    def __init__(self):\n        \"\"\"initialize an empty list\n        \"\"\"\n        self.tasks = []\n\n        \"\"\"Task is a 6-tuple (task, priority, date, tags, delegate, completed)\n        \"\"\"\n\n    def add_task(self, task, priority='Medium', date=None):\n        \"\"\"\n        Adds a new task to the list if it doesn't already exist.\n    \n        Args:\n        task (_type_): a string. Leading or trailing whitespace will be removed. Cannot add a duplicate task.\n        priority (str, optional): the priority of the task. Defaults to \"Medium\".\n        date (_type_, optional): the due date of the task. Defaults to None.\n        \"\"\"\n",
        "input": "",
        "output": "        task = task.strip()  # Remove any leading/trailing whitespace\n        task_number = self.task_exists(task)\n        if task_number:\n            print(f\"Task '{task}' already exists at position {task_number}.\")\n            return\n\n        self.tasks.append((task, priority, date, [], None, False))\n        print(f\"Task added: {task} with priority '{priority}' and due date: '{date}'\")\n    \n",
        "idx": "556"
    },
    {
        "instruction": "## TodoList.py\nfrom datetime import datetime\n\nclass TodoList:\n    \"\"\"A class to store and manage one list of tasks\n    \"\"\"\n    def __init__(self):\n        \"\"\"initialize an empty list\n        \"\"\"\n        self.tasks = []\n\n        \"\"\"Task is a 6-tuple (task, priority, date, tags, delegate, completed)\n        \"\"\"\n\n    def add_task(self, task, priority = \"Medium\", date = None):\n        \"\"\"Adds a new task to the list if it doesn't already exist.\n\n        Args:\n            task (_type_): a string. Leading or trailing whitespace will be removed. Cannot add a duplicate task.\n            priority (str, optional): the priority of the task. Defaults to \"Medium\".\n            date (_type_, optional): the due date of the task. Defaults to None.\n        \"\"\"\n\n        task = task.strip()  # Remove any leading/trailing whitespace\n        task_number = self.task_exists(task)\n        if task_number:\n            print(f\"Task '{task}' already exists at position {task_number}.\")\n            return\n\n        self.tasks.append((task, priority, date, [], None, False))\n        print(f\"Task added: {task} with priority '{priority}' and due date: '{date}'\")\n\n    def list_tasks(self):\n        \"\"\"Lists all tasks in the to-do list.\n        \"\"\"\n        if not self.tasks:\n            print(\"No tasks in the list!\")\n        else:\n            for idx, task in enumerate(self.tasks, start=1):\n                print(f'{idx}. {task}')\n\n    def list_tasks_numeric(self):\n        \"\"\"Lists all tasks in the to-do list in numerical order, including due dates if available.\n        \"\"\"\n        if not self.tasks:\n            print(\"No tasks in the list!\")\n        else:\n            print(\"\\nCurrent To-Do List:\")\n            for idx, task in enumerate(self.tasks, start=1):\n                task_name, priority, due_date, _, _, _ = task\n                if due_date:\n                    print(f'{idx}. {task_name} (Due: {due_date}) [Priority: {priority}]')\n                else:\n                    print(f'{idx}. {task_name} (Due: None) [Priority: {priority}]')\n                    \n    # Good job with implementing this function and listing the list in alphabetical order\n    def list_tasks_alphabetic(self):\n        \"\"\"lists all tasks in the to-do list in alphabetical order, \n           including due dates if available.\n        \"\"\"\n        if not self.tasks:\n            print(\"No tasks in the list!\")\n        else:\n            sorted_tasks = [] \n            # Although I would review the for loops to make code smaller and faster\n            for idx, task in enumerate(self.tasks, start=1):\n                item = (idx, task) \n                sorted_tasks.append(item)\n            sorted_tasks = sorted(sorted_tasks, key=lambda x: x[1][0].lower() if isinstance(x[1], tuple) else x[1].lower())\n            for idx, task in sorted_tasks:\n                if isinstance(task, tuple):  # Task with due date\n                    task_name, priority, due_date, _, _, _ = task\n                    if due_date:\n                        print(f'{idx}. {task_name} (Due: {due_date}) [Priority: {priority}]')\n                    else:\n                        print(f'{idx}. {task_name} (Due: None) [Priority: {priority}]')\n                else:  # Task without due date\n                    # all the tasks should now be a tuple\n                    raise Exception(\"Internal error: the task is not a tuple.\")\n\n    def delete_task(self, task_number):\n        \"\"\"\n        Deletes a task by its number in the list.\n    \n        Args:\n        task_number (_type_): an integer\n        \"\"\"\n",
        "input": "",
        "output": "        if not self.tasks:\n            print(\"No tasks in the list to delete!\")\n            return\n\n        if task_number <= 0 or task_number > len(self.tasks):\n            print(\"Invalid task number!\")\n        else:\n            removed_task = self.tasks.pop(task_number - 1)\n            print(f'Task removed: {removed_task}')\n    \n",
        "idx": "557"
    },
    {
        "instruction": "## TodoList.py\nfrom datetime import datetime\n\nclass TodoList:\n    \"\"\"A class to store and manage one list of tasks\n    \"\"\"\n    def __init__(self):\n        \"\"\"initialize an empty list\n        \"\"\"\n        self.tasks = []\n\n        \"\"\"Task is a 6-tuple (task, priority, date, tags, delegate, completed)\n        \"\"\"\n\n    def add_task(self, task, priority = \"Medium\", date = None):\n        \"\"\"Adds a new task to the list if it doesn't already exist.\n\n        Args:\n            task (_type_): a string. Leading or trailing whitespace will be removed. Cannot add a duplicate task.\n            priority (str, optional): the priority of the task. Defaults to \"Medium\".\n            date (_type_, optional): the due date of the task. Defaults to None.\n        \"\"\"\n\n        task = task.strip()  # Remove any leading/trailing whitespace\n        task_number = self.task_exists(task)\n        if task_number:\n            print(f\"Task '{task}' already exists at position {task_number}.\")\n            return\n\n        self.tasks.append((task, priority, date, [], None, False))\n        print(f\"Task added: {task} with priority '{priority}' and due date: '{date}'\")\n\n    def list_tasks(self):\n        \"\"\"Lists all tasks in the to-do list.\n        \"\"\"\n        if not self.tasks:\n            print(\"No tasks in the list!\")\n        else:\n            for idx, task in enumerate(self.tasks, start=1):\n                print(f'{idx}. {task}')\n\n    def list_tasks_numeric(self):\n        \"\"\"Lists all tasks in the to-do list in numerical order, including due dates if available.\n        \"\"\"\n        if not self.tasks:\n            print(\"No tasks in the list!\")\n        else:\n            print(\"\\nCurrent To-Do List:\")\n            for idx, task in enumerate(self.tasks, start=1):\n                task_name, priority, due_date, _, _, _ = task\n                if due_date:\n                    print(f'{idx}. {task_name} (Due: {due_date}) [Priority: {priority}]')\n                else:\n                    print(f'{idx}. {task_name} (Due: None) [Priority: {priority}]')\n                    \n    # Good job with implementing this function and listing the list in alphabetical order\n    def list_tasks_alphabetic(self):\n        \"\"\"lists all tasks in the to-do list in alphabetical order, \n           including due dates if available.\n        \"\"\"\n        if not self.tasks:\n            print(\"No tasks in the list!\")\n        else:\n            sorted_tasks = [] \n            # Although I would review the for loops to make code smaller and faster\n            for idx, task in enumerate(self.tasks, start=1):\n                item = (idx, task) \n                sorted_tasks.append(item)\n            sorted_tasks = sorted(sorted_tasks, key=lambda x: x[1][0].lower() if isinstance(x[1], tuple) else x[1].lower())\n            for idx, task in sorted_tasks:\n                if isinstance(task, tuple):  # Task with due date\n                    task_name, priority, due_date, _, _, _ = task\n                    if due_date:\n                        print(f'{idx}. {task_name} (Due: {due_date}) [Priority: {priority}]')\n                    else:\n                        print(f'{idx}. {task_name} (Due: None) [Priority: {priority}]')\n                else:  # Task without due date\n                    # all the tasks should now be a tuple\n                    raise Exception(\"Internal error: the task is not a tuple.\")\n\n    def delete_task(self, task_number):\n        \"\"\"Deletes a task by its number in the list.\n\n        Args:\n            task_number (_type_): an integer\n        \"\"\"\n        if not self.tasks:\n            print(\"No tasks in the list to delete!\")\n            return\n\n        if task_number <= 0 or task_number > len(self.tasks):\n            print(\"Invalid task number!\")\n        else:\n            removed_task = self.tasks.pop(task_number - 1)\n            print(f'Task removed: {removed_task}')\n\n\n    # this method was generated by ChatGPT as well as the subsequent adjustments\n    def add_task_date(self, task_number, due_date):\n        \"\"\"Adds or updates a due date for a specific task.\n\n        Args:\n            task_number (_type_): an integer\n            due_date (_type_): string\n        \"\"\"\n        if not self.tasks:\n            print(\"No tasks in the list to update!\")\n            return\n        \n        if task_number <= 0 or task_number > len(self.tasks):\n            print(\"Invalid task number!\")\n        else:\n            try:\n                # Validate date format\n                datetime.strptime(due_date, \"%Y-%m-%d\")\n            except ValueError:\n                print(\"Invalid date format! Please enter the date in YYYY-MM-DD format.\")\n                return\n        \n            task_name, priority, _, tags, delegate, completed = self.tasks[task_number - 1]\n            self.tasks[task_number - 1] = (task_name, priority, due_date, tags, delegate, completed)\n            print(f'Task updated with due date: {self.tasks[task_number - 1]}')\n            \n\n    def add_tag(self, task_number, tag):\n        if not self.tasks:\n            print(\"No tasks in the list to add a tag!\")\n            return\n        \n        if task_number <= 0 or task_number > len(self.tasks):\n            print(\"Invalid task number!\")\n        else:\n            task = self.tasks[task_number - 1]\n            if type(task) is tuple:\n                task_name, priority, due_date, tags, delegate, _ = task\n                tags.append(tag)\n                print(f'Task updated: {self.tasks[task_number - 1]}')\n            else:\n                # all the tasks should now be a tuple\n                raise Exception(\"Internal error: the task is not a tuple.\")\n\n    \n    def update_task(self, task_number, updated_message):\n        \"\"\"\n        Change the description of a task\n        \"\"\"\n",
        "input": "",
        "output": "        if not self.tasks:\n            print(\"No tasks in the list to update!\")\n            return\n\n        if task_number <= 0 or task_number > len(self.tasks):\n            print(\"Invalid task number!\")\n        else:\n            task_name, priority, due_date, tags, delegate, completed = self.tasks[task_number - 1]\n            self.tasks[task_number - 1] = (updated_message, priority, due_date, tags, delegate, completed)\n            print(f'Task updated: {self.tasks[task_number - 1]}')\n    \n",
        "idx": "558"
    },
    {
        "instruction": "# Here are some relevant code fragments from other files of the repo:\n# --------------------------------------------------\n# the below code fragment can be found in:\n# hypixel_api_lib/utils.py\n# --------------------------------------------------\n# from datetime import datetime, timezone\n# \n# def convert_timestamp(timestamp: int | None) -> datetime | None:\n#     \"\"\"Convert a timestamp in milliseconds to a timezone-aware datetime object in UTC.\"\"\"\n#     if timestamp:\n#         return datetime.fromtimestamp(timestamp / 1000, tz=timezone.utc)\n#     return None\n# \n# --------------------------------------------------\n\n\n## hypixel_api_lib/Auctions.py\nfrom datetime import datetime, timezone, tzinfo\n\nimport requests\n\nfrom hypixel_api_lib.utils import get_uuid_from_username, convert_timestamp\n\nACTIVE_AUCTIONS_API_URL = r\"https://api.hypixel.net/skyblock/auctions\"\n\nclass Bid:\n    \"\"\"\n    Represents a single bid in an auction.\n\n    Attributes:\n        auction_id (str): The ID of the auction.\n        bidder (str): The UUID of the bidder.\n        profile_id (str): The profile ID of the bidder.\n        amount (int): The amount of the bid.\n        timestamp (datetime): The timestamp of the bid.\n    \"\"\"\n\n    def __init__(self, bid_data : dict) -> None:\n        self.auction_id: str = bid_data.get('auction_id')\n        self.bidder: str = bid_data.get('bidder')\n        self.profile_id: str = bid_data.get('profile_id')\n        self.amount: int = bid_data.get('amount')\n        self.timestamp: datetime | None = convert_timestamp(bid_data.get('timestamp'))\n\n    def __str__(self) -> str:\n        timestamp_str = self.timestamp.strftime(\"%Y-%m-%d %H:%M:%S %Z\") if self.timestamp else \"N/A\"\n        return f\"Bid of {self.amount} by {self.bidder} at {timestamp_str}\"\n\nclass SkyBlockAuction:\n    \"\"\"\n    Represents a single SkyBlock auction.\n\n    Attributes:\n        _id (str): The unique identifier of the auction.\n        uuid (str): The UUID of the auction.\n        auctioneer (str): The UUID of the auctioneer.\n        profile_id (str): The profile ID of the auctioneer.\n        coop (list of str): List of coop member UUIDs.\n        start (datetime): The start time of the auction.\n        end (datetime): The end time of the auction.\n        item_name (str): The name of the item being auctioned.\n        item_lore (str): The lore of the item.\n        extra (str): Additional information.\n        category (str): The category of the item.\n        tier (str): The tier of the item.\n        starting_bid (int): The starting bid amount.\n        item_bytes (object): Serialized item data.\n        claimed (bool): Whether the auction has been claimed.\n        claimed_bidders (list): List of bidders who have claimed the item.\n        highest_bid_amount (int): The highest bid amount.\n        bids (list[Bid]): List of bids.\n    \"\"\"\n\n    def __init__(self, auction_data: dict) -> None:\n        self._id: str = auction_data.get('_id')\n        self.uuid: str = auction_data.get('uuid')\n        self.auctioneer: str = auction_data.get('auctioneer')\n        self.profile_id: str = auction_data.get('profile_id')\n        self.coop: list[str] = auction_data.get('coop', [])\n        self.start: datetime | None = convert_timestamp(auction_data.get('start'))\n        self.end: datetime | None = convert_timestamp(auction_data.get('end'))\n        self.item_name: str = auction_data.get('item_name')\n        self.item_lore: str = auction_data.get('item_lore')\n        self.extra: str = auction_data.get('extra')\n        self.category: str = auction_data.get('category')\n        self.tier: str = auction_data.get('tier')\n        self.starting_bid: int = auction_data.get('starting_bid')\n        self.item_bytes: object = auction_data.get('item_bytes')\n        self.claimed: bool = auction_data.get('claimed')\n        self.claimed_bidders: list = auction_data.get('claimed_bidders', [])\n        self.highest_bid_amount: int = auction_data.get('highest_bid_amount')\n        self.bids: list[Bid] | None = [Bid(bid) for bid in auction_data.get('bids', [])]\n\n    def get_start_time_in_timezone(self, tz: tzinfo) -> datetime | None:\n        \"\"\"\n        Get the start time converted to the specified time zone.\n\n        Args:\n            tz (timezone): A timezone object.\n\n        Returns:\n            datetime: The start time in the specified time zone.\n        \"\"\"\n        if self.start:\n            return self.start.astimezone(tz)\n        return None\n\n    def get_end_time_in_timezone(self, tz: tzinfo) -> datetime | None:\n        \"\"\"\n        Get the end time converted to the specified time zone.\n\n        Args:\n            tz (timezone): A timezone object.\n\n        Returns:\n            datetime: The end time in the specified time zone.\n        \"\"\"\n        if self.end:\n            return self.end.astimezone(tz)\n        return None\n\n    @property\n    def current_price(self) -> int:\n        \"\"\"\n        Get the current price of the auction.\n\n        For BIN auctions (with no bids), this is the starting_bid.\n        For regular auctions, this is the highest_bid_amount.\n\n        Returns:\n            int: The current price of the auction.\n        \"\"\"\n        if not self.bids:\n            return self.starting_bid\n        else:\n            return max(self.starting_bid, self.highest_bid_amount)\n\n    @property\n    def is_bin(self) -> bool:\n        \"\"\"\n        Estimate whether the auction is a BIN auction.\n\n        Returns:\n            bool: True if the auction is likely a BIN auction, False otherwise.\n        \"\"\"\n        # Since I can't know from the API, I'm assume auctions with no bids are BIN\n        return not self.bids\n\n    def __str__(self) -> str:\n        auction_type = \"BIN\" if self.is_bin else \"Auction\"\n        return f\"{auction_type} '{self.item_name}' by {self.auctioneer}, Price: {self.current_price}\"\n\nclass AuctionsPage:\n    \"\"\"\n    Represents a single page of auctions from the Hypixel SkyBlock Auctions API.\n\n    Attributes:\n        success (bool): Indicates whether the API request was successful.\n        page (int): The current page number.\n        totalPages (int): The total number of pages.\n        totalAuctions (int): The total number of auctions.\n        lastUpdated (datetime): The last updated timestamp.\n        auctions (list[SkyBlockAuction]): The list of auctions on this page.\n    \"\"\"\n\n    def __init__(self, page_data: dict) -> None:\n        self.success: bool = page_data.get('success', False)\n        self.page: int = page_data.get('page', 0)\n        self.totalPages: int = page_data.get('totalPages', 0)\n        self.totalAuctions: int = page_data.get('totalAuctions', 0)\n        self.lastUpdated: datetime | None = convert_timestamp(page_data.get('lastUpdated'))\n        self.auctions: list[SkyBlockAuction] = [SkyBlockAuction(auction) for auction in page_data.get('auctions', [])]\n\n    def get_auction_by_id(self, auction_id: str) -> SkyBlockAuction | None:\n        \"\"\"\n        Retrieve an auction by its ID from the current page.\n\n        Args:\n            auction_id (str): The ID of the auction.\n\n        Returns:\n            SkyBlockAuction or None: The auction object, or None if not found.\n        \"\"\"\n        return next((auction for auction in self.auctions if auction._id == auction_id), None)\n\n    def get_auctions_by_item_name(self, item_name: str) -> SkyBlockAuction:\n        \"\"\"\n        Retrieve auctions by item name from the current page.\n\n        Args:\n            item_name (str): The name of the item.\n\n        Returns:\n            list of SkyBlockAuction: A list of auctions matching the item name.\n        \"\"\"\n        return [auction for auction in self.auctions if auction.item_name.lower() == item_name.lower()]\n\n    def __str__(self) -> str:\n        return f\"Auctions Page {self.page}/{self.totalPages}, Total Auctions: {self.totalAuctions}\"\n\nclass ActiveAuctions:\n    \"\"\"\n    Manages fetching and storing auction data from the Hypixel SkyBlock Auctions API.\n\n    Attributes:\n        api_endpoint (str): The API endpoint URL.\n        all_auctions (list of SkyBlockAuction): Cached list of all auctions.\n        cache_pages (dict): Cached pages of auctions.\n    \"\"\"\n\n    def __init__(self, api_endpoint: str = ACTIVE_AUCTIONS_API_URL, preload_all: bool = False) -> None:\n        self._api_endpoint: str = api_endpoint\n        self.all_auctions: list[SkyBlockAuction] | list = []\n        self.cache_pages: dict[int, AuctionsPage] | dict = {}\n        if preload_all:\n            self.all_auctions = self.get_all_auctions()\n\n    def get_page(self, page_number: int=0) -> AuctionsPage:\n        \"\"\"\n        Fetch a specific page of auctions, using cache if available.\n    \n        Args:\n        page_number (int): The page number to fetch.\n    \n        Returns:\n        AuctionsPage: The AuctionsPage object for the requested page.\n        \"\"\"\n",
        "input": "",
        "output": "        if page_number in self.cache_pages:\n            return self.cache_pages[page_number]\n\n        params = {'page': page_number}\n        try:\n            response = requests.get(self._api_endpoint, params=params)\n            response.raise_for_status()\n            data = response.json()\n\n            if data.get('success'):\n                page = AuctionsPage(data)\n                self.cache_pages[page_number] = page\n                return page\n            else:\n                raise ValueError(\"API response was not successful\")\n        except requests.exceptions.RequestException as e:\n            raise ConnectionError(f\"An error occurred while fetching page {page_number}: {e}\")\n    \n",
        "idx": "559"
    },
    {
        "instruction": "## hypixel_api_lib/member/Slayer.py\nclass SlayerBoss:\n    \"\"\"\n    Represents a generic slayer boss with common attributes.\n\n    Attributes:\n        claimed_levels (dict[str,bool]): Dictionary of claimed levels.\n        boss_kills (dict[int,int]): Dictionary of boss kills per tier.\n        boss_attempts (dict[int,int]): Dictionary of boss attempts per tier.\n        xp (int): Total experience gained from this slayer boss.\n    \"\"\"\n\n    def __init__(self, data: dict) -> None:\n        self.claimed_levels: dict[str, bool] = data.get('claimed_levels', {})\n        self.xp: int = data.get('xp', 0)\n        self.boss_kills: dict[int,int] = self._extract_tier_data(data, 'boss_kills_tier_')\n        self.boss_attempts: dict[int,int] = self._extract_tier_data(data, 'boss_attempts_tier_')\n\n    @staticmethod\n    def _extract_tier_data(data: dict, prefix: str) -> dict[int, int]:\n        \"\"\"\n        Extracts boss kills or attempts per tier.\n    \n        Args:\n        data (dict): The data dictionary.\n        prefix (str): The prefix to look for in keys.\n    \n        Returns:\n        dict[int,int]: A dictionary with tier as key and count as value.\n        \"\"\"\n",
        "input": "",
        "output": "        result = {}\n        for key, value in data.items():\n            if key.startswith(prefix):\n                tier = int(key[len(prefix):])\n                result[tier] = value\n        return result\n    \n",
        "idx": "560"
    },
    {
        "instruction": "# Here are some relevant code fragments from other files of the repo:\n# --------------------------------------------------\n# the below code fragment can be found in:\n# hypixel_api_lib/utils.py\n# --------------------------------------------------\n# from datetime import datetime, timezone\n# \n# def convert_timestamp(timestamp: int | None) -> datetime | None:\n#     \"\"\"Convert a timestamp in milliseconds to a timezone-aware datetime object in UTC.\"\"\"\n#     if timestamp:\n#         return datetime.fromtimestamp(timestamp / 1000, tz=timezone.utc)\n#     return None\n# \n# --------------------------------------------------\n\n\n## hypixel_api_lib/Bazaar.py\nfrom datetime import datetime\n\nimport requests\n\nfrom hypixel_api_lib.utils import convert_timestamp\n\nimport re\n\nfrom difflib import get_close_matches\n\nBAZAAR_API_URL = \"https://api.hypixel.net/skyblock/bazaar\"\n\nclass BazaarOrderSummaryItem:\n    \"\"\"\n    Represents an order summary item in the bazaar.\n\n    Attributes:\n        amount (int): The total amount of items in the order.\n        price_per_unit (float): The price per unit of the item.\n        orders (int): The number of orders at this price.\n    \"\"\"\n\n    def __init__(self, data: dict) -> None:\n        self.amount: int = data.get('amount', 0)\n        self.price_per_unit: float = data.get('pricePerUnit', 0.0)\n        self.orders: int = data.get('orders', 0)\n\n    def __str__(self) -> str:\n        return f\"Amount: {self.amount}, Price per Unit: {self.price_per_unit}, Orders: {self.orders}\"\n\nclass BazaarProductQuickStatus:\n    \"\"\"\n    Represents the quick status of a bazaar product.\n\n    Attributes:\n        product_id (str): The product ID.\n        sell_price (float): The weighted average sell price.\n        sell_volume (int): The total sell volume.\n        sell_moving_week (int): The sell volume over the moving week.\n        sell_orders (int): The number of sell orders.\n        buy_price (float): The weighted average buy price.\n        buy_volume (int): The total buy volume.\n        buy_moving_week (int): The buy volume over the moving week.\n        buy_orders (int): The number of buy orders.\n    \"\"\"\n\n    def __init__(self, data: dict) -> None:\n        self.product_id: str = data.get('productId', '')\n        self.sell_price: float = data.get('sellPrice', 0.0)\n        self.sell_volume: int = data.get('sellVolume', 0)\n        self.sell_moving_week: int = data.get('sellMovingWeek', 0)\n        self.sell_orders: int = data.get('sellOrders', 0)\n        self.buy_price: float = data.get('buyPrice', 0.0)\n        self.buy_volume: int = data.get('buyVolume', 0)\n        self.buy_moving_week: int = data.get('buyMovingWeek', 0)\n        self.buy_orders: int = data.get('buyOrders', 0)\n\n    def __str__(self) -> str:\n        return (f\"Product ID: {self.product_id}, Sell Price: {self.sell_price}, Sell Volume: {self.sell_volume}, \"\n                f\"Sell Moving Week: {self.sell_moving_week}, Sell Orders: {self.sell_orders}, \"\n                f\"Buy Price: {self.buy_price}, Buy Volume: {self.buy_volume}, \"\n                f\"Buy Moving Week: {self.buy_moving_week}, Buy Orders: {self.buy_orders}\")\n\nclass BazaarProduct:\n    \"\"\"\n    Represents a bazaar product.\n\n    Attributes:\n        product_id (str): The product ID.\n        sell_summary (list of BazaarOrderSummaryItem): The sell order summaries.\n        buy_summary (list of BazaarOrderSummaryItem): The buy order summaries.\n        quick_status (BazaarProductQuickStatus): The quick status of the product.\n    \"\"\"\n\n    def __init__(self, product_id: str, data: dict) -> None:\n        self.product_id: str = product_id\n        self.sell_summary: list[BazaarOrderSummaryItem] = [BazaarOrderSummaryItem(item) for item in data.get('sell_summary', [])]\n        self.buy_summary: list[BazaarOrderSummaryItem] = [BazaarOrderSummaryItem(item) for item in data.get('buy_summary', [])]\n        self.quick_status: BazaarProductQuickStatus = BazaarProductQuickStatus(data.get('quick_status', {}))\n\n    def get_top_buy_order(self) -> BazaarOrderSummaryItem | None:\n        \"\"\"\n        Returns the top buy order summary item.\n\n        Returns:\n            BazaarOrderSummaryItem or None: The top buy order summary item, or None if not available.\n        \"\"\"\n        return self.buy_summary[0] if self.buy_summary else None\n\n    def get_top_sell_order(self) -> BazaarOrderSummaryItem | None:\n        \"\"\"\n        Returns the top sell order summary item.\n\n        Returns:\n            BazaarOrderSummaryItem or None: The top sell order summary item, or None if not available.\n        \"\"\"\n        return self.sell_summary[0] if self.sell_summary else None\n\n    def __str__(self) -> str:\n        return f\"Bazaar Product: {self.product_id}\"\n\nclass Bazaar:\n    \"\"\"\n    Manages fetching and storing the bazaar data from the API.\n\n    Attributes:\n        last_updated (datetime): The timestamp of the last update.\n        products (dict of str to BazaarProduct): The bazaar products.\n        normalized_product_ids (dict of str to str): Mapping of normalized product names to actual product IDs.\n    \"\"\"\n\n    COMMON_PREFIXES = [\n        \"ENCHANTMENT_ULTIMATE_\",\n        \"ENCHANTMENT_\",\n        \"DUNGEON_\",\n    ]\n\n    COMMON_SUFFIXES = [\n        \"_ITEM\",\n        \"_SCROLL\",\n        \"_GEM\",\n        \"_ORE\",\n        \"_1\",\n        \"_2\",\n        \"_3\",\n        \"_4\",\n        \"_5\",\n        \"_6\",\n        \"_7\",\n        \"_8\",\n        \"_9\",\n        \"_10\",\n    ]\n\n    def __init__(self, api_endpoint: str = BAZAAR_API_URL) -> None:\n        self.api_endpoint: str = api_endpoint\n        self.last_updated: datetime | None = None\n        self.products: dict[str, BazaarProduct] = {}\n        self.normalized_product_ids: dict[str, str] = {}\n        self._load_bazaar_data()\n\n    def _load_bazaar_data(self) -> None:\n        \"\"\"Fetch the bazaar data from the API.\"\"\"\n        try:\n            response = requests.get(self.api_endpoint)\n            response.raise_for_status()\n            data = response.json()\n\n            if data.get('success'):\n                self.last_updated = convert_timestamp(data.get('lastUpdated'))\n                products_data = data.get('products', {})\n                for product_id, product_data in products_data.items():\n                    self.products[product_id] = BazaarProduct(product_id, product_data)\n                    normalized_id = self._normalize_product_id(product_id)\n                    self.normalized_product_ids[normalized_id] = product_id\n            else:\n                raise ValueError(\"Failed to fetch bazaar data\")\n        except requests.exceptions.RequestException as e:\n            raise ConnectionError(f\"An error occurred: {e}\")\n\n    def _normalize_product_id(self, product_id: str) -> str:\n        \"\"\"Normalize the product ID for easier searching.\"\"\"\n        normalized = product_id.upper()\n        for prefix in self.COMMON_PREFIXES:\n            if normalized.startswith(prefix):\n                normalized = normalized[len(prefix):]\n                break\n        for suffix in self.COMMON_SUFFIXES:\n            if normalized.endswith(suffix):\n                normalized = normalized[:-len(suffix)]\n                break\n        normalized = re.sub(r'[^A-Z0-9]', '_', normalized)\n        return normalized\n\n    def search_product(self, search_term: str) -> BazaarProduct | None:\n        \"\"\"\n        Search for a product using a search term.\n\n        Args:\n            search_term (str): The search term provided by the user.\n\n        Returns:\n            BazaarProduct or None: The matching BazaarProduct object, or None if not found.\n        \"\"\"\n        normalized_search = self._normalize_search_term(search_term)\n        product_id = self.normalized_product_ids.get(normalized_search)\n        if product_id and product_id in self.products:\n            return self.products[product_id]\n        possible_ids = self._generate_possible_product_ids(normalized_search)\n        for pid in possible_ids:\n            if pid in self.products:\n                return self.products[pid]\n        return self._fuzzy_search(normalized_search)\n\n    def _normalize_search_term(self, search_term: str) -> str:\n        \"\"\"Normalize the search term to match normalized product IDs.\"\"\"\n        normalized = search_term.upper().replace(' ', '_')\n        normalized = re.sub(r'[^A-Z0-9]', '_', normalized)\n        return normalized\n\n    def _generate_possible_product_ids(self, base_term: str) -> list[str]:\n        \"\"\"\n        Generate possible product IDs by adding common prefixes and suffixes.\n        \"\"\"\n",
        "input": "",
        "output": "        possible_ids = []\n        for prefix in [''] + self.COMMON_PREFIXES:\n            term_with_prefix = prefix + base_term\n            for suffix in [''] + self.COMMON_SUFFIXES:\n                possible_id = term_with_prefix + suffix\n                possible_ids.append(possible_id)\n        possible_ids = list(set(possible_ids))\n        return possible_ids\n    \n",
        "idx": "561"
    },
    {
        "instruction": "## hypixel_api_lib/member/Rift.py\nimport zlib\n\nimport base64\n\nimport gzip\n\nfrom io import BytesIO\n\nclass InventoryData:\n    \"\"\"\n    Represents inventory-related data, handling Minecraft-specific encoding and compression formats.\n\n    Attributes:\n        type (int): Type identifier of the inventory data.\n        raw_data (str): Raw compressed data of the inventory.\n        data (str): Decoded or decompressed data, or an error message if decoding fails.\n    \"\"\"\n\n    def __init__(self, data: dict) -> None:\n        self.type: int = data.get('type')\n        self.raw_data: str = data.get('data', '')\n\n        self.data: str = self._decode_data(self.raw_data)\n\n    def _decode_data(self, data: str) -> str:\n        \"\"\"\n        Attempt to decode and decompress the inventory data.\n        \"\"\"\n",
        "input": "",
        "output": "        if not data:\n            return \"No data available\"\n        \n        try:\n            decoded_data = base64.b64decode(data)\n            \n            try:\n                decompressed_data = zlib.decompress(decoded_data)\n                return decompressed_data.decode('utf-8', errors='ignore')\n            except zlib.error as e:\n                try:\n                    with gzip.open(BytesIO(decoded_data), 'rb') as f:\n                        return f.read().decode('utf-8', errors='ignore')\n                except gzip.BadGzipFile as e:\n                    return f\"Error decoding inventory: Gzip decompression failed - {e}\"\n\n        except (base64.binascii.Error, zlib.error) as e:\n            return f\"Error decoding inventory: {e}\"\n    \n",
        "idx": "563"
    },
    {
        "instruction": "# Here are some relevant code fragments from other files of the repo:\n# --------------------------------------------------\n# the below code fragment can be found in:\n# hypixel_api_lib/utils.py\n# --------------------------------------------------\n# from datetime import datetime, timezone\n# \n# def convert_timestamp(timestamp: int | None) -> datetime | None:\n#     \"\"\"Convert a timestamp in milliseconds to a timezone-aware datetime object in UTC.\"\"\"\n#     if timestamp:\n#         return datetime.fromtimestamp(timestamp / 1000, tz=timezone.utc)\n#     return None\n# \n# --------------------------------------------------\n\n\n## hypixel_api_lib/Auctions.py\nfrom datetime import datetime, timezone, tzinfo\n\nimport requests\n\nfrom hypixel_api_lib.utils import get_uuid_from_username, convert_timestamp\n\nACTIVE_AUCTIONS_API_URL = r\"https://api.hypixel.net/skyblock/auctions\"\n\nclass Bid:\n    \"\"\"\n    Represents a single bid in an auction.\n\n    Attributes:\n        auction_id (str): The ID of the auction.\n        bidder (str): The UUID of the bidder.\n        profile_id (str): The profile ID of the bidder.\n        amount (int): The amount of the bid.\n        timestamp (datetime): The timestamp of the bid.\n    \"\"\"\n\n    def __init__(self, bid_data : dict) -> None:\n        self.auction_id: str = bid_data.get('auction_id')\n        self.bidder: str = bid_data.get('bidder')\n        self.profile_id: str = bid_data.get('profile_id')\n        self.amount: int = bid_data.get('amount')\n        self.timestamp: datetime | None = convert_timestamp(bid_data.get('timestamp'))\n\n    def __str__(self) -> str:\n        timestamp_str = self.timestamp.strftime(\"%Y-%m-%d %H:%M:%S %Z\") if self.timestamp else \"N/A\"\n        return f\"Bid of {self.amount} by {self.bidder} at {timestamp_str}\"\n\nclass SkyBlockAuction:\n    \"\"\"\n    Represents a single SkyBlock auction.\n\n    Attributes:\n        _id (str): The unique identifier of the auction.\n        uuid (str): The UUID of the auction.\n        auctioneer (str): The UUID of the auctioneer.\n        profile_id (str): The profile ID of the auctioneer.\n        coop (list of str): List of coop member UUIDs.\n        start (datetime): The start time of the auction.\n        end (datetime): The end time of the auction.\n        item_name (str): The name of the item being auctioned.\n        item_lore (str): The lore of the item.\n        extra (str): Additional information.\n        category (str): The category of the item.\n        tier (str): The tier of the item.\n        starting_bid (int): The starting bid amount.\n        item_bytes (object): Serialized item data.\n        claimed (bool): Whether the auction has been claimed.\n        claimed_bidders (list): List of bidders who have claimed the item.\n        highest_bid_amount (int): The highest bid amount.\n        bids (list[Bid]): List of bids.\n    \"\"\"\n\n    def __init__(self, auction_data: dict) -> None:\n        self._id: str = auction_data.get('_id')\n        self.uuid: str = auction_data.get('uuid')\n        self.auctioneer: str = auction_data.get('auctioneer')\n        self.profile_id: str = auction_data.get('profile_id')\n        self.coop: list[str] = auction_data.get('coop', [])\n        self.start: datetime | None = convert_timestamp(auction_data.get('start'))\n        self.end: datetime | None = convert_timestamp(auction_data.get('end'))\n        self.item_name: str = auction_data.get('item_name')\n        self.item_lore: str = auction_data.get('item_lore')\n        self.extra: str = auction_data.get('extra')\n        self.category: str = auction_data.get('category')\n        self.tier: str = auction_data.get('tier')\n        self.starting_bid: int = auction_data.get('starting_bid')\n        self.item_bytes: object = auction_data.get('item_bytes')\n        self.claimed: bool = auction_data.get('claimed')\n        self.claimed_bidders: list = auction_data.get('claimed_bidders', [])\n        self.highest_bid_amount: int = auction_data.get('highest_bid_amount')\n        self.bids: list[Bid] | None = [Bid(bid) for bid in auction_data.get('bids', [])]\n\n    def get_start_time_in_timezone(self, tz: tzinfo) -> datetime | None:\n        \"\"\"\n        Get the start time converted to the specified time zone.\n\n        Args:\n            tz (timezone): A timezone object.\n\n        Returns:\n            datetime: The start time in the specified time zone.\n        \"\"\"\n        if self.start:\n            return self.start.astimezone(tz)\n        return None\n\n    def get_end_time_in_timezone(self, tz: tzinfo) -> datetime | None:\n        \"\"\"\n        Get the end time converted to the specified time zone.\n\n        Args:\n            tz (timezone): A timezone object.\n\n        Returns:\n            datetime: The end time in the specified time zone.\n        \"\"\"\n        if self.end:\n            return self.end.astimezone(tz)\n        return None\n\n    @property\n    def current_price(self) -> int:\n        \"\"\"\n        Get the current price of the auction.\n\n        For BIN auctions (with no bids), this is the starting_bid.\n        For regular auctions, this is the highest_bid_amount.\n\n        Returns:\n            int: The current price of the auction.\n        \"\"\"\n        if not self.bids:\n            return self.starting_bid\n        else:\n            return max(self.starting_bid, self.highest_bid_amount)\n\n    @property\n    def is_bin(self) -> bool:\n        \"\"\"\n        Estimate whether the auction is a BIN auction.\n\n        Returns:\n            bool: True if the auction is likely a BIN auction, False otherwise.\n        \"\"\"\n        # Since I can't know from the API, I'm assume auctions with no bids are BIN\n        return not self.bids\n\n    def __str__(self) -> str:\n        auction_type = \"BIN\" if self.is_bin else \"Auction\"\n        return f\"{auction_type} '{self.item_name}' by {self.auctioneer}, Price: {self.current_price}\"\n\nclass AuctionsPage:\n    \"\"\"\n    Represents a single page of auctions from the Hypixel SkyBlock Auctions API.\n\n    Attributes:\n        success (bool): Indicates whether the API request was successful.\n        page (int): The current page number.\n        totalPages (int): The total number of pages.\n        totalAuctions (int): The total number of auctions.\n        lastUpdated (datetime): The last updated timestamp.\n        auctions (list[SkyBlockAuction]): The list of auctions on this page.\n    \"\"\"\n\n    def __init__(self, page_data: dict) -> None:\n        self.success: bool = page_data.get('success', False)\n        self.page: int = page_data.get('page', 0)\n        self.totalPages: int = page_data.get('totalPages', 0)\n        self.totalAuctions: int = page_data.get('totalAuctions', 0)\n        self.lastUpdated: datetime | None = convert_timestamp(page_data.get('lastUpdated'))\n        self.auctions: list[SkyBlockAuction] = [SkyBlockAuction(auction) for auction in page_data.get('auctions', [])]\n\n    def get_auction_by_id(self, auction_id: str) -> SkyBlockAuction | None:\n        \"\"\"\n        Retrieve an auction by its ID from the current page.\n\n        Args:\n            auction_id (str): The ID of the auction.\n\n        Returns:\n            SkyBlockAuction or None: The auction object, or None if not found.\n        \"\"\"\n        return next((auction for auction in self.auctions if auction._id == auction_id), None)\n\n    def get_auctions_by_item_name(self, item_name: str) -> SkyBlockAuction:\n        \"\"\"\n        Retrieve auctions by item name from the current page.\n\n        Args:\n            item_name (str): The name of the item.\n\n        Returns:\n            list of SkyBlockAuction: A list of auctions matching the item name.\n        \"\"\"\n        return [auction for auction in self.auctions if auction.item_name.lower() == item_name.lower()]\n\n    def __str__(self) -> str:\n        return f\"Auctions Page {self.page}/{self.totalPages}, Total Auctions: {self.totalAuctions}\"\n\nclass ActiveAuctions:\n    \"\"\"\n    Manages fetching and storing auction data from the Hypixel SkyBlock Auctions API.\n\n    Attributes:\n        api_endpoint (str): The API endpoint URL.\n        all_auctions (list of SkyBlockAuction): Cached list of all auctions.\n        cache_pages (dict): Cached pages of auctions.\n    \"\"\"\n\n    def __init__(self, api_endpoint: str = ACTIVE_AUCTIONS_API_URL, preload_all: bool = False) -> None:\n        self._api_endpoint: str = api_endpoint\n        self.all_auctions: list[SkyBlockAuction] | list = []\n        self.cache_pages: dict[int, AuctionsPage] | dict = {}\n        if preload_all:\n            self.all_auctions = self.get_all_auctions()\n\n    def get_page(self, page_number: int = 0) -> AuctionsPage:\n        \"\"\"\n        Fetch a specific page of auctions, using cache if available.\n\n        Args:\n            page_number (int): The page number to fetch.\n\n        Returns:\n            AuctionsPage: The AuctionsPage object for the requested page.\n        \"\"\"\n        if page_number in self.cache_pages:\n            return self.cache_pages[page_number]\n\n        params = {'page': page_number}\n        try:\n            response = requests.get(self._api_endpoint, params=params)\n            response.raise_for_status()\n            data = response.json()\n\n            if data.get('success'):\n                page = AuctionsPage(data)\n                self.cache_pages[page_number] = page\n                return page\n            else:\n                raise ValueError(\"API response was not successful\")\n        except requests.exceptions.RequestException as e:\n            raise ConnectionError(f\"An error occurred while fetching page {page_number}: {e}\")\n\n    def get_all_auctions(self) -> list[SkyBlockAuction]:\n        \"\"\"\n        Fetch all auctions by iterating through all available pages.\n    \n        Returns:\n        list of SkyBlockAuction: A list of all auctions.\n        \"\"\"\n",
        "input": "",
        "output": "        if self.all_auctions:\n            return self.all_auctions  # Return cached data\n\n        all_auctions = []\n        first_page = self.get_page(0)\n        total_pages = first_page.totalPages\n        all_auctions.extend(first_page.auctions)\n\n        for page_number in range(1, total_pages):\n            page = self.get_page(page_number)\n            all_auctions.extend(page.auctions)\n\n        self.all_auctions = all_auctions  # Cache the results\n        return all_auctions\n    \n",
        "idx": "567"
    },
    {
        "instruction": "# Here are some relevant code fragments from other files of the repo:\n# --------------------------------------------------\n# the below code fragment can be found in:\n# hypixel_api_lib/utils.py\n# --------------------------------------------------\n# from datetime import datetime, timezone\n# \n# def convert_timestamp(timestamp: int | None) -> datetime | None:\n#     \"\"\"Convert a timestamp in milliseconds to a timezone-aware datetime object in UTC.\"\"\"\n#     if timestamp:\n#         return datetime.fromtimestamp(timestamp / 1000, tz=timezone.utc)\n#     return None\n# \n# --------------------------------------------------\n\n\n## hypixel_api_lib/member/PlayerData.py\nfrom datetime import datetime\n\nfrom hypixel_api_lib.utils import convert_timestamp\n\nclass Perk:\n    \"\"\"\n    Represents a perk and its level.\n\n    Attributes:\n        name (str): The name of the perk.\n        level (int): The level of the perk.\n    \"\"\"\n\n    def __init__(self, name: str, level: int) -> None:\n        self.name: str = name\n        self.level: int = level\n\n    def __str__(self) -> str:\n        return f\"{self.name}: Level {self.level}\"\n\nclass SkillExperience:\n    \"\"\"\n    Represents experience in a specific skill.\n\n    Attributes:\n        skill_name (str): The name of the skill.\n        experience (float): The amount of experience in the skill.\n    \"\"\"\n\n    def __init__(self, skill_name: str, experience: float) -> None:\n        self.skill_name: str = skill_name\n        self.experience: float = experience\n\n    def __str__(self) -> str:\n        return f\"{self.skill_name}: {self.experience} XP\"\n    \n    def __repr__(self) -> str:\n        return f\"{self.skill_name}: {self.experience} XP\"\n\nclass PlayerData:\n    \"\"\"\n    Represents the player data for a SkyBlock profile member.\n\n    Attributes:\n        visited_zones (list of str): List of zones the player has visited.\n        last_death (datetime): Datetime of the player's last death.\n        perks (dict of str to int): Perks and their levels.\n        active_effects (list): List of active effects.\n        paused_effects (list): List of paused effects.\n        temp_stat_buffs (list): List of temporary stat buffs.\n        death_count (int): Total number of deaths.\n        disabled_potion_effects (list of str): List of disabled potion effects.\n        achievement_spawned_island_types (list of str): List of spawned island types for achievements.\n        visited_modes (list of str): List of game modes the player has visited.\n        unlocked_coll_tiers (list of str): List of unlocked collection tiers.\n        crafted_generators (list of str): List of crafted generators.\n        fastest_target_practice (float): Fastest time in target practice.\n        fishing_treasure_caught (int): Number of fishing treasures caught.\n        experience (dict of str to float): Experience in various skills.\n    \"\"\"\n\n    def __init__(self, data: dict) -> None:\n        self.visited_zones: list = data.get('visited_zones', [])\n        self.last_death: datetime | None = convert_timestamp(data.get('last_death'))\n        self.perks: dict[str,int] = self._parse_perks(data.get('perks', {}))\n        self.active_effects: list = data.get('active_effects', [])\n        self.paused_effects: list = data.get('paused_effects', [])\n        self.temp_stat_buffs: list = data.get('temp_stat_buffs', [])\n        self.death_count: int = data.get('death_count', 0)\n        self.disabled_potion_effects: list[str] = data.get('disabled_potion_effects', [])\n        self.achievement_spawned_island_types: list[str] = data.get('achievement_spawned_island_types', [])\n        self.visited_modes: list[str] = data.get('visited_modes', [])\n        self.unlocked_coll_tiers: list[str] = data.get('unlocked_coll_tiers', [])\n        self.crafted_generators: list[str] = data.get('crafted_generators', [])\n        self.fastest_target_practice: float | None = data.get('fastest_target_practice', None)\n        self.fishing_treasure_caught: int = data.get('fishing_treasure_caught', 0)\n        self.experience: dict[str,float] = self._parse_experience(data.get('experience', {}))\n    \n    def _parse_perks(self, perks_dict: dict) -> list[Perk]:\n        \"\"\"\n        Convert the perks dictionary into a list of Perk objects.\n        \"\"\"\n",
        "input": "",
        "output": "        return [Perk(name, level) for name, level in perks_dict.items()]\n    \n",
        "idx": "568"
    },
    {
        "instruction": "## hypixel_api_lib/member/TrophyFish.py\nclass TrophyFish:\n    \"\"\"\n    Represents a single type of trophy fish with counts per tier.\n\n    Attributes:\n        name (str): The name of the fish.\n        total_caught (int): Total number of this fish caught.\n        tiers (dict[str,int]): Counts per tier (bronze, silver, gold, diamond).\n    \"\"\"\n\n    def __init__(self, name: str) -> None:\n        self.name: str = name\n        self.total_caught: int = 0\n        self.tiers: dict[str,int] = {}  # e.g., {'bronze': 10, 'silver': 5}\n\n    def add_catch(self, tier: str | None, count: int) -> None:\n        \"\"\"\n        Adds catch count to the fish.\n\n        Args:\n            tier (Optional[str]): The tier of the catch (e.g., 'bronze', 'silver').\n            count (int): Number of fish caught.\n        \"\"\"\n        if tier:\n            self.tiers[tier] = self.tiers.get(tier, 0) + count\n        else:\n            self.total_caught += count\n\n    def total_tier_catches(self) -> int:\n        \"\"\"\n        Calculates the total catches across all tiers.\n\n        Returns:\n            int: Total catches across all tiers.\n        \"\"\"\n        return sum(self.tiers.values())\n\n    def __str__(self) -> str:\n        return (\n            f\"TrophyFish(name={self.name}, total_caught={self.total_caught}, \"\n            f\"tiers={self.tiers})\"\n        )\n\nclass TrophyFishStats:\n    \"\"\"\n    Represents the player's trophy fish statistics.\n\n    Attributes:\n        rewards (list[int]): List of reward IDs.\n        total_caught (int): Total number of trophy fish caught.\n        fish_types (dict[str,TrophyFish]): Dictionary of trophy fish by name.\n        last_caught (str): The last trophy fish caught with its tier.\n    \"\"\"\n\n    def __init__(self, data: dict) -> None:\n        self.rewards: list[int] = data.get('rewards', [])\n        self.total_caught: int = data.get('total_caught', 0)\n        self.last_caught: str = data.get('last_caught', '')\n        self.fish_types: dict[str,TrophyFish] = {}\n\n        self._parse_fish_data(data)\n\n    def _parse_fish_data(self, data: dict) -> None:\n        \"\"\"\n        Parses the fish data and populates the fish_types dictionary.\n    \n        Args:\n        data (dict): The data dictionary.\n        \"\"\"\n",
        "input": "",
        "output": "        special_keys = {'rewards', 'total_caught', 'last_caught'}\n        for key, value in data.items():\n            if key in special_keys:\n                continue\n            parts = key.split('_')\n            if parts[-1] in {'bronze', 'silver', 'gold', 'diamond'}:\n                tier = parts[-1]\n                fish_name = '_'.join(parts[:-1])\n            else:\n                tier = None\n                fish_name = key\n\n            if fish_name not in self.fish_types:\n                self.fish_types[fish_name] = TrophyFish(fish_name)\n\n            self.fish_types[fish_name].add_catch(tier, value)\n    \n",
        "idx": "569"
    },
    {
        "instruction": "## hypixel_api_lib/member/Bestiary.py\nclass Bestiary:\n    \"\"\"\n    Represents the player's Bestiary data.\n\n    Attributes:\n        migrated_stats (bool): Whether the stats have been migrated.\n        migration (bool): Migration status.\n        kills (dict[str, int]): Dictionary of mobs and their kill counts.\n        deaths (dict[str, int]): Dictionary of mobs and their death counts.\n        milestone (int): Last claimed milestone.\n        miscellaneous (bool): Whether max kills are visible.\n    \"\"\"\n\n    def __init__(self, data: dict) -> None:\n        self.migrated_stats: bool = data.get(\"migrated_stats\", False)\n        self.migration: bool = data.get(\"migration\", False)\n        self.kills: dict[str, int] = data.get(\"kills\", {}).copy()\n        self.last_killed_mob: str | None = self.kills.pop('last_killed_mob', None) \n        self.deaths: dict[str,int] = data.get(\"deaths\", {})\n        self.milestone: int = data.get(\"milestone\", {}).get(\"last_claimed_milestone\", 0)\n        self.miscellaneous: bool = data.get(\"miscellaneous\", {}).get(\"max_kills_visible\", False)\n\n    def get_kill_count(self, mob_name: str) -> int:\n        \"\"\"\n        Get the kill count for a specific mob.\n\n        Args:\n            mob_name (str): The name of the mob.\n\n        Returns:\n            int: The kill count for the mob, or 0 if not found.\n        \"\"\"\n        return self.kills.get(mob_name, 0)\n\n    def get_death_count(self, mob_name: str) -> int:\n        \"\"\"\n        Get the death count for a specific mob.\n\n        Args:\n            mob_name (str): The name of the mob.\n\n        Returns:\n            int: The death count for the mob, or 0 if not found.\n        \"\"\"\n        return self.deaths.get(mob_name, 0)\n\n    def top_kills(self, n: int = 5) -> list[tuple[str, int]]:\n        \"\"\"\n        Get the top N mobs by kill count.\n\n        Args:\n            n (int): The number of top mobs to return.\n\n        Returns:\n            list[tuple[str, int]]: A list of tuples containing mob names and kill counts.\n        \"\"\"\n        sorted_kills = sorted(self.kills.items(), key=lambda item: item[1], reverse=True)\n        return sorted_kills[:n]\n\n    def top_deaths(self, n: int = 5) -> list[tuple[str, int]]:\n        \"\"\"\n        Get the top N mobs by death count.\n\n        Args:\n            n (int): The number of top mobs to return.\n\n        Returns:\n            list[tuple[str, int]]: A list of tuples containing mob names and death counts.\n        \"\"\"\n        sorted_deaths = sorted(self.deaths.items(), key=lambda item: item[1], reverse=True)\n        return sorted_deaths[:n]\n\n    def total_kills(self) -> int:\n        \"\"\"\n        Get the total number of kills across all mobs.\n\n        Returns:\n            int: Total kills.\n        \"\"\"\n        return sum(self.kills.values())\n\n    def total_deaths(self) -> int:\n        \"\"\"\n        Get the total number of deaths across all mobs.\n\n        Returns:\n            int: Total deaths.\n        \"\"\"\n        return sum(self.deaths.values())\n\n    def search_mobs(self, query: str) -> list[str]:\n        \"\"\"\n        Search for mobs containing the query string in their names.\n    \n        Args:\n        query (str): The search query string.\n    \n        Returns:\n        list[str]: A list of mob names that match the query.\n        \"\"\"\n",
        "input": "",
        "output": "        query_lower = query.lower()\n        matched_mobs = [mob for mob in self.kills.keys() if query_lower in mob.lower()]\n        return matched_mobs\n    \n",
        "idx": "570"
    },
    {
        "instruction": "## hypixel_api_lib/member/Quests.py\nclass HarpQuest:\n    \"\"\"\n    Represents the player's Harp Quest data.\n\n    Attributes:\n        selected_song (str): The currently selected song.\n        selected_song_epoch (int): The epoch time when the song was selected.\n        songs (Dict[str, Dict[str, float or int]]): A dictionary containing song statistics.\n        claimed_talisman (bool): Whether the talisman has been claimed.\n    \"\"\"\n\n    def __init__(self, data: dict) -> None:\n        harp_data = data.get('harp_quest', {})\n        self.selected_song: str | None = harp_data.get('selected_song')\n        self.selected_song_epoch: int | None = harp_data.get('selected_song_epoch')\n        self.claimed_talisman: bool = harp_data.get('claimed_talisman', False)\n        self.songs: dict[str,dict[str,float|int]] = self._extract_song_stats(harp_data)\n\n    def _extract_song_stats(self, harp_data: dict) -> dict[str, dict[str, float | int]]:\n        \"\"\"\n        Extracts song statistics from the harp quest data.\n    \n        Args:\n        harp_data (dict): The harp quest data.\n    \n        Returns:\n        Dict[str, Dict[str, float or int]]: A dictionary of song statistics.\n        \"\"\"\n",
        "input": "",
        "output": "        songs = {}\n        for key, value in harp_data.items():\n            if key.startswith('song_') and not key.endswith('_completions') and not key.endswith('_perfect_completions') and not key.endswith('_best_completion'):\n                continue\n            if key.startswith('song_'):\n                parts = key.split('_')\n                song_name = '_'.join(parts[1:-1])\n                stat_type = parts[-1]\n                if song_name not in songs:\n                    songs[song_name] = {}\n                songs[song_name][stat_type] = value\n        return songs\n    \n",
        "idx": "571"
    },
    {
        "instruction": "## labjackt7/temperature.py\nclass Temperature:\n    def __init__(self, labjack):\n        self.labjack = labjack\n\n    def configure(self, pos_ch: int, neg_ch: int, thermocouple_type: str, arange=0.05):\n        \"\"\"\n        Enables temperature sensing on a given channel pair for\n        thermocouple_type = 'J' or 'K'.\n        \"\"\"\n",
        "input": "",
        "output": "        kind = {'J': 21, 'K': 22}[thermocouple_type]\n        self.labjack._command(f'AIN{pos_ch}_EF_INDEX', kind)\n        self.labjack._write_dict({f'AIN{pos_ch}_EF_INDEX': kind,\n                                  f'AIN{pos_ch}_EF_CONFIG_B': 60052,\n                                  f'AIN{pos_ch}_EF_CONFIG_D': 1,\n                                  f'AIN{pos_ch}_EF_CONFIG_E': 0,\n                                  f'AIN{pos_ch}_NEGATIVE_CH': neg_ch,\n                                  f'AIN{pos_ch}_RANGE': arange\n                                  })\n    \n",
        "idx": "576"
    },
    {
        "instruction": "## labjackt7/digital.py\nimport numpy as np\n\nclass Digital():\n    ''' Handles digital subsystems of the LabJack T-series device family, covering\n        digital in/out, simultaneous DIO_STATE updates, and streaming.\n    '''\n    def __init__(self, labjack):\n        self.labjack = labjack\n\n    def din(self, channel) -> int:\n        ''' Read a digital signal.\n\n            Args:\n                channel (str or int): a digital channel on the LabJack, e.g. 'FIO4'.\n            Return:\n                state (int): 1 or 0\n        '''\n        channel = self._chan_to_str(channel)\n        return int(self.labjack._query(channel))\n\n    def dout(self, channel, state:int):\n        ''' Output a digital signal.\n\n            Args:\n                channel (str or int): a digital channel on the LabJack, e.g. 'FIO4'.\n                state (int): 1 or 0\n        '''\n        channel = self._chan_to_str(channel)\n        self.labjack._command(channel, state)\n\n    def dout_multi(self, channels:list, states:list):\n        ''' Set multiple digital channels simultaneously. \n        \n            Args:\n                channels (list of numbers): numerical channels (str NOT supported)\n                states (list of 1/0): 1's or 0's\n        '''\n        bitstate = 0\n        for i in range(len(channels)):\n            bitstate = bitstate | (states[i] << channels[i])\n\n        bitmask = self.bitmask(channels)\n        self.labjack._write_dict({'DIO_INHIBIT':   0x7FFFFF-bitmask,\n                                  'DIO_DIRECTION': bitmask,\n                                  'DIO_STATE':     bitstate})\n\n    @staticmethod\n    def inhibit_string(channels):\n        inhibit = ''\n        for i in range(23):\n            if 23-i-1 in channels:\n                inhibit += '0'\n            else:\n                inhibit += '1'\n        return inhibit\n\n    @staticmethod\n    def array_to_bitmask(arr, channels):\n        ''' Convert multidimensional array with one column for each channel to an array of bitmasks. '''\n        y = np.zeros(len(arr))\n\n        inhibit = 0x7FFFFF-Digital.bitmask(channels)\n        inhibit_string = Digital.inhibit_string(channels)\n        for i in range(len(arr)):\n            states = arr[i,:]\n            bitmask = Digital.state(channels, states)\n            lower_bits = format(bitmask, '#010b')\n            y[i] = int(inhibit_string[-8:]+lower_bits[2:], 2)\n        return y\n\n    @staticmethod\n    def bitmask(channels):\n        bm = 0\n        for ch in channels:\n            bm |= 1 << ch\n        return bm\n\n    @staticmethod\n    def state(channels, states):\n        \"\"\"\n        Returns a bitmask representation of the passed channels and states.\n        \"\"\"\n",
        "input": "",
        "output": "        bitmask = 0\n        for j in range(len(channels)):\n            bitmask = bitmask | (int(states[j]) << channels[j])\n        return bitmask\n    \n",
        "idx": "584"
    },
    {
        "instruction": "## labjackt7/stream.py\nfrom labjack import ljm\n\nimport numpy as np\n\nfrom datetime import datetime\n\nclass Stream():\n    def __init__(self, labjack):\n        self.labjack = labjack\n        self.configure()\n\n    def configure(self, settling_time=0, resolution_index=0, clock_source=0):\n        self.stop()\n        self.labjack._write_dict({\n            'STREAM_SETTLING_US': settling_time,\n            'STREAM_RESOLUTION_INDEX': resolution_index,\n            'STREAM_CLOCK_SOURCE': clock_source\n        })\n        #STREAM_TRIGGER_INDEX\n\n    def configure_from_dict(self, stream_options: dict):\n        self.labjack._write_dict(stream_options)\n\n    def set_inhibit(self, channels):\n        bitmask = self.labjack.digital.bitmask(channels)\n        inhibit = 0x7FFFFF-bitmask\n\n        self.labjack._write_dict({'DIO_INHIBIT': inhibit,\n                                  'DIO_DIRECTION': bitmask\n                                  })\n\n    def stop(self):\n        ''' Stop streaming if currently running '''\n        try:\n            ljm.eStreamStop(self.labjack.handle)\n        except:\n            pass\n\n    #disabled because removed scipy.signal.resample()\n    # def resample(self, array, period, max_samples = 8191):\n    #     ''' Compute optimum scan rate and number of samples '''\n    #     max_speed = self._device_scanRate()\n    #     cutoff = max_samples / max_speed\n    #     if period >= cutoff:\n    #         samples = max_samples\n    #         scanRate = int(samples/period)\n    #     else:\n    #         scanRate = max_speed\n    #         samples = int(period*scanRate)\n    #     # stream = resample(array, samples)\n    #     stream = []\n    #     scanRate /= array.shape[1]    ## divide by number of channels being streamed\n    #     return stream, scanRate\n\n    def stream_burst(self, aScanListNames:list, scanRate:int=0, scanTime_s:float=1) -> list:\n        ''' \n            Args:\n                scanListNames: [\"AIN0\", \"AIN1\"] etc\n                scan_rate: 0 for max rate\n                scan_time_s: number of seconds to sample (default 1)\n        '''\n        aScanList = ljm.namesToAddresses(len(aScanListNames), aScanListNames)[0]  # Names to addresses for streamBurst\n        if (scanRate <= 0) or (scanRate > self._device_scanRate()):\n            scanRate = self._device_scanRate()\n        num_scans = int(scanTime_s*scanRate)  # Number of scans to perform\n        num_scans = num_scans - (num_scans % len(aScanList)) # ensure all channels have equal samples\n        start = datetime.now()\n        scanRate, aData = ljm.streamBurst(self.labjack.handle, len(aScanList), aScanList, scanRate, num_scans)\n        end = datetime.now()\n        if False:\n            print(f\"Channels: {len(aScanListNames)},  Samples per Ch: {len(aData)/len(aScanListNames)}, ScanRate: {scanRate}, Elapsed Time = {(end - start).seconds + float((end - start).microseconds) / 1000000}s\" )\n        if aData.count(-9999.0) > 0:\n            print(f\"WARNING: some samples were skipped! Total skips, all channels) = f{aData.count(-9999.0)}\")\n        return scanRate, self._reshape_data(aData, len(aScanList))\n\n    def stream_start(self, channels: list, scan_rate):\n",
        "input": "",
        "output": "        self.stop()\n        scan_list = ljm.namesToAddresses(len(channels), channels)[0]\n\n        scans_per_read = int(scan_rate/2)\n        ljm.eStreamStart(self.labjack.handle, scans_per_read, len(channels), scan_list, scan_rate)\n    \n",
        "idx": "585"
    },
    {
        "instruction": "## labjackt7/analog.py\nfrom labjack import ljm\n\nclass Analog():\n    def __init__(self, labjack):\n        self.labjack = labjack\n        self.configure()\n\n    def configure(self, range=10):\n        self.labjack._write_dict({\n            \"AIN_ALL_NEGATIVE_CH\" : ljm.constants.GND,\n            \"AIN_ALL_RANGE\" : range\n        })\n\n    def ain(self, channel):\n        ''' Read a channel and return the voltage.\n         \n            Args:\n                channel (int or str): number of the target DAC channel.\n        '''\n        channel = self._chan_to_ain(channel)\n        return self.labjack._query(channel)\n\n    def aout(self, channel, value):\n        ''' Output an analog voltage.\n\n            Args:\n                channel (int or str): number of the target DAC channel.\n                value (float): Voltage in volts.\n        '''\n        channel = self._chan_to_dac(channel)\n        self.labjack._command(channel, value)\n\n    # def TDAC(self, channel, value):\n    #     ''' Output an analog voltage.\n\n    #         Args:\n    #             channel (int): number of the target TDAC channel.\n    #             value (float): Voltage in volts.\n    #             TDAC (bool): If False, use a DAC channel (0-5 V); if True, use a TDAC channel with the LJTick-DAC accessory (+/-10 V).\n    #     '''\n    #     self.labjack._command(\"TDAC%i\"%channel, value)\n\n\n    def _chan_to_ain(self, channel):\n",
        "input": "",
        "output": "        if type(channel) is int:\n            channel = f'AIN{channel}'\n        return channel\n    \n",
        "idx": "586"
    },
    {
        "instruction": "# Here are some relevant code fragments from other files of the repo:\n# --------------------------------------------------\n# the below code fragment can be found in:\n# custom_components/nsplus/const.py\n# --------------------------------------------------\n# ATTR_DEVICE = \"device\"\n# \n# ATTR_DELTA = \"delta\"\n# \n# ATTR_DIRECTION = \"direction\"\n# \n# --------------------------------------------------\n\n\n## custom_components/nsplus/sensor.py\nimport logging\n\nfrom typing import Any\n\nfrom aiohttp import ClientError\n\nfrom py_nightscout import Api as NightscoutAPI\n\nfrom homeassistant.components.sensor import SensorEntity\n\nfrom homeassistant.const import ATTR_DATE\n\nfrom .const import ATTR_DELTA, ATTR_DEVICE, ATTR_DIRECTION, DOMAIN\n\n_LOGGER = logging.getLogger(__name__)\n\nclass NightscoutSensor(SensorEntity):\n    \"\"\"Implementation of a Nightscout sensor.\"\"\"\n\n    _attr_native_unit_of_measurement = \"mg/dL\"\n    _attr_icon = \"mdi:cloud-question\"\n\n    def __init__(self, api: NightscoutAPI, name: str, unique_id: str | None) -> None:\n        \"\"\"Initialize the Nightscout sensor.\"\"\"\n        self.api = api\n        self._attr_unique_id = unique_id\n        self._attr_name = name\n        self._attr_extra_state_attributes: dict[str, Any] = {}\n\n    async def async_update(self) -> None:\n        \"\"\"Fetch the latest data from Nightscout REST API and update the state.\"\"\"\n        try:\n            values = await self.api.get_sgvs()\n        except (ClientError, TimeoutError, OSError) as error:\n            _LOGGER.error(\"Error fetching data. Failed with %s\", error)\n            self._attr_available = False\n            return\n\n        self._attr_available = True\n        self._attr_extra_state_attributes = {}\n        self._attr_native_value = None\n        if values:\n            value = values[0]\n            self._attr_extra_state_attributes = {\n                ATTR_DEVICE: value.device,\n                ATTR_DATE: value.date,\n                ATTR_DELTA: value.delta,\n                ATTR_DIRECTION: value.direction,\n            }\n            self._attr_native_value = value.sgv\n            self._attr_icon = self._parse_icon(value.direction)\n        else:\n            self._attr_available = False\n            _LOGGER.warning(\"Empty reply found when expecting JSON data\")\n\n    def _parse_icon(self, direction: str) -> str:\n        \"\"\"\n        Update the icon based on the direction attribute.\n        \"\"\"\n",
        "input": "",
        "output": "        switcher = {\n            \"Flat\": \"mdi:arrow-right\",\n            \"SingleDown\": \"mdi:arrow-down\",\n            \"FortyFiveDown\": \"mdi:arrow-bottom-right\",\n            \"DoubleDown\": \"mdi:chevron-triple-down\",\n            \"SingleUp\": \"mdi:arrow-up\",\n            \"FortyFiveUp\": \"mdi:arrow-top-right\",\n            \"DoubleUp\": \"mdi:chevron-triple-up\",\n        }\n        return switcher.get(direction, \"mdi:cloud-question\")\n    \n",
        "idx": "599"
    },
    {
        "instruction": "# Here are some relevant code fragments from other files of the repo:\n# --------------------------------------------------\n# the below code fragment can be found in:\n# async_rithmic/enums.py\n# --------------------------------------------------\n# from . import protocol_buffers as pb\n# \n# --------------------------------------------------\n# the below code fragment can be found in:\n# async_rithmic/__init__.py\n# --------------------------------------------------\n# from .enums import *\n# \n# --------------------------------------------------\n# the below code fragment can be found in:\n# async_rithmic/logger.py\n# --------------------------------------------------\n# import logging\n# \n# import sys\n# \n# class Logger:\n#     def __init__(self, level: int = logging.INFO):\n#         self.logger = logging.getLogger(\"rithmic\")\n#         self.logger.setLevel(level)\n# \n#         formatter = logging.Formatter(\"%(asctime)s - %(name)s - %(levelname)s - %(message)s\")\n# \n#         console_handler = logging.StreamHandler(sys.stdout)\n#         console_handler.setFormatter(formatter)\n# \n#         if not self.logger.hasHandlers():\n#             self.logger.addHandler(console_handler)\n# \n#     def get_logger(self):\n#         return self.logger\n# \n# logger = Logger(level=logging.DEBUG).get_logger()\n# \n# --------------------------------------------------\n\n\n## async_rithmic/plants/base.py\nimport websockets\n\nfrom websockets import ConnectionClosedError, ConnectionClosedOK\n\nfrom websockets.protocol import OPEN\n\nimport asyncio\n\nimport time\n\nimport traceback\n\nfrom datetime import datetime\n\nimport pytz\n\nfrom tzlocal import get_localzone\n\nfrom google.protobuf.descriptor import FieldDescriptor\n\nfrom google.protobuf.json_format import MessageToDict\n\nfrom .. import protocol_buffers as pb\n\nfrom ..logger import logger\n\nTEMPLATES_MAP = {\n    # Shared\n    10: pb.request_login_pb2.RequestLogin,\n    11: pb.response_login_pb2.ResponseLogin,\n    12: pb.request_logout_pb2.RequestLogout,\n    13: pb.response_logout_pb2.ResponseLogout,\n    14: pb.request_reference_data_pb2.RequestReferenceData,\n    15: pb.response_reference_data_pb2.ResponseReferenceData,\n    16: pb.request_rithmic_system_info_pb2.RequestRithmicSystemInfo,\n    17: pb.response_rithmic_system_info_pb2.ResponseRithmicSystemInfo,\n    18: pb.request_heartbeat_pb2.RequestHeartbeat,\n    19: pb.response_heartbeat_pb2.ResponseHeartbeat,\n\n    # Market Data Infrastructure\n    100: pb.request_market_data_update_pb2.RequestMarketDataUpdate,\n    101: pb.response_market_data_update_pb2.ResponseMarketDataUpdate,\n    109: pb.request_search_symbols_pb2.RequestSearchSymbols,\n    110: pb.response_search_symbols_pb2.ResponseSearchSymbols,\n    113: pb.request_front_month_contract_pb2.RequestFrontMonthContract,\n    114: pb.response_front_month_contract_pb2.ResponseFrontMonthContract,\n\n    #115: pb.request_depth_by_order_snapshot_pb2.RequestDepthByOrderSnapshot,\n    #116: pb.response_depth_by_order_snapshot_pb2.ResponseDepthByOrderSnapshot,\n    #117: pb.request_depth_by_order_updates_pb2.RequestDepthByOrderUpdates,\n    #118: pb.response_depth_by_order_updates_pb2.ResponseDepthByOrderUpdates,\n\n    150: pb.last_trade_pb2.LastTrade,\n    151: pb.best_bid_offer_pb2.BestBidOffer,\n    #156: pb.order_book_pb2.OrderBook,\n    #160: pb.depth_by_order.DepthByOrder,\n    #161: pb.depth_by_order_end_event.DepthByOrderEndEvent,\n\n    # Order Plant Infrastructure\n    300: pb.request_login_info_pb2.RequestLoginInfo,\n    301: pb.response_login_info_pb2.ResponseLoginInfo,\n    302: pb.request_account_list_pb2.RequestAccountList,\n    303: pb.response_account_list_pb2.ResponseAccountList,\n    304: pb.request_account_rms_info_pb2.RequestAccountRmsInfo,\n    305: pb.response_account_rms_info_pb2.ResponseAccountRmsInfo,\n    306: pb.request_product_rms_info_pb2.RequestProductRmsInfo,\n    307: pb.response_product_rms_info_pb2.ResponseProductRmsInfo,\n    308: pb.request_subscribe_for_order_updates_pb2.RequestSubscribeForOrderUpdates,\n    309: pb.response_subscribe_for_order_updates_pb2.ResponseSubscribeForOrderUpdates,\n    310: pb.request_trade_routes_pb2.RequestTradeRoutes,\n    311: pb.response_trade_routes_pb2.ResponseTradeRoutes,\n    312: pb.request_new_order_pb2.RequestNewOrder,\n    313: pb.response_new_order_pb2.ResponseNewOrder,\n    314: pb.request_modify_order_pb2.RequestModifyOrder,\n    315: pb.response_modify_order_pb2.ResponseModifyOrder,\n    316: pb.request_cancel_order_pb2.RequestCancelOrder,\n    317: pb.response_cancel_order_pb2.ResponseCancelOrder,\n    320: pb.request_show_orders_pb2.RequestShowOrders,\n    321: pb.response_show_orders_pb2.ResponseShowOrders,\n    330: pb.request_bracket_order_pb2.RequestBracketOrder,\n    331: pb.response_bracket_order_pb2.ResponseBracketOrder,\n    332: pb.request_update_target_bracket_level_pb2.RequestUpdateTargetBracketLevel,\n    333: pb.response_update_target_bracket_level_pb2.ResponseUpdateTargetBracketLevel,\n    334: pb.request_update_stop_bracket_level_pb2.RequestUpdateStopBracketLevel,\n    335: pb.response_update_stop_bracket_level_pb2.ResponseUpdateStopBracketLevel,\n    336: pb.request_subscribe_to_bracket_updates_pb2.RequestSubscribeToBracketUpdates,\n    337: pb.response_subscribe_to_bracket_updates_pb2.ResponseSubscribeToBracketUpdates,\n\n    350: pb.trade_route_pb2.TradeRoute,\n    351: pb.rithmic_order_notification_pb2.RithmicOrderNotification,\n    352: pb.exchange_order_notification_pb2.ExchangeOrderNotification,\n    353: pb.bracket_updates_pb2.BracketUpdates,\n\n    # History Plant Infrastructure\n    200: pb.request_time_bar_update_pb2.RequestTimeBarUpdate,\n    201: pb.response_time_bar_update_pb2.ResponseTimeBarUpdate,\n    202: pb.request_time_bar_replay_pb2.RequestTimeBarReplay,\n    203: pb.response_time_bar_replay_pb2.ResponseTimeBarReplay,\n    204: pb.request_tick_bar_update_pb2.RequestTickBarUpdate,\n    205: pb.response_tick_bar_update_pb2.ResponseTickBarUpdate,\n    206: pb.request_tick_bar_replay_pb2.RequestTickBarReplay,\n    207: pb.response_tick_bar_replay_pb2.ResponseTickBarReplay,\n    250: pb.time_bar_pb2.TimeBar,\n    251: pb.tick_bar_pb2.TickBar,\n\n    # PnL Plant Infrastructure\n    400: pb.request_pnl_position_updates_pb2.RequestPnLPositionUpdates,\n    401: pb.response_pnl_position_updates_pb2.ResponsePnLPositionUpdates,\n    402: pb.request_pnl_position_snapshot_pb2.RequestPnLPositionSnapshot,\n    403: pb.response_pnl_position_snapshot_pb2.ResponsePnLPositionSnapshot,\n    450: pb.instrument_pnl_position_update_pb2.InstrumentPnLPositionUpdate,\n    451: pb.account_pnl_position_update_pb2.AccountPnLPositionUpdate,\n}\n\nclass BasePlant:\n    infra_type = None\n\n    def __init__(self, client, listen_interval=0.1):\n        self.ws = None\n        self.client = client\n        self.lock = asyncio.Lock()\n\n        # Heartbeats has to be sent every {interval} seconds, unless an update was received\n        self.heartbeat_interval = None\n        self.listen_interval = listen_interval\n        self.last_message_time = None\n\n    @property\n    def is_connected(self) -> bool:\n        return self.ws is not None and self.ws.state == OPEN\n\n    @property\n    def credentials(self):\n        return self.client.credentials\n\n    @property\n    def ssl_context(self):\n        return self.client.ssl_context\n\n    @property\n    def plant_type(self):\n        return {\n            pb.request_login_pb2.RequestLogin.SysInfraType.HISTORY_PLANT: \"history\",\n            pb.request_login_pb2.RequestLogin.SysInfraType.PNL_PLANT: \"pnl\",\n            pb.request_login_pb2.RequestLogin.SysInfraType.TICKER_PLANT: \"ticker\",\n            pb.request_login_pb2.RequestLogin.SysInfraType.ORDER_PLANT: \"order\",\n        }[self.infra_type]\n\n    async def _connect(self):\n        \"\"\"\n        Clients should follow the below sequence for communicating with protocol server,\n        1. Open a websocket, upon connecting send 'RequestRithmicSystemInfo' message.\n           Parse the response and record list of 'system names' available. Close this connection\n\n        2. Open a new websocket, and login using the desired 'system_name'.\n        \"\"\"\n        self.ws = await websockets.connect(\n            self.credentials[\"gateway\"],\n            ssl=self.ssl_context,\n            ping_interval=10\n        )\n\n        if self.plant_type == \"ticker\":\n            info = await self.get_system_info()\n            await self._disconnect()\n\n            if self.credentials[\"system_name\"] not in info.system_name:\n                raise Exception(f\"You must specify valid SYSTEM_NAME in the credentials file: {info.system_name}\")\n\n            self.ws = await websockets.connect(\n                self.credentials[\"gateway\"],\n                ssl=self.ssl_context,\n                ping_interval=10\n            )\n\n    async def _disconnect(self):\n        if self.is_connected:\n            await self.ws.close(1000, \"Closing Connection\")\n\n    async def _login(self):\n        response = await self._send_and_recv(\n            template_id=10,\n            template_version=\"3.9\",\n            user=self.credentials[\"user\"],\n            password=self.credentials[\"password\"],\n            system_name=self.credentials[\"system_name\"],\n            app_name=self.credentials[\"app_name\"],\n            app_version=self.credentials[\"app_version\"],\n            infra_type=self.infra_type,\n        )\n\n        self.heartbeat_interval = response.heartbeat_interval\n\n        # Upon making a successful login, clients are expected to send at least a heartbeat request to the server\n        await self._send_heartbeat()\n\n        return response\n\n    async def _logout(self):\n        try:\n            return await self._send_and_recv(template_id=12)\n        except ConnectionClosedOK:\n            pass\n\n    async def get_system_info(self):\n        return await self._send_and_recv(template_id=16)\n\n    async def get_reference_data(self, symbol: str, exchange: str):\n        return await self._send_and_recv(\n            template_id=14,\n            symbol=symbol,\n            exchange=exchange\n        )\n\n    async def _send(self, message: bytes):\n        await self.ws.send(message)\n\n    async def _recv(self):\n        buffer = await self.ws.recv()\n        self.last_message_time = time.time()\n        return buffer\n\n    async def _send_request(self, **kwargs):\n        template_id = kwargs[\"template_id\"]\n\n        if template_id not in TEMPLATES_MAP:\n            raise Exception(f\"Unknown request template id: {template_id}\")\n\n        request = TEMPLATES_MAP[template_id]()\n        for k, v in kwargs.items():\n            self._set_pb_field(request, k, v)\n\n        buffer = self._convert_request_to_bytes(request)\n        await self._send(buffer)\n\n        return template_id\n\n    async def _send_and_recv(self, **kwargs):\n        \"\"\"\n        Sends a request to the API and decode the response\n        \"\"\"\n\n        async with self.lock:\n            template_id = await self._send_request(**kwargs)\n\n            while True:\n                buffer = await self._recv()\n                response = self._convert_bytes_to_response(buffer)\n\n                if not hasattr(response, \"rp_code\") or response.template_id != template_id + 1:\n                    await self._process_response(response)\n                    continue\n\n                break\n\n        if len(response.rp_code) and response.rp_code[0] != '0':\n            raise Exception(f\"Rithmic returned an error after request {template_id}: {', '.join(response.rp_code)}\")\n\n        return response\n\n    async def _send_and_recv_many(self, **kwargs):\n        \"\"\"\n        Sends a request to the API and expect 1...n responses back\n        \"\"\"\n\n        template_id = kwargs[\"template_id\"]\n\n        if template_id not in TEMPLATES_MAP:\n            raise Exception(f\"Unknown request template id: {template_id}\")\n\n        request = TEMPLATES_MAP[template_id]()\n        for k, v in kwargs.items():\n            self._set_pb_field(request, k, v)\n\n        results = []\n        async with self.lock:\n            await self._send(self._convert_request_to_bytes(request))\n\n            while True:\n                buffer = await self._recv()\n                response = self._convert_bytes_to_response(buffer)\n\n                if response.template_id != template_id + 1:\n                    await self._process_response(response)\n                    continue\n\n                if len(response.rp_code) > 0:\n                    if response.rp_code[0] != '0':\n                        raise Exception(f\"Server returned an error after request {template_id}: {', '.join(response.rp_code)}\")\n\n                    break\n                else:\n                    results.append(response)\n\n        return results\n\n    def _convert_request_to_bytes(self, request):\n        serialized = request.SerializeToString()\n        length = len(serialized)\n        buffer = length.to_bytes(4, byteorder='big', signed=True)\n        buffer += serialized\n        return buffer\n\n    def _convert_bytes_to_response(self, buffer):\n        b = pb.base_pb2.Base()\n        b.ParseFromString(buffer[4:])\n        if b.template_id not in TEMPLATES_MAP:\n            raise Exception(f\"Unknown response template id: {b.template_id}\")\n\n        response = TEMPLATES_MAP[b.template_id]()\n        response.ParseFromString(buffer[4:])\n        return response\n\n    def _set_pb_field(self, obj, field_name, value):\n        field_descriptor = obj.DESCRIPTOR.fields_by_name[field_name]\n\n        if field_descriptor.label == FieldDescriptor.LABEL_REPEATED:\n            # Handle repeated fields (lists in protobuf)\n            field = getattr(obj, field_name)\n            if isinstance(value, list):\n                field.extend(value)\n            else:\n                field.append(value)\n        elif field_descriptor.type == FieldDescriptor.TYPE_MESSAGE:\n            # Handle nested message fields\n            nested_message = getattr(obj, field_name)\n            for sub_key, sub_value in value.items():\n                self._set_pb_field(nested_message, sub_key, sub_value)\n        else:\n            # Handle normal fields\n            try:\n                setattr(obj, field_name, value)\n            except:\n                logger.error(f\"Error when trying to set {field_name}\")\n                raise\n\n    async def _send_heartbeat(self):\n        return await self._send_and_recv(template_id=18)\n\n    async def _listen(self, max_iterations=None):\n        iteration_count = 0\n\n        try:\n            while True:\n                if max_iterations and iteration_count >= max_iterations:\n                    break\n\n                try:\n                    async with self.lock:\n                        buffer = await asyncio.wait_for(self._recv(), timeout=self.listen_interval)\n\n                    response = self._convert_bytes_to_response(buffer)\n                    await self._process_response(response)\n                    iteration_count += 1\n\n                except asyncio.TimeoutError:\n                    current_time = time.time()\n\n                    # Send regular heartbeats\n                    if current_time - self.last_message_time > self.heartbeat_interval-2:\n                        await self._send_heartbeat()\n\n                except ConnectionClosedError:\n                    logger.exception(\"WebSocket connection closed with error\")\n                    if not await self._handle_reconnection():\n                        break\n\n                except ConnectionClosedOK:\n                    logger.info(f\"WebSocket connection closed normally\")\n                    break\n\n        except Exception as e:\n            logger.error(f\"Exception in listener: {e}\")\n            traceback.print_exc()\n\n    async def _handle_reconnection(self, attempt=1):\n        max_retries = 5\n        wait_time = min(2 ** attempt, 120)\n\n        logger.info(f\"{self.plant_type} plant reconnection attempt {attempt} in {wait_time} seconds...\")\n        await asyncio.sleep(wait_time)\n\n        try:\n            # Attempt to reconnect this specific plant\n            await self._connect()\n            await self._login()\n\n            logger.info(f\"{self.plant_type} plant reconnection successful.\")\n            return True\n\n        except Exception as e:\n            if attempt < max_retries:\n                logger.warning(f\"{self.plant_type} plant reconnection failed: {e}. Retrying...\")\n                return await self._handle_reconnection(attempt + 1)\n            else:\n                logger.error(f\"{self.plant_type} plant max reconnection attempts reached. Could not reconnect: {e}\")\n\n        return False\n\n\n    def _response_to_dict(self, response):\n        data = MessageToDict(response, preserving_proto_field_name=True, use_integers_for_enums=True)\n\n        data.pop(\"template_id\", None)\n        data.pop(\"request_key\", None)\n        data.pop(\"user_msg\", None)\n        data.pop(\"rq_handler_rp_code\", None)\n        data.pop(\"rp_code\", None)\n\n        return data\n\n    async def _process_response(self, response):\n        raise NotImplementedError\n\n    def _datetime_to_utc(self, dt: datetime):\n",
        "input": "",
        "output": "        if dt.tzinfo is None:\n            # Use system timezone\n            system_timezone = pytz.timezone(str(get_localzone()))\n            dt = system_timezone.localize(dt)\n\n        if dt.tzinfo != pytz.utc:\n            # Convert to utc\n            dt = dt.astimezone(pytz.utc)\n\n        return dt\n    \n",
        "idx": "607"
    },
    {
        "instruction": "# Here are some relevant code fragments from other files of the repo:\n# --------------------------------------------------\n# the below code fragment can be found in:\n# async_rithmic/enums.py\n# --------------------------------------------------\n# from . import protocol_buffers as pb\n# \n# --------------------------------------------------\n# the below code fragment can be found in:\n# async_rithmic/__init__.py\n# --------------------------------------------------\n# from .enums import *\n# \n# --------------------------------------------------\n# the below code fragment can be found in:\n# async_rithmic/logger.py\n# --------------------------------------------------\n# import logging\n# \n# import sys\n# \n# class Logger:\n#     def __init__(self, level: int = logging.INFO):\n#         self.logger = logging.getLogger(\"rithmic\")\n#         self.logger.setLevel(level)\n# \n#         formatter = logging.Formatter(\"%(asctime)s - %(name)s - %(levelname)s - %(message)s\")\n# \n#         console_handler = logging.StreamHandler(sys.stdout)\n#         console_handler.setFormatter(formatter)\n# \n#         if not self.logger.hasHandlers():\n#             self.logger.addHandler(console_handler)\n# \n#     def get_logger(self):\n#         return self.logger\n# \n# logger = Logger(level=logging.DEBUG).get_logger()\n# \n# --------------------------------------------------\n\n\n## async_rithmic/plants/base.py\nimport websockets\n\nfrom websockets import ConnectionClosedError, ConnectionClosedOK\n\nfrom websockets.protocol import OPEN\n\nimport asyncio\n\nimport time\n\nimport traceback\n\nfrom datetime import datetime\n\nimport pytz\n\nfrom tzlocal import get_localzone\n\nfrom google.protobuf.descriptor import FieldDescriptor\n\nfrom google.protobuf.json_format import MessageToDict\n\nfrom .. import protocol_buffers as pb\n\nfrom ..logger import logger\n\nTEMPLATES_MAP = {\n    # Shared\n    10: pb.request_login_pb2.RequestLogin,\n    11: pb.response_login_pb2.ResponseLogin,\n    12: pb.request_logout_pb2.RequestLogout,\n    13: pb.response_logout_pb2.ResponseLogout,\n    14: pb.request_reference_data_pb2.RequestReferenceData,\n    15: pb.response_reference_data_pb2.ResponseReferenceData,\n    16: pb.request_rithmic_system_info_pb2.RequestRithmicSystemInfo,\n    17: pb.response_rithmic_system_info_pb2.ResponseRithmicSystemInfo,\n    18: pb.request_heartbeat_pb2.RequestHeartbeat,\n    19: pb.response_heartbeat_pb2.ResponseHeartbeat,\n\n    # Market Data Infrastructure\n    100: pb.request_market_data_update_pb2.RequestMarketDataUpdate,\n    101: pb.response_market_data_update_pb2.ResponseMarketDataUpdate,\n    109: pb.request_search_symbols_pb2.RequestSearchSymbols,\n    110: pb.response_search_symbols_pb2.ResponseSearchSymbols,\n    113: pb.request_front_month_contract_pb2.RequestFrontMonthContract,\n    114: pb.response_front_month_contract_pb2.ResponseFrontMonthContract,\n\n    #115: pb.request_depth_by_order_snapshot_pb2.RequestDepthByOrderSnapshot,\n    #116: pb.response_depth_by_order_snapshot_pb2.ResponseDepthByOrderSnapshot,\n    #117: pb.request_depth_by_order_updates_pb2.RequestDepthByOrderUpdates,\n    #118: pb.response_depth_by_order_updates_pb2.ResponseDepthByOrderUpdates,\n\n    150: pb.last_trade_pb2.LastTrade,\n    151: pb.best_bid_offer_pb2.BestBidOffer,\n    #156: pb.order_book_pb2.OrderBook,\n    #160: pb.depth_by_order.DepthByOrder,\n    #161: pb.depth_by_order_end_event.DepthByOrderEndEvent,\n\n    # Order Plant Infrastructure\n    300: pb.request_login_info_pb2.RequestLoginInfo,\n    301: pb.response_login_info_pb2.ResponseLoginInfo,\n    302: pb.request_account_list_pb2.RequestAccountList,\n    303: pb.response_account_list_pb2.ResponseAccountList,\n    304: pb.request_account_rms_info_pb2.RequestAccountRmsInfo,\n    305: pb.response_account_rms_info_pb2.ResponseAccountRmsInfo,\n    306: pb.request_product_rms_info_pb2.RequestProductRmsInfo,\n    307: pb.response_product_rms_info_pb2.ResponseProductRmsInfo,\n    308: pb.request_subscribe_for_order_updates_pb2.RequestSubscribeForOrderUpdates,\n    309: pb.response_subscribe_for_order_updates_pb2.ResponseSubscribeForOrderUpdates,\n    310: pb.request_trade_routes_pb2.RequestTradeRoutes,\n    311: pb.response_trade_routes_pb2.ResponseTradeRoutes,\n    312: pb.request_new_order_pb2.RequestNewOrder,\n    313: pb.response_new_order_pb2.ResponseNewOrder,\n    314: pb.request_modify_order_pb2.RequestModifyOrder,\n    315: pb.response_modify_order_pb2.ResponseModifyOrder,\n    316: pb.request_cancel_order_pb2.RequestCancelOrder,\n    317: pb.response_cancel_order_pb2.ResponseCancelOrder,\n    320: pb.request_show_orders_pb2.RequestShowOrders,\n    321: pb.response_show_orders_pb2.ResponseShowOrders,\n    330: pb.request_bracket_order_pb2.RequestBracketOrder,\n    331: pb.response_bracket_order_pb2.ResponseBracketOrder,\n    332: pb.request_update_target_bracket_level_pb2.RequestUpdateTargetBracketLevel,\n    333: pb.response_update_target_bracket_level_pb2.ResponseUpdateTargetBracketLevel,\n    334: pb.request_update_stop_bracket_level_pb2.RequestUpdateStopBracketLevel,\n    335: pb.response_update_stop_bracket_level_pb2.ResponseUpdateStopBracketLevel,\n    336: pb.request_subscribe_to_bracket_updates_pb2.RequestSubscribeToBracketUpdates,\n    337: pb.response_subscribe_to_bracket_updates_pb2.ResponseSubscribeToBracketUpdates,\n\n    350: pb.trade_route_pb2.TradeRoute,\n    351: pb.rithmic_order_notification_pb2.RithmicOrderNotification,\n    352: pb.exchange_order_notification_pb2.ExchangeOrderNotification,\n    353: pb.bracket_updates_pb2.BracketUpdates,\n\n    # History Plant Infrastructure\n    200: pb.request_time_bar_update_pb2.RequestTimeBarUpdate,\n    201: pb.response_time_bar_update_pb2.ResponseTimeBarUpdate,\n    202: pb.request_time_bar_replay_pb2.RequestTimeBarReplay,\n    203: pb.response_time_bar_replay_pb2.ResponseTimeBarReplay,\n    204: pb.request_tick_bar_update_pb2.RequestTickBarUpdate,\n    205: pb.response_tick_bar_update_pb2.ResponseTickBarUpdate,\n    206: pb.request_tick_bar_replay_pb2.RequestTickBarReplay,\n    207: pb.response_tick_bar_replay_pb2.ResponseTickBarReplay,\n    250: pb.time_bar_pb2.TimeBar,\n    251: pb.tick_bar_pb2.TickBar,\n\n    # PnL Plant Infrastructure\n    400: pb.request_pnl_position_updates_pb2.RequestPnLPositionUpdates,\n    401: pb.response_pnl_position_updates_pb2.ResponsePnLPositionUpdates,\n    402: pb.request_pnl_position_snapshot_pb2.RequestPnLPositionSnapshot,\n    403: pb.response_pnl_position_snapshot_pb2.ResponsePnLPositionSnapshot,\n    450: pb.instrument_pnl_position_update_pb2.InstrumentPnLPositionUpdate,\n    451: pb.account_pnl_position_update_pb2.AccountPnLPositionUpdate,\n}\n\nclass BasePlant:\n    infra_type = None\n\n    def __init__(self, client, listen_interval=0.1):\n        self.ws = None\n        self.client = client\n        self.lock = asyncio.Lock()\n\n        # Heartbeats has to be sent every {interval} seconds, unless an update was received\n        self.heartbeat_interval = None\n        self.listen_interval = listen_interval\n        self.last_message_time = None\n\n    @property\n    def is_connected(self) -> bool:\n        return self.ws is not None and self.ws.state == OPEN\n\n    @property\n    def credentials(self):\n        return self.client.credentials\n\n    @property\n    def ssl_context(self):\n        return self.client.ssl_context\n\n    @property\n    def plant_type(self):\n        return {\n            pb.request_login_pb2.RequestLogin.SysInfraType.HISTORY_PLANT: \"history\",\n            pb.request_login_pb2.RequestLogin.SysInfraType.PNL_PLANT: \"pnl\",\n            pb.request_login_pb2.RequestLogin.SysInfraType.TICKER_PLANT: \"ticker\",\n            pb.request_login_pb2.RequestLogin.SysInfraType.ORDER_PLANT: \"order\",\n        }[self.infra_type]\n\n    async def _connect(self):\n        \"\"\"\n        Clients should follow the below sequence for communicating with protocol server,\n        1. Open a websocket, upon connecting send 'RequestRithmicSystemInfo' message.\n           Parse the response and record list of 'system names' available. Close this connection\n\n        2. Open a new websocket, and login using the desired 'system_name'.\n        \"\"\"\n        self.ws = await websockets.connect(\n            self.credentials[\"gateway\"],\n            ssl=self.ssl_context,\n            ping_interval=10\n        )\n\n        if self.plant_type == \"ticker\":\n            info = await self.get_system_info()\n            await self._disconnect()\n\n            if self.credentials[\"system_name\"] not in info.system_name:\n                raise Exception(f\"You must specify valid SYSTEM_NAME in the credentials file: {info.system_name}\")\n\n            self.ws = await websockets.connect(\n                self.credentials[\"gateway\"],\n                ssl=self.ssl_context,\n                ping_interval=10\n            )\n\n    async def _disconnect(self):\n        if self.is_connected:\n            await self.ws.close(1000, \"Closing Connection\")\n\n    async def _login(self):\n        response = await self._send_and_recv(\n            template_id=10,\n            template_version=\"3.9\",\n            user=self.credentials[\"user\"],\n            password=self.credentials[\"password\"],\n            system_name=self.credentials[\"system_name\"],\n            app_name=self.credentials[\"app_name\"],\n            app_version=self.credentials[\"app_version\"],\n            infra_type=self.infra_type,\n        )\n\n        self.heartbeat_interval = response.heartbeat_interval\n\n        # Upon making a successful login, clients are expected to send at least a heartbeat request to the server\n        await self._send_heartbeat()\n\n        return response\n\n    async def _logout(self):\n        try:\n            return await self._send_and_recv(template_id=12)\n        except ConnectionClosedOK:\n            pass\n\n    async def get_system_info(self):\n        return await self._send_and_recv(template_id=16)\n\n    async def get_reference_data(self, symbol: str, exchange: str):\n        return await self._send_and_recv(\n            template_id=14,\n            symbol=symbol,\n            exchange=exchange\n        )\n\n    async def _send(self, message: bytes):\n        await self.ws.send(message)\n\n    async def _recv(self):\n        buffer = await self.ws.recv()\n        self.last_message_time = time.time()\n        return buffer\n\n    async def _send_request(self, **kwargs):\n        template_id = kwargs[\"template_id\"]\n\n        if template_id not in TEMPLATES_MAP:\n            raise Exception(f\"Unknown request template id: {template_id}\")\n\n        request = TEMPLATES_MAP[template_id]()\n        for k, v in kwargs.items():\n            self._set_pb_field(request, k, v)\n\n        buffer = self._convert_request_to_bytes(request)\n        await self._send(buffer)\n\n        return template_id\n\n    async def _send_and_recv(self, **kwargs):\n        \"\"\"\n        Sends a request to the API and decode the response\n        \"\"\"\n\n        async with self.lock:\n            template_id = await self._send_request(**kwargs)\n\n            while True:\n                buffer = await self._recv()\n                response = self._convert_bytes_to_response(buffer)\n\n                if not hasattr(response, \"rp_code\") or response.template_id != template_id + 1:\n                    await self._process_response(response)\n                    continue\n\n                break\n\n        if len(response.rp_code) and response.rp_code[0] != '0':\n            raise Exception(f\"Rithmic returned an error after request {template_id}: {', '.join(response.rp_code)}\")\n\n        return response\n\n    async def _send_and_recv_many(self, **kwargs):\n        \"\"\"\n        Sends a request to the API and expect 1...n responses back\n        \"\"\"\n\n        template_id = kwargs[\"template_id\"]\n\n        if template_id not in TEMPLATES_MAP:\n            raise Exception(f\"Unknown request template id: {template_id}\")\n\n        request = TEMPLATES_MAP[template_id]()\n        for k, v in kwargs.items():\n            self._set_pb_field(request, k, v)\n\n        results = []\n        async with self.lock:\n            await self._send(self._convert_request_to_bytes(request))\n\n            while True:\n                buffer = await self._recv()\n                response = self._convert_bytes_to_response(buffer)\n\n                if response.template_id != template_id + 1:\n                    await self._process_response(response)\n                    continue\n\n                if len(response.rp_code) > 0:\n                    if response.rp_code[0] != '0':\n                        raise Exception(f\"Server returned an error after request {template_id}: {', '.join(response.rp_code)}\")\n\n                    break\n                else:\n                    results.append(response)\n\n        return results\n\n    def _convert_request_to_bytes(self, request):\n        serialized = request.SerializeToString()\n        length = len(serialized)\n        buffer = length.to_bytes(4, byteorder='big', signed=True)\n        buffer += serialized\n        return buffer\n\n    def _convert_bytes_to_response(self, buffer):\n        b = pb.base_pb2.Base()\n        b.ParseFromString(buffer[4:])\n        if b.template_id not in TEMPLATES_MAP:\n            raise Exception(f\"Unknown response template id: {b.template_id}\")\n\n        response = TEMPLATES_MAP[b.template_id]()\n        response.ParseFromString(buffer[4:])\n        return response\n\n    def _set_pb_field(self, obj, field_name, value):\n        field_descriptor = obj.DESCRIPTOR.fields_by_name[field_name]\n\n        if field_descriptor.label == FieldDescriptor.LABEL_REPEATED:\n            # Handle repeated fields (lists in protobuf)\n            field = getattr(obj, field_name)\n            if isinstance(value, list):\n                field.extend(value)\n            else:\n                field.append(value)\n        elif field_descriptor.type == FieldDescriptor.TYPE_MESSAGE:\n            # Handle nested message fields\n            nested_message = getattr(obj, field_name)\n            for sub_key, sub_value in value.items():\n                self._set_pb_field(nested_message, sub_key, sub_value)\n        else:\n            # Handle normal fields\n            try:\n                setattr(obj, field_name, value)\n            except:\n                logger.error(f\"Error when trying to set {field_name}\")\n                raise\n\n    async def _send_heartbeat(self):\n        return await self._send_and_recv(template_id=18)\n\n    async def _listen(self, max_iterations=None):\n        iteration_count = 0\n\n        try:\n            while True:\n                if max_iterations and iteration_count >= max_iterations:\n                    break\n\n                try:\n                    async with self.lock:\n                        buffer = await asyncio.wait_for(self._recv(), timeout=self.listen_interval)\n\n                    response = self._convert_bytes_to_response(buffer)\n                    await self._process_response(response)\n                    iteration_count += 1\n\n                except asyncio.TimeoutError:\n                    current_time = time.time()\n\n                    # Send regular heartbeats\n                    if current_time - self.last_message_time > self.heartbeat_interval-2:\n                        await self._send_heartbeat()\n\n                except ConnectionClosedError:\n                    logger.exception(\"WebSocket connection closed with error\")\n                    if not await self._handle_reconnection():\n                        break\n\n                except ConnectionClosedOK:\n                    logger.info(f\"WebSocket connection closed normally\")\n                    break\n\n        except Exception as e:\n            logger.error(f\"Exception in listener: {e}\")\n            traceback.print_exc()\n\n    async def _handle_reconnection(self, attempt=1):\n        max_retries = 5\n        wait_time = min(2 ** attempt, 120)\n\n        logger.info(f\"{self.plant_type} plant reconnection attempt {attempt} in {wait_time} seconds...\")\n        await asyncio.sleep(wait_time)\n\n        try:\n            # Attempt to reconnect this specific plant\n            await self._connect()\n            await self._login()\n\n            logger.info(f\"{self.plant_type} plant reconnection successful.\")\n            return True\n\n        except Exception as e:\n            if attempt < max_retries:\n                logger.warning(f\"{self.plant_type} plant reconnection failed: {e}. Retrying...\")\n                return await self._handle_reconnection(attempt + 1)\n            else:\n                logger.error(f\"{self.plant_type} plant max reconnection attempts reached. Could not reconnect: {e}\")\n\n        return False\n\n\n    def _response_to_dict(self, response):\n        data = MessageToDict(response, preserving_proto_field_name=True, use_integers_for_enums=True)\n\n        data.pop(\"template_id\", None)\n        data.pop(\"request_key\", None)\n        data.pop(\"user_msg\", None)\n        data.pop(\"rq_handler_rp_code\", None)\n        data.pop(\"rp_code\", None)\n\n        return data\n\n    async def _process_response(self, response):\n        raise NotImplementedError\n\n    def _datetime_to_utc(self, dt: datetime):\n        if dt.tzinfo is None:\n            # Use system timezone\n            system_timezone = pytz.timezone(str(get_localzone()))\n            dt = system_timezone.localize(dt)\n\n        if dt.tzinfo != pytz.utc:\n            # Convert to utc\n            dt = dt.astimezone(pytz.utc)\n\n        return dt\n\n    def _ssboe_usecs_to_datetime(self, ssboe: int, usecs: int):\n",
        "input": "",
        "output": "        ts = '{0}.{1}'.format(ssboe, usecs)\n        return datetime.fromtimestamp(float(ts), tz=pytz.utc)\n    \n",
        "idx": "608"
    },
    {
        "instruction": "## src/rpi_gpio/RGB_LED.py\nimport RPi.GPIO as GPIO\n\nimport time as t\n\nimport threading\n\nclass RGB_LED:\n    def __init__(self, red_pin, green_pin, blue_pin):\n        self.red_pin = red_pin\n        self.green_pin = green_pin\n        self.blue_pin = blue_pin\n\n        GPIO.setup(self.red_pin, GPIO.OUT)\n        GPIO.setup(self.green_pin, GPIO.OUT)\n        GPIO.setup(self.blue_pin, GPIO.OUT)\n\n        self.red_pwm = GPIO.PWM(self.red_pin, 100)\n        self.green_pwm = GPIO.PWM(self.green_pin, 100)\n        self.blue_pwm = GPIO.PWM(self.blue_pin, 100)\n\n        self.red_pwm.start(0)\n        self.green_pwm.start(0)\n        self.blue_pwm.start(0)\n\n        self.running = False\n        self.rainbow_thread = None\n\n    def set_color(self, hex_color):\n        \"\"\"Set the RGB LED to a specific hex color.\"\"\"\n        try:\n            hex_color = hex_color.lstrip('#')\n            red = int(hex_color[0:2], 16)\n            green = int(hex_color[2:4], 16)\n            blue = int(hex_color[4:6], 16)\n\n            # Convert RGB values (0-255) to PWM duty cycle (0-100)\n            self.red_pwm.ChangeDutyCycle(red / 255 * 100)\n            self.green_pwm.ChangeDutyCycle(green / 255 * 100)\n            self.blue_pwm.ChangeDutyCycle(blue / 255 * 100)\n        except ValueError:\n            print(\"Invalid hex color format. Please use a hex string (e.g., '#FF00FF').\")\n\n    def rainbow_cycle_sequence(self, wait=0.05):\n        \"\"\"Cycle through colors in a rainbow effect until stopped.\"\"\"\n        self.running = True\n        position = 0  # Start at the beginning of the color wheel\n        while self.running:\n            red, green, blue = self.wheel(position % 256)\n            self.red_pwm.ChangeDutyCycle(red / 255 * 100)\n            self.green_pwm.ChangeDutyCycle(green / 255 * 100)\n            self.blue_pwm.ChangeDutyCycle(blue / 255 * 100)\n            t.sleep(wait)\n            position += 1\n\n    def rainbow_cycle(self, wait=0.05):\n        \"\"\"Start the rainbow cycle in a separate thread if not already running.\"\"\"\n        if self.rainbow_thread is None or not self.rainbow_thread.is_alive():\n            self.rainbow_thread = threading.Thread(target=self.rainbow_cycle_sequence, args=(wait,))\n            self.rainbow_thread.start()\n\n    def stop_rainbow_cycle(self):\n        \"\"\"Stop the rainbow cycle.\"\"\"\n        self.running = False\n        self.off()\n\n    @staticmethod\n    def wheel(position=0):\n        \"\"\"\n        Generate rainbow colors across 0-255 positions.\n        \"\"\"\n",
        "input": "",
        "output": "        if position < 85:\n            return (position * 3, 255 - position * 3, 0)\n        elif position < 170:\n            position -= 85\n            return (255 - position * 3, 0, position * 3)\n        else:\n            position -= 170\n            return (0, position * 3, 255 - position * 3)\n    \n",
        "idx": "613"
    },
    {
        "instruction": "## src/rpi_gpio/RGB_LED.py\nimport RPi.GPIO as GPIO\n\nimport time as t\n\nimport threading\n\nclass RGB_LED:\n    def __init__(self, red_pin, green_pin, blue_pin):\n        self.red_pin = red_pin\n        self.green_pin = green_pin\n        self.blue_pin = blue_pin\n\n        GPIO.setup(self.red_pin, GPIO.OUT)\n        GPIO.setup(self.green_pin, GPIO.OUT)\n        GPIO.setup(self.blue_pin, GPIO.OUT)\n\n        self.red_pwm = GPIO.PWM(self.red_pin, 100)\n        self.green_pwm = GPIO.PWM(self.green_pin, 100)\n        self.blue_pwm = GPIO.PWM(self.blue_pin, 100)\n\n        self.red_pwm.start(0)\n        self.green_pwm.start(0)\n        self.blue_pwm.start(0)\n\n        self.running = False\n        self.rainbow_thread = None\n\n    def set_color(self, hex_color):\n        \"\"\"Set the RGB LED to a specific hex color.\"\"\"\n        try:\n            hex_color = hex_color.lstrip('#')\n            red = int(hex_color[0:2], 16)\n            green = int(hex_color[2:4], 16)\n            blue = int(hex_color[4:6], 16)\n\n            # Convert RGB values (0-255) to PWM duty cycle (0-100)\n            self.red_pwm.ChangeDutyCycle(red / 255 * 100)\n            self.green_pwm.ChangeDutyCycle(green / 255 * 100)\n            self.blue_pwm.ChangeDutyCycle(blue / 255 * 100)\n        except ValueError:\n            print(\"Invalid hex color format. Please use a hex string (e.g., '#FF00FF').\")\n\n    def rainbow_cycle_sequence(self, wait=0.05):\n        \"\"\"Cycle through colors in a rainbow effect until stopped.\"\"\"\n        self.running = True\n        position = 0  # Start at the beginning of the color wheel\n        while self.running:\n            red, green, blue = self.wheel(position % 256)\n            self.red_pwm.ChangeDutyCycle(red / 255 * 100)\n            self.green_pwm.ChangeDutyCycle(green / 255 * 100)\n            self.blue_pwm.ChangeDutyCycle(blue / 255 * 100)\n            t.sleep(wait)\n            position += 1\n\n    def rainbow_cycle(self, wait=0.05):\n        \"\"\"Start the rainbow cycle in a separate thread if not already running.\"\"\"\n        if self.rainbow_thread is None or not self.rainbow_thread.is_alive():\n            self.rainbow_thread = threading.Thread(target=self.rainbow_cycle_sequence, args=(wait,))\n            self.rainbow_thread.start()\n\n    def stop_rainbow_cycle(self):\n        \"\"\"Stop the rainbow cycle.\"\"\"\n        self.running = False\n        self.off()\n\n    @staticmethod\n    def wheel(position=0):\n        \"\"\"Generate rainbow colors across 0-255 positions.\"\"\"\n        if position < 85:\n            return (position * 3, 255 - position * 3, 0)\n        elif position < 170:\n            position -= 85\n            return (255 - position * 3, 0, position * 3)\n        else:\n            position -= 170\n            return (0, position * 3, 255 - position * 3)\n\n    def off(self):\n        \"\"\"\n        Turn off the RGB LED.\n        \"\"\"\n",
        "input": "",
        "output": "        self.red_pwm.ChangeDutyCycle(0)\n        self.green_pwm.ChangeDutyCycle(0)\n        self.blue_pwm.ChangeDutyCycle(0)\n    \n",
        "idx": "614"
    },
    {
        "instruction": "## src/rpi_gpio/buzzer.py\nimport RPi.GPIO as GPIO\n\nimport time as t\n\nimport threading\n\nclass buzzer:\n    \"\"\"This uses GPIO pin-number on the pi.\\n\n    This class is for controlling basic Piezo Buzzers.\"\"\"\n    def __init__(self, pin):\n        self.pin = pin\n\n        self.beep_thread = None\n\n        GPIO.setup(pin, GPIO.OUT)\n\n    def on(self):\n        if GPIO.input(self.pin) == 0:\n            GPIO.output(self.pin, GPIO.HIGH)\n\n    def off(self):\n        if GPIO.input(self.pin) == 1:\n            GPIO.output(self.pin, GPIO.LOW)\n\n    def toggle(self):\n        if GPIO.input(self.pin) == 0:\n            self.on()\n        else:\n            self.off()\n\n    def beep_sequence(self, duration):\n        GPIO.output(self.pin, GPIO.LOW)\n        for i in range(int(duration)):\n            self.on()\n            t.sleep(0.5)\n            self.off()\n            t.sleep(0.5)\n\n    def beep(self, duration):\n        \"\"\"\n        Uses threads to make Beep() a non-blocking function\n        \"\"\"\n",
        "input": "",
        "output": "        if self.beep_thread and self.beep_thread.is_alive():\n            self.beep_thread.join()\n\n        self.beep_thread = threading.Thread(target=self.beep_sequence, args=(duration,))\n        self.beep_thread.start()\n    \n",
        "idx": "615"
    },
    {
        "instruction": "## src/rpi_gpio/Motor_Driver.py\nimport RPi.GPIO as GPIO\n\nclass Motor_Driver:\n    def __init__(self, in1=0, in2=0, ena=0, in3=0, in4=0, enb=0):\n        \"\"\"This uses GPIO pin-number on the pi.\\n\n        This class is for the L298N Motor Driver\"\"\"\n        self.in1 = int(in1)\n        self.in2 = int(in2)\n        self.ena = int(ena)\n\n        self.in3 = int(in3)\n        self.in4 = int(in4)\n        self.enb = int(enb)\n\n        GPIO.setup(self.in1, GPIO.OUT)\n        GPIO.output(self.in1, GPIO.LOW)\n        GPIO.setup(self.in2, GPIO.OUT)\n        GPIO.output(self.in2, GPIO.LOW)\n\n        GPIO.setup(self.ena, GPIO.OUT)\n\n        GPIO.setup(self.in3, GPIO.OUT)\n        GPIO.output(self.in3, GPIO.LOW)\n        GPIO.setup(self.in4, GPIO.OUT)\n        GPIO.output(self.in4, GPIO.LOW)\n\n        GPIO.setup(self.enb, GPIO.OUT)\n\n        self.en_a = GPIO.PWM(self.ena, 100)\n        self.en_a.start(0)\n\n        self.en_b = GPIO.PWM(self.enb, 100)\n        self.en_b.start(0)\n\n    def forward(self, speed=90):\n        \"\"\"Turns IN1 and IN3 on\"\"\"\n        GPIO.output(self.in1, GPIO.HIGH)\n        GPIO.output(self.in2, GPIO.LOW)\n        self.en_a.ChangeDutyCycle(speed)\n\n        GPIO.output(self.in3, GPIO.HIGH)\n        GPIO.output(self.in4, GPIO.LOW)\n        self.en_b.ChangeDutyCycle(speed)\n\n    def backward(self, speed=75):\n        \"\"\"Turns IN2 and IN4 on\"\"\"\n        GPIO.output(self.in1, GPIO.LOW)\n        GPIO.output(self.in2, GPIO.HIGH)\n        self.en_a.ChangeDutyCycle(speed)\n\n        GPIO.output(self.in3, GPIO.LOW)\n        GPIO.output(self.in4, GPIO.HIGH)\n        self.en_b.ChangeDutyCycle(speed)\n\n    def turn_right(self, speed=90):\n        \"\"\"\n        Turns IN2 and IN3 on\n        \"\"\"\n",
        "input": "",
        "output": "        GPIO.output(self.in1, GPIO.LOW)\n        GPIO.output(self.in2, GPIO.HIGH)\n        self.en_a.ChangeDutyCycle(speed)\n\n        GPIO.output(self.in3, GPIO.HIGH)\n        GPIO.output(self.in4, GPIO.LOW)\n        self.en_b.ChangeDutyCycle(speed)\n    \n",
        "idx": "618"
    },
    {
        "instruction": "## src/rpi_gpio/Motor_Driver.py\nimport RPi.GPIO as GPIO\n\nclass Motor_Driver:\n    def __init__(self, in1=0, in2=0, ena=0, in3=0, in4=0, enb=0):\n        \"\"\"This uses GPIO pin-number on the pi.\\n\n        This class is for the L298N Motor Driver\"\"\"\n        self.in1 = int(in1)\n        self.in2 = int(in2)\n        self.ena = int(ena)\n\n        self.in3 = int(in3)\n        self.in4 = int(in4)\n        self.enb = int(enb)\n\n        GPIO.setup(self.in1, GPIO.OUT)\n        GPIO.output(self.in1, GPIO.LOW)\n        GPIO.setup(self.in2, GPIO.OUT)\n        GPIO.output(self.in2, GPIO.LOW)\n\n        GPIO.setup(self.ena, GPIO.OUT)\n\n        GPIO.setup(self.in3, GPIO.OUT)\n        GPIO.output(self.in3, GPIO.LOW)\n        GPIO.setup(self.in4, GPIO.OUT)\n        GPIO.output(self.in4, GPIO.LOW)\n\n        GPIO.setup(self.enb, GPIO.OUT)\n\n        self.en_a = GPIO.PWM(self.ena, 100)\n        self.en_a.start(0)\n\n        self.en_b = GPIO.PWM(self.enb, 100)\n        self.en_b.start(0)\n\n    def forward(self, speed=90):\n        \"\"\"Turns IN1 and IN3 on\"\"\"\n        GPIO.output(self.in1, GPIO.HIGH)\n        GPIO.output(self.in2, GPIO.LOW)\n        self.en_a.ChangeDutyCycle(speed)\n\n        GPIO.output(self.in3, GPIO.HIGH)\n        GPIO.output(self.in4, GPIO.LOW)\n        self.en_b.ChangeDutyCycle(speed)\n\n    def backward(self, speed=75):\n        \"\"\"Turns IN2 and IN4 on\"\"\"\n        GPIO.output(self.in1, GPIO.LOW)\n        GPIO.output(self.in2, GPIO.HIGH)\n        self.en_a.ChangeDutyCycle(speed)\n\n        GPIO.output(self.in3, GPIO.LOW)\n        GPIO.output(self.in4, GPIO.HIGH)\n        self.en_b.ChangeDutyCycle(speed)\n\n    def turn_right(self, speed=90):\n        \"\"\"Turns IN2 and IN3 on\"\"\"\n        GPIO.output(self.in1, GPIO.LOW)\n        GPIO.output(self.in2, GPIO.HIGH)\n        self.en_a.ChangeDutyCycle(speed)\n\n        GPIO.output(self.in3, GPIO.HIGH)\n        GPIO.output(self.in4, GPIO.LOW)\n        self.en_b.ChangeDutyCycle(speed)\n\n    def turn_left(self, speed=90):\n        \"\"\"\n        Turns IN1 and IN4 on\n        \"\"\"\n",
        "input": "",
        "output": "        GPIO.output(self.in1, GPIO.HIGH)\n        GPIO.output(self.in2, GPIO.LOW)\n        self.en_a.ChangeDutyCycle(speed)\n\n        GPIO.output(self.in3, GPIO.LOW)\n        GPIO.output(self.in4, GPIO.HIGH)\n        self.en_b.ChangeDutyCycle(speed)\n    \n",
        "idx": "619"
    },
    {
        "instruction": "## src/rpi_gpio/LED.py\nimport RPi.GPIO as GPIO\n\nimport time as t\n\nimport threading\n\nclass LED:\n    def __init__(self, pin):\n        \"\"\"This uses GPIO pin-number on the pi.\\n\n        This class is for controlling basic LED's.\"\"\"\n        self.pin = int(pin)\n\n        self.led_thread = None\n\n        GPIO.setup(self.pin, GPIO.OUT)\n\n    def on(self):\n        if GPIO.input(self.pin) == 0:\n            GPIO.output(self.pin, GPIO.HIGH)\n\n    def off(self):\n        if GPIO.input(self.pin) == 1:\n            GPIO.output(self.pin, GPIO.LOW)\n\n    def toggle(self):\n        if GPIO.input(self.pin) == 0:\n            self.on()\n        else:\n            self.off()\n\n    def blink_sequence(self, duration=6):\n        GPIO.output(self.pin, GPIO.LOW)\n        for i in range(int(duration)):\n            self.on()\n            t.sleep(0.5)\n            self.off()\n            t.sleep(0.5)\n\n    def blink(self, duration=6):\n",
        "input": "",
        "output": "        if self.led_thread and self.led_thread.is_alive():\n            self.led_thread.join()\n\n        self.led_thread = threading.Thread(target=self.blink_sequence, args=(duration,))\n        self.led_thread.start()\n    \n",
        "idx": "621"
    },
    {
        "instruction": "## src/rpi_gpio/Temperature_Sensor.py\nimport RPi.GPIO as GPIO\n\nimport Adafruit_DHT as DHT\n\nclass Temperature_Sensor:\n    def __init__(self, out, sensor_type):\n        \"\"\"This uses GPIO pin-numbers on the pi.\"\"\"\n        self.out = out\n        self.sensor_type = sensor_type\n\n        GPIO.setup(self.out, GPIO.IN)\n\n    def temperature(self, measure_mode=\"C\"):\n        \"\"\"measure_mode is for:/n\n        'F', 'Fahrenheit', 'C', 'Celsius', 'Centigrade'\"\"\"\n        humidity, temp = DHT.read_retry(self.sensor_type, self.out)\n\n        if temp is not None:\n            if measure_mode in ['F', 'Fahrenheit']:\n                return temp * 9.0 / 5.0 + 32.0\n            elif measure_mode in ['C', 'Celsius', 'Centigrade']:\n                return temp\n        else:\n            return None\n\n    def humidity(self):\n",
        "input": "",
        "output": "        humidity, _ = DHT.read_retry(self.sensor_type, self.out)\n\n        if humidity is not None:\n            return humidity\n        else:\n            return None\n    \n",
        "idx": "622"
    },
    {
        "instruction": "## src/rpi_gpio/IR.py\nimport RPi.GPIO as GPIO\n\nimport pigpio\n\nimport time as t\n\nclass IR_LED:\n    def __init__(self, pin):\n        self.pin = pin\n        self.pi = pigpio.pi()\n\n        if not self.pi.connected:\n            raise Exception('could not connect to pigpio daemon')\n\n        self.pi.set_mode(self.pin, pigpio.OUTPUT)\n\n    def send_signal(self, hex_code, protocol=\"NEC\", frequency=38000):\n        if protocol == \"NEC\":\n            data = self._hex_to_bin(hex_code)\n            self._send_nec(data, frequency)\n        else:\n            raise Exception('unsupported protocol')\n\n    def _send_nec(self, data, frequency=38000):\n        self.pi.set_PWM_frequency(self.pin, frequency)\n        self.pi.set_PWM_dutycycle(self.pin, 128)\n\n        self._send_pulse(9000, 4500)\n\n        for i in range(32):\n            bit = (data >> (31 - i)) & 1\n            if bit == 1:\n                self._send_pulse(560, 1690)\n            else:\n                self._send_pulse(560, 560)\n\n        self.pi.set_PWM_dutycycle(self.pin, 0)\n\n    def _send_pulse(self, high_time, low_time):\n",
        "input": "",
        "output": "        self.pi.gpio_trigger(self.pin, high_time, 1)\n        t.sleep(low_time / 1000000.0)\n    \n",
        "idx": "623"
    },
    {
        "instruction": "## src/rpi_gpio/IR.py\nimport RPi.GPIO as GPIO\n\nimport pigpio\n\nimport time as t\n\nclass IR_LED:\n    def __init__(self, pin):\n        self.pin = pin\n        self.pi = pigpio.pi()\n\n        if not self.pi.connected:\n            raise Exception('could not connect to pigpio daemon')\n\n        self.pi.set_mode(self.pin, pigpio.OUTPUT)\n\n    def send_signal(self, hex_code, protocol=\"NEC\", frequency=38000):\n        if protocol == \"NEC\":\n            data = self._hex_to_bin(hex_code)\n            self._send_nec(data, frequency)\n        else:\n            raise Exception('unsupported protocol')\n\n    def _send_nec(self, data, frequency=38000):\n        self.pi.set_PWM_frequency(self.pin, frequency)\n        self.pi.set_PWM_dutycycle(self.pin, 128)\n\n        self._send_pulse(9000, 4500)\n\n        for i in range(32):\n            bit = (data >> (31 - i)) & 1\n            if bit == 1:\n                self._send_pulse(560, 1690)\n            else:\n                self._send_pulse(560, 560)\n\n        self.pi.set_PWM_dutycycle(self.pin, 0)\n\n    def _send_pulse(self, high_time, low_time):\n        self.pi.gpio_trigger(self.pin, high_time, 1)\n        t.sleep(low_time / 1000000.0)\n\n    def _hex_to_bin(self, hex_code):\n",
        "input": "",
        "output": "        hex_code = hex_code.lstrip(\"0x\").zfill(8)\n        bin_code = bin(int(hex_code, 16))[2:].zfill(32)\n        return bin_code\n    \n",
        "idx": "624"
    },
    {
        "instruction": "## code/fov_summary/session_evaluation.py\nimport json\n\nimport math\n\nimport operator\n\nimport sys\n\nfrom pathlib import Path\n\nfrom typing import Any, Callable, Dict, List, Optional, Union\n\nfrom aind_data_schema.core.quality_control import (QCEvaluation, QCMetric,\n                                                   QCStatus, Stage)\n\nfrom aind_data_schema_models.modalities import Modality\n\nfrom PIL import Image, ImageDraw, ImageFont\n\nfrom pydantic import BaseModel, Field\n\nclass EvaluationSettings(BaseModel):\n    \"\"\"Settings for the evaluation of the registration.\"\"\"\n\n    # Path to the reference image\n    input_directory: Path = Field(..., description=\"Input directory containing the data\")\n    output_directory: Path = Field(\n        ..., description=\"Output directory to store the results\"\n    )\n    pattern: Optional[List] = Field(\n        default=[], description=\"Pattern to match in file search\"\n    )\n    folder_name: str = Field(..., description=\"Name of the folder to search for files\")\n    metric_name: str = Field(..., description=\"Name of the metric\")\n    metric_status_history: list[QCStatus] = Field(\n        default=[], description=\"Status history for the metric\"\n    )\n    stage: Stage = Field(..., description=\"Stage of the evaluation\")\n    modality: Modality.ONE_OF = Field(..., description=\"Modality of the data\")\n    evaluations_name: str = Field(..., description=\"Name of the evaluation\")\n    allow_failed_metrics: bool = Field(..., description=\"Allow failed metrics\")\n\nclass Evaluation:\n    \"\"\"Build evaluation from provided settings.\"\"\"\n\n    OPERATORS = {\n        \"==\": operator.eq,\n        \"!=\": operator.ne,\n        \"<\": operator.lt,\n        \"<=\": operator.le,\n        \">\": operator.gt,\n        \">=\": operator.ge,\n    }\n\n    def __init__(self, settings: EvaluationSettings):\n        self.settings = settings\n        self.initalize_evaluation()\n\n    def initalize_evaluation(self):\n        \"\"\"\n        Initialize the evaluation.\n        \"\"\"\n",
        "input": "",
        "output": "        self.directories = self._get_directories()\n        self.output_directory = self._make_directory(self.settings.output_directory)\n    \n",
        "idx": "625"
    },
    {
        "instruction": "## code/fov_summary/session_evaluation.py\nimport json\n\nimport math\n\nimport operator\n\nimport sys\n\nfrom pathlib import Path\n\nfrom typing import Any, Callable, Dict, List, Optional, Union\n\nfrom aind_data_schema.core.quality_control import (QCEvaluation, QCMetric,\n                                                   QCStatus, Stage)\n\nfrom aind_data_schema_models.modalities import Modality\n\nfrom PIL import Image, ImageDraw, ImageFont\n\nfrom pydantic import BaseModel, Field\n\nclass EvaluationSettings(BaseModel):\n    \"\"\"Settings for the evaluation of the registration.\"\"\"\n\n    # Path to the reference image\n    input_directory: Path = Field(..., description=\"Input directory containing the data\")\n    output_directory: Path = Field(\n        ..., description=\"Output directory to store the results\"\n    )\n    pattern: Optional[List] = Field(\n        default=[], description=\"Pattern to match in file search\"\n    )\n    folder_name: str = Field(..., description=\"Name of the folder to search for files\")\n    metric_name: str = Field(..., description=\"Name of the metric\")\n    metric_status_history: list[QCStatus] = Field(\n        default=[], description=\"Status history for the metric\"\n    )\n    stage: Stage = Field(..., description=\"Stage of the evaluation\")\n    modality: Modality.ONE_OF = Field(..., description=\"Modality of the data\")\n    evaluations_name: str = Field(..., description=\"Name of the evaluation\")\n    allow_failed_metrics: bool = Field(..., description=\"Allow failed metrics\")\n\nclass Evaluation:\n    \"\"\"Build evaluation from provided settings.\"\"\"\n\n    OPERATORS = {\n        \"==\": operator.eq,\n        \"!=\": operator.ne,\n        \"<\": operator.lt,\n        \"<=\": operator.le,\n        \">\": operator.gt,\n        \">=\": operator.ge,\n    }\n\n    def __init__(self, settings: EvaluationSettings):\n        self.settings = settings\n        self.initalize_evaluation()\n\n    def initalize_evaluation(self):\n        \"\"\"Initialize the evaluation.\"\"\"\n        self.directories = self._get_directories()\n        self.output_directory = self._make_directory(self.settings.output_directory)\n\n    def _get_directories(self) -> list:\n        \"\"\"Get directories containing the data.\n\n        Returns\n        -------\n        list\n            List of directories containing the data\n        \"\"\"\n        input_dir = self.settings.input_directory\n        if len(list(input_dir.glob(\"*\"))) == 1:\n            return [plane for plane in input_dir.glob(\"*/*\")]\n        return [plane for plane in input_dir.rglob(\"*\")]\n\n    def _make_directory(self, directory: Path) -> Path:\n        \"\"\"\n        Make a directory if it does not exist.\n    \n        Parameters\n        ----------\n        directory : Path\n        Directory path\n    \n        Returns\n        -------\n        Path\n        Directory path\n        \"\"\"\n",
        "input": "",
        "output": "        directory.mkdir(exist_ok=True)\n        return directory\n    \n",
        "idx": "627"
    },
    {
        "instruction": "## geometry.py\nimport numpy as np\n\nfrom typing import Union\n\nclass Point:\n    def __init__(self, x: float, y: float):\n        self.x = float(x)\n        self.y = float(y)\n        \n    def __str__(self):\n        return 'Point(' + str(self.x) + ', ' + str(self.y) + ')'\n        \n    def __add__(self, other: 'Point') -> 'Point':\n        return Point(self.x + other.x, self.y + other.y)\n        \n    def __sub__(self, other: 'Point') -> 'Point':\n        return Point(self.x - other.x, self.y - other.y)\n    \n    def norm(self, p: int = 2) -> float:\n        return (self.x ** p + self.y ** p)**(1./p)\n        \n    def dot(self, other: 'Point') -> float:\n        return self.x * other.x + self.y * other.y\n        \n    def __mul__(self, other: float) -> 'Point':\n        return Point(other * self.x, other * self.y)\n    \n    def __rmul__(self, other: float) -> 'Point':\n        return self.__mul__(other)\n        \n    def __truediv__(self, other: float) -> 'Point':\n        return self.__mul__(1./other)\n        \n        \n    def isInside(self, other: Union['Line', 'Rectangle', 'Circle', 'Ring']) -> bool:\n        if isinstance(other, Line):\n            AM = Line(other.p1, self)\n            MB = Line(self, other.p2)\n            return np.close(np.abs(AM.dot(BM)), AM.length * MB.length)\n        \n        elif isinstance(other, Rectangle):\n            # Based on https://stackoverflow.com/a/2763387\n            AB = Line(other.c1, other.c2)\n            AM = Line(other.c1, self)\n            BC = Line(other.c2, other.c3)\n            BM = Line(other.c2, self)\n        \n            return 0 <= AB.dot(AM) <= AB.dot(AB) and 0 <= BC.dot(BM) <= BC.dot(BC)\n            \n        elif isinstance(other, Circle):\n            return self.distanceTo(other.m) <= other.r\n            \n        elif isinstance(other, Ring):\n            return other.r_inner <= self.distanceTo(other.m) <= other.r_outer\n            \n        raise NotImplementedError\n        \n    def hasPassed(self, other: Union['Point', 'Line', 'Rectangle', 'Circle', 'Ring'], direction: 'Point') -> bool:\n        if isinstance(other, Point):\n            p = other\n        elif isinstance(other, Line):\n            p = (other.p1 + other.p2) / 2.\n        elif isinstance(other, Rectangle):\n            p = (other.c1 + other.c2 + other.c3 + other.c4) / 4.\n        elif isinstance(other, Circle):\n            p = other.m\n        elif isinstance(other, Ring):\n            p = other.m\n        else:\n            raise NotImplementedError\n        return direction.dot(p - self) <= 0\n                    \n    def distanceTo(self, other: Union['Point', 'Line', 'Rectangle', 'Circle', 'Ring']) -> float:\n        if isinstance(other, Point):\n            return (self - other).norm(p = 2)\n    \n        elif isinstance(other, Line):\n            # Based on https://math.stackexchange.com/a/330329\n            s2_minus_s1 = other.p2 - other.p1\n            that = (self - other.p1).dot(s2_minus_s1) / s2_minus_s1.dot(s2_minus_s1)\n            tstar = np.minimum(1, np.maximum(0, that))\n            return (other.p1 + tstar * s2_minus_s1 - self).norm(p = 2)\n        \n        elif isinstance(other, Rectangle):\n            if self.isInside(other): return 0\n            E = other.edges\n            return np.min([self.distanceTo(e) for e in E])\n        \n        elif isinstance(other, Circle):\n            return np.maximum(0, self.distanceTo(other.m) - other.r)\n            \n        elif isinstance(other, Ring):\n            d = self.distanceTo(other.m)\n            return np.max([r_inner - d, d - r_outer, 0])\n            \n        else:\n            try:\n                return other.distanceTo(self) # do we really need to try this? Does it ever succeed?\n            except NameError:\n                raise NotImplementedError\n            print('Something went wrong!')\n            raise\n\ndef onSegment(p: Point, q: Point, r: Point) -> bool:\n    return (q.x <= np.maximum(p.x, r.x) and q.x >= np.minimum(p.x, r.x) and \n        q.y <= np.maximum(p.y, r.y) and q.y >= np.minimum(p.y, r.y))\n\nclass Line:\n    def __init__(self, p1: Point, p2: Point):\n        self.p1 = p1\n        self.p2 = p2\n        \n    def __str__(self):\n        return 'Line(' + str(self.p1) +  ', ' + str(self.p2) + ')'\n        \n    def intersectsWith(self, other: Union['Line','Rectangle','Circle','Ring']):\n        if isinstance(other, Line):\n            p1 = self.p1\n            q1 = self.p2\n            p2 = other.p1\n            q2 = other.p2\n        \n            # Based on https://www.geeksforgeeks.org/check-if-two-given-line-segments-intersect/\n            # Find the four orientations needed for general and special cases \n            o1 = orientation(p1, q1, p2) \n            o2 = orientation(p1, q1, q2) \n            o3 = orientation(p2, q2, p1) \n            o4 = orientation(p2, q2, q1)\n      \n            # General case \n            if o1 != o2 and o3 != o4:\n                return True\n\n            # Special Cases \n            # p1, q1 and p2 are colinear and p2 lies on segment p1q1 \n            if o1 == 0 and onSegment(p1, p2, q1): return True\n      \n            # p1, q1 and q2 are colinear and q2 lies on segment p1q1 \n            if o2 == 0 and onSegment(p1, q2, q1): return True\n      \n            # p2, q2 and p1 are colinear and p1 lies on segment p2q2\n            if o3 == 0 and onSegment(p2, p1, q2): return True\n      \n            # p2, q2 and q1 are colinear and q1 lies on segment p2q2\n            if o4 == 0 and onSegment(p2, q1, q2): return True\n      \n            return False # Doesn't fall in any of the above cases \n            \n        elif isinstance(other, Rectangle):\n            if self.p1.isInside(other) or self.p2.isInside(other): return True\n            E = other.edges\n            for edge in E:\n                if self.intersectsWith(edge): return True\n            return False\n            \n        elif isinstance(other, Circle):\n            return other.m.distanceTo(self) <= other.r\n            \n        elif isinstance(other, Ring):\n            return (other.m.distanceTo(self.p1) >= other.r_inner or other.m.distanceTo(self.p2) >= other.r_inner) and other.m.distanceTo(self) < other.r_outer\n            \n        raise NotImplementedError\n        \n    @property\n    def length(self):\n        return self.p1.distanceTo(self.p2)\n        \n    def dot(self, other: 'Line') -> float: # assumes Line is a vector from p1 to p2\n        v1 = (self.p2 - self.p1)\n        v2 = (other.p2 - other.p1)\n        return v1.dot(v2)\n        \n    def hasPassed(self, other: Union['Point', 'Line', 'Rectangle', 'Circle', 'Ring'], direction: Point) -> bool:\n        p = (self.p1 + self.p2) / 2.\n        return p.hasPassed(other, direction)\n        \n    def distanceTo(self, other: Union['Point', 'Line', 'Rectangle', 'Circle', 'Ring']) -> float:\n        if isinstance(other, Point):\n            return other.distanceTo(self)\n            \n        elif isinstance(other, Line):\n            if self.intersectsWith(other): return 0.\n            return np.min([self.p1.distanceTo(other.p1), self.p1.distanceTo(other.p2), self.p2.distanceTo(other.p1), self.p2.distanceTo(other.p2)])\n            \n        elif isinstance(other, Rectangle):\n            if self.intersectsWith(other): return 0.\n            other_edges = other.edges\n            return np.min([self.distanceTo(e) for e in other_edges])\n            \n        elif isinstance(other, Circle):\n            return np.maximum(0, other.m.distanceTo(self) - other.r)\n            \n        elif isinstance(other, Ring):\n            if self.intersectsWith(other): return 0.\n            p1m = self.p1.distanceTo(other.m)\n            if p1m < other.r_inner: # the line is inside the ring\n                p2m = self.p2.distanceTo(other.m)\n                return other.r_inner - np.maximum(p1m, p2m)\n            else: # the line is completely outside\n                return np.maximum(0, other.m.distanceTo(self) - other.r_outer)   \n                \n        raise NotImplementedError\n\nclass Rectangle:\n    def __init__(self, c1: Point, c2: Point, c3: Point): # 3 points are enough to represent a rectangle\n        self.c1 = c1\n        self.c2 = c2\n        self.c3 = c3\n        self.c4 = c3 + c1 - c2\n        \n    def __str__(self):\n        return 'Rectangle(' + str(self.c1) +  ', ' + str(self.c2) +  ', ' + str(self.c3) +  ', ' + str(self.c4) + ')'\n        \n    @property\n    def edges(self):\n        e1 = Line(self.c1, self.c2)\n        e2 = Line(self.c2, self.c3)\n        e3 = Line(self.c3, self.c4)\n        e4 = Line(self.c4, self.c1)\n        return [e1, e2, e3, e4]\n\n    @property\n    def corners(self):\n        return [self.c1, self.c2, self.c3, self.c4]\n        \n    def intersectsWith(self, other: Union['Line', 'Rectangle', 'Circle', 'Ring']) -> bool:\n        if isinstance(other, Line):\n            return other.intersectsWith(self)\n            \n        elif isinstance(other, Rectangle) or isinstance(other, Circle) or isinstance(other, Ring):\n            E = self.edges\n            for e in E:\n                if e.intersectsWith(other): return True\n            return False\n\n        raise NotImplementedError\n        \n    def hasPassed(self, other: Union['Point', 'Line', 'Rectangle', 'Circle', 'Ring'], direction: Point) -> bool:\n        p = (self.c1 + self.c2 + self.c3 + self.c4) / 4.\n        return p.hasPassed(other, direction)\n        \n    def distanceTo(self, other: Union['Point', 'Line', 'Rectangle', 'Circle', 'Ring']) -> float:\n        if isinstance(other, Point) or isinstance(other, Line):\n            return other.distanceTo(self)\n\n        elif isinstance(other, Rectangle) or isinstance(other, Circle) or isinstance(other, Ring):\n            if self.intersectsWith(other): return 0.\n            E = self.edges\n            return np.min([e.distanceTo(other) for e in E])\n\n        raise NotImplementedError\n\nclass Circle:\n    def __init__(self, m: Point, r: float):\n        self.m = m\n        self.r = r\n        \n    def __str__(self):\n        return 'Circle(' + str(self.m) +  ', radius = ' + str(self.r) + ')'\n        \n    def intersectsWith(self, other: Union['Line', 'Rectangle', 'Circle', 'Ring']):\n        if isinstance(other, Line) or isinstance(other, Rectangle):\n            return other.intersectsWith(self)\n            \n        elif isinstance(other, Circle):\n            return self.m.distanceTo(other.m) <= self.r + other.r\n            \n        elif isinstance(other, Ring):\n            return other.r_inner - self.r <= self.m.distanceTo(other.m) <= self.r + other.r_outer\n            \n        raise NotImplementedError\n        \n    def hasPassed(self, other: Union['Point', 'Line', 'Rectangle', 'Circle', 'Ring'], direction: Point) -> bool:\n        return self.m.hasPassed(other, direction)\n        \n    def distanceTo(self, other: Union['Point', 'Line', 'Rectangle', 'Circle', 'Ring']) -> float:\n        if isinstance(other, Point) or isinstance(other, Line) or isinstance(other, Rectangle):\n            return other.distanceTo(self)\n            \n        elif isinstance(other, Circle):\n            return np.maximum(0, self.m.distanceTo(other.m) - self.r - other.r)\n            \n        elif isinstance(other, Ring):\n            if self.intersectsWith(other): return 0.\n            d = self.m.distanceTo(other.m)\n            return np.maximum(other.r_inner - d, d - other.r_outer) - self.r\n            \n        raise NotImplementedError\n\nclass Ring:\n    def __init__(self, m: Point, r_inner: float, r_outer: float):\n        self.m = m\n        assert r_inner < r_outer\n        self.r_inner = r_inner\n        self.r_outer = r_outer\n        \n    def __str__(self):\n        return 'Ring(' + str(self.m) +  ', inner radius = ' + str(self.r_inner) +  ', outer radius = ' + str(self.r_outer) + ')'\n        \n    def intersectsWith(self, other: Union['Line', 'Rectangle', 'Circle', 'Ring']):\n        if isinstance(other, Line) or isinstance(other, Rectangle) or isinstance(other, Circle):\n            return other.intersectsWith(self)\n            \n        elif isinstance(other, Ring):\n            d = self.m.distanceTo(other.m)\n            if d > self.r_outer + other.r_outer: return False # rings are far away\n            if d + self.r_outer < other.r_inner: return False # self is completely inside other\n            if d + other.r_outer < self.r_inner: return False # other is completely inside self\n            return True\n            \n        raise NotImplementedError\n        \n    def hasPassed(self, other: Union['Point', 'Line', 'Rectangle', 'Circle', 'Ring'], direction: Point) -> bool:\n        return self.m.hasPassed(other, direction)\n        \n    def distanceTo(self, other: Union['Point', 'Line', 'Rectangle', 'Circle', 'Ring']) -> float:\n        if isinstance(other, Point) or isinstance(other, Line) or isinstance(other, Rectangle) or isinstance(other, Circle):\n            return other.distanceTo(self)\n            \n        if isinstance(other, Ring):\n            if d > self.r_outer + other.r_outer: return d - self.r_outer - other.r_outer # rings are far away\n            if d + self.r_outer < other.r_inner: return other.r_inner - d - self.r_outer # self is completely inside other\n            if d + other.r_outer < self.r_inner: return self.r_inner - d - other.r_outer # other is completely inside self\n            return 0\n            \n        raise NotImplementedError\n\ndef orientation(p: Point, q: Point, r: Point) -> int:\n",
        "input": "",
        "output": "    val = (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y)\n    if val == 0: return 0 # colinear \n    return 1 if val > 0 else 2\n\n",
        "idx": "632"
    },
    {
        "instruction": "## ACC_algo.py\nDESIRED_TIME_GAP = 1.8\n\nMAX_ACCEL = 2.5\n\nMAX_DECEL = -3.0\n\nMIN_FOLLOWING_DISTANCE = 2.0\n\nDETECTION_RANGE = 100\n\nclass ACCController:\n    def __init__(self):\n        self.desired_cruise_speed = 30  # Default cruise speed in km/h\n        \n    def set_desired_cruise_speed(self, speed_kph):\n        \"\"\"Set the desired cruise speed in km/h\"\"\"\n        self.desired_cruise_speed = speed_kph\n        \n    def target_follow_control(self, ego_car, target_car):\n        \"\"\"\n        Calculate acceleration command to follow target vehicle\n        \"\"\"\n",
        "input": "",
        "output": "        current_distance = ego_car.distanceTo(target_car)\n        desired_distance = ego_car.velocity.x * DESIRED_TIME_GAP + MIN_FOLLOWING_DISTANCE\n\n        # Determine acceleration based on distance error\n        distance_error = current_distance - desired_distance\n        acceleration = distance_error / DESIRED_TIME_GAP\n        \n        # Limit acceleration between max deceleration and acceleration\n        if acceleration < MAX_DECEL:\n            return MAX_DECEL\n        elif acceleration > MAX_ACCEL:\n            return MAX_ACCEL\n        return acceleration\n    \n",
        "idx": "642"
    },
    {
        "instruction": "## ACC_algo.py\nDESIRED_TIME_GAP = 1.8\n\nMAX_ACCEL = 2.5\n\nMAX_DECEL = -3.0\n\nMIN_FOLLOWING_DISTANCE = 2.0\n\nDETECTION_RANGE = 100\n\nclass ACCController:\n    def __init__(self):\n        self.desired_cruise_speed = 30  # Default cruise speed in km/h\n        \n    def set_desired_cruise_speed(self, speed_kph):\n        \"\"\"Set the desired cruise speed in km/h\"\"\"\n        self.desired_cruise_speed = speed_kph\n        \n    def target_follow_control(self, ego_car, target_car):\n        \"\"\"Calculate acceleration command to follow target vehicle\"\"\"\n        # Calculate current distance and desired following distance\n        current_distance = ego_car.distanceTo(target_car)\n        desired_distance = ego_car.velocity.x * DESIRED_TIME_GAP + MIN_FOLLOWING_DISTANCE\n\n        # Determine acceleration based on distance error\n        distance_error = current_distance - desired_distance\n        acceleration = distance_error / DESIRED_TIME_GAP\n        \n        # Limit acceleration between max deceleration and acceleration\n        if acceleration < MAX_DECEL:\n            return MAX_DECEL\n        elif acceleration > MAX_ACCEL:\n            return MAX_ACCEL\n        return acceleration\n    \n    def cruise_control(self, ego_car):\n        \"\"\"\n        Calculate acceleration command to maintain cruise speed\n        \"\"\"\n",
        "input": "",
        "output": "        target_speed_ms = self.desired_cruise_speed / 3.6\n            \n        # Determine acceleration based on speed error\n        speed_error = target_speed_ms - ego_car.velocity.x\n        acceleration = speed_error / DESIRED_TIME_GAP\n        \n        # Limit acceleration to vehicle constraints\n        if acceleration < MAX_DECEL:\n            return MAX_DECEL\n        elif acceleration > MAX_ACCEL:\n            return MAX_ACCEL\n        return acceleration\n    \n",
        "idx": "646"
    },
    {
        "instruction": "## powerwallToChords.py\nimport os\n\ndef check_auth_files(pw_auth_path: str) -> bool:\n",
        "input": "",
        "output": "    ok = True\n    auth_files = [f'{pw_auth_path}/.pypowerwall.auth', f'{pw_auth_path}/.pypowerwall.site']\n    for f in auth_files:\n        if not (os.path.isfile(f) and os.access(f, os.R_OK)):\n            print(f'Unable to access tesla credentials file {f}')\n            ok = False\n    return ok\n\n",
        "idx": "649"
    },
    {
        "instruction": "## powerwallToChords.py\nimport pypowerwall\n\nimport time\n\nimport statistics\n\nimport datetime\n\nclass TimeAndValue:\n    '''Just a structure to hold a time and value pair.'''\n    def __init__(self, time, value):\n        self.time = time\n        self.average = value\n\nclass Aggregator: \n    '''Collect and average a queue of values\n    \n    When an average is called for, the average over all values \n    is calculated, and then all values except for the last one in the\n    queue is removed.\n    '''\n    def __init__(self, name:str)->None:\n        self.name = name\n        self.times = []\n        self.values = []\n\n    def add(self, value:float, time:str)->None:\n        self.values.append(value)\n        self.times.append(time)\n\n    def avg(self)->list:\n        avg = statistics.mean(self.values)\n        time = statistics.mean(self.times)\n        #print(f'>>> {self.name}')\n        #print(self.values)\n        #print(avg)\n        self.values = [self.values[-1]]\n        self.times = [self.times[-1]]\n        return TimeAndValue(time=time, value=avg)\n\nclass PW_Aggregator:\n    '''Poll Tesla every time poll_pw() is called, and aggregate selected data.\n    \n    avg() returns the averaged values, which causes the Aggregator()s\n    to restart the averaging.\n    '''\n    def __init__(self, pw:pypowerwall.Powerwall):\n        self.pw = pw\n        \n        self.time_aggregator = Aggregator('time')\n        self.grid_aggregator = Aggregator('grid')\n        self.solar_aggregator = Aggregator('solar')\n        self.battery_aggregator = Aggregator('battery')\n        self.load_aggregator = Aggregator('load')\n        self.level_aggregator = Aggregator('level')\n\n    def poll_pw(self):\n        '''Poll Tesla and add data to the set of Aggregators'''\n        pw_success = False\n        while not pw_success:\n            try:\n                # pw.grid() will make a request to Tesla\n                grid = self.pw.grid(verbose=True)\n                if grid:\n                    data_time = datetime.datetime.fromisoformat(grid['last_communication_time']).timestamp()\n                    # pw.power() will make a request to Tesla\n                    power = self.pw.power()\n                    if power:\n                        pw_success = True\n            except Exception as e:\n                print('Exception during Tesla API access')\n                print(e)\n            if not pw_success:\n                time.sleep(6)\n                print('Retrying Tesla access')\n\n        self.time_aggregator.add(time=data_time, value=data_time)\n        self.grid_aggregator.add(time=data_time, value=power['site'])\n        self.solar_aggregator.add(time=data_time, value=power['solar'])\n        self.battery_aggregator.add(time=data_time, value=power['battery'])\n        self.load_aggregator.add(time=data_time, value=power['load'])\n        self.level_aggregator.add(time=data_time, value=self.pw.level())\n\n    def avg(self):\n        \"\"\"\n        Return a dictionary of TimeAndValue averages.\n    \n        The aggregators are restarted when their .avg() functions are called.\n        \"\"\"\n",
        "input": "",
        "output": "        ret_val = {}\n        ret_val['time'] = self.time_aggregator.avg().average\n        ret_val['grid'] = self.grid_aggregator.avg().average\n        ret_val['solar'] = self.solar_aggregator.avg().average\n        ret_val['battery'] = self.battery_aggregator.avg().average\n        ret_val['load'] = self.load_aggregator.avg().average\n        ret_val['level'] = self.level_aggregator.avg().average\n        return ret_val\n    \n",
        "idx": "650"
    },
    {
        "instruction": "## blog_generator.py\nfrom typing import Dict, List\n\nfrom openai import OpenAI\n\nimport os\n\nclass OpenAIBlogGenerator:                                                                                                 \n    def __init__(self):\n        self.client = OpenAI(api_key=os.getenv(\"OPENAI_API_KEY\"))\n\n    def generate(self, content: List[Dict]) -> str:                                                                        \n        \"\"\"Generate blog content using OpenAI.\"\"\"                                                                          \n        try:\n            # Prepare the content for the prompt                                                                           \n            combined_content = self._prepare_content(content)                                                              \n            \n            # Generate blog using OpenAI                                                                                   \n            response = self.client.chat.completions.create(                                                                       \n                model=\"gpt-4\",                                                                                             \n                messages=[                                                                                                 \n                    {\"role\": \"system\", \"content\": \"You are a professional blog writer. Create a well-structured, engaging  blog post from the provided content.\"},                                                                                    \n                    {\"role\": \"user\", \"content\": f\"Create a blog post from this content: {combined_content}\\n\\nInclude images with alt text accurately describing what the image is all about. The blog should be formatted in markdown syntax\"}\n                ]                                                                                                          \n            )                                                                                                              \n\n            return response.choices[0].message.content                                                                     \n\n        except Exception as e:                                                                                             \n            raise Exception(f\"Failed to generate blog with OpenAI: {str(e)}\")                                              \n\n    def _prepare_content(self, content: List[Dict]) -> str:\n        \"\"\"\n        Prepare content for the AI prompt.\n        \"\"\"\n",
        "input": "",
        "output": "        combined = \"\"                                                                                                      \n        for item in content:                                                                                               \n            combined += f\"Title: {item.get('title', '')}\\n\"                                                                \n            combined += f\"Content: {item.get('text', '')}\\n\"                                                               \n            if 'comments' in item:                                                                                         \n                combined += f\"Comments: {' '.join(item['comments'])}\\n\"                                                    \n        return combined\n    \n",
        "idx": "654"
    },
    {
        "instruction": "## blog_generator.py\nfrom typing import Dict, List\n\nfrom anthropic import Anthropic\n\nimport os\n\nclass ClaudeBlogGenerator:                                                                                                 \n    def __init__(self):                                                                                                    \n        self.client = Anthropic(api_key=os.getenv('CLAUDE_API_KEY'))                                                       \n                                                                                                                            \n    def generate(self, content: List[Dict]) -> str:                                                                        \n        \"\"\"Generate blog content using Claude.\"\"\"                                                                          \n        try:                                                                                                               \n            # Prepare the content for the prompt                                                                           \n            combined_content = self._prepare_content(content)                                                              \n                                                                                                                            \n            # Generate blog using Claude                                                                                   \n            response = self.client.messages.create(                                                                        \n                model=\"claude-2\",                                                                                          \n                max_tokens=1000,                                                                                           \n                messages=[{                                                                                                \n                    \"role\": \"user\",                                                                                        \n                    \"content\": f\"Create a well-structured, engaging blog post from this content: {combined_content}\\n\\nInclude images with alt text accurately describing what the image is all about\"       \n                }]                                                                                                         \n            )                                                                                                              \n                                                                                                                            \n            return response.content[0].text                                                                                \n                                                                                                                            \n        except Exception as e:                                                                                             \n            raise Exception(f\"Failed to generate blog with Claude: {str(e)}\")                                              \n                                                                                                                            \n    def _prepare_content(self, content: List[Dict]) -> str:\n        \"\"\"\n        Prepare content for the AI prompt.\n        \"\"\"\n",
        "input": "",
        "output": "        combined = \"\"                                                                                                      \n        for item in content:                                                                                               \n            combined += f\"Title: {item.get('title', '')}\\n\"                                                                \n            combined += f\"Content: {item.get('text', '')}\\n\"                                                               \n            if 'comments' in item:                                                                                         \n                combined += f\"Comments: {' '.join(item['comments'])}\\n\"                                                    \n        return combined\n    \n",
        "idx": "655"
    },
    {
        "instruction": "# Here are some relevant code fragments from other files of the repo:\n# --------------------------------------------------\n# the below code fragment can be found in:\n# lib/data_types.py\n# --------------------------------------------------\n# import time\n# \n# from dataclasses import dataclass, field\n# \n# from typing import Dict, Any, Union, Tuple, Optional, Set, TypeVar, Generic, Type\n# \n# import psutil\n# \n# class SystemMetrics:\n#     \"\"\"General system metrics\"\"\"\n# \n#     model_loading_start: float\n#     model_loading_time: Union[float, None]\n#     last_disk_usage: float\n#     additional_disk_usage: float\n#     model_is_loaded: bool\n# \n#     @staticmethod\n#     def get_disk_usage_GB():\n#         return psutil.disk_usage(\"/\").used / (2**30)  # want units of GB\n# \n#     @classmethod\n#     def empty(cls):\n#         return cls(\n#             model_loading_start=time.time(),\n#             model_loading_time=None,\n#             last_disk_usage=SystemMetrics.get_disk_usage_GB(),\n#             additional_disk_usage=0.0,\n#             model_is_loaded=False,\n#         )\n# \n#     def update_disk_usage(self):\n#         disk_usage = SystemMetrics.get_disk_usage_GB()\n#         self.additional_disk_usage = disk_usage - self.last_disk_usage\n#         self.last_disk_usage = disk_usage\n# \n#     def reset(self):\n#         # autoscaler excepts model_loading_time to be populated only once, when the instance has\n#         # finished benchmarking and is ready to receive requests. This applies to restarted instances\n#         # as well: they should send model_loading_time once when they are done loading\n#         self.model_loading_time = None\n# \n# class ModelMetrics:\n#     \"\"\"Model specific metrics\"\"\"\n# \n#     # these are reset after being sent to autoscaler\n#     workload_served: float\n#     workload_received: float\n#     workload_cancelled: float\n#     workload_errored: float\n#     workload_pending: float\n#     # these are not\n#     cur_perf: float\n#     error_msg: Optional[str]\n#     max_throughput: float\n#     requests_recieved: Set[int] = field(default_factory=set)\n#     requests_working: Set[int] = field(default_factory=set)\n# \n#     @classmethod\n#     def empty(cls):\n#         return cls(\n#             workload_pending=0.0,\n#             workload_served=0.0,\n#             workload_cancelled=0.0,\n#             workload_errored=0.0,\n#             cur_perf=0.0,\n#             workload_received=0.0,\n#             error_msg=None,\n#             max_throughput=0.0,\n#         )\n# \n#     @property\n#     def workload_processing(self) -> float:\n#         return max(self.workload_received - self.workload_cancelled, 0.0)\n# \n#     def set_errored(self, error_msg):\n#         self.reset()\n#         self.error_msg = error_msg\n# \n#     def reset(self):\n#         self.workload_served = 0\n#         self.workload_received = 0\n#         self.workload_cancelled = 0\n#         self.workload_errored = 0\n# \n# class AutoScalaerData:\n#     \"\"\"Data that is reported to autoscaler\"\"\"\n# \n#     id: int\n#     loadtime: float\n#     cur_load: float\n#     error_msg: str\n#     max_perf: float\n#     cur_perf: float\n#     cur_capacity: float\n#     max_capacity: float\n#     num_requests_working: int\n#     num_requests_recieved: int\n#     additional_disk_usage: float\n#     url: str\n#     type: str\n#     provider: str\n# \n# --------------------------------------------------\n\n\n## lib/metrics.py\nfrom enum import Enum\n\nimport os\n\nimport time\n\nimport logging\n\nfrom asyncio import sleep\n\nfrom dataclasses import dataclass, asdict, field\n\nfrom functools import cache\n\nfrom urllib.parse import urljoin\n\nimport requests\n\nfrom lib.data_types import AutoScalaerData, SystemMetrics, ModelMetrics\n\nfrom typing import Awaitable, NoReturn, List\n\nclass InstanceProvider(Enum):\n    RUNPOD = \"runpod\"\n    VASTAI = \"vastai\"\n\nMETRICS_UPDATE_INTERVAL = 1\n\nlog = logging.getLogger(__file__)\n\ndef get_container_id() -> str:\n    return os.environ.get(\"CONTAINER_ID\", None) or os.environ.get(\n        \"RUNPOD_POD_ID\", \"unknown\"\n    )\n\ndef is_runpod_provider() -> bool:\n    return os.environ.get(\"PROVIDER\", None) == \"runpod\"\n\ndef get_provider() -> str:\n    if is_runpod_provider():\n        return InstanceProvider.RUNPOD.value\n    return InstanceProvider.VASTAI.value\n\ndef get_url() -> str:\n    internal_worker_port = os.environ[\"WORKER_PORT\"]\n    if is_runpod_provider():\n        runpod_id = os.environ[\"RUNPOD_POD_ID\"]\n        return f\"https://{runpod_id}-{internal_worker_port}.proxy.runpod.net\"\n    use_ssl = os.environ.get(\"USE_SSL\", \"false\") == \"true\"\n    worker_port = os.environ[f\"VAST_TCP_PORT_{internal_worker_port}\"]\n    public_ip = os.environ[\"PUBLIC_IPADDR\"]\n    return f\"http{'s' if use_ssl else ''}://{public_ip}:{worker_port}\"\n\nclass Metrics:\n    last_metric_update: float = 0.0\n    update_pending: bool = False\n    id: str = field(default_factory=lambda: get_container_id())\n    report_addr: List[str] = field(\n        default_factory=lambda: os.environ[\"REPORT_ADDR\"].split(\",\")\n    )\n    url: str = field(default_factory=get_url)\n    system_metrics: SystemMetrics = field(default_factory=SystemMetrics.empty)\n    model_metrics: ModelMetrics = field(default_factory=ModelMetrics.empty)\n\n    def _request_start(self, workload: float, reqnum: int) -> None:\n        \"\"\"\n        this function is called prior to forwarding a request to a model API.\n        \"\"\"\n        log.debug(\"request start\")\n        self.model_metrics.workload_pending += workload\n        self.model_metrics.workload_received += workload\n        self.model_metrics.requests_recieved.add(reqnum)\n        self.model_metrics.requests_working.add(reqnum)\n\n    def _request_end(\n        self, workload: float, req_response_time: float, reqnum: int\n    ) -> None:\n        \"\"\"\n        this function is called after a response from model API is received.\n        \"\"\"\n        self.model_metrics.workload_served += workload\n        self.model_metrics.workload_pending -= workload\n        self.model_metrics.requests_working.discard(reqnum)\n        self.model_metrics.cur_perf = workload / req_response_time\n        self.update_pending = True\n\n    def _request_errored(self, workload: float, reqnum: int) -> None:\n        \"\"\"\n        this function is called if model API returns an error\n        \"\"\"\n        self.model_metrics.workload_pending -= workload\n        self.model_metrics.workload_errored += workload\n        self.model_metrics.requests_working.discard(reqnum)\n\n    def _request_canceled(self, workload: float, reqnum: int) -> None:\n        \"\"\"\n        this function is called if client drops connection before model API has responded\n        \"\"\"\n",
        "input": "",
        "output": "        self.model_metrics.workload_pending -= workload\n        self.model_metrics.workload_cancelled += workload\n        self.model_metrics.requests_working.discard(reqnum)\n    \n",
        "idx": "666"
    },
    {
        "instruction": "## lib/data_types.py\nimport time\n\nfrom dataclasses import dataclass, field\n\nfrom typing import Dict, Any, Union, Tuple, Optional, Set, TypeVar, Generic, Type\n\nimport psutil\n\nclass SystemMetrics:\n    \"\"\"General system metrics\"\"\"\n\n    model_loading_start: float\n    model_loading_time: Union[float, None]\n    last_disk_usage: float\n    additional_disk_usage: float\n    model_is_loaded: bool\n\n    @staticmethod\n    def get_disk_usage_GB():\n        return psutil.disk_usage(\"/\").used / (2**30)  # want units of GB\n\n    @classmethod\n    def empty(cls):\n        return cls(\n            model_loading_start=time.time(),\n            model_loading_time=None,\n            last_disk_usage=SystemMetrics.get_disk_usage_GB(),\n            additional_disk_usage=0.0,\n            model_is_loaded=False,\n        )\n\n    def update_disk_usage(self):\n",
        "input": "",
        "output": "        disk_usage = SystemMetrics.get_disk_usage_GB()\n        self.additional_disk_usage = disk_usage - self.last_disk_usage\n        self.last_disk_usage = disk_usage\n    \n",
        "idx": "671"
    },
    {
        "instruction": "## lib/data_types.py\nfrom dataclasses import dataclass, field\n\nfrom typing import Dict, Any, Union, Tuple, Optional, Set, TypeVar, Generic, Type\n\nclass ModelMetrics:\n    \"\"\"Model specific metrics\"\"\"\n\n    # these are reset after being sent to autoscaler\n    workload_served: float\n    workload_received: float\n    workload_cancelled: float\n    workload_errored: float\n    workload_pending: float\n    # these are not\n    cur_perf: float\n    error_msg: Optional[str]\n    max_throughput: float\n    requests_recieved: Set[int] = field(default_factory=set)\n    requests_working: Set[int] = field(default_factory=set)\n\n    @classmethod\n    def empty(cls):\n        return cls(\n            workload_pending=0.0,\n            workload_served=0.0,\n            workload_cancelled=0.0,\n            workload_errored=0.0,\n            cur_perf=0.0,\n            workload_received=0.0,\n            error_msg=None,\n            max_throughput=0.0,\n        )\n\n    @property\n    def workload_processing(self) -> float:\n        return max(self.workload_received - self.workload_cancelled, 0.0)\n\n    def set_errored(self, error_msg):\n        self.reset()\n        self.error_msg = error_msg\n\n    def reset(self):\n",
        "input": "",
        "output": "        self.workload_served = 0\n        self.workload_received = 0\n        self.workload_cancelled = 0\n        self.workload_errored = 0\n    \n",
        "idx": "672"
    },
    {
        "instruction": "## workers/vision/data_types.py\nimport dataclasses\n\nimport inspect\n\nfrom typing import Dict, Any\n\nfrom lib.data_types import ApiPayload, JsonDataException\n\nclass InputParameters:\n    max_new_tokens: int = 256\n\n    @classmethod\n    def from_json_msg(cls, json_msg: Dict[str, Any]) -> 'InputParameters':\n",
        "input": "",
        "output": "        errors = {}\n        for param in inspect.signature(cls).parameters:\n            if param not in json_msg:\n                errors[param] = \"missing parameter\"\n        if errors:\n            raise JsonDataException(errors)\n        return cls(\n            **{\n                k: v\n                for k, v in json_msg.items()\n                if k in inspect.signature(cls).parameters\n            }\n        )\n    \n",
        "idx": "674"
    },
    {
        "instruction": "\ndef _generate_base_unit(current_class: str, units: dict[str, str]) -> list[str]:\n",
        "input": "",
        "output": "    base_unit = None\n    for unit, factor in units.items():\n        if float(eval(factor)) == 1:\n            base_unit = unit\n            break\n\n    if base_unit is None:\n        raise ValueError(f\"{current_class} needs a unit with factor equal to 1.\")\n\n    return [f'    BASE_UNIT = \"{base_unit}\"', \"\"]\n\n",
        "idx": "676"
    },
    {
        "instruction": "## generate/generate_boilerplate.py\ndef _indent(text: str, number_of_indents: int) -> str:\n    return \" \" * 4 * number_of_indents + text\n\ndef _generate_properties(current_class: str, units: dict[str, str]) -> list[str]:\n",
        "input": "",
        "output": "    code = []\n\n    for unit, factor in units.items():\n        code.append(_indent(\"@property\", 1))\n        code.append(_indent(f\"def {unit}(self) -> float:\", 1))\n        code.append(_indent(f'\"\"\"The {current_class.lower()} in {unit.replace(\"_\", \" \")}.\"\"\"', 2))\n        code.append(_indent(f\"return self._base_value / {factor}\", 2))\n        code.append(\"\")\n\n    return code\n\n",
        "idx": "677"
    },
    {
        "instruction": "## generate/generate_boilerplate.py\ndef _indent(text: str, number_of_indents: int) -> str:\n    return \" \" * 4 * number_of_indents + text\n\ndef _generate_init(units: dict[str, str]) -> list[str]:\n",
        "input": "",
        "output": "    code = [\n        _indent(\"def __init__(\", 1),\n        _indent(\"self,\", 2),\n        _indent(\"_base_value: float = 0.0,\", 2),\n    ]\n\n    for unit in units:\n        code.append(_indent(f\"{unit}: float | None = None,\", 2))\n\n    code.append(_indent(\") -> None:\", 1))\n    code.append(_indent(\"self._base_value = _base_value\", 2))\n\n    for unit, factor in units.items():\n        code.append(_indent(f\"if {unit} is not None:\", 2))\n        code.append(_indent(f\"self._base_value += {unit} * {factor}\", 3))\n\n    code.append(\"\")\n    return code\n\n",
        "idx": "678"
    },
    {
        "instruction": "# Here are some relevant code fragments from other files of the repo:\n# --------------------------------------------------\n# the below code fragment can be found in:\n# quantio/exceptions.py\n# --------------------------------------------------\n# class CanNotAddTypesError(TypeError):\n#     \"\"\"Raised when two uncompatible quantities are added to one another.\"\"\"\n# \n#     def __init__(self, self_type_descriptor: str, other_type_descriptor: str) -> None:\n#         super().__init__(f\"Can not add {other_type_descriptor} to {self_type_descriptor}\")\n# \n# class CanNotSubtractTypesError(TypeError):\n#     \"\"\"Raised when two uncompatible quantities are subtracted from one another.\"\"\"\n# \n#     def __init__(self, self_type_descriptor: str, other_type_descriptor: str) -> None:\n#         super().__init__(f\"Can not subtract {other_type_descriptor} from {self_type_descriptor}\")\n# \n# --------------------------------------------------\n\n\n## quantio/quantities.py\nfrom abc import ABC\n\nfrom .exceptions import CanNotAddTypesError, CanNotSubtractTypesError\n\nclass Quantity(ABC):\n    \"\"\"Parent class to all quantities.\"\"\"\n\n    _base_value: float\n    \"The base unit of the quantity.\"\n\n    BASE_UNIT: str\n    \"Name of the unit with a factor of 1.\"\n\n    def __eq__(self, other: object) -> bool:\n        \"\"\"Assess if this object is the same as another.\"\"\"\n        if isinstance(other, type(self)):\n            return self._base_value == other._base_value\n\n        return False\n\n    def __add__(self, other: Quantity) -> Quantity:\n        \"\"\"Add two quantities of the same type.\"\"\"\n        if type(self) is not type(other):\n            raise CanNotAddTypesError(self.__class__.__name__, other.__class__.__name__)\n\n        result = type(self)()\n        result._base_value = self._base_value + other._base_value\n        return result\n\n    def __sub__(self, other: Quantity) -> Quantity:\n        \"\"\"Subtract two quantities of the same type.\"\"\"\n        if type(self) is not type(other):\n            raise CanNotSubtractTypesError(self.__class__.__name__, other.__class__.__name__)\n\n        result = type(self)()\n        result._base_value = self._base_value - other._base_value\n        return result\n\n    def __repr__(self) -> str:\n        \"\"\"Return an unambiguous representation of this quantity.\"\"\"\n        return self.__str__()\n\nclass Area(Quantity):\n    \"\"\"The two-dimensional extent of an object.\"\"\"\n\n    # --- This part is auto generated. Do not change manually. ---\n\n    BASE_UNIT = \"square_meters\"\n\n    @property\n    def square_miles(self) -> float:\n        \"\"\"The area in square miles.\"\"\"\n        return self._base_value / 1609.34**2\n\n    @property\n    def square_kilometers(self) -> float:\n        \"\"\"The area in square kilometers.\"\"\"\n        return self._base_value / 10 ** (3 * 2)\n\n    @property\n    def square_meters(self) -> float:\n        \"\"\"The area in square meters.\"\"\"\n        return self._base_value / 1\n\n    @property\n    def square_feet(self) -> float:\n        \"\"\"The area in square feet.\"\"\"\n        return self._base_value / 0.3048**2\n\n    @property\n    def square_inches(self) -> float:\n        \"\"\"The area in square inches.\"\"\"\n        return self._base_value / 0.0254**2\n\n    @property\n    def square_centimeters(self) -> float:\n        \"\"\"The area in square centimeters.\"\"\"\n        return self._base_value / 10 ** (-2 * 2)\n\n    @property\n    def square_millimeters(self) -> float:\n        \"\"\"The area in square millimeters.\"\"\"\n        return self._base_value / 10 ** (-3 * 2)\n\n    @property\n    def square_micrometers(self) -> float:\n        \"\"\"The area in square micrometers.\"\"\"\n        return self._base_value / 10 ** (-6 * 2)\n\n    def __init__(\n        self,\n        _base_value: float = 0.0,\n        square_miles: float | None = None,\n        square_kilometers: float | None = None,\n        square_meters: float | None = None,\n        square_feet: float | None = None,\n        square_inches: float | None = None,\n        square_centimeters: float | None = None,\n        square_millimeters: float | None = None,\n        square_micrometers: float | None = None,\n    ) -> None:\n        self._base_value = _base_value\n        if square_miles is not None:\n            self._base_value += square_miles * 1609.34**2\n        if square_kilometers is not None:\n            self._base_value += square_kilometers * 10 ** (3 * 2)\n        if square_meters is not None:\n            self._base_value += square_meters * 1\n        if square_feet is not None:\n            self._base_value += square_feet * 0.3048**2\n        if square_inches is not None:\n            self._base_value += square_inches * 0.0254**2\n        if square_centimeters is not None:\n            self._base_value += square_centimeters * 10 ** (-2 * 2)\n        if square_millimeters is not None:\n            self._base_value += square_millimeters * 10 ** (-3 * 2)\n        if square_micrometers is not None:\n            self._base_value += square_micrometers * 10 ** (-6 * 2)\n\n    @classmethod\n    def zero(cls) -> Area:\n        \"\"\"\n        Create a Area with a value of zero.\n        \"\"\"\n",
        "input": "",
        "output": "        return Area()\n    \n",
        "idx": "679"
    },
    {
        "instruction": "# Here are some relevant code fragments from other files of the repo:\n# --------------------------------------------------\n# the below code fragment can be found in:\n# quantio/exceptions.py\n# --------------------------------------------------\n# class CanNotAddTypesError(TypeError):\n#     \"\"\"Raised when two uncompatible quantities are added to one another.\"\"\"\n# \n#     def __init__(self, self_type_descriptor: str, other_type_descriptor: str) -> None:\n#         super().__init__(f\"Can not add {other_type_descriptor} to {self_type_descriptor}\")\n# \n# class CanNotSubtractTypesError(TypeError):\n#     \"\"\"Raised when two uncompatible quantities are subtracted from one another.\"\"\"\n# \n#     def __init__(self, self_type_descriptor: str, other_type_descriptor: str) -> None:\n#         super().__init__(f\"Can not subtract {other_type_descriptor} from {self_type_descriptor}\")\n# \n# --------------------------------------------------\n\n\n## quantio/quantities.py\nfrom abc import ABC\n\nfrom .exceptions import CanNotAddTypesError, CanNotSubtractTypesError\n\nclass Quantity(ABC):\n    \"\"\"Parent class to all quantities.\"\"\"\n\n    _base_value: float\n    \"The base unit of the quantity.\"\n\n    BASE_UNIT: str\n    \"Name of the unit with a factor of 1.\"\n\n    def __eq__(self, other: object) -> bool:\n        \"\"\"Assess if this object is the same as another.\"\"\"\n        if isinstance(other, type(self)):\n            return self._base_value == other._base_value\n\n        return False\n\n    def __add__(self, other: Quantity) -> Quantity:\n        \"\"\"Add two quantities of the same type.\"\"\"\n        if type(self) is not type(other):\n            raise CanNotAddTypesError(self.__class__.__name__, other.__class__.__name__)\n\n        result = type(self)()\n        result._base_value = self._base_value + other._base_value\n        return result\n\n    def __sub__(self, other: Quantity) -> Quantity:\n        \"\"\"Subtract two quantities of the same type.\"\"\"\n        if type(self) is not type(other):\n            raise CanNotSubtractTypesError(self.__class__.__name__, other.__class__.__name__)\n\n        result = type(self)()\n        result._base_value = self._base_value - other._base_value\n        return result\n\n    def __repr__(self) -> str:\n        \"\"\"Return an unambiguous representation of this quantity.\"\"\"\n        return self.__str__()\n\nclass ElectricCurrent(Quantity):\n    \"\"\"The flow of charged particles moving through an electrical conductor or space.\"\"\"\n\n    # --- This part is auto generated. Do not change manually. ---\n\n    BASE_UNIT = \"amperes\"\n\n    @property\n    def gigaamperes(self) -> float:\n        \"\"\"The electriccurrent in gigaamperes.\"\"\"\n        return self._base_value / 10**9\n\n    @property\n    def megaamperes(self) -> float:\n        \"\"\"The electriccurrent in megaamperes.\"\"\"\n        return self._base_value / 10**6\n\n    @property\n    def kiloamperes(self) -> float:\n        \"\"\"The electriccurrent in kiloamperes.\"\"\"\n        return self._base_value / 10**3\n\n    @property\n    def amperes(self) -> float:\n        \"\"\"The electriccurrent in amperes.\"\"\"\n        return self._base_value / 1\n\n    @property\n    def milliamperes(self) -> float:\n        \"\"\"The electriccurrent in milliamperes.\"\"\"\n        return self._base_value / 10**-3\n\n    def __init__(\n        self,\n        _base_value: float = 0.0,\n        gigaamperes: float | None = None,\n        megaamperes: float | None = None,\n        kiloamperes: float | None = None,\n        amperes: float | None = None,\n        milliamperes: float | None = None,\n    ) -> None:\n        self._base_value = _base_value\n        if gigaamperes is not None:\n            self._base_value += gigaamperes * 10**9\n        if megaamperes is not None:\n            self._base_value += megaamperes * 10**6\n        if kiloamperes is not None:\n            self._base_value += kiloamperes * 10**3\n        if amperes is not None:\n            self._base_value += amperes * 1\n        if milliamperes is not None:\n            self._base_value += milliamperes * 10**-3\n\n    @classmethod\n    def zero(cls) -> ElectricCurrent:\n        \"\"\"\n        Create a ElectricCurrent with a value of zero.\n        \"\"\"\n",
        "input": "",
        "output": "        return ElectricCurrent()\n    \n",
        "idx": "680"
    },
    {
        "instruction": "# Here are some relevant code fragments from other files of the repo:\n# --------------------------------------------------\n# the below code fragment can be found in:\n# quantio/exceptions.py\n# --------------------------------------------------\n# class CanNotAddTypesError(TypeError):\n#     \"\"\"Raised when two uncompatible quantities are added to one another.\"\"\"\n# \n#     def __init__(self, self_type_descriptor: str, other_type_descriptor: str) -> None:\n#         super().__init__(f\"Can not add {other_type_descriptor} to {self_type_descriptor}\")\n# \n# class CanNotSubtractTypesError(TypeError):\n#     \"\"\"Raised when two uncompatible quantities are subtracted from one another.\"\"\"\n# \n#     def __init__(self, self_type_descriptor: str, other_type_descriptor: str) -> None:\n#         super().__init__(f\"Can not subtract {other_type_descriptor} from {self_type_descriptor}\")\n# \n# --------------------------------------------------\n\n\n## quantio/quantities.py\nfrom abc import ABC\n\nfrom .exceptions import CanNotAddTypesError, CanNotSubtractTypesError\n\nclass Quantity(ABC):\n    \"\"\"Parent class to all quantities.\"\"\"\n\n    _base_value: float\n    \"The base unit of the quantity.\"\n\n    BASE_UNIT: str\n    \"Name of the unit with a factor of 1.\"\n\n    def __eq__(self, other: object) -> bool:\n        \"\"\"Assess if this object is the same as another.\"\"\"\n        if isinstance(other, type(self)):\n            return self._base_value == other._base_value\n\n        return False\n\n    def __add__(self, other: Quantity) -> Quantity:\n        \"\"\"Add two quantities of the same type.\"\"\"\n        if type(self) is not type(other):\n            raise CanNotAddTypesError(self.__class__.__name__, other.__class__.__name__)\n\n        result = type(self)()\n        result._base_value = self._base_value + other._base_value\n        return result\n\n    def __sub__(self, other: Quantity) -> Quantity:\n        \"\"\"Subtract two quantities of the same type.\"\"\"\n        if type(self) is not type(other):\n            raise CanNotSubtractTypesError(self.__class__.__name__, other.__class__.__name__)\n\n        result = type(self)()\n        result._base_value = self._base_value - other._base_value\n        return result\n\n    def __repr__(self) -> str:\n        \"\"\"Return an unambiguous representation of this quantity.\"\"\"\n        return self.__str__()\n\nclass Angle(Quantity):\n    \"\"\"The figure formed by two rays.\"\"\"\n\n    # --- This part is auto generated. Do not change manually. ---\n\n    BASE_UNIT = \"radians\"\n\n    @property\n    def degrees(self) -> float:\n        \"\"\"The angle in degrees.\"\"\"\n        return self._base_value / (3.141592653589793 / 180)\n\n    @property\n    def radians(self) -> float:\n        \"\"\"The angle in radians.\"\"\"\n        return self._base_value / 1\n\n    def __init__(\n        self,\n        _base_value: float = 0.0,\n        degrees: float | None = None,\n        radians: float | None = None,\n    ) -> None:\n        self._base_value = _base_value\n        if degrees is not None:\n            self._base_value += degrees * (3.141592653589793 / 180)\n        if radians is not None:\n            self._base_value += radians * 1\n\n    @classmethod\n    def zero(cls) -> Angle:\n        \"\"\"\n        Create a Angle with a value of zero.\n        \"\"\"\n",
        "input": "",
        "output": "        return Angle()\n    \n",
        "idx": "681"
    },
    {
        "instruction": "# Here are some relevant code fragments from other files of the repo:\n# --------------------------------------------------\n# the below code fragment can be found in:\n# quantio/exceptions.py\n# --------------------------------------------------\n# class CanNotAddTypesError(TypeError):\n#     \"\"\"Raised when two uncompatible quantities are added to one another.\"\"\"\n# \n#     def __init__(self, self_type_descriptor: str, other_type_descriptor: str) -> None:\n#         super().__init__(f\"Can not add {other_type_descriptor} to {self_type_descriptor}\")\n# \n# class CanNotSubtractTypesError(TypeError):\n#     \"\"\"Raised when two uncompatible quantities are subtracted from one another.\"\"\"\n# \n#     def __init__(self, self_type_descriptor: str, other_type_descriptor: str) -> None:\n#         super().__init__(f\"Can not subtract {other_type_descriptor} from {self_type_descriptor}\")\n# \n# --------------------------------------------------\n\n\n## quantio/quantities.py\nfrom abc import ABC\n\nfrom .exceptions import CanNotAddTypesError, CanNotSubtractTypesError\n\nclass Quantity(ABC):\n    \"\"\"Parent class to all quantities.\"\"\"\n\n    _base_value: float\n    \"The base unit of the quantity.\"\n\n    BASE_UNIT: str\n    \"Name of the unit with a factor of 1.\"\n\n    def __eq__(self, other: object) -> bool:\n        \"\"\"Assess if this object is the same as another.\"\"\"\n        if isinstance(other, type(self)):\n            return self._base_value == other._base_value\n\n        return False\n\n    def __add__(self, other: Quantity) -> Quantity:\n        \"\"\"Add two quantities of the same type.\"\"\"\n        if type(self) is not type(other):\n            raise CanNotAddTypesError(self.__class__.__name__, other.__class__.__name__)\n\n        result = type(self)()\n        result._base_value = self._base_value + other._base_value\n        return result\n\n    def __sub__(self, other: Quantity) -> Quantity:\n        \"\"\"Subtract two quantities of the same type.\"\"\"\n        if type(self) is not type(other):\n            raise CanNotSubtractTypesError(self.__class__.__name__, other.__class__.__name__)\n\n        result = type(self)()\n        result._base_value = self._base_value - other._base_value\n        return result\n\n    def __repr__(self) -> str:\n        \"\"\"Return an unambiguous representation of this quantity.\"\"\"\n        return self.__str__()\n\nclass Length(Quantity):\n    \"\"\"The one-dimensional extent of an object or the distance between two points.\"\"\"\n\n    # --- This part is auto generated. Do not change manually. ---\n\n    BASE_UNIT = \"meters\"\n\n    @property\n    def miles(self) -> float:\n        \"\"\"The length in miles.\"\"\"\n        return self._base_value / 1609.34\n\n    @property\n    def kilometers(self) -> float:\n        \"\"\"The length in kilometers.\"\"\"\n        return self._base_value / 10**3\n\n    @property\n    def meters(self) -> float:\n        \"\"\"The length in meters.\"\"\"\n        return self._base_value / 1\n\n    @property\n    def feet(self) -> float:\n        \"\"\"The length in feet.\"\"\"\n        return self._base_value / 0.3048\n\n    @property\n    def inches(self) -> float:\n        \"\"\"The length in inches.\"\"\"\n        return self._base_value / 0.0254\n\n    @property\n    def centimeters(self) -> float:\n        \"\"\"The length in centimeters.\"\"\"\n        return self._base_value / 10**-2\n\n    @property\n    def millimeters(self) -> float:\n        \"\"\"The length in millimeters.\"\"\"\n        return self._base_value / 10**-3\n\n    @property\n    def micrometers(self) -> float:\n        \"\"\"The length in micrometers.\"\"\"\n        return self._base_value / 10**-6\n\n    def __init__(\n        self,\n        _base_value: float = 0.0,\n        miles: float | None = None,\n        kilometers: float | None = None,\n        meters: float | None = None,\n        feet: float | None = None,\n        inches: float | None = None,\n        centimeters: float | None = None,\n        millimeters: float | None = None,\n        micrometers: float | None = None,\n    ) -> None:\n        self._base_value = _base_value\n        if miles is not None:\n            self._base_value += miles * 1609.34\n        if kilometers is not None:\n            self._base_value += kilometers * 10**3\n        if meters is not None:\n            self._base_value += meters * 1\n        if feet is not None:\n            self._base_value += feet * 0.3048\n        if inches is not None:\n            self._base_value += inches * 0.0254\n        if centimeters is not None:\n            self._base_value += centimeters * 10**-2\n        if millimeters is not None:\n            self._base_value += millimeters * 10**-3\n        if micrometers is not None:\n            self._base_value += micrometers * 10**-6\n\n    @classmethod\n    def zero(cls) -> Length:\n        \"\"\"\n        Create a Length with a value of zero.\n        \"\"\"\n",
        "input": "",
        "output": "        return Length()\n    \n",
        "idx": "682"
    },
    {
        "instruction": "# Here are some relevant code fragments from other files of the repo:\n# --------------------------------------------------\n# the below code fragment can be found in:\n# quantio/exceptions.py\n# --------------------------------------------------\n# class CanNotAddTypesError(TypeError):\n#     \"\"\"Raised when two uncompatible quantities are added to one another.\"\"\"\n# \n#     def __init__(self, self_type_descriptor: str, other_type_descriptor: str) -> None:\n#         super().__init__(f\"Can not add {other_type_descriptor} to {self_type_descriptor}\")\n# \n# class CanNotSubtractTypesError(TypeError):\n#     \"\"\"Raised when two uncompatible quantities are subtracted from one another.\"\"\"\n# \n#     def __init__(self, self_type_descriptor: str, other_type_descriptor: str) -> None:\n#         super().__init__(f\"Can not subtract {other_type_descriptor} from {self_type_descriptor}\")\n# \n# --------------------------------------------------\n\n\n## quantio/quantities.py\nfrom abc import ABC\n\nfrom .exceptions import CanNotAddTypesError, CanNotSubtractTypesError\n\nclass Quantity(ABC):\n    \"\"\"Parent class to all quantities.\"\"\"\n\n    _base_value: float\n    \"The base unit of the quantity.\"\n\n    BASE_UNIT: str\n    \"Name of the unit with a factor of 1.\"\n\n    def __eq__(self, other: object) -> bool:\n        \"\"\"Assess if this object is the same as another.\"\"\"\n        if isinstance(other, type(self)):\n            return self._base_value == other._base_value\n\n        return False\n\n    def __add__(self, other: Quantity) -> Quantity:\n        \"\"\"Add two quantities of the same type.\"\"\"\n        if type(self) is not type(other):\n            raise CanNotAddTypesError(self.__class__.__name__, other.__class__.__name__)\n\n        result = type(self)()\n        result._base_value = self._base_value + other._base_value\n        return result\n\n    def __sub__(self, other: Quantity) -> Quantity:\n        \"\"\"Subtract two quantities of the same type.\"\"\"\n        if type(self) is not type(other):\n            raise CanNotSubtractTypesError(self.__class__.__name__, other.__class__.__name__)\n\n        result = type(self)()\n        result._base_value = self._base_value - other._base_value\n        return result\n\n    def __repr__(self) -> str:\n        \"\"\"Return an unambiguous representation of this quantity.\"\"\"\n        return self.__str__()\n\nclass Frequency(Quantity):\n    \"\"\"The number of occurrences of a repeating event per unit of time.\"\"\"\n\n    # --- This part is auto generated. Do not change manually. ---\n\n    BASE_UNIT = \"hertz\"\n\n    @property\n    def gigahertz(self) -> float:\n        \"\"\"The frequency in gigahertz.\"\"\"\n        return self._base_value / 10**9\n\n    @property\n    def megahertz(self) -> float:\n        \"\"\"The frequency in megahertz.\"\"\"\n        return self._base_value / 10**6\n\n    @property\n    def kilohertz(self) -> float:\n        \"\"\"The frequency in kilohertz.\"\"\"\n        return self._base_value / 10**3\n\n    @property\n    def hertz(self) -> float:\n        \"\"\"The frequency in hertz.\"\"\"\n        return self._base_value / 1\n\n    def __init__(\n        self,\n        _base_value: float = 0.0,\n        gigahertz: float | None = None,\n        megahertz: float | None = None,\n        kilohertz: float | None = None,\n        hertz: float | None = None,\n    ) -> None:\n        self._base_value = _base_value\n        if gigahertz is not None:\n            self._base_value += gigahertz * 10**9\n        if megahertz is not None:\n            self._base_value += megahertz * 10**6\n        if kilohertz is not None:\n            self._base_value += kilohertz * 10**3\n        if hertz is not None:\n            self._base_value += hertz * 1\n\n    @classmethod\n    def zero(cls) -> Frequency:\n        \"\"\"\n        Create a Frequency with a value of zero.\n        \"\"\"\n",
        "input": "",
        "output": "        return Frequency()\n    \n",
        "idx": "683"
    },
    {
        "instruction": "# Here are some relevant code fragments from other files of the repo:\n# --------------------------------------------------\n# the below code fragment can be found in:\n# quantio/exceptions.py\n# --------------------------------------------------\n# class CanNotAddTypesError(TypeError):\n#     \"\"\"Raised when two uncompatible quantities are added to one another.\"\"\"\n# \n#     def __init__(self, self_type_descriptor: str, other_type_descriptor: str) -> None:\n#         super().__init__(f\"Can not add {other_type_descriptor} to {self_type_descriptor}\")\n# \n# class CanNotSubtractTypesError(TypeError):\n#     \"\"\"Raised when two uncompatible quantities are subtracted from one another.\"\"\"\n# \n#     def __init__(self, self_type_descriptor: str, other_type_descriptor: str) -> None:\n#         super().__init__(f\"Can not subtract {other_type_descriptor} from {self_type_descriptor}\")\n# \n# --------------------------------------------------\n\n\n## quantio/quantities.py\nfrom abc import ABC\n\nfrom .exceptions import CanNotAddTypesError, CanNotSubtractTypesError\n\nclass Quantity(ABC):\n    \"\"\"Parent class to all quantities.\"\"\"\n\n    _base_value: float\n    \"The base unit of the quantity.\"\n\n    BASE_UNIT: str\n    \"Name of the unit with a factor of 1.\"\n\n    def __eq__(self, other: object) -> bool:\n        \"\"\"Assess if this object is the same as another.\"\"\"\n        if isinstance(other, type(self)):\n            return self._base_value == other._base_value\n\n        return False\n\n    def __add__(self, other: Quantity) -> Quantity:\n        \"\"\"Add two quantities of the same type.\"\"\"\n        if type(self) is not type(other):\n            raise CanNotAddTypesError(self.__class__.__name__, other.__class__.__name__)\n\n        result = type(self)()\n        result._base_value = self._base_value + other._base_value\n        return result\n\n    def __sub__(self, other: Quantity) -> Quantity:\n        \"\"\"Subtract two quantities of the same type.\"\"\"\n        if type(self) is not type(other):\n            raise CanNotSubtractTypesError(self.__class__.__name__, other.__class__.__name__)\n\n        result = type(self)()\n        result._base_value = self._base_value - other._base_value\n        return result\n\n    def __repr__(self) -> str:\n        \"\"\"Return an unambiguous representation of this quantity.\"\"\"\n        return self.__str__()\n\nclass Energy(Quantity):\n    \"\"\"Energy describes the ability of an object to perform work.\"\"\"\n\n    # --- This part is auto generated. Do not change manually. ---\n\n    BASE_UNIT = \"joules\"\n\n    @property\n    def gigajoules(self) -> float:\n        \"\"\"The energy in gigajoules.\"\"\"\n        return self._base_value / 10**9\n\n    @property\n    def megajoules(self) -> float:\n        \"\"\"The energy in megajoules.\"\"\"\n        return self._base_value / 10**6\n\n    @property\n    def kilojoules(self) -> float:\n        \"\"\"The energy in kilojoules.\"\"\"\n        return self._base_value / 10**3\n\n    @property\n    def joules(self) -> float:\n        \"\"\"The energy in joules.\"\"\"\n        return self._base_value / 1\n\n    @property\n    def millijoules(self) -> float:\n        \"\"\"The energy in millijoules.\"\"\"\n        return self._base_value / 10**-3\n\n    def __init__(\n        self,\n        _base_value: float = 0.0,\n        gigajoules: float | None = None,\n        megajoules: float | None = None,\n        kilojoules: float | None = None,\n        joules: float | None = None,\n        millijoules: float | None = None,\n    ) -> None:\n        self._base_value = _base_value\n        if gigajoules is not None:\n            self._base_value += gigajoules * 10**9\n        if megajoules is not None:\n            self._base_value += megajoules * 10**6\n        if kilojoules is not None:\n            self._base_value += kilojoules * 10**3\n        if joules is not None:\n            self._base_value += joules * 1\n        if millijoules is not None:\n            self._base_value += millijoules * 10**-3\n\n    @classmethod\n    def zero(cls) -> Energy:\n        \"\"\"\n        Create a Energy with a value of zero.\n        \"\"\"\n",
        "input": "",
        "output": "        return Energy()\n    \n",
        "idx": "684"
    },
    {
        "instruction": "# Here are some relevant code fragments from other files of the repo:\n# --------------------------------------------------\n# the below code fragment can be found in:\n# quantio/exceptions.py\n# --------------------------------------------------\n# class CanNotAddTypesError(TypeError):\n#     \"\"\"Raised when two uncompatible quantities are added to one another.\"\"\"\n# \n#     def __init__(self, self_type_descriptor: str, other_type_descriptor: str) -> None:\n#         super().__init__(f\"Can not add {other_type_descriptor} to {self_type_descriptor}\")\n# \n# class CanNotSubtractTypesError(TypeError):\n#     \"\"\"Raised when two uncompatible quantities are subtracted from one another.\"\"\"\n# \n#     def __init__(self, self_type_descriptor: str, other_type_descriptor: str) -> None:\n#         super().__init__(f\"Can not subtract {other_type_descriptor} from {self_type_descriptor}\")\n# \n# --------------------------------------------------\n\n\n## quantio/quantities.py\nfrom abc import ABC\n\nfrom .exceptions import CanNotAddTypesError, CanNotSubtractTypesError\n\nclass Quantity(ABC):\n    \"\"\"Parent class to all quantities.\"\"\"\n\n    _base_value: float\n    \"The base unit of the quantity.\"\n\n    BASE_UNIT: str\n    \"Name of the unit with a factor of 1.\"\n\n    def __eq__(self, other: object) -> bool:\n        \"\"\"Assess if this object is the same as another.\"\"\"\n        if isinstance(other, type(self)):\n            return self._base_value == other._base_value\n\n        return False\n\n    def __add__(self, other: Quantity) -> Quantity:\n        \"\"\"Add two quantities of the same type.\"\"\"\n        if type(self) is not type(other):\n            raise CanNotAddTypesError(self.__class__.__name__, other.__class__.__name__)\n\n        result = type(self)()\n        result._base_value = self._base_value + other._base_value\n        return result\n\n    def __sub__(self, other: Quantity) -> Quantity:\n        \"\"\"Subtract two quantities of the same type.\"\"\"\n        if type(self) is not type(other):\n            raise CanNotSubtractTypesError(self.__class__.__name__, other.__class__.__name__)\n\n        result = type(self)()\n        result._base_value = self._base_value - other._base_value\n        return result\n\n    def __repr__(self) -> str:\n        \"\"\"Return an unambiguous representation of this quantity.\"\"\"\n        return self.__str__()\n\nclass Power(Quantity):\n    \"\"\"The amount of energy transferred or converted per unit time.\"\"\"\n\n    # --- This part is auto generated. Do not change manually. ---\n\n    BASE_UNIT = \"watts\"\n\n    @property\n    def gigawatts(self) -> float:\n        \"\"\"The power in gigawatts.\"\"\"\n        return self._base_value / 10**9\n\n    @property\n    def megawatts(self) -> float:\n        \"\"\"The power in megawatts.\"\"\"\n        return self._base_value / 10**6\n\n    @property\n    def kilowatts(self) -> float:\n        \"\"\"The power in kilowatts.\"\"\"\n        return self._base_value / 10**3\n\n    @property\n    def watts(self) -> float:\n        \"\"\"The power in watts.\"\"\"\n        return self._base_value / 1\n\n    @property\n    def milliwatts(self) -> float:\n        \"\"\"The power in milliwatts.\"\"\"\n        return self._base_value / 10**-3\n\n    def __init__(\n        self,\n        _base_value: float = 0.0,\n        gigawatts: float | None = None,\n        megawatts: float | None = None,\n        kilowatts: float | None = None,\n        watts: float | None = None,\n        milliwatts: float | None = None,\n    ) -> None:\n        self._base_value = _base_value\n        if gigawatts is not None:\n            self._base_value += gigawatts * 10**9\n        if megawatts is not None:\n            self._base_value += megawatts * 10**6\n        if kilowatts is not None:\n            self._base_value += kilowatts * 10**3\n        if watts is not None:\n            self._base_value += watts * 1\n        if milliwatts is not None:\n            self._base_value += milliwatts * 10**-3\n\n    @classmethod\n    def zero(cls) -> Power:\n        \"\"\"\n        Create a Power with a value of zero.\n        \"\"\"\n",
        "input": "",
        "output": "        return Power()\n    \n",
        "idx": "687"
    },
    {
        "instruction": "# Here are some relevant code fragments from other files of the repo:\n# --------------------------------------------------\n# the below code fragment can be found in:\n# quantio/exceptions.py\n# --------------------------------------------------\n# class CanNotAddTypesError(TypeError):\n#     \"\"\"Raised when two uncompatible quantities are added to one another.\"\"\"\n# \n#     def __init__(self, self_type_descriptor: str, other_type_descriptor: str) -> None:\n#         super().__init__(f\"Can not add {other_type_descriptor} to {self_type_descriptor}\")\n# \n# class CanNotSubtractTypesError(TypeError):\n#     \"\"\"Raised when two uncompatible quantities are subtracted from one another.\"\"\"\n# \n#     def __init__(self, self_type_descriptor: str, other_type_descriptor: str) -> None:\n#         super().__init__(f\"Can not subtract {other_type_descriptor} from {self_type_descriptor}\")\n# \n# --------------------------------------------------\n\n\n## quantio/quantities.py\nfrom abc import ABC\n\nfrom .exceptions import CanNotAddTypesError, CanNotSubtractTypesError\n\nclass Quantity(ABC):\n    \"\"\"Parent class to all quantities.\"\"\"\n\n    _base_value: float\n    \"The base unit of the quantity.\"\n\n    BASE_UNIT: str\n    \"Name of the unit with a factor of 1.\"\n\n    def __eq__(self, other: object) -> bool:\n        \"\"\"Assess if this object is the same as another.\"\"\"\n        if isinstance(other, type(self)):\n            return self._base_value == other._base_value\n\n        return False\n\n    def __add__(self, other: Quantity) -> Quantity:\n        \"\"\"Add two quantities of the same type.\"\"\"\n        if type(self) is not type(other):\n            raise CanNotAddTypesError(self.__class__.__name__, other.__class__.__name__)\n\n        result = type(self)()\n        result._base_value = self._base_value + other._base_value\n        return result\n\n    def __sub__(self, other: Quantity) -> Quantity:\n        \"\"\"Subtract two quantities of the same type.\"\"\"\n        if type(self) is not type(other):\n            raise CanNotSubtractTypesError(self.__class__.__name__, other.__class__.__name__)\n\n        result = type(self)()\n        result._base_value = self._base_value - other._base_value\n        return result\n\n    def __repr__(self) -> str:\n        \"\"\"Return an unambiguous representation of this quantity.\"\"\"\n        return self.__str__()\n\nclass AngularVelocity(Quantity):\n    \"\"\"The change in angle per time.\"\"\"\n\n    # --- This part is auto generated. Do not change manually. ---\n\n    BASE_UNIT = \"radians_per_second\"\n\n    @property\n    def degrees_per_second(self) -> float:\n        \"\"\"The angularvelocity in degrees per second.\"\"\"\n        return self._base_value / (3.141592653589793 / 180)\n\n    @property\n    def radians_per_second(self) -> float:\n        \"\"\"The angularvelocity in radians per second.\"\"\"\n        return self._base_value / 1\n\n    def __init__(\n        self,\n        _base_value: float = 0.0,\n        degrees_per_second: float | None = None,\n        radians_per_second: float | None = None,\n    ) -> None:\n        self._base_value = _base_value\n        if degrees_per_second is not None:\n            self._base_value += degrees_per_second * (3.141592653589793 / 180)\n        if radians_per_second is not None:\n            self._base_value += radians_per_second * 1\n\n    @classmethod\n    def zero(cls) -> AngularVelocity:\n        \"\"\"\n        Create a AngularVelocity with a value of zero.\n        \"\"\"\n",
        "input": "",
        "output": "        return AngularVelocity()\n    \n",
        "idx": "688"
    },
    {
        "instruction": "# Here are some relevant code fragments from other files of the repo:\n# --------------------------------------------------\n# the below code fragment can be found in:\n# quantio/exceptions.py\n# --------------------------------------------------\n# class CanNotAddTypesError(TypeError):\n#     \"\"\"Raised when two uncompatible quantities are added to one another.\"\"\"\n# \n#     def __init__(self, self_type_descriptor: str, other_type_descriptor: str) -> None:\n#         super().__init__(f\"Can not add {other_type_descriptor} to {self_type_descriptor}\")\n# \n# class CanNotSubtractTypesError(TypeError):\n#     \"\"\"Raised when two uncompatible quantities are subtracted from one another.\"\"\"\n# \n#     def __init__(self, self_type_descriptor: str, other_type_descriptor: str) -> None:\n#         super().__init__(f\"Can not subtract {other_type_descriptor} from {self_type_descriptor}\")\n# \n# --------------------------------------------------\n\n\n## quantio/quantities.py\nfrom abc import ABC\n\nfrom .exceptions import CanNotAddTypesError, CanNotSubtractTypesError\n\nclass Quantity(ABC):\n    \"\"\"Parent class to all quantities.\"\"\"\n\n    _base_value: float\n    \"The base unit of the quantity.\"\n\n    BASE_UNIT: str\n    \"Name of the unit with a factor of 1.\"\n\n    def __eq__(self, other: object) -> bool:\n        \"\"\"Assess if this object is the same as another.\"\"\"\n        if isinstance(other, type(self)):\n            return self._base_value == other._base_value\n\n        return False\n\n    def __add__(self, other: Quantity) -> Quantity:\n        \"\"\"Add two quantities of the same type.\"\"\"\n        if type(self) is not type(other):\n            raise CanNotAddTypesError(self.__class__.__name__, other.__class__.__name__)\n\n        result = type(self)()\n        result._base_value = self._base_value + other._base_value\n        return result\n\n    def __sub__(self, other: Quantity) -> Quantity:\n        \"\"\"Subtract two quantities of the same type.\"\"\"\n        if type(self) is not type(other):\n            raise CanNotSubtractTypesError(self.__class__.__name__, other.__class__.__name__)\n\n        result = type(self)()\n        result._base_value = self._base_value - other._base_value\n        return result\n\n    def __repr__(self) -> str:\n        \"\"\"Return an unambiguous representation of this quantity.\"\"\"\n        return self.__str__()\n\nclass Density(Quantity):\n    \"\"\"A substance's mass per unit of volume.\"\"\"\n\n    # --- This part is auto generated. Do not change manually. ---\n\n    BASE_UNIT = \"kilograms_per_cubic_meter\"\n\n    @property\n    def grams_per_cubic_meter(self) -> float:\n        \"\"\"The density in grams per cubic meter.\"\"\"\n        return self._base_value / 10**3\n\n    @property\n    def kilograms_per_cubic_meter(self) -> float:\n        \"\"\"The density in kilograms per cubic meter.\"\"\"\n        return self._base_value / 1\n\n    @property\n    def kilograms_per_liter(self) -> float:\n        \"\"\"The density in kilograms per liter.\"\"\"\n        return self._base_value / 10**-3\n\n    @property\n    def grams_per_milliliter(self) -> float:\n        \"\"\"The density in grams per milliliter.\"\"\"\n        return self._base_value / 10**-3\n\n    def __init__(\n        self,\n        _base_value: float = 0.0,\n        grams_per_cubic_meter: float | None = None,\n        kilograms_per_cubic_meter: float | None = None,\n        kilograms_per_liter: float | None = None,\n        grams_per_milliliter: float | None = None,\n    ) -> None:\n        self._base_value = _base_value\n        if grams_per_cubic_meter is not None:\n            self._base_value += grams_per_cubic_meter * 10**3\n        if kilograms_per_cubic_meter is not None:\n            self._base_value += kilograms_per_cubic_meter * 1\n        if kilograms_per_liter is not None:\n            self._base_value += kilograms_per_liter * 10**-3\n        if grams_per_milliliter is not None:\n            self._base_value += grams_per_milliliter * 10**-3\n\n    @classmethod\n    def zero(cls) -> Density:\n        \"\"\"\n        Create a Density with a value of zero.\n        \"\"\"\n",
        "input": "",
        "output": "        return Density()\n    \n",
        "idx": "689"
    },
    {
        "instruction": "# Here are some relevant code fragments from other files of the repo:\n# --------------------------------------------------\n# the below code fragment can be found in:\n# quantio/exceptions.py\n# --------------------------------------------------\n# class CanNotAddTypesError(TypeError):\n#     \"\"\"Raised when two uncompatible quantities are added to one another.\"\"\"\n# \n#     def __init__(self, self_type_descriptor: str, other_type_descriptor: str) -> None:\n#         super().__init__(f\"Can not add {other_type_descriptor} to {self_type_descriptor}\")\n# \n# class CanNotSubtractTypesError(TypeError):\n#     \"\"\"Raised when two uncompatible quantities are subtracted from one another.\"\"\"\n# \n#     def __init__(self, self_type_descriptor: str, other_type_descriptor: str) -> None:\n#         super().__init__(f\"Can not subtract {other_type_descriptor} from {self_type_descriptor}\")\n# \n# --------------------------------------------------\n\n\n## quantio/quantities.py\nfrom abc import ABC\n\nfrom .exceptions import CanNotAddTypesError, CanNotSubtractTypesError\n\nclass Quantity(ABC):\n    \"\"\"Parent class to all quantities.\"\"\"\n\n    _base_value: float\n    \"The base unit of the quantity.\"\n\n    BASE_UNIT: str\n    \"Name of the unit with a factor of 1.\"\n\n    def __eq__(self, other: object) -> bool:\n        \"\"\"Assess if this object is the same as another.\"\"\"\n        if isinstance(other, type(self)):\n            return self._base_value == other._base_value\n\n        return False\n\n    def __add__(self, other: Quantity) -> Quantity:\n        \"\"\"Add two quantities of the same type.\"\"\"\n        if type(self) is not type(other):\n            raise CanNotAddTypesError(self.__class__.__name__, other.__class__.__name__)\n\n        result = type(self)()\n        result._base_value = self._base_value + other._base_value\n        return result\n\n    def __sub__(self, other: Quantity) -> Quantity:\n        \"\"\"Subtract two quantities of the same type.\"\"\"\n        if type(self) is not type(other):\n            raise CanNotSubtractTypesError(self.__class__.__name__, other.__class__.__name__)\n\n        result = type(self)()\n        result._base_value = self._base_value - other._base_value\n        return result\n\n    def __repr__(self) -> str:\n        \"\"\"Return an unambiguous representation of this quantity.\"\"\"\n        return self.__str__()\n\nclass Time(Quantity):\n    \"\"\"The duration of an event.\"\"\"\n\n    # --- This part is auto generated. Do not change manually. ---\n\n    BASE_UNIT = \"seconds\"\n\n    @property\n    def hours(self) -> float:\n        \"\"\"The time in hours.\"\"\"\n        return self._base_value / 60 * 60\n\n    @property\n    def minutes(self) -> float:\n        \"\"\"The time in minutes.\"\"\"\n        return self._base_value / 60\n\n    @property\n    def seconds(self) -> float:\n        \"\"\"The time in seconds.\"\"\"\n        return self._base_value / 1\n\n    @property\n    def milliseconds(self) -> float:\n        \"\"\"The time in milliseconds.\"\"\"\n        return self._base_value / 10**-3\n\n    @property\n    def microseconds(self) -> float:\n        \"\"\"The time in microseconds.\"\"\"\n        return self._base_value / 10**-6\n\n    @property\n    def nanoseconds(self) -> float:\n        \"\"\"The time in nanoseconds.\"\"\"\n        return self._base_value / 10**-9\n\n    def __init__(\n        self,\n        _base_value: float = 0.0,\n        hours: float | None = None,\n        minutes: float | None = None,\n        seconds: float | None = None,\n        milliseconds: float | None = None,\n        microseconds: float | None = None,\n        nanoseconds: float | None = None,\n    ) -> None:\n        self._base_value = _base_value\n        if hours is not None:\n            self._base_value += hours * 60 * 60\n        if minutes is not None:\n            self._base_value += minutes * 60\n        if seconds is not None:\n            self._base_value += seconds * 1\n        if milliseconds is not None:\n            self._base_value += milliseconds * 10**-3\n        if microseconds is not None:\n            self._base_value += microseconds * 10**-6\n        if nanoseconds is not None:\n            self._base_value += nanoseconds * 10**-9\n\n    @classmethod\n    def zero(cls) -> Time:\n        \"\"\"\n        Create a Time with a value of zero.\n        \"\"\"\n",
        "input": "",
        "output": "        return Time()\n    \n",
        "idx": "690"
    },
    {
        "instruction": "# Here are some relevant code fragments from other files of the repo:\n# --------------------------------------------------\n# the below code fragment can be found in:\n# quantio/exceptions.py\n# --------------------------------------------------\n# class CanNotAddTypesError(TypeError):\n#     \"\"\"Raised when two uncompatible quantities are added to one another.\"\"\"\n# \n#     def __init__(self, self_type_descriptor: str, other_type_descriptor: str) -> None:\n#         super().__init__(f\"Can not add {other_type_descriptor} to {self_type_descriptor}\")\n# \n# class CanNotSubtractTypesError(TypeError):\n#     \"\"\"Raised when two uncompatible quantities are subtracted from one another.\"\"\"\n# \n#     def __init__(self, self_type_descriptor: str, other_type_descriptor: str) -> None:\n#         super().__init__(f\"Can not subtract {other_type_descriptor} from {self_type_descriptor}\")\n# \n# --------------------------------------------------\n\n\n## quantio/quantities.py\nfrom abc import ABC\n\nfrom .exceptions import CanNotAddTypesError, CanNotSubtractTypesError\n\nclass Quantity(ABC):\n    \"\"\"Parent class to all quantities.\"\"\"\n\n    _base_value: float\n    \"The base unit of the quantity.\"\n\n    BASE_UNIT: str\n    \"Name of the unit with a factor of 1.\"\n\n    def __eq__(self, other: object) -> bool:\n        \"\"\"Assess if this object is the same as another.\"\"\"\n        if isinstance(other, type(self)):\n            return self._base_value == other._base_value\n\n        return False\n\n    def __add__(self, other: Quantity) -> Quantity:\n        \"\"\"Add two quantities of the same type.\"\"\"\n        if type(self) is not type(other):\n            raise CanNotAddTypesError(self.__class__.__name__, other.__class__.__name__)\n\n        result = type(self)()\n        result._base_value = self._base_value + other._base_value\n        return result\n\n    def __sub__(self, other: Quantity) -> Quantity:\n        \"\"\"Subtract two quantities of the same type.\"\"\"\n        if type(self) is not type(other):\n            raise CanNotSubtractTypesError(self.__class__.__name__, other.__class__.__name__)\n\n        result = type(self)()\n        result._base_value = self._base_value - other._base_value\n        return result\n\n    def __repr__(self) -> str:\n        \"\"\"Return an unambiguous representation of this quantity.\"\"\"\n        return self.__str__()\n\nclass Velocity(Quantity):\n    \"\"\"Distance per time.\"\"\"\n\n    # --- This part is auto generated. Do not change manually. ---\n\n    BASE_UNIT = \"meters_per_second\"\n\n    @property\n    def meters_per_second(self) -> float:\n        \"\"\"The velocity in meters per second.\"\"\"\n        return self._base_value / 1\n\n    @property\n    def kilometers_per_hour(self) -> float:\n        \"\"\"The velocity in kilometers per hour.\"\"\"\n        return self._base_value / (1 / 3.6)\n\n    @property\n    def miles_per_hour(self) -> float:\n        \"\"\"The velocity in miles per hour.\"\"\"\n        return self._base_value / (1 / 2.23694)\n\n    def __init__(\n        self,\n        _base_value: float = 0.0,\n        meters_per_second: float | None = None,\n        kilometers_per_hour: float | None = None,\n        miles_per_hour: float | None = None,\n    ) -> None:\n        self._base_value = _base_value\n        if meters_per_second is not None:\n            self._base_value += meters_per_second * 1\n        if kilometers_per_hour is not None:\n            self._base_value += kilometers_per_hour * (1 / 3.6)\n        if miles_per_hour is not None:\n            self._base_value += miles_per_hour * (1 / 2.23694)\n\n    @classmethod\n    def zero(cls) -> Velocity:\n        \"\"\"\n        Create a Velocity with a value of zero.\n        \"\"\"\n",
        "input": "",
        "output": "        return Velocity()\n    \n",
        "idx": "691"
    },
    {
        "instruction": "# Here are some relevant code fragments from other files of the repo:\n# --------------------------------------------------\n# the below code fragment can be found in:\n# quantio/exceptions.py\n# --------------------------------------------------\n# class CanNotAddTypesError(TypeError):\n#     \"\"\"Raised when two uncompatible quantities are added to one another.\"\"\"\n# \n#     def __init__(self, self_type_descriptor: str, other_type_descriptor: str) -> None:\n#         super().__init__(f\"Can not add {other_type_descriptor} to {self_type_descriptor}\")\n# \n# class CanNotSubtractTypesError(TypeError):\n#     \"\"\"Raised when two uncompatible quantities are subtracted from one another.\"\"\"\n# \n#     def __init__(self, self_type_descriptor: str, other_type_descriptor: str) -> None:\n#         super().__init__(f\"Can not subtract {other_type_descriptor} from {self_type_descriptor}\")\n# \n# --------------------------------------------------\n\n\n## quantio/quantities.py\nfrom abc import ABC\n\nfrom .exceptions import CanNotAddTypesError, CanNotSubtractTypesError\n\nclass Quantity(ABC):\n    \"\"\"Parent class to all quantities.\"\"\"\n\n    _base_value: float\n    \"The base unit of the quantity.\"\n\n    BASE_UNIT: str\n    \"Name of the unit with a factor of 1.\"\n\n    def __eq__(self, other: object) -> bool:\n        \"\"\"Assess if this object is the same as another.\"\"\"\n        if isinstance(other, type(self)):\n            return self._base_value == other._base_value\n\n        return False\n\n    def __add__(self, other: Quantity) -> Quantity:\n        \"\"\"Add two quantities of the same type.\"\"\"\n        if type(self) is not type(other):\n            raise CanNotAddTypesError(self.__class__.__name__, other.__class__.__name__)\n\n        result = type(self)()\n        result._base_value = self._base_value + other._base_value\n        return result\n\n    def __sub__(self, other: Quantity) -> Quantity:\n        \"\"\"Subtract two quantities of the same type.\"\"\"\n        if type(self) is not type(other):\n            raise CanNotSubtractTypesError(self.__class__.__name__, other.__class__.__name__)\n\n        result = type(self)()\n        result._base_value = self._base_value - other._base_value\n        return result\n\n    def __repr__(self) -> str:\n        \"\"\"Return an unambiguous representation of this quantity.\"\"\"\n        return self.__str__()\n\nclass Acceleration(Quantity):\n    \"\"\"Rate of change of velocity.\"\"\"\n\n    # --- This part is auto generated. Do not change manually. ---\n\n    BASE_UNIT = \"meters_per_square_second\"\n\n    @property\n    def meters_per_square_second(self) -> float:\n        \"\"\"The acceleration in meters per square second.\"\"\"\n        return self._base_value / 1\n\n    @property\n    def g_force(self) -> float:\n        \"\"\"The acceleration in g force.\"\"\"\n        return self._base_value / (1 / 9.8)\n\n    def __init__(\n        self,\n        _base_value: float = 0.0,\n        meters_per_square_second: float | None = None,\n        g_force: float | None = None,\n    ) -> None:\n        self._base_value = _base_value\n        if meters_per_square_second is not None:\n            self._base_value += meters_per_square_second * 1\n        if g_force is not None:\n            self._base_value += g_force * (1 / 9.8)\n\n    @classmethod\n    def zero(cls) -> Acceleration:\n        \"\"\"\n        Create a Acceleration with a value of zero.\n        \"\"\"\n",
        "input": "",
        "output": "        return Acceleration()\n    \n",
        "idx": "692"
    },
    {
        "instruction": "# Here are some relevant code fragments from other files of the repo:\n# --------------------------------------------------\n# the below code fragment can be found in:\n# quantio/exceptions.py\n# --------------------------------------------------\n# class CanNotAddTypesError(TypeError):\n#     \"\"\"Raised when two uncompatible quantities are added to one another.\"\"\"\n# \n#     def __init__(self, self_type_descriptor: str, other_type_descriptor: str) -> None:\n#         super().__init__(f\"Can not add {other_type_descriptor} to {self_type_descriptor}\")\n# \n# class CanNotSubtractTypesError(TypeError):\n#     \"\"\"Raised when two uncompatible quantities are subtracted from one another.\"\"\"\n# \n#     def __init__(self, self_type_descriptor: str, other_type_descriptor: str) -> None:\n#         super().__init__(f\"Can not subtract {other_type_descriptor} from {self_type_descriptor}\")\n# \n# --------------------------------------------------\n\n\n## quantio/quantities.py\nfrom abc import ABC\n\nfrom .exceptions import CanNotAddTypesError, CanNotSubtractTypesError\n\nclass Quantity(ABC):\n    \"\"\"Parent class to all quantities.\"\"\"\n\n    _base_value: float\n    \"The base unit of the quantity.\"\n\n    BASE_UNIT: str\n    \"Name of the unit with a factor of 1.\"\n\n    def __eq__(self, other: object) -> bool:\n        \"\"\"Assess if this object is the same as another.\"\"\"\n        if isinstance(other, type(self)):\n            return self._base_value == other._base_value\n\n        return False\n\n    def __add__(self, other: Quantity) -> Quantity:\n        \"\"\"Add two quantities of the same type.\"\"\"\n        if type(self) is not type(other):\n            raise CanNotAddTypesError(self.__class__.__name__, other.__class__.__name__)\n\n        result = type(self)()\n        result._base_value = self._base_value + other._base_value\n        return result\n\n    def __sub__(self, other: Quantity) -> Quantity:\n        \"\"\"Subtract two quantities of the same type.\"\"\"\n        if type(self) is not type(other):\n            raise CanNotSubtractTypesError(self.__class__.__name__, other.__class__.__name__)\n\n        result = type(self)()\n        result._base_value = self._base_value - other._base_value\n        return result\n\n    def __repr__(self) -> str:\n        \"\"\"Return an unambiguous representation of this quantity.\"\"\"\n        return self.__str__()\n\nclass Pressure(Quantity):\n    \"\"\"The amount of force per unit area.\"\"\"\n\n    # --- This part is auto generated. Do not change manually. ---\n\n    BASE_UNIT = \"kilopascal\"\n\n    @property\n    def terapascal(self) -> float:\n        \"\"\"The pressure in terapascal.\"\"\"\n        return self._base_value / 10**9\n\n    @property\n    def gigapascal(self) -> float:\n        \"\"\"The pressure in gigapascal.\"\"\"\n        return self._base_value / 10**6\n\n    @property\n    def megapascal(self) -> float:\n        \"\"\"The pressure in megapascal.\"\"\"\n        return self._base_value / 10**3\n\n    @property\n    def kilopascal(self) -> float:\n        \"\"\"The pressure in kilopascal.\"\"\"\n        return self._base_value / 1\n\n    @property\n    def bar(self) -> float:\n        \"\"\"The pressure in bar.\"\"\"\n        return self._base_value / 10**-2\n\n    @property\n    def pascal(self) -> float:\n        \"\"\"The pressure in pascal.\"\"\"\n        return self._base_value / 10**-3\n\n    @property\n    def millipascal(self) -> float:\n        \"\"\"The pressure in millipascal.\"\"\"\n        return self._base_value / 10**-3\n\n    def __init__(\n        self,\n        _base_value: float = 0.0,\n        terapascal: float | None = None,\n        gigapascal: float | None = None,\n        megapascal: float | None = None,\n        kilopascal: float | None = None,\n        bar: float | None = None,\n        pascal: float | None = None,\n        millipascal: float | None = None,\n    ) -> None:\n        self._base_value = _base_value\n        if terapascal is not None:\n            self._base_value += terapascal * 10**9\n        if gigapascal is not None:\n            self._base_value += gigapascal * 10**6\n        if megapascal is not None:\n            self._base_value += megapascal * 10**3\n        if kilopascal is not None:\n            self._base_value += kilopascal * 1\n        if bar is not None:\n            self._base_value += bar * 10**-2\n        if pascal is not None:\n            self._base_value += pascal * 10**-3\n        if millipascal is not None:\n            self._base_value += millipascal * 10**-3\n\n    @classmethod\n    def zero(cls) -> Pressure:\n        \"\"\"\n        Create a Pressure with a value of zero.\n        \"\"\"\n",
        "input": "",
        "output": "        return Pressure()\n    \n",
        "idx": "693"
    },
    {
        "instruction": "## scripts/sac.py\nimport torch\n\nimport torch.nn as nn\n\nclass Critic(nn.Module):\n    \"\"\"\n    Class to represent a Critic in the context of the SAC algorithm. Children class of nn.Module.\n    \"\"\"\n    def __init__(self, in_dim: int, out_dim: int, n_hidden: tuple[int], lr: float=1e-3):\n        super(Critic, self).__init__()\n        self.role_type = \"Critic\"\n        self.in_dim = in_dim\n        self.out_dim = out_dim\n        self.n_hidden = n_hidden\n        self.lr = lr\n\n        layers = []\n        \n        for i in range(len(n_hidden)):\n            if i == 0:\n                layers.append(nn.Linear(in_dim, n_hidden[i]))\n            else:\n                layers.append(nn.Linear(n_hidden[i-1], n_hidden[i]))\n            layers.append(nn.ReLU())\n\n        layers.append(nn.Linear(n_hidden[-1], out_dim))\n\n        self.sequential = nn.Sequential(*layers)\n\n        self.init_weights()\n\n    def init_weights(self):\n        initrange = 0.1\n        for module in self.sequential:\n            if type(module) == torch.nn.Linear:\n                    nn.init.zeros_(module.bias)\n                    nn.init.uniform_(module.weight, -initrange, initrange)\n\n    def forward(self, x):\n        return self.sequential(x)\n\nclass VNetwork(Critic):\n\n    \"\"\"\n    Class to represent a V-network. Children class of Critic.\n    \"\"\"\n    def __init__(self, state_dim: int, action_dim: int, max_len: int, out_dim: int, n_hidden: tuple[int], lr: float=1e-3, aug_state_contains_actions: bool=False):\n        # Adjust the size of the augmented state based on the architecture\n        if aug_state_contains_actions:\n            aug_state_size = (state_dim + action_dim) * max_len\n        else:\n            aug_state_size = state_dim * max_len\n\n        super(VNetwork, self).__init__(in_dim=aug_state_size, out_dim=out_dim, n_hidden=n_hidden, lr=lr)\n        self.critic_type = \"V-network\"\n        self.state_dim = state_dim\n        self.action_dim = action_dim\n        self.max_len = max_len\n        self.aug_state_contains_actions = aug_state_contains_actions\n        self.gpu_device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n\n    def forward(self, states, actions):\n",
        "input": "",
        "output": "        if states.shape[-2] != actions.shape[-2]:\n            raise ValueError(\"The states and actions sequences must have the same length!\")\n\n        # Fill the state and actions tensors so that there are max_len elements\n        if states.shape[-2] < self.max_len:\n            states = torch.cat([states, torch.zeros(states.shape[0], self.max_len - states.shape[-2], states.shape[-1], device=self.gpu_device)], dim=-2)\n            actions = torch.cat([actions, torch.zeros(actions.shape[0], self.max_len - actions.shape[-2], actions.shape[-1], device=self.gpu_device)], dim=-2)\n\n        if self.aug_state_contains_actions:\n            aug_state_1D = torch.cat([states, actions], dim=2).view(-1)\n        else:\n            aug_state_1D = states.view(-1)\n\n        x = aug_state_1D\n        x = super(VNetwork, self).forward(x)\n        return x\n    \n",
        "idx": "708"
    },
    {
        "instruction": "## pagify/core/cursor_paginator.py\nfrom typing import Optional, List, Union\n\nclass CursorPaginator:\n    def __init__(self, queryset: List[dict], cursor: Optional[Union[int, str]] = None, limit: int = 10):\n        \"\"\"\n        Initializes the paginator with a dataset, cursor, and limit.\n\n        :param queryset: The dataset, typically a list of dictionaries with an 'id' field.\n        :param cursor: The id of the last item from the previous page to continue pagination.\n        :param limit: The number of items per page.\n        \"\"\"\n        self.queryset = queryset\n        self.cursor = cursor\n        self.limit = limit\n\n    def get_paginated_data(self) -> List[dict]:\n        \"\"\"\n        Retrieves a slice of the data based on the cursor and limit.\n\n        :return: A list of items for the current page.\n        \"\"\"\n        if self.cursor is not None:\n            return [item for item in self.queryset if 'id' in item and item['id'] > self.cursor][:self.limit]\n        return self.queryset[:self.limit]\n\n    def get_next_cursor(self, data: List[dict]) -> Optional[Union[int, str]]:\n        \"\"\"\n        Determines the next cursor based on the last item of the current data.\n    \n        :param data: The list of items from the current page.\n        :return: The id of the last item in the data to be used as the cursor for the next page, or None if empty.\n        \"\"\"\n",
        "input": "",
        "output": "        return data[-1]['id'] if data and 'id' in data[-1] else None\n    \n",
        "idx": "712"
    },
    {
        "instruction": "## pagify/utils/serializer.py\nfrom typing import List, Any\n\nclass Serializer:\n    @staticmethod\n    def serialize(data: List[Any]) -> List[dict]:\n        \"\"\"\n        Converts a list of items into a list of dictionaries.\n        \"\"\"\n",
        "input": "",
        "output": "        return [dict(item) for item in data]\n    \n",
        "idx": "713"
    },
    {
        "instruction": "## pagify/utils/response_formatting.py\nimport json\n\nfrom typing import Any, Dict, Optional, List, Union\n\nclass JSONResponseFormatter:\n    \"\"\"Provides helper methods to format responses as JSON for consistency across the application.\"\"\"\n\n    @staticmethod\n    def success(data: Any, message: str='Success') -> str:\n",
        "input": "",
        "output": "        response = {\n            \"status\": \"success\",\n            \"message\": message,\n            \"data\": data\n        }\n        return json.dumps(response)\n    \n",
        "idx": "714"
    },
    {
        "instruction": "## pagify/utils/response_formatting.py\nimport json\n\nfrom typing import Any, Dict, Optional, List, Union\n\nclass JSONResponseFormatter:\n    \"\"\"Provides helper methods to format responses as JSON for consistency across the application.\"\"\"\n\n    @staticmethod\n    def success(data: Any, message: str = \"Success\") -> str:\n        response = {\n            \"status\": \"success\",\n            \"message\": message,\n            \"data\": data\n        }\n        return json.dumps(response)\n\n    @staticmethod\n    def error(message: str, code: int=400) -> str:\n",
        "input": "",
        "output": "        response = {\n            \"status\": \"error\",\n            \"message\": message,\n            \"code\": code\n        }\n        return json.dumps(response)\n    \n",
        "idx": "715"
    },
    {
        "instruction": "# Here are some relevant code fragments from other files of the repo:\n# --------------------------------------------------\n# the below code fragment can be found in:\n# backend/app/models/base.py\n# --------------------------------------------------\n# from sqlalchemy.ext.declarative import declarative_base\n# \n# Base = declarative_base()\n# \n# --------------------------------------------------\n\n\n## backend/app/models/analysis.py\nfrom sqlalchemy import Column, Integer, String, Float, DateTime, Text, JSON\n\nfrom datetime import datetime\n\nfrom .base import Base\n\nimport json\n\nclass Analysis(Base):\n    __tablename__ = 'analyses'\n\n    id = Column(Integer, primary_key=True, index=True)\n    text = Column(Text, nullable=False)\n    analysis_type = Column(String(50), nullable=False)  # e.g., \"gender_equity\"\n    results = Column(JSON, nullable=False)  # Store complete analysis results\n    context = Column(JSON, nullable=True)  # Store analysis context\n    industry = Column(String(50), nullable=True)\n    language = Column(String(10), nullable=True)\n    location = Column(String(100), nullable=True)\n    \n    # Derived metrics for querying and filtering\n    equity_score = Column(Float, nullable=True)\n    violence_prevention_score = Column(Float, nullable=True)\n    care_support_score = Column(Float, nullable=True)\n    policy_implementation_score = Column(Float, nullable=True)\n    \n    created_at = Column(DateTime, default=datetime.utcnow, nullable=False)\n    updated_at = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)\n\n    def __init__(self, **kwargs):\n        super().__init__(**kwargs)\n        if self.results:\n            self._extract_scores()\n\n    def _extract_scores(self):\n        \"\"\"\n        Extract key scores from analysis results for querying\n        \"\"\"\n",
        "input": "",
        "output": "        if isinstance(self.results, str):\n            results = json.loads(self.results)\n        else:\n            results = self.results\n\n        self.equity_score = results.get('overall_assessment', {}).get('equity_score')\n        \n        if 'industry_context' in results:\n            industry_context = results['industry_context']\n            self.violence_prevention_score = industry_context.get('violence_prevention', {}).get('benchmark_comparison', {}).get('current_score')\n            self.care_support_score = industry_context.get('unpaid_care', {}).get('benchmark_comparison', {}).get('current_score')\n            self.policy_implementation_score = industry_context.get('policy_effectiveness', {}).get('benchmark_comparison', {}).get('current_score')\n    \n",
        "idx": "718"
    },
    {
        "instruction": "# backend/app/services/analysis_service.py\n\nclass AnalysisService:\n\n    def __init__(self):\n        try:\n            load_dotenv()\n            script_dir = os.path.dirname(os.path.abspath(__file__))\n            script_dir = os.path.dirname(os.path.abspath(__file__))\n            credentials_path = os.path.join(script_dir, os.getenv('GOOGLE_APPLICATION_CREDENTIALS'))\n            os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = credentials_path\n            api_key = os.getenv('GOOGLE_API_KEY')\n            genai.configure(api_key=api_key)\n            self.model = genai.GenerativeModel('gemini-pro')\n            self.translate_client = translate.Client()\n            self.gender_terms = self._load_gender_terms()\n            self.industry_benchmarks = self._load_industry_benchmarks()\n            self.violence_indicators = self._load_violence_indicators()\n            self.care_work_metrics = self._load_care_work_metrics()\n            self.policy_frameworks = self._load_policy_frameworks()\n        except Exception as e:\n            print(f'Error initializing services: {e}')\n            raise\n\n    def detect_language(self, text: str) -> str:\n        \"\"\"Detect the language of the provided text.\"\"\"\n        result = self.translate_client.detect_language(text)\n        return result['language']\n\n    def get_user_location(self) -> str:\n        \"\"\"Detect the user's approximate location based on their IP address.\"\"\"\n        try:\n            response = requests.get('https://ipinfo.io')\n            if response.status_code == 200:\n                data = response.json()\n                return data.get('country', 'global')\n        except Exception as e:\n            print(f'Location detection failed: {e}')\n        return 'global'\n\n    def translate_text(self, text: str, target_language: str) -> str:\n        \"\"\"Translate text to the specified target language.\"\"\"\n        translation = self.translate_client.translate(text, target_language=target_language)\n        return translation['translatedText']\n\n    def _load_gender_terms(self) -> Dict:\n        \"\"\"Load database of gender-related terms and their contexts\"\"\"\n        return {'explicit_bias': [\"women can't\", \"girls shouldn't\", 'male-only', 'feminine weakness', 'maternal risk', 'emotional decision', 'bossy woman', 'hysteric'], 'implicit_bias': ['nurturing role', 'support position', 'office mom', 'aggressive for a woman', 'ambitious woman', 'work-life balance', 'family responsibilities'], 'violence_related': ['threatening', 'intimidating', 'controlling', 'coercive', 'hostile', 'aggressive', 'retaliatory', 'punitive'], 'care_work_related': ['childcare duties', 'eldercare responsibilities', 'domestic duties', 'household management', 'family obligations', 'caretaking role'], 'inclusive_alternatives': {'chairman': 'chairperson', 'businessman': 'business person', 'policeman': 'police officer', 'mankind': 'humanity', 'manpower': 'workforce'}, 'empowerment_terms': ['leadership', 'achievement', 'expertise', 'professional growth', 'equal opportunity', 'mentorship', 'advancement']}\n\n    def _load_care_work_metrics(self) -> Dict:\n        \"\"\"Load metrics for analyzing unpaid care work impact\"\"\"\n        return {'time_allocation': {'childcare_hours': 0, 'eldercare_hours': 0, 'household_maintenance': 0, 'emotional_labor': 0}, 'workplace_policies': {'flexible_hours': False, 'remote_work': False, 'parental_leave': 0, 'caregiving_support': False}, 'economic_impact': {'career_interruptions': 0, 'promotion_delays': 0, 'wage_penalties': 0, 'retirement_impact': 0}, 'support_indicators': {'childcare_facilities': False, 'eldercare_assistance': False, 'domestic_help_allowance': False, 'caregiver_networks': False}}\n\n    def _load_policy_frameworks(self) -> Dict:\n        \"\"\"Load gender equity policy frameworks and recommendations\"\"\"\n        return {'workplace_policies': {'recruitment': ['blind recruitment processes', 'diverse interview panels', 'standardized evaluation criteria'], 'advancement': ['transparent promotion criteria', 'leadership development programs', 'mentorship initiatives'], 'compensation': ['pay equity audits', 'transparent salary bands', 'performance evaluation standardization']}, 'care_support_policies': {'leave_policies': ['paid parental leave', 'flexible caregiving leave', 'sabbatical options'], 'workplace_flexibility': ['flexible hours', 'remote work options', 'compressed work weeks'], 'support_services': ['on-site childcare', 'eldercare referral services', 'caregiver support networks']}, 'safety_policies': {'prevention': ['anti-harassment training', 'bystander intervention programs', 'climate surveys'], 'response': ['reporting mechanisms', 'investigation procedures', 'victim support services'], 'accountability': ['clear consequences', 'regular policy review', 'transparency reports']}}\n\n    def _load_industry_benchmarks(self) -> Dict:\n        \"\"\"Load industry-specific gender equity benchmarks\"\"\"\n        return {'tech': {'leadership_representation': 0.3, 'pay_gap_threshold': 0.05, 'promotion_rate_ratio': 1.0, 'violence_prevention_score': 0.8, 'care_support_score': 0.7, 'policy_implementation_score': 0.75}, 'healthcare': {'leadership_representation': 0.4, 'pay_gap_threshold': 0.03, 'promotion_rate_ratio': 1.0, 'violence_prevention_score': 0.9, 'care_support_score': 0.8, 'policy_implementation_score': 0.85}}\n\n    async def analyze_content(self, text: str, context: Optional[Dict]=None, industry: Optional[str]=None, db: Session=None) -> Dict:\n        \"\"\"\n        Analyze content for gender equity issues with industry-specific context including violence prevention,\n        care work recognition, and policy recommendations\n        \"\"\"\n        source_language = self.detect_language(text)\n        analysis_text = text if source_language == 'en' else self.translate_text(text, 'en')\n        prompt = self._generate_gender_equity_prompt(analysis_text, industry)\n        try:\n            response = await self.model.generate_content_async(prompt, generation_config={'temperature': 0.2, 'top_p': 0.9, 'top_k': 50, 'max_output_tokens': 2048}, safety_settings={'HARASSMENT': 'BLOCK_NONE', 'HATE_SPEECH': 'BLOCK_NONE'})\n            cleaned_response = re.sub('```(?:json)?\\\\n?(.*?)\\\\n?```|^(?:json|JSON)\\\\s*', '\\\\1', response.text, flags=re.DOTALL).strip()\n            analysis = json.loads(cleaned_response)\n            enhanced_analysis = self._enhance_gender_analysis(analysis, industry)\n            if db:\n                self._store_analysis(db, text, enhanced_analysis, context)\n            return enhanced_analysis\n        except Exception as e:\n            print(f'Analysis failed: {str(e)}')\n            return {'status': 'error', 'error': str(e)}\n\n    def _generate_gender_equity_prompt(self, text: str, industry: Optional[str]=None) -> str:\n        \"\"\"Generate a gender equity focused prompt for Gemini\"\"\"\n        industry_context = f'Industry Context: {industry.upper()} sector analysis' if industry else ''\n        return f'\\n        You are an advanced AI system specialized in gender equity analysis. Analyze the following text with special attention to gender-related issues, biases, violence prevention, unpaid care work, policy implications and opportunities for promoting equality.\\n\\n        {industry_context}\\n\\n        1. GENDER BIAS DETECTION\\n        - Identify explicit and implicit gender biases\\n        - Detect stereotypical language and assumptions\\n        - Flag discriminatory patterns in language\\n        - Identify missed opportunities for inclusion\\n        \\n        2. REPRESENTATION ANALYSIS\\n        - Analyze representation of women and girls\\n        - Assess power dynamics and agency\\n        - Evaluate visibility and voice\\n        \\n        3. WORKPLACE EQUITY ASSESSMENT\\n        - Identify barriers to advancement\\n        - Analyze leadership opportunity language\\n        - Detect pay equity issues\\n        - Assess work-life balance assumptions\\n        \\n        4. SAFETY AND DIGNITY\\n        - Flag potential harassment indicators\\n        - Identify undermining or diminishing language\\n        - Assess psychological safety implications\\n        \\n        5. EMPOWERMENT OPPORTUNITIES\\n        - Identify areas for strengthening agency\\n        - Flag mentorship and growth opportunities\\n        - Suggest inclusive alternatives\\n\\n        6. VIOLENCE PREVENTION\\n        - Identify explicit and subtle forms of violence\\n        - Detect harassment risk indicators\\n        - Analyze power dynamics and vulnerabilities\\n        - Assess existing safety measures\\n        - Flag potential escalation patterns\\n        - Evaluate reporting and support mechanisms\\n        \\n        7. UNPAID CARE WORK \\n        - Identify assumptions about care responsibilities\\n        - Analyze work-life balance implications\\n        - Assess recognition of unpaid work\\n        - Evaluate support for caregivers\\n        - Analyze career impact of care duties\\n        - Flag discriminatory patterns\\n        \\n        8. POLICY IMPLICATIONS \\n        - Identify policy gaps and opportunities\\n        - Assess implementation effectiveness\\n        - Evaluate monitoring mechanisms\\n        - Analyze resource allocation\\n        - Flag enforcement challenges\\n        - Suggest policy improvements\\n\\n\\n        Text to analyze: {text}\\n\\n        Please make response really detailed. Any metric that has a score should also have some backup details. If the text request does not qualify for any oof the issues we are analyzing, please say so instead of leaving them blank. There must always be priority actions for overall assessment. Respond ONLY in JSON format with the following structure:\\n        {{\\n            \"bias_detection\": {{\\n                \"explicit_biases\": [\\n                    {{\\n                        \"bias\": <specific bias>,\\n                        \"context\": <explanation>,\\n                        \"impact\": <potential harm>,\\n                        \"suggestion\": <improvement>\\n                    }}\\n                ],\\n                \"implicit_biases\": [<similar structure>],\\n                \"stereotypes\": [<similar structure>],\\n                \"bias_score\": <float 0-1>\\n            }},\\n            \"representation_analysis\": {{\\n                \"visibility_score\": <float 0-1>,\\n                \"agency_score\": <float 0-1>,\\n                \"power_dynamics\": [<specific observations>],\\n                \"improvement_areas\": [<specific suggestions>]\\n            }},\\n            \"workplace_equity\": {{\\n                \"advancement_barriers\": [<specific barriers>],\\n                \"leadership_language\": {{\\n                    \"inclusive_score\": <float 0-1>,\\n                    \"flags\": [<specific issues>]\\n                }},\\n                \"pay_equity_flags\": [<potential issues>],\\n                \"work_life_assumptions\": [<detected assumptions>]\\n            }},\\n            \"safety_assessment\": {{\\n                \"harassment_indicators\": [<potential flags>],\\n                \"undermining_language\": [<specific examples>],\\n                \"psychological_safety\": {{\\n                    \"score\": <float 0-1>,\\n                    \"concerns\": [<specific issues>]\\n                }}\\n            }},\\n            \"empowerment_opportunities\": {{\\n                \"growth_language\": [<positive examples>],\\n                \"mentorship_opportunities\": [<specific suggestions>],\\n                \"inclusive_alternatives\": [<specific improvements>]\\n            }},\\n            \"violence_prevention\": {{\\n                \"risk_indicators\": [\\n                    {{\\n                        \"type\": <violence type>,\\n                        \"indicator\": <specific flag>,\\n                        \"context\": <situation details>,\\n                        \"severity\": <\"high\", \"medium\", \"low\">,\\n                        \"mitigation\": <specific recommendation>\\n                    }}\\n                ],\\n                \"safety_measures\": {{\\n                    \"existing\": [<current measures>],\\n                    \"gaps\": [<missing measures>],\\n                    \"recommendations\": [<specific improvements>]\\n                }},\\n                \"power_dynamics\": {{\\n                    \"risk_factors\": [<specific factors>],\\n                    \"protective_factors\": [<existing protections>],\\n                    \"improvements\": [<recommended changes>]\\n                }},\\n                \"overall_safety_score\": <float 0-1>\\n            }},\\n            \"unpaid_care_analysis\": {{\\n                \"care_responsibilities\": [\\n                    {{\\n                        \"type\": <care type>,\\n                        \"assumption\": <specific assumption>,\\n                        \"impact\": <career/workplace effect>,\\n                        \"support_needed\": <specific support>\\n                    }}\\n                ],\\n                \"work_life_measures\": {{\\n                    \"flexibility_score\": <float 0-1>,\\n                    \"support_score\": <float 0-1>,\\n                    \"gaps\": [<specific gaps>],\\n                    \"recommendations\": [<specific improvements>]\\n                }},\\n                \"economic_impact\": {{\\n                    \"career_progression\": <impact assessment>,\\n                    \"compensation_effects\": [<specific effects>],\\n                    \"mitigation_strategies\": [<specific strategies>]\\n                }},\\n                \"care_recognition_score\": <float 0-1>\\n            }},\\n            \"policy_recommendations\": {{\\n                \"current_policies\": {{\\n                    \"strengths\": [<existing good policies>],\\n                    \"weaknesses\": [<policy gaps>],\\n                    \"implementation_score\": <float 0-1>\\n                }},\\n                \"recommended_policies\": [\\n                    {{\\n                        \"focus_area\": <specific area>,\\n                        \"recommendation\": <policy suggestion>,\\n                        \"rationale\": <justification>,\\n                        \"implementation_steps\": [<specific steps>],\\n                        \"success_metrics\": [<measurement criteria>],\\n                        \"priority\": <\"high\", \"medium\", \"low\">\\n                    }}\\n                ],\\n                \"resource_implications\": {{\\n                    \"required_resources\": [<specific needs>],\\n                    \"potential_challenges\": [<specific challenges>],\\n                    \"mitigation_strategies\": [<specific strategies>]\\n                }},\\n                \"monitoring_framework\": {{\\n                    \"metrics\": [<specific metrics>],\\n                    \"data_needs\": [<required data>],\\n                    \"review_frequency\": <recommended frequency>\\n                }}\\n            }},\\n            \"overall_assessment\": {{\\n                \"equity_score\": <float 0-1>,\\n                \"priority_actions\": [\\n                    {{\\n                        \"issue\": <specific issue>,\\n                        \"impact\": <potential harm>,\\n                        \"recommendation\": <specific suggestion>,\\n                        \"priority\": <\"high\", \"medium\", \"low\">\\n                    }}\\n                ]\\n            }}\\n        }}\\n        '\n\n    def _enhance_gender_analysis(self, analysis: Dict, industry: Optional[str]=None) -> Dict:\n        \"\"\"Enhance the basic analysis with industry-specific insights\"\"\"\n        if not industry or industry not in self.industry_benchmarks:\n            return analysis\n        benchmarks = self.industry_benchmarks[industry]\n        analysis['industry_context'] = {'benchmarks': benchmarks, 'gap_analysis': self._calculate_industry_gaps(analysis, benchmarks), 'recommendations': self._generate_industry_recommendations(analysis, benchmarks), 'violence_prevention': self._analyze_violence_prevention(analysis, benchmarks), 'unpaid_care': self._analyze_care_work(analysis, benchmarks), 'policy_effectiveness': self._analyze_policy_framework(analysis, benchmarks)}\n        return analysis\n\n    def _calculate_industry_gaps(self, analysis: Dict, benchmarks: Dict) -> Dict:\n        \"\"\"Calculate comprehensive gaps between current state and industry benchmarks\"\"\"\n        return {'leadership_gaps': {'executive_gap': benchmarks['leadership_representation']['executive_level'] - analysis.get('representation_analysis', {}).get('visibility_score', 0), 'management_gap': benchmarks['leadership_representation']['senior_management'] - analysis.get('representation_analysis', {}).get('agency_score', 0), 'pipeline_gap': benchmarks['advancement_metrics']['leadership_pipeline'] - analysis.get('workplace_equity', {}).get('leadership_language', {}).get('inclusive_score', 0)}, 'pay_equity_gaps': {'base_pay_gap': benchmarks['pay_equity']['gap_threshold'], 'bonus_gap': benchmarks['pay_equity']['bonus_gap_threshold'], 'promotion_gap': benchmarks['pay_equity']['promotion_adjustment']}, 'safety_gaps': {'prevention_gap': benchmarks['safety_metrics']['violence_prevention_score'] - analysis.get('violence_prevention', {}).get('overall_safety_score', 0), 'reporting_gap': benchmarks['safety_metrics']['harassment_reporting_mechanism'] - analysis.get('safety_assessment', {}).get('psychological_safety', {}).get('score', 0), 'response_gap': benchmarks['safety_metrics']['response_effectiveness'] - analysis.get('violence_prevention', {}).get('overall_safety_score', 0)}, 'care_support_gaps': {'leave_gap': benchmarks['care_support']['parental_leave_score'] - analysis.get('unpaid_care_analysis', {}).get('care_recognition_score', 0), 'flexibility_gap': benchmarks['care_support']['flexible_work_score'] - analysis.get('unpaid_care_analysis', {}).get('work_life_measures', {}).get('flexibility_score', 0), 'support_gap': benchmarks['care_support']['caregiving_support'] - analysis.get('unpaid_care_analysis', {}).get('work_life_measures', {}).get('support_score', 0)}, 'policy_gaps': {'implementation_gap': benchmarks['policy_implementation']['overall_score'] - analysis.get('policy_recommendations', {}).get('current_policies', {}).get('implementation_score', 0), 'accountability_gap': benchmarks['policy_implementation']['accountability_measures'], 'resource_gap': benchmarks['policy_implementation']['resource_allocation']}}\n\n    def _generate_industry_recommendations(self, analysis: Dict, benchmarks: Dict) -> List[Dict]:\n        \"\"\"Generate comprehensive industry-specific recommendations based on analysis and benchmarks\"\"\"\n        gaps = self._calculate_industry_gaps(analysis, benchmarks)\n        recommendations = []\n        if gaps['leadership_gaps']['executive_gap'] > 0.1:\n            recommendations.append({'area': 'leadership_representation', 'priority': 'high', 'type': 'structural', 'recommendation': 'Implement targeted executive leadership development program', 'actions': ['Establish sponsorship program pairing senior executives with high-potential women', 'Create rotation opportunities in P&L roles', 'Set clear diversity targets for executive searches'], 'metrics': ['Percentage increase in women executives', 'Promotion rates to executive positions', 'Retention rates of women in leadership pipeline'], 'timeline': '12-18 months', 'resources_needed': ['Executive development budget', 'External leadership coaches', 'Mentorship program infrastructure']})\n        if gaps['pay_equity_gaps']['base_pay_gap'] > benchmarks['pay_equity']['gap_threshold']:\n            recommendations.append({'area': 'pay_equity', 'priority': 'high', 'type': 'immediate', 'recommendation': 'Implement comprehensive pay equity analysis and adjustment program', 'actions': ['Conduct detailed pay equity audit', 'Establish clear salary bands', 'Create standardized promotion criteria', 'Implement regular pay gap monitoring'], 'metrics': ['Reduction in pay gap percentage', 'Pay equity by role and level', 'Promotion rate parity'], 'timeline': '6-12 months', 'resources_needed': ['Compensation analysis tools', 'Budget for pay adjustments', 'HR analytics capabilities']})\n        if gaps['safety_gaps']['prevention_gap'] > 0.1:\n            recommendations.append({'area': 'safety', 'priority': 'high', 'type': 'critical', 'recommendation': 'Enhance workplace safety and violence prevention framework', 'actions': ['Implement comprehensive safety training', 'Establish anonymous reporting system', 'Create rapid response protocol', 'Develop support services network'], 'metrics': ['Incident reporting rates', 'Response time to reports', 'Training completion rates', 'Employee safety perception scores'], 'timeline': '3-6 months', 'resources_needed': ['Training platform', 'Reporting system', 'Support services budget']})\n        if gaps['care_support_gaps']['support_gap'] > 0.15:\n            recommendations.append({'area': 'care_support', 'priority': 'high', 'type': 'structural', 'recommendation': 'Develop comprehensive care support infrastructure', 'actions': ['Implement flexible work policies', 'Establish care support allowances', 'Create return-to-work programs', 'Develop caregiver networks'], 'metrics': ['Utilization of care support programs', 'Return-to-work rates', 'Career progression of caregivers', 'Employee satisfaction scores'], 'timeline': '6-12 months', 'resources_needed': ['Care support budget', 'Policy framework', 'Program management resources']})\n        if gaps['policy_gaps']['implementation_gap'] > 0.1:\n            recommendations.append({'area': 'policy', 'priority': 'medium', 'type': 'systemic', 'recommendation': 'Strengthen policy implementation and monitoring framework', 'actions': ['Establish policy oversight committee', 'Create implementation roadmap', 'Develop monitoring mechanisms', 'Regular policy effectiveness reviews'], 'metrics': ['Policy implementation rates', 'Compliance scores', 'Employee awareness levels', 'Policy effectiveness measures'], 'timeline': '9-12 months', 'resources_needed': ['Policy management system', 'Training resources', 'Monitoring tools']})\n        industry_specific = self._generate_industry_specific_recommendations(analysis, benchmarks, gaps)\n        recommendations.extend(industry_specific)\n        return self._prioritize_recommendations(recommendations, gaps)\n\n    def _generate_industry_specific_recommendations(self, analysis: Dict, benchmarks: Dict, gaps: Dict) -> List[Dict]:\n        \"\"\"Generate industry-specific recommendations based on sector characteristics\"\"\"\n        industry_recs = []\n        industry = analysis.get('industry', '').lower()\n        if industry == 'tech':\n            if gaps['leadership_gaps']['pipeline_gap'] > 0.1:\n                industry_recs.append({'area': 'tech_pipeline', 'priority': 'high', 'type': 'structural', 'recommendation': 'Build inclusive technical leadership pipeline', 'actions': ['Create technical mentorship programs', 'Implement blind coding assessments', 'Establish returnship programs', 'Partner with women in tech organizations'], 'metrics': ['Women in technical leadership roles', 'Technical hiring diversity', 'Technical promotion rates'], 'timeline': '12-18 months'})\n        elif industry == 'healthcare':\n            if gaps['care_support_gaps']['flexibility_gap'] > 0.1:\n                industry_recs.append({'area': 'healthcare_workforce', 'priority': 'high', 'type': 'operational', 'recommendation': 'Implement healthcare-specific flexibility framework', 'actions': ['Create shift-trading platform', 'Establish predictive scheduling', 'Develop emergency care support', 'Implement job-sharing programs'], 'metrics': ['Schedule flexibility usage', 'Staff satisfaction scores', 'Care coverage metrics'], 'timeline': '6-12 months'})\n        elif industry == 'finance':\n            if gaps['pay_equity_gaps']['bonus_gap'] > benchmarks['pay_equity']['bonus_gap_threshold']:\n                industry_recs.append({'area': 'financial_compensation', 'priority': 'high', 'type': 'immediate', 'recommendation': 'Address finance-specific compensation disparities', 'actions': ['Review bonus allocation criteria', 'Analyze client assignment patterns', 'Standardize deal credit attribution', 'Implement transparent commission structures'], 'metrics': ['Bonus gap reduction', 'Deal participation equity', 'Client portfolio diversity'], 'timeline': '3-6 months'})\n        return industry_recs\n\n    def _prioritize_recommendations(self, recommendations: List[Dict], gaps: Dict) -> List[Dict]:\n        \"\"\"Prioritize recommendations based on gap analysis and impact potential\"\"\"\n\n        def calculate_priority_score(rec):\n            priority_scores = {'high': 3, 'medium': 2, 'low': 1}\n            score = priority_scores[rec['priority']]\n            gap_area = rec['area']\n            if gap_area in gaps:\n                gap_severity = max(gaps[gap_area].values())\n                score += gap_severity * 2\n            type_multipliers = {'critical': 2.0, 'immediate': 1.8, 'structural': 1.5, 'systemic': 1.3, 'operational': 1.2}\n            score *= type_multipliers.get(rec['type'], 1.0)\n            return score\n        sorted_recs = sorted(recommendations, key=calculate_priority_score, reverse=True)\n        for i, rec in enumerate(sorted_recs, 1):\n            rec['implementation_sequence'] = i\n        return sorted_recs\n\n    def _analyze_violence_prevention(self, analysis: Dict, benchmarks: Dict) -> Dict:\n        \"\"\"Analyze violence prevention measures and gaps\"\"\"\n        violence_indicators = self._extract_violence_indicators(analysis)\n        current_score = self._calculate_violence_prevention_score(violence_indicators)\n        return {'risk_assessment': {'severity_levels': self._evaluate_violence_risks(violence_indicators), 'risk_patterns': self._identify_risk_patterns(violence_indicators), 'vulnerability_factors': self._assess_vulnerabilities(violence_indicators)}, 'prevention_measures': {'existing_measures': self._evaluate_existing_measures(violence_indicators), 'recommended_measures': self._recommend_prevention_measures(violence_indicators), 'implementation_timeline': self._generate_implementation_timeline(violence_indicators)}, 'benchmark_comparison': {'current_score': current_score, 'industry_benchmark': benchmarks['safety_metrics']['violence_prevention_score'], 'gap_analysis': {'prevention_gap': benchmarks['safety_metrics']['violence_prevention_score'] - current_score, 'reporting_gap': benchmarks['safety_metrics']['harassment_reporting_mechanism'] - analysis.get('safety_assessment', {}).get('psychological_safety', {}).get('score', 0), 'response_gap': benchmarks['safety_metrics']['response_effectiveness'] - current_score}, 'improvement_priorities': self._identify_improvement_priorities(violence_indicators, benchmarks)}, 'monitoring_framework': {'metrics': self._define_monitoring_metrics(violence_indicators), 'reporting_schedule': self._create_reporting_schedule(), 'accountability_measures': self._define_accountability_measures()}}\n\n    def _analyze_care_work(self, analysis: Dict, benchmarks: Dict) -> Dict:\n        \"\"\"Analyze unpaid care work recognition and support\"\"\"\n        care_indicators = self._extract_care_indicators(analysis)\n        return {'care_burden_assessment': self._evaluate_care_burden(care_indicators), 'support_measures': self._recommend_care_support(care_indicators), 'benchmark_comparison': {'current_score': self._calculate_care_support_score(care_indicators), 'industry_benchmark': benchmarks['care_support_score'], 'gap_analysis': self._calculate_care_support_gaps(care_indicators, benchmarks)}}\n\n    def _analyze_policy_framework(self, analysis: Dict, benchmarks: Dict) -> Dict:\n        \"\"\"Analyze policy framework effectiveness\"\"\"\n        policy_indicators = self._extract_policy_indicators(analysis)\n        return {'policy_assessment': self._evaluate_policy_effectiveness(policy_indicators), 'policy_recommendations': self._generate_policy_recommendations(policy_indicators), 'benchmark_comparison': {'current_score': self._calculate_policy_score(policy_indicators), 'industry_benchmark': benchmarks['policy_implementation_score'], 'gap_analysis': self._calculate_policy_gaps(policy_indicators, benchmarks)}}\n\n    def _store_analysis(self, db: Session, text: str, analysis: Dict, context: Optional[Dict]=None):\n        \"\"\"Store analysis results in database\"\"\"\n        analysis_record = Analysis(text=text, analysis_type='gender_equity', results=json.dumps(analysis), context=json.dumps(context) if context else None, created_at=datetime.utcnow())\n        db.add(analysis_record)\n        db.commit()\n        db.refresh(analysis_record)\n\n    def _load_violence_indicators(self) -> Dict:\n        \"\"\"\n        Load comprehensive violence and harassment indicators\n        \"\"\"\n",
        "input": "",
        "output": "        return {'physical_violence': ['physical threats', 'intimidation', 'unsafe conditions', 'restricted movement', 'physical isolation'], 'psychological_violence': ['verbal abuse', 'gaslighting', 'manipulation', 'emotional abuse', 'psychological manipulation'], 'economic_violence': ['financial control', 'economic threats', 'withholding resources', 'salary discrimination', 'promotion discrimination'], 'digital_violence': ['online harassment', 'cyberstalking', 'digital surveillance', 'online threats', 'privacy violations'], 'risk_factors': ['power imbalance', 'isolation', 'lack of support systems', 'financial dependency', 'fear of retaliation'], 'protective_factors': ['clear reporting mechanisms', 'support networks', 'financial independence', 'strong policies', 'accountability measures']}\n    \n",
        "idx": "720"
    },
    {
        "instruction": "## autocomplete.py\nclass CppSuggestions:\n    @staticmethod\n    def get_suggestions(word_fragment):\n",
        "input": "",
        "output": "        keywords = [\n            'auto', 'break', 'case', 'char', 'const', 'continue', 'default', 'do', 'double', 'else', 'enum', 'extern',\n            'float', 'print', 'for', 'goto', 'if', 'inline', 'int', 'long', 'register', 'restrict', 'return', 'short', 'signed',\n            'sizeof', 'static', 'struct', 'switch', 'typedef', 'union', 'unsigned', 'void', 'volatile', 'while', '_Alignas',\n            '_Alignof', '_Atomic', '_Bool', '_Complex', '_Generic', '_Imaginary', '_Noreturn', '_Static_assert', '_Thread_local'\n        ]\n        return [kw for kw in keywords if kw.startswith(word_fragment)]\n    \n",
        "idx": "734"
    },
    {
        "instruction": "## autocomplete.py\nclass CSuggestions:\n    @staticmethod\n    def get_suggestions(word_fragment):\n",
        "input": "",
        "output": "        keywords = [\n            'auto', 'break', 'case', 'char', 'const', 'continue', 'default', 'do', 'double', 'else', 'enum', 'extern',\n            'float', 'for', 'goto', 'if', 'inline', 'int', 'long', 'register', 'restrict', 'return', 'short', 'signed',\n            'sizeof', 'static', 'struct', 'switch', 'typedef', 'union', 'unsigned', 'void', 'volatile', 'while', '_Alignas',\n            '_Alignof', '_Atomic', '_Bool', '_Complex', '_Generic', '_Imaginary', '_Noreturn', '_Static_assert', '_Thread_local'\n        ]\n        return [kw for kw in keywords if kw.startswith(word_fragment)]\n    \n",
        "idx": "736"
    },
    {
        "instruction": "## autocomplete.py\nclass JavaScriptSuggestions:\n    @staticmethod\n    def get_suggestions(word_fragment):\n",
        "input": "",
        "output": "        keywords = [\n            'break', 'case', 'catch', 'class', 'const', 'continue', 'debugger', 'default', 'delete', 'do', 'else', 'export',\n            'extends', 'finally', 'for', 'function', 'if', 'import', 'in', 'instanceof', 'let', 'new', 'return', 'super', 'switch',\n            'this', 'throw', 'try', 'typeof', 'var', 'void', 'while', 'with', 'yield'\n        ]\n        return [kw for kw in keywords if kw.startswith(word_fragment)]\n    \n",
        "idx": "737"
    },
    {
        "instruction": "# Here are some relevant code fragments from other files of the repo:\n# --------------------------------------------------\n# the below code fragment can be found in:\n# src/gpt/assistants/question/schemas.py\n# --------------------------------------------------\n# from pydantic import Field, constr, field_validator, BaseModel\n# \n# class UserAnswer(BaseModel):\n#     question: str\n#     correct: bool = Field(description='Correct answer.')\n# \n# --------------------------------------------------\n\n\n## src/gpt/assistants/question/__init__.py\nfrom gpt.assistants.question.schemas import QuizQuestion, QuizQuestionGpt, UserAnswer\n\nPROMPT_SYS = file.read()\n\nPROMPT_PREV_ANS_CORRECT = file.read()\n\nPROMPT_PREV_ANS_INCORRECT = file.read()\n\nPROMPT_NOT_REPEAT = file.read()\n\ndef _get_system_prompt(prev_answers: list[UserAnswer], number: str):\n",
        "input": "",
        "output": "    prompt = [PROMPT_SYS.format(number=number)]\n\n    if prev_answers:\n        correct = []\n        incorrect = []\n\n        for answer in prev_answers:\n            (correct if answer.correct else incorrect).append(answer.question)\n\n        if correct:\n            prompt.append(PROMPT_PREV_ANS_CORRECT.format(prev_answers=\"\\n- \".join(correct)))\n        if incorrect:\n            prompt.append(PROMPT_PREV_ANS_INCORRECT.format(prev_answers=\"\\n- \".join(incorrect)))\n        prompt.append(PROMPT_NOT_REPEAT)\n\n    return \"\\n\".join(prompt)\n\n",
        "idx": "748"
    },
    {
        "instruction": "## lstm.py\nimport pandas as pd\n\nimport numpy as np\n\nimport os\n\nimport json\n\nfrom sklearn.metrics import accuracy_score, classification_report, confusion_matrix\n\nfrom dataclasses import dataclass\n\nfrom tensorflow.keras import Sequential\n\nfrom tensorflow.keras.layers import LSTM, Dense, Dropout\n\nfrom tensorflow.keras.callbacks import EarlyStopping\n\nclass LSTMClassifier:\n    \n    ticker  : str\n    x_train : np.array\n    x_test  : np.array\n    y_train : pd.DataFrame\n    y_test  : pd.DataFrame\n\n    # def save_model(self, model):\n    #     model_path = f\"./models/{self.ticker}.pkl\"\n    #     os.makedirs(os.path.dirname(model_path), exist_ok=True)\n    #     joblib.dump(model, model_path)\n    #     print(f\"Model saved for ticker: {self.ticker}\")\n        \n    def save_results(self, forecast_accuracy, conf_matrix, class_report, y_test, y_pred):\n        results = {\n            \"forecast_accuracy\": forecast_accuracy,\n            \"confusion_matrix\": conf_matrix.tolist(),  # Convert to list for JSON compatibility\n            \"classification_report\": class_report,\n            \"y_test\": y_test.tolist(),  # Convert to list\n            \"y_pred\": y_pred.tolist()   # Convert to list\n        }\n        result_path = f\"./results/{self.ticker}.json\"\n        os.makedirs(os.path.dirname(result_path), exist_ok=True)\n        with open(result_path, \"w\") as f:\n            json.dump(results, f, indent=4)\n        print(f\"Results saved for ticker: {self.ticker}\")\n        \n    def _train(self):\n        # Reshape input to 3D for LSTM [samples, timesteps, features]\n        x_train_reshaped = self.x_train.reshape((self.x_train.shape[0], 1, self.x_train.shape[1]))\n        # x_test_reshaped = self.x_test.reshape((self.x_test.shape[0], 1, self.x_test.shape[1]))\n        \n        lstm_model = Sequential()\n        lstm_model.add(LSTM(100, input_shape=(x_train_reshaped.shape[1], x_train_reshaped.shape[2]), activation='relu', return_sequences=True))\n        lstm_model.add(Dropout(0.6))\n        lstm_model.add(LSTM(50, activation='relu', return_sequences=True))\n        lstm_model.add(Dropout(0.6))\n        lstm_model.add(LSTM(25, activation='relu'))\n        lstm_model.add(Dropout(0.6))\n        lstm_model.add(Dense(1, activation='sigmoid'))\n        \n        lstm_model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])\n        \n        lstm_history = lstm_model.fit(\n            x_train_reshaped, self.y_train, epochs=100, batch_size=32,\n            validation_split=0.2, callbacks=[EarlyStopping(monitor='val_loss', patience=5)], verbose=1\n        )\n        lstm_metrics = pd.DataFrame(lstm_history.history)\n        # self.save_model(lstm_model)\n        return lstm_model, lstm_metrics\n    \n    def _test(self, lstm_model):\n",
        "input": "",
        "output": "        x_test_reshaped = self.x_test.reshape((self.x_test.shape[0], 1, self.x_test.shape[1]))\n        y_predicted = lstm_model.predict(x_test_reshaped)\n        y_pred = np.where(y_predicted > 0.99, 1, 0)  # Threshold for binary classification\n        forecast_accuracy = accuracy_score(self.y_test, y_pred)\n        conf_matrix = confusion_matrix(self.y_test, y_pred)\n        class_report = classification_report(self.y_test, y_pred, output_dict=True)\n        \n        # Save results to JSON\n        self.save_results(forecast_accuracy, conf_matrix, class_report, self.y_test, y_pred)\n        \n        return forecast_accuracy, conf_matrix, class_report\n    \n",
        "idx": "752"
    },
    {
        "instruction": "## UtilityFunctions/Utility.py\nimport zlib\n\ndef ComputeCRC32(Input):\n",
        "input": "",
        "output": "    Hash= zlib.crc32(bytes(Input,\"utf-8\"))\n    if (Hash & (1 << (32 - 1))) != 0:\n        Hash = Hash - (1 << 32)\n    return Hash\n\n",
        "idx": "753"
    },
    {
        "instruction": "\ndef MakeIntIfClose(Num):\n",
        "input": "",
        "output": "    try:\n        float(Num)\n    except:\n        return Num\n    if int(Num) - float(Num) < 0.0000000001:\n        return int(Num)\n    return Num\n\n",
        "idx": "754"
    },
    {
        "instruction": "\ndef SplitNotStringSpaces(String, SplitChar):\n",
        "input": "",
        "output": "    Splits=[]\n    CurrentString=\"\"\n    InBadString=False\n    for X in String:\n        if X == '\"':\n            InBadString=not InBadString\n        if InBadString == False:\n            if X == SplitChar:\n                Splits.append(CurrentString)\n                CurrentString=\"\"\n                continue\n        CurrentString+=X\n    Splits.append(CurrentString)\n    return Splits\n\n",
        "idx": "755"
    },
    {
        "instruction": "# EmulatorFunctions/CodeRunner.py\n\nclass CodeRunner:\n\n    def __init__(self, Parent, FilePath='Configs/Functions.json', DeviceFile: str='Configs/Devices.json'):\n        self.DevicesList = json.loads(open(DeviceFile, 'r').read())\n        self.FunctionMap = json.load(open(FilePath, 'r'))\n        for X, Y in self.FunctionMap['SpecialTypes'].items():\n            Y['ConfirmFunction'] = getattr(self, Y['ConfirmFunction'])\n            Y['GetArgFunction'] = getattr(self, Y['GetArgFunction'])\n        for X, Y in self.FunctionMap['Functions'].items():\n            Y['Function'] = getattr(self, Y['Function'])\n        self.Parent = Parent\n        self.Code = self.Parent.Code.split('\\n')\n        self.Registers = {f'r{X}': 0 for X in range(0, 18)}\n        self.RegisterAliases = copy.copy(Constants.DEFAULT_REGISTER_ALIAS)\n        self.PinAliases = {}\n        if self.Parent.StackEnabled == True:\n            self.Stack = [0 for X in range(self.Parent.StackLength)]\n        self.Constants = copy.copy(Constants.DEFAULT_CONSTANTS)\n        self.ParseCode()\n        self.HighestSP = 0\n\n    def ParseCode(self):\n        self.LogicTypesList = set(['ReferenceId', 'PrefabHash'] + [f'Channel{X}' for X in range(8)])\n        for X, Y in self.DevicesList.items():\n            for A, B in Y['Fields'].items():\n                if B['Read'] or B['Write']:\n                    self.LogicTypesList.add(A)\n        for X, Y in enumerate(self.Code):\n            if '#' in Y:\n                Location = Y.find('#')\n                self.Code[X] = Y[:Location].strip()\n            YTemp = self.Code[X].strip()\n            if ' ' not in YTemp:\n                if YTemp.endswith(':'):\n                    if YTemp not in self.Constants:\n                        self.Constants[YTemp[:-1]] = X\n                    else:\n                        Log.Warning('You cannot declare two lables with the same name', Caller=f\"Script line {self.Parent.Fields['LineNumber'].Value}\")\n                        self.Parent.Fields['Error'].Value = 1\n                    self.Code[X] = ''\n\n    def PrintRegisters(self):\n        Output = ['\\n+------------+-------+\\n|Registers   |       |']\n        for X, Y in self.Registers.items():\n            Output.append(f'|{X:<12}|{Y:<7}|')\n        Log.Info('\\n'.join(Output) + '\\n+------------+-------+')\n\n    def PrintConstants(self):\n        Output = ['\\n+------------+-------+\\n|Constants   |       |']\n        for X, Y in self.Constants.items():\n            Output.append(f'|{X:<12}|{Y:<7}|')\n        Log.Info('\\n'.join(Output) + '\\n+------------+-------+')\n\n    def PrintAlias(self):\n        Output = ['\\n+------------+-------+\\n|Aliases     |       |']\n        for X, Y in self.RegisterAliases.items():\n            Output.append(f'|{X:<12}|{Y:<7}|')\n        for X, Y in self.PinAliases.items():\n            Output.append(f'|{X:<12}|{Y:<7}|')\n        Log.Info('\\n'.join(Output) + '\\n+------------+-------+')\n\n    def PrintStack(self):\n        Output = ['\\n+------------+-------+\\n|Stack       |       |']\n        for X in range(self.HighestSP + 1):\n            Output.append(f'|{X:<12}|{self.Stack[X]:<7}|')\n        Log.Info('\\n'.join(Output) + '\\n+------------+-------+')\n\n    def ScriptLength(self):\n        return len(self.Script)\n\n    def Special_LogicTypes(self, Value, BaseType):\n        return Value in self.LogicTypesList\n\n    def Special_Get_LogicType(self, Value):\n        return Value\n\n    def Special_BatchMode(self, Value, BaseType):\n        if BaseType == 'String':\n            return Value in list(Constants.BATCH_TYPES_VALUES.keys())\n        return True\n\n    def Special_Get_BatchMode(self, Value):\n        if type(Value) == str:\n            if str(Value) in Constants.BATCH_TYPES_VALUES:\n                return Constants.BATCH_TYPES_VALUES[Value]\n        RawValue = self.GetArgValue(Value)\n        if RawValue >= 0 and RawValue < len(Constants.BATCH_TYPES_VALUES):\n            return RawValue\n        else:\n            Log.Warning(f'Batch mode value must bettween greater then or euqal too 0 and less then {len(Constants.BATCH_TYPES_VALUES)}', Caller=f\"Script line {self.Parent.Fields['LineNumber'].Value} \")\n            self.Parent.Fields['Error'].Value = 1\n            return None\n\n    def Special_DeviceHash(self, Value, BaseType):\n        return True\n\n    def Special_Get_DeviceHash(self, Value):\n        return Value\n\n    def Special_NameHash(self, Value, BaseType):\n        return True\n\n    def Special_Get_NameHash(self, Value):\n        return Value\n\n    def Special_ReferenceID(self, Value, BaseType):\n        return True\n\n    def Special_Get_ReferenceID(self, Value):\n        return Value\n\n    def GetArgBaseType(self, Value, TargetTypes=[]):\n        if len(Value) == 0:\n            return 'None'\n        if Value in self.Constants and 'Constant' in TargetTypes:\n            return 'Constant'\n        if Value in self.RegisterAliases and 'Register' in TargetTypes:\n            return 'Register'\n        if Value in self.PinAliases and 'Device' in TargetTypes:\n            return 'Device'\n        if Value[0] == 'd' and len(Value) > 1 and ('Device' in TargetTypes):\n            if 'r' in Value:\n                try:\n                    InValue = int(Value[1:].replace('r', ''))\n                    if InValue >= 0 and InValue < 18:\n                        return 'Device'\n                except:\n                    pass\n            else:\n                try:\n                    DeviceNumberList = [str(X) for X in range(self.Parent.PinsNumber)] + ['b']\n                    if Value[1:] in DeviceNumberList:\n                        return 'Device'\n                except:\n                    pass\n        if Value[0] == 'r' and len(Value) > 1 and ('Register' in TargetTypes):\n            try:\n                InValue = int(Value.replace('r', ''))\n                if InValue >= 0 and InValue < 18:\n                    return 'Register'\n            except:\n                pass\n        if Value.startswith('HASH(\"') and Value.endswith('\")') and ('Hash' in TargetTypes):\n            return 'Hash'\n        if 'Number' in TargetTypes:\n            if Value[0] == '$':\n                try:\n                    int(Value[1:], 16)\n                    return 'Number'\n                except:\n                    pass\n            try:\n                int(Value)\n                return 'Number'\n            except:\n                try:\n                    float(Value)\n                    return 'Number'\n                except:\n                    pass\n        return 'String'\n\n    def GetArgType(self, Value, TargetTypes=[]):\n        IsSpecialType = TargetTypes[0] in self.FunctionMap['SpecialTypes']\n        if IsSpecialType:\n            SpecialType = TargetTypes[0]\n            TargetTypes = self.FunctionMap['SpecialTypes'][SpecialType]['Types'].split('|')\n        BaseType = self.GetArgBaseType(Value, TargetTypes)\n        if IsSpecialType:\n            if BaseType in TargetTypes:\n                Confirmed = self.FunctionMap['SpecialTypes'][SpecialType]['ConfirmFunction'](Value, BaseType)\n                if Confirmed:\n                    return SpecialType\n                else:\n                    return 'None'\n        return BaseType\n\n    def GetArgIndex(self, Value):\n        if Value in self.Constants:\n            Log.Warning('You cannot change a constant value', Caller=f\"Script line {self.Parent.Fields['LineNumber'].Value} \")\n            self.Parent.Fields['Error'].Value = 1\n            return None\n        if Value in self.RegisterAliases:\n            return self.GetArgIndex(self.RegisterAliases[Value])\n        if Value in self.PinAliases:\n            return self.GetArgIndex(self.PinAliases[Value])\n        if Value[0] == 'd':\n            if 'r' in Value:\n                try:\n                    TempValue = Value[1:]\n                    RegisterIndex = int(TempValue.replace('r', ''))\n                    for X in range(TempValue.count('r')):\n                        if RegisterIndex not in Constants.NOT_NUMBER_NUMBERS:\n                            if RegisterIndex >= 0 and RegisterIndex < 18:\n                                RegisterIndex = self.Registers[f'r{RegisterIndex}']\n                            else:\n                                Log.Warning('Indirect device values have to be bettween 0 and 17', Caller=f\"Script line {self.Parent.Fields['LineNumber'].Value}\")\n                                self.Parent.Fields['Error'].Value = 1\n                                return None\n                        else:\n                            Log.Warning('Indirect device values have to be bettween 0 and 17 not NaN', Caller=f\"Script line {self.Parent.Fields['LineNumber'].Value}\")\n                            self.Parent.Fields['Error'].Value = 1\n                            return None\n                    RegisterIndex = f'd{RegisterIndex}'\n                    if RegisterIndex in self.Parent.Pins:\n                        return RegisterIndex\n                    Log.Warning('Indirect device values have to be bettween 0 and 5', Caller=f\"Script line {self.Parent.Fields['LineNumber'].Value}\")\n                    self.Parent.Fields['Error'].Value = 1\n                    return None\n                except:\n                    pass\n            elif Value[0] == 'd' and Value[1:] in [str(X) for X in range(self.Parent.PinsNumber)] + ['b']:\n                return Value\n        if Value[0] == 'r':\n            try:\n                RegisterIndex = int(Value.replace('r', ''))\n                for X in range(Value.count('r') - 1):\n                    if RegisterIndex not in Constants.NOT_NUMBER_NUMBERS:\n                        if RegisterIndex >= 0 and RegisterIndex < 18:\n                            RegisterIndex = self.Registers[f'r{RegisterIndex}']\n                        else:\n                            Log.Warning('Indirect refrences values have to be bettween 0 and 17', Caller=f\"Script line {self.Parent.Fields['LineNumber'].Value}\")\n                            self.Parent.Fields['Error'].Value = 1\n                            return None\n                    else:\n                        Log.Warning('Indirect refrences values have to be bettween 0 and 17 not NaN', Caller=f\"Script line {self.Parent.Fields['LineNumber'].Value}\")\n                        self.Parent.Fields['Error'].Value = 1\n                        return None\n                return f'r{RegisterIndex}'\n            except:\n                pass\n        Log.Warning('Unknown value', Caller=f\"Script line {self.Parent.Fields['LineNumber'].Value}\")\n        self.Parent.Fields['Error'].Value = 1\n        return None\n\n    def GetArgValue(self, Value, TargetType=[]):\n        Value = str(Value)\n        if Value in self.Constants:\n            return self.Constants[Value]\n        if Value[0] == 'r':\n            try:\n                RegisterIndex = int(Value.replace('r', ''))\n                for X in range(Value.count('r') - 1):\n                    if RegisterIndex not in Constants.NOT_NUMBER_NUMBERS:\n                        if RegisterIndex >= 0 and RegisterIndex < 18:\n                            RegisterIndex = self.Registers[f'r{RegisterIndex}']\n                        else:\n                            Log.Warning('Indirect refrences values have to be bettween 0 and 17', Caller=f\"Script line {self.Parent.Fields['LineNumber'].Value}\")\n                            self.Parent.Fields['Error'].Value = 1\n                            return None\n                    else:\n                        Log.Warning('Indirect refrences values have to be bettween 0 and 17 not NaN', Caller=f\"Script line {self.Parent.Fields['LineNumber'].Value}\")\n                        self.Parent.Fields['Error'].Value = 1\n                        return None\n                return self.Registers[f'r{RegisterIndex}']\n            except:\n                pass\n        if Value in self.RegisterAliases:\n            return self.GetArgValue(self.RegisterAliases[Value])\n        if Value[0] == '$':\n            try:\n                return int(Value[1:], 16)\n            except:\n                pass\n        if Value.startswith('HASH(\"') and Value.endswith('\")'):\n            Value = Value[6:-2]\n            return ComputeCRC32(Value)\n        try:\n            return int(Value)\n        except:\n            try:\n                return float(Value)\n            except:\n                pass\n        return str(Value)\n\n    def GetSpecialArgValue(self, Value, Type):\n        if Type in self.FunctionMap['SpecialTypes']:\n            ProcessedValue = self.GetArgValue(Value, Type)\n            if self.Parent.Fields['Error'].Value == 1:\n                return\n            return self.FunctionMap['SpecialTypes'][Type]['GetArgFunction'](ProcessedValue)\n        else:\n            Log.Warning(f'Invalid special arg type', Caller=f\"Script line {self.Parent.Fields['LineNumber'].Value}\")\n            self.Parent.Fields['Error'].Value = 1\n\n    def GetDeviceObject(self, RefID: int, DoError: bool=True):\n        if self.Parent.Fields['Error'].Value == 1:\n            return\n        RefObject = self.Parent.Network.GetDevice(RefID)\n        if RefObject != None:\n            return RefObject\n        elif DoError:\n            Log.Warning(f'Unknown device at reference id {RefID}', Caller=f\"Script line {self.Parent.Fields['LineNumber'].Value}\")\n            self.Parent.Fields['Error'].Value = 1\n        else:\n            return None\n\n    def Instruction_Define(self, *args):\n        Value = int(args[2])\n        if args[1] not in self.Constants:\n            self.Constants[args[1]] = Value\n            if args[1] in self.RegisterAliases:\n                del self.RegisterAliases[args[1]]\n        else:\n            Log.Warning('You cannot change a constant value', Caller=f\"Script line {self.Parent.Fields['LineNumber'].Value}\")\n            if self.Parent.Fields['Error'].Value == 1:\n                return\n\n    def Instruction_Move(self, *args):\n        Index1 = self.GetArgIndex(args[1])\n        Value2 = self.GetArgValue(args[2])\n        if self.Parent.Fields['Error'].Value == 1:\n            return\n        self.Registers[Index1] = Value2\n\n    def Instruction_Alias(self, *args):\n        if self.GetArgType(args[1], ['String']) == 'String':\n            if args[1] not in self.Constants and args[1] not in self.Parent.Pins and (args[1] not in self.Registers):\n                if args[1] in self.RegisterAliases:\n                    del self.RegisterAliases[args[1]]\n                if args[1] in self.PinAliases:\n                    del self.PinAliases[args[1]]\n                if args[2][0] == 'r':\n                    self.RegisterAliases[args[1]] = args[2]\n                elif args[2][0] == 'd':\n                    self.PinAliases[args[1]] = args[2]\n                else:\n                    Log.Error('Unkown alias type not caught by update')\n            else:\n                Log.Warning('Cannot overwrite a constant/builtin register/builtin device index', Caller=f\"Script line {self.Parent.Fields['LineNumber'].Value}\")\n                if self.Parent.Fields['Error'].Value == 1:\n                    return\n        else:\n            Log.Warning('You cannot set a register alias to a device name or a register', Caller=f\"Script line {self.Parent.Fields['LineNumber'].Value}\")\n            self.Parent.Fields['Error'].Value = 1\n\n    def Instruction_Add(self, *args):\n        Index1 = self.GetArgIndex(args[1])\n        Value1 = self.GetArgValue(args[2])\n        Value2 = self.GetArgValue(args[3])\n        if self.Parent.Fields['Error'].Value == 1:\n            return\n        if Value1 in Constants.NOT_NUMBER_NUMBERS:\n            self.Registers[Index1] = Value1\n            return\n        if Value2 in Constants.NOT_NUMBER_NUMBERS:\n            self.Registers[Index1] = Value2\n            return\n        self.Registers[Index1] = Value1 + Value2\n\n    def Instruction_Sub(self, *args):\n        Index1 = self.GetArgIndex(args[1])\n        Value1 = self.GetArgValue(args[2])\n        Value2 = self.GetArgValue(args[3])\n        if self.Parent.Fields['Error'].Value == 1:\n            return\n        if Value1 in Constants.NOT_NUMBER_NUMBERS:\n            self.Registers[Index1] = Value1\n            return\n        if Value2 in Constants.NOT_NUMBER_NUMBERS:\n            self.Registers[Index1] = Value2\n            return\n        self.Registers[Index1] = Value1 - Value2\n\n    def Instruction_Mul(self, *args):\n        Index1 = self.GetArgIndex(args[1])\n        Value1 = self.GetArgValue(args[2])\n        Value2 = self.GetArgValue(args[3])\n        if self.Parent.Fields['Error'].Value == 1:\n            return\n        if Value1 in Constants.NOT_NUMBER_NUMBERS:\n            self.Registers[Index1] = Value1\n            return\n        if Value2 in Constants.NOT_NUMBER_NUMBERS:\n            self.Registers[Index1] = Value2\n            return\n        self.Registers[Index1] = Value1 * Value2\n\n    def Instruction_Div(self, *args):\n        Index1 = self.GetArgIndex(args[1])\n        Value1 = self.GetArgValue(args[2])\n        Value2 = self.GetArgValue(args[3])\n        if self.Parent.Fields['Error'].Value == 1:\n            return\n        if Value1 in Constants.NOT_NUMBER_NUMBERS:\n            self.Registers[Index1] = Value1\n            return\n        if Value2 in Constants.NOT_NUMBER_NUMBERS:\n            self.Registers[Index1] = Value2\n            return\n        if Value2 == 0:\n            self.Registers[Index1] = 'NaN'\n            return\n        self.Registers[Index1] = Value1 / Value2\n\n    def Instruction_Abs(self, *args):\n        Index1 = self.GetArgIndex(args[1])\n        Value1 = self.GetArgValue(args[2])\n        if self.Parent.Fields['Error'].Value == 1:\n            return\n        if Value1 in Constants.NOT_NUMBER_NUMBERS:\n            self.Registers[Index1] = Value1\n            return\n        self.Registers[Index1] = abs(Value1)\n\n    def Instruction_Ceil(self, *args):\n        Index1 = self.GetArgIndex(args[1])\n        Value1 = self.GetArgValue(args[2])\n        if self.Parent.Fields['Error'].Value == 1:\n            return\n        if Value1 in Constants.NOT_NUMBER_NUMBERS:\n            self.Registers[Index1] = Value1\n            return\n        self.Registers[Index1] = math.ceil(Value1)\n\n    def Instruction_Floor(self, *args):\n        Index1 = self.GetArgIndex(args[1])\n        Value1 = self.GetArgValue(args[2])\n        if self.Parent.Fields['Error'].Value == 1:\n            return\n        if Value1 in Constants.NOT_NUMBER_NUMBERS:\n            self.Registers[Index1] = Value1\n            return\n        self.Registers[Index1] = math.floor(Value1)\n\n    def Instruction_Exp(self, *args):\n        Index1 = self.GetArgIndex(args[1])\n        Value1 = self.GetArgValue(args[2])\n        if self.Parent.Fields['Error'].Value == 1:\n            return\n        if Value1 in Constants.NOT_NUMBER_NUMBERS:\n            self.Registers[Index1] = Value1\n            return\n        self.Registers[Index1] = math.e ** Value1\n\n    def Instruction_Log(self, *args):\n        Index1 = self.GetArgIndex(args[1])\n        Value1 = self.GetArgValue(args[2])\n        if self.Parent.Fields['Error'].Value == 1:\n            return\n        if Value1 in Constants.NOT_NUMBER_NUMBERS:\n            self.Registers[Index1] = Value1\n            return\n        self.Registers[Index1] = math.log(Value1)\n\n    def Instruction_Rand(self, *args):\n        Index1 = self.GetArgIndex(args[1])\n        if self.Parent.Fields['Error'].Value == 1:\n            return\n        self.Registers[Index1] = random.random()\n\n    def Instruction_Round(self, *args):\n        Index1 = self.GetArgIndex(args[1])\n        Value1 = self.GetArgValue(args[2])\n        if self.Parent.Fields['Error'].Value == 1:\n            return\n        if Value1 in Constants.NOT_NUMBER_NUMBERS:\n            self.Registers[Index1] = Value1\n            return\n        Decimal = Value1 - math.floor(Value1)\n        if Decimal >= 0.5:\n            self.Registers[Index1] = math.ceil(Value1)\n        else:\n            self.Registers[Index1] = math.floor(Value1)\n\n    def Instruction_Sqrt(self, *args):\n        Index1 = self.GetArgIndex(args[1])\n        Value1 = self.GetArgValue(args[2])\n        if self.Parent.Fields['Error'].Value == 1:\n            return\n        if Value1 in Constants.NOT_NUMBER_NUMBERS:\n            self.Registers[Index1] = Value1\n            return\n        self.Registers[Index1] = math.sqrt(Value1)\n\n    def Instruction_Trunc(self, *args):\n        Index1 = self.GetArgIndex(args[1])\n        Value1 = self.GetArgValue(args[2])\n        if self.Parent.Fields['Error'].Value == 1:\n            return\n        if Value1 in Constants.NOT_NUMBER_NUMBERS:\n            self.Registers[Index1] = Value1\n            return\n        self.Registers[Index1] = math.trunc(Value1)\n\n    def Instruction_Asin(self, *args):\n        Index1 = self.GetArgIndex(args[1])\n        Value1 = self.GetArgValue(args[2])\n        if self.Parent.Fields['Error'].Value == 1:\n            return\n        if Value1 in Constants.NOT_NUMBER_NUMBERS:\n            self.Registers[Index1] = Value1\n            return\n        try:\n            self.Registers[Index1] = math.asin(Value1)\n        except:\n            self.Registers[Index1] = 'NaN'\n\n    def Instruction_Acos(self, *args):\n        Index1 = self.GetArgIndex(args[1])\n        Value1 = self.GetArgValue(args[2])\n        if self.Parent.Fields['Error'].Value == 1:\n            return\n        if Value1 in Constants.NOT_NUMBER_NUMBERS:\n            self.Registers[Index1] = Value1\n            return\n        try:\n            self.Registers[Index1] = math.acos(Value1)\n        except:\n            self.Registers[Index1] = 'NaN'\n\n    def Instruction_Atan(self, *args):\n        Index1 = self.GetArgIndex(args[1])\n        Value1 = self.GetArgValue(args[2])\n        if self.Parent.Fields['Error'].Value == 1:\n            return\n        if Value1 in Constants.NOT_NUMBER_NUMBERS:\n            self.Registers[Index1] = Value1\n            return\n        try:\n            self.Registers[Index1] = math.atan(Value1)\n        except:\n            self.Registers[Index1] = 'NaN'\n\n    def Instruction_Atan2(self, *args):\n        Index1 = self.GetArgIndex(args[1])\n        Value1 = self.GetArgValue(args[2])\n        Value2 = self.GetArgValue(args[3])\n        if self.Parent.Fields['Error'].Value == 1:\n            return\n        if Value1 in Constants.NOT_NUMBER_NUMBERS:\n            self.Registers[Index1] = Value1\n            return\n        if Value2 in Constants.NOT_NUMBER_NUMBERS:\n            self.Registers[Index1] = Value2\n            return\n        try:\n            self.Registers[Index1] = math.atan2(Value1, Value2)\n        except:\n            self.Registers[Index1] = 'NaN'\n\n    def Instruction_Cos(self, *args):\n        Index1 = self.GetArgIndex(args[1])\n        Value1 = self.GetArgValue(args[2])\n        if self.Parent.Fields['Error'].Value == 1:\n            return\n        if Value1 in Constants.NOT_NUMBER_NUMBERS:\n            self.Registers[Index1] = Value1\n            return\n        try:\n            self.Registers[Index1] = math.cos(Value1)\n        except:\n            self.Registers[Index1] = 'NaN'\n\n    def Instruction_Tan(self, *args):\n        Index1 = self.GetArgIndex(args[1])\n        Value1 = self.GetArgValue(args[2])\n        if self.Parent.Fields['Error'].Value == 1:\n            return\n        if Value1 in Constants.NOT_NUMBER_NUMBERS:\n            self.Registers[Index1] = Value1\n            return\n        try:\n            self.Registers[Index1] = math.tan(Value1)\n        except:\n            self.Registers[Index1] = 'NaN'\n\n    def Instruction_Peek(self, *args):\n        Index1 = self.Registers[self.RegisterAliases['sp']]\n        Index2 = self.GetArgIndex(args[1])\n        if self.Parent.Fields['Error'].Value == 1:\n            return\n        if Index1 in Constants.NOT_NUMBER_NUMBERS:\n            Log.Warning('Cannot peek at NaN index', Caller=f\"Script line {self.Parent.Fields['LineNumber'].Value}\")\n            self.Parent.Fields['Error'].Value = 1\n            return\n        if Index1 >= 1 and Index1 <= self.Parent.StackLength:\n            self.Registers[Index2] = self.Stack[Index1 - 1]\n        else:\n            Log.Warning(f'Peek index must be greater then 0 and less then or equal to {self.Parent.StackLength}', Caller=f\"Script line {self.Parent.Fields['LineNumber'].Value}\")\n            self.Parent.Fields['Error'].Value = 1\n\n    def Instruction_Push(self, *args):\n        Index1 = self.Registers[self.RegisterAliases['sp']]\n        Value1 = self.GetArgValue(args[1])\n        if self.Parent.Fields['Error'].Value == 1:\n            return\n        if Index1 in Constants.NOT_NUMBER_NUMBERS:\n            Log.Warning('Cannot push at NaN index', Caller=f\"Script line {self.Parent.Fields['LineNumber'].Value}\")\n            self.Parent.Fields['Error'].Value = 1\n            return\n        if Index1 >= 0 and Index1 < self.Parent.StackLength:\n            self.Stack[Index1] = Value1\n            self.Registers[self.RegisterAliases['sp']] += 1\n        else:\n            Log.Warning(f'Push index must be greater then or euqal to 0 and less then {self.Parent.StackLength}', Caller=f\"Script line {self.Parent.Fields['LineNumber'].Value}\")\n            self.Parent.Fields['Error'].Value = 1\n\n    def Instruction_Pop(self, *args):\n        Index1 = self.Registers[self.RegisterAliases['sp']]\n        Index2 = self.GetArgIndex(args[1])\n        if self.Parent.Fields['Error'].Value == 1:\n            return\n        if Index1 in Constants.NOT_NUMBER_NUMBERS:\n            Log.Warning('Cannot pop at NaN index', Caller=f\"Script line {self.Parent.Fields['LineNumber'].Value}\")\n            self.Parent.Fields['Error'].Value = 1\n            return\n        if Index1 > 0 and Index1 <= self.Parent.StackLength:\n            self.Registers[Index2] = self.Stack[Index1 - 1]\n            self.Registers[self.RegisterAliases['sp']] -= 1\n        else:\n            Log.Warning(f'Pop index must be greater then 0 and less then or equal to {self.Parent.StackLength}', Caller=f\"Script line {self.Parent.Fields['LineNumber'].Value}\")\n            self.Parent.Fields['Error'].Value = 1\n\n    def Instruction_Get(self, *args):\n        Index1 = self.GetArgIndex(args[1])\n        Index2 = self.GetArgIndex(args[2])\n        Index3 = self.GetArgValue(args[3])\n        if self.Parent.Fields['Error'].Value == 1:\n            return\n        if Index2 in self.Parent.Pins:\n            DeviceObject = self.GetDeviceObject(self.Parent.Pins[Index2])\n        else:\n            Log.Warning(f'No device at {Index2}', Caller=f\"Script line {self.Parent.Fields['LineNumber'].Value}\")\n            self.Parent.Fields['Error'].Value = 1\n            return\n        if DeviceObject.StackEnabled == False:\n            Log.Warning(f'Device does not have a stack', Caller=f\"Script line {self.Parent.Fields['LineNumber'].Value}\")\n            self.Parent.Fields['Error'].Value = 1\n            return\n        if Index3 in Constants.NOT_NUMBER_NUMBERS:\n            Log.Warning('Cannot get at NaN index', Caller=f\"Script line {self.Parent.Fields['LineNumber'].Value}\")\n            self.Parent.Fields['Error'].Value = 1\n            return\n        if Index3 >= 1 and Index3 <= DeviceObject.StackLength:\n            self.Registers[Index1] = self.Stack[Index3 - 1]\n            Log.Warning(f'Needs further testing', Caller=f\"Script line {self.Parent.Fields['LineNumber'].Value}\")\n        else:\n            Log.Warning(f'Get must be greater then 0 and less then or equal to {DeviceObject.StackLength}', Caller=f\"Script line {self.Parent.Fields['LineNumber'].Value}\")\n            self.Parent.Fields['Error'].Value = 1\n\n    def Instruction_GetD(self, *args):\n        pass\n\n    def Instruction_Poke(self, *args):\n        Value1 = self.GetArgValue(args[1])\n        Value2 = self.GetArgValue(args[2])\n        if self.Parent.Fields['Error'].Value == 1:\n            return\n        if Value1 in Constants.NOT_NUMBER_NUMBERS:\n            Log.Warning('Cannot poke at NaN index', Caller=f\"Script line {self.Parent.Fields['LineNumber'].Value}\")\n            self.Parent.Fields['Error'].Value = 1\n            return\n        if Value1 >= 0 and Value1 < self.Parent.StackLength:\n            self.Stack[Value1] = Value2\n        else:\n            Log.Warning(f'Pop index must be greater then or equal to 0 and less then {self.Parent.StackLength}', Caller=f\"Script line {self.Parent.Fields['LineNumber'].Value}\")\n            self.Parent.Fields['Error'].Value = 1\n\n    def Instruction_Load(self, *args):\n        Index1 = self.GetArgIndex(args[1])\n        Index2 = self.GetArgIndex(args[2])\n        Value1 = self.GetSpecialArgValue(args[3], 'LogicType')\n        if self.Parent.Fields['Error'].Value == 1:\n            return\n        if Index2 in self.Parent.Pins:\n            DeviceObject = self.GetDeviceObject(self.Parent.Pins[Index2])\n        else:\n            Log.Warning(f'No device at {Index2}', Caller=f\"Script line {self.Parent.Fields['LineNumber'].Value}\")\n            self.Parent.Fields['Error'].Value = 1\n            return\n        if self.Parent.Fields['Error'].Value == 1:\n            return\n        FieldValue = DeviceObject.GetFieldValue(Value1)\n        if FieldValue[0] == None:\n            Log.Warning(FieldValue[1], Caller=f\"Script line {self.Parent.Fields['LineNumber'].Value}\")\n            self.Parent.Fields['Error'].Value = 1\n            return None\n        self.Registers[Index1] = FieldValue[0]\n\n    def ApplyBatchOperation(self, Values, BatchMode):\n        try:\n            BatchMode = int(BatchMode)\n            if BatchMode < 0 or BatchMode >= len(Constants.BATCH_NO_RESPONSE):\n                return 0\n        except:\n            return 0\n        if len(Values) == 0:\n            return Constants.BATCH_NO_RESPONSE[BatchMode]\n        if BatchMode == 0:\n            return sum(Values) / len(Values)\n        elif BatchMode == 1:\n            return sum(Values)\n        elif BatchMode == 2:\n            return min(Values)\n        elif BatchMode == 3:\n            return max(Values)\n        return 'NaN'\n\n    def CollectDevicesValueBatch(self, Devices, Value, BatchMode):\n        Values = []\n        for X in Devices:\n            FieldValue = X.GetFieldValue(Value)\n            if FieldValue[0] != None:\n                Values.append(FieldValue[0])\n        if len(Values) == 0:\n            return Constants.BATCH_NO_RESPONSE[BatchMode]\n        return MakeIntIfClose(self.ApplyBatchOperation(Values, BatchMode))\n\n    def Instruction_LoadBatch(self, *args):\n        Index1 = self.GetArgIndex(args[1])\n        Value1 = self.GetSpecialArgValue(args[2], 'DeviceHash')\n        Value2 = self.GetSpecialArgValue(args[3], 'LogicType')\n        Value3 = self.GetSpecialArgValue(args[4], 'BatchMode')\n        if self.Parent.Fields['Error'].Value == 1:\n            return\n        if Value1 in Constants.NOT_NUMBER_NUMBERS:\n            self.Registers[Index1] = 'Nan'\n            return\n        Devices = self.Parent.Network.GetBatchDevices(Value1)\n        Result = self.CollectDevicesValueBatch(Devices, Value2, Value3)\n        self.Registers[Index1] = Result\n\n    def Instruction_LoadBatchNamed(self, *args):\n        Index1 = self.GetArgIndex(args[1])\n        Value1 = self.GetSpecialArgValue(args[2], 'DeviceHash')\n        Value2 = self.GetSpecialArgValue(args[3], 'NameHash')\n        Value3 = self.GetSpecialArgValue(args[4], 'LogicType')\n        Value4 = self.GetSpecialArgValue(args[5], 'BatchMode')\n        if self.Parent.Fields['Error'].Value == 1:\n            return\n        if Value1 in Constants.NOT_NUMBER_NUMBERS:\n            self.Registers[Index1] = 'NaN'\n            return\n        if Value2 in Constants.NOT_NUMBER_NUMBERS:\n            Log.Warning(f'Cannot get a device with a NameHash of NaN', Caller=f\"Script line {self.Parent.Fields['LineNumber'].Value}\")\n            self.Parent.Fields['Error'].Value = 1\n            return\n        Devices = self.Parent.Network.GetBatchDevices(Value1, Value2)\n        Result = self.CollectDevicesValueBatch(Devices, Value3, Value4)\n        self.Registers[Index1] = Result\n\n    def Instruction_Set(self, *args):\n        Index1 = self.GetArgIndex(args[1])\n        Value1 = self.GetSpecialArgValue(args[2], 'LogicType')\n        Value2 = self.GetArgValue(args[3])\n        if self.Parent.Fields['Error'].Value == 1:\n            return\n        if Index1 in self.Parent.Pins:\n            DeviceObject = self.GetDeviceObject(self.Parent.Pins[Index1])\n        else:\n            Log.Warning(f'No device at {Index1}', Caller=f\"Script line {self.Parent.Fields['LineNumber'].Value}\")\n            self.Parent.Fields['Error'].Value = 1\n            return\n        if self.Parent.Fields['Error'].Value == 1:\n            return\n        Result = DeviceObject.SetFieldValue(Value1, Value2)\n        if Result[0] == None:\n            Log.Warning(Result[1], Caller=f\"Script line {self.Parent.Fields['LineNumber'].Value}\")\n            self.Parent.Fields['Error'].Value = 1\n\n    def Instruction_SetBatch(self, *args):\n        Value1 = self.GetSpecialArgValue(args[1], 'DeviceHash')\n        Value2 = self.GetSpecialArgValue(args[2], 'LogicType')\n        Value3 = self.GetArgValue(args[3])\n        if self.Parent.Fields['Error'].Value == 1:\n            return\n        Devices = self.Parent.Network.GetBatchDevices(Value1)\n        for X in Devices:\n            X.SetFieldValue(Value2, Value3)\n\n    def Instruction_SetBatchNamed(self, *args):\n        Value1 = self.GetSpecialArgValue(args[1], 'DeviceHash')\n        Value2 = self.GetSpecialArgValue(args[2], 'NameHash')\n        Value3 = self.GetSpecialArgValue(args[3], 'LogicType')\n        Value4 = self.GetArgValue(args[4])\n        if self.Parent.Fields['Error'].Value == 1:\n            return\n        Devices = self.Parent.Network.GetBatchDevices(Value1, Value2)\n        for X in Devices:\n            X.SetFieldValue(Value3, Value4)\n\n    def Instruction_SetDevice(self, *args):\n        Index1 = self.GetSpecialArgValue(args[1], 'ReferenceID')\n        Value1 = self.GetSpecialArgValue(args[2], 'LogicType')\n        Value2 = self.GetArgValue(args[3])\n        if self.Parent.Fields['Error'].Value == 1:\n            return\n        DeviceObject = self.GetDeviceObject(Index1)\n        if self.Parent.Fields['Error'].Value == 1:\n            return\n        Result = DeviceObject.SetFieldValue(Value1, Value2)\n        if Result[0] == None:\n            Log.Warning(Result[1], Caller=f\"Script line {self.Parent.Fields['LineNumber'].Value}\")\n            self.Parent.Fields['Error'].Value = 1\n\n    def Instruction_LoadDevice(self, *args):\n        Index1 = self.GetArgIndex(args[1])\n        Index2 = self.GetSpecialArgValue(args[2], 'ReferenceID')\n        Value1 = self.GetSpecialArgValue(args[3], 'LogicType')\n        if self.Parent.Fields['Error'].Value == 1:\n            return\n        DeviceObject = self.GetDeviceObject(self.Parent.Pins[Index2])\n        if self.Parent.Fields['Error'].Value == 1:\n            return\n        FieldValue = DeviceObject.GetFieldValue(Value1)\n        if FieldValue[0] == None:\n            Log.Warning(FieldValue[1], Caller=f\"Script line {self.Parent.Fields['LineNumber'].Value}\")\n            self.Parent.Fields['Error'].Value = 1\n            return None\n        self.Registers[Index1] = FieldValue[0]\n\n    def Instruction_Yield(self, *args):\n        return\n\n    def Instruction_Hcf(self, *args):\n        Log.Warning('Hcf triggered', Caller=f\"Script line {self.Parent.Fields['LineNumber'].Value}\")\n        self.Parent.Fields['Error'].Value = 1\n        return\n\n    def Instruction_Jump(self, *args):\n        Line = self.GetArgValue(args[1])\n        if self.Parent.Fields['Error'].Value == 1:\n            return\n        if Line in Constants.NOT_NUMBER_NUMBERS:\n            Log.Warning('You cannot jump to a NaN line', Caller=f\"Script line {self.Parent.Fields['LineNumber'].Value}\")\n            self.Parent.Fields['Error'].Value = 1\n            return\n        self.Parent.Fields['LineNumber'].Value = Line - 1\n\n    def Instruction_JumpAL(self, *args):\n        Line = self.GetArgValue(args[1])\n        if self.Parent.Fields['Error'].Value == 1:\n            return\n        if Line in Constants.NOT_NUMBER_NUMBERS:\n            Log.Warning('You cannot jump to a NaN line', Caller=f\"Script line {self.Parent.Fields['LineNumber'].Value}\")\n            self.Parent.Fields['Error'].Value = 1\n            return\n        self.Registers[self.RegisterAliases['ra']] = self.Parent.Fields['LineNumber'].Value + 1\n        self.Parent.Fields['LineNumber'].Value = Line - 1\n\n    def Instruction_JumpR(self, *args):\n        Line = self.GetArgValue(args[1])\n        if self.Parent.Fields['Error'].Value == 1:\n            return\n        if Line in Constants.NOT_NUMBER_NUMBERS:\n            Log.Warning('You cannot jump relative to a NaN line', Caller=f\"Script line {self.Parent.Fields['LineNumber'].Value}\")\n            self.Parent.Fields['Error'].Value = 1\n            return\n        NewLineNumber = self.Parent.Fields['LineNumber'].Value + Line - 1\n        if NewLineNumber < 0:\n            NewLineNumber = self.Parent.Fields['LineNumber'].Value\n        if NewLineNumber >= len(self.Code) - 1:\n            NewLineNumber = self.Parent.Fields['LineNumber'].Value - 1\n        self.Parent.Fields['LineNumber'].Value = NewLineNumber\n\n    def GetBranchRoot(self, FunctionName):\n        if FunctionName.endswith('al'):\n            StoreNextLine = True\n            FunctionName = FunctionName[:-2]\n        else:\n            StoreNextLine = False\n        if FunctionName.startswith('br'):\n            Relative = True\n            FunctionName = FunctionName[2:]\n        else:\n            Relative = False\n            FunctionName = FunctionName[1:]\n        return (FunctionName, StoreNextLine, Relative)\n\n    def Instruction_Branch(self, *args):\n        global epsilon\n        FunctionName, StoreNextLine, Relative = self.GetBranchRoot(args[0])\n        Values = [self.GetArgValue(X) for X in args[1:]]\n        if self.Parent.Fields['Error'].Value == 1:\n            return\n        Matched = False\n        if FunctionName == 'eq':\n            JumpLine = Values[2]\n            Matched = Values[0] == Values[1]\n        elif FunctionName == 'eqz':\n            JumpLine = Values[1]\n            Matched = Values[0] == 0\n        elif FunctionName == 'ge':\n            JumpLine = Values[2]\n            Matched = Values[0] >= Values[1]\n        elif FunctionName == 'gez':\n            JumpLine = Values[1]\n            Matched = Values[0] >= 0\n        elif FunctionName == 'gt':\n            JumpLine = Values[2]\n            Matched = Values[0] > Values[1]\n        elif FunctionName == 'gtz':\n            JumpLine = Values[1]\n            Matched = Values[0] > 0\n        elif FunctionName == 'le':\n            JumpLine = Values[2]\n            Matched = Values[0] <= Values[1]\n        elif FunctionName == 'lez':\n            JumpLine = Values[1]\n            Matched = Values[0] <= 0\n        elif FunctionName == 'lt':\n            JumpLine = Values[2]\n            Matched = Values[0] < Values[1]\n        elif FunctionName == 'ltz':\n            JumpLine = Values[1]\n            Matched = Values[0] >= 0\n        elif FunctionName == 'ne':\n            JumpLine = Values[2]\n            Matched = Values[0] != Values[1]\n        elif FunctionName == 'nez':\n            JumpLine = Values[1]\n            Matched = Values[0] != 0\n        elif FunctionName == 'nan':\n            JumpLine = Values[1]\n            Matched = Values[0] == 'NaN'\n        elif FunctionName == 'ap':\n            JumpLine = Values[3]\n            Matched = abs(Values[0] - Values[1]) <= max(Values[2] * max(abs(Values[0]), abs(Values[1])), epsilon * 8)\n        elif FunctionName == 'apz':\n            JumpLine = Values[2]\n            Matched = abs(Values[0]) <= max(Values[1] * abs(Values[0]), epsilon * 8)\n        elif FunctionName == 'na':\n            JumpLine = Values[3]\n            Matched = abs(Values[0] - Values[1]) > max(Values[2] * max(abs(Values[0]), abs(Values[1])), epsilon * 8)\n        elif FunctionName == 'naz':\n            JumpLine = Values[2]\n            Matched = abs(Values[0]) > max(Values[1] * abs(Values[0]), epsilon * 8)\n        else:\n            Log.Warning('Unknown branch type', Caller=f\"Script line {self.Parent.Fields['LineNumber'].Value}\")\n            self.Parent.Fields['Error'].Value = 1\n            return\n        if Matched == True:\n            if StoreNextLine == True:\n                self.Registers[self.RegisterAliases['ra']] = self.Parent.Fields['LineNumber'].Value + 1\n            if Relative == True:\n                self.Parent.Fields['LineNumber'].Value += JumpLine - 1\n            else:\n                self.Parent.Fields['LineNumber'].Value = JumpLine - 1\n\n    def Instruction_Branch_Devices(self, *args):\n        global epsilon\n        FunctionName, StoreNextLine, Relative = self.GetBranchRoot(args[0])\n        Index1 = self.GetArgIndex(args[1])\n        JumpLine = self.GetArgValue(args[2])\n        if self.Parent.Fields['Error'].Value == 1:\n            return\n        if Index1 in self.Parent.Pins:\n            Matched = self.GetDeviceObject(self.Parent.Pins[Index1], DoError=False) != None\n        else:\n            Matched = False\n        if FunctionName == 'dns':\n            Matched = not Matched\n        elif FunctionName == 'dse':\n            pass\n        else:\n            Log.Warning('Unknown branch type', Caller=f\"Script line {self.Parent.Fields['LineNumber'].Value}\")\n            self.Parent.Fields['Error'].Value = 1\n            return\n        if Matched == True:\n            if StoreNextLine == True:\n                self.Registers[self.RegisterAliases['ra']] = self.Parent.Fields['LineNumber'].Value + 1\n            if Relative == True:\n                self.Parent.Fields['LineNumber'].Value += JumpLine - 1\n            else:\n                self.Parent.Fields['LineNumber'].Value = JumpLine - 1\n\n    def Instruction_Set_Conditional_Register(self, *args):\n        global epsilon\n        FunctionName, _, _ = self.GetBranchRoot(args[0])\n        Values = [self.GetArgValue(X) for X in args[2:]]\n        Index1 = self.GetArgIndex(args[1])\n        if self.Parent.Fields['Error'].Value == 1:\n            return\n        Matched = False\n        if FunctionName == 'eq':\n            Matched = Values[0] == Values[1]\n        elif FunctionName == 'eqz':\n            Matched = Values[0] == 0\n        elif FunctionName == 'ge':\n            Matched = Values[0] >= Values[1]\n        elif FunctionName == 'gez':\n            Matched = Values[0] >= 0\n        elif FunctionName == 'gt':\n            Matched = Values[0] > Values[1]\n        elif FunctionName == 'gtz':\n            Matched = Values[0] > 0\n        elif FunctionName == 'le':\n            Matched = Values[0] <= Values[1]\n        elif FunctionName == 'lez':\n            Matched = Values[0] <= 0\n        elif FunctionName == 'lt':\n            Matched = Values[0] < Values[1]\n        elif FunctionName == 'ltz':\n            Matched = Values[0] >= 0\n        elif FunctionName == 'ne':\n            Matched = Values[0] != Values[1]\n        elif FunctionName == 'nez':\n            Matched = Values[0] != 0\n        elif FunctionName == 'nan':\n            Matched = Values[0] == 'NaN'\n        elif FunctionName == 'nanz':\n            Matched = Values[0] != 'NaN'\n        elif FunctionName == 'ap':\n            Matched = abs(Values[0] - Values[1]) <= max(Values[2] * max(abs(Values[0]), abs(Values[1])), epsilon * 8)\n        elif FunctionName == 'apz':\n            Matched = abs(Values[0]) <= max(Values[1] * abs(Values[0]), epsilon * 8)\n        elif FunctionName == 'na':\n            Matched = abs(Values[0] - Values[1]) > max(Values[2] * max(abs(Values[0]), abs(Values[1])), epsilon * 8)\n        elif FunctionName == 'naz':\n            Matched = abs(Values[0]) > max(Values[1] * abs(Values[0]), epsilon * 8)\n        else:\n            Log.Warning('Unknown conditional type', Caller=f\"Script line {self.Parent.Fields['LineNumber'].Value}\")\n            self.Parent.Fields['Error'].Value = 1\n            return\n        self.Registers[Index1] = int(Matched)\n\n    def Instruction_Set_Conditional_Register_Devices(self, *args):\n        global epsilon\n        FunctionName, _, _ = self.GetBranchRoot(args[0])\n        Index1 = self.GetArgIndex(args[1])\n        Index2 = self.GetArgIndex(args[2])\n        if self.Parent.Fields['Error'].Value == 1:\n            return\n        if Index2 in self.Parent.Pins:\n            Matched = self.GetDeviceObject(self.Parent.Pins[Index2], DoError=False) != None\n        else:\n            Matched = False\n        if FunctionName == 'dns':\n            Matched = not Matched\n        elif FunctionName == 'dse':\n            pass\n        else:\n            Log.Warning('Unknown conditional type', Caller=f\"Script line {self.Parent.Fields['LineNumber'].Value}\")\n            self.Parent.Fields['Error'].Value = 1\n            return\n        self.Registers[Index1] = int(Matched)\n\n    def Instruction_Select(self, *args):\n        Index1 = self.GetArgIndex(args[1])\n        Value1 = self.GetArgValue(args[2])\n        Value2 = self.GetArgValue(args[3])\n        Value3 = self.GetArgValue(args[4])\n        Output = 0\n        if Value1 != 0:\n            Output = Value2\n        else:\n            Output = Value3\n        self.Registers[Index1] = Output\n\n    def Instruction_Bitwise_And(self, *args):\n        Index1 = self.GetArgIndex(args[1])\n        Value1 = self.GetArgValue(args[2])\n        Value2 = self.GetArgValue(args[3])\n        self.Registers[Index1] = Value1 & Value2\n\n    def Instruction_Bitwise_Nor(self, *args):\n        Index1 = self.GetArgIndex(args[1])\n        Value1 = self.GetArgValue(args[2])\n        Value2 = self.GetArgValue(args[3])\n        Log.Error('DO THIS LOL NOR')\n\n    def Instruction_Bitwise_Not(self, *args):\n        Index1 = self.GetArgIndex(args[1])\n        Value1 = self.GetArgValue(args[2])\n        Value2 = self.GetArgValue(args[3])\n        Log.Error('DO THIS LOL NOT')\n\n    def Instruction_Bitwise_Or(self, *args):\n        Index1 = self.GetArgIndex(args[1])\n        Value1 = self.GetArgValue(args[2])\n        Value2 = self.GetArgValue(args[3])\n        Log.Error('DO THIS LOL OR')\n        self.Registers[Index1] = Value1 | Value2\n\n    def RunUpdate(self):\n        if self.Parent.Fields['LineNumber'].Value >= len(self.Code) or self.Parent.Fields['Error'].Value != 0:\n            return\n        CurrentLine = self.Code[self.Parent.Fields['LineNumber'].Value].strip()\n        if CurrentLine != '':\n            CurrentLine = SplitNotStringSpaces(CurrentLine, ' ')\n            for CurrentIndex, CurrentFunction in self.FunctionMap['Functions'].items():\n                if CurrentLine[0] in CurrentFunction['Alias']:\n                    if len(CurrentLine) - 1 == CurrentFunction['Alias'][CurrentLine[0]]:\n                        for X in range(0, len(CurrentLine) - 1):\n                            TargetArgTypes = CurrentFunction['Args'][X].split('|')\n                            CurrentArgTypes = self.GetArgType(CurrentLine[X + 1], TargetArgTypes)\n                            if CurrentArgTypes not in TargetArgTypes:\n                                print(CurrentArgTypes)\n                                Log.Warning(f\"Arg {X + 1} of {CurrentLine[0]} must be of type {CurrentFunction['Args'][X]}\", Caller=f\"Script line {self.Parent.Fields['LineNumber'].Value}\")\n                                self.Parent.Fields['Error'].Value = 1\n                                break\n                        else:\n                            self.FunctionMap['Functions'][CurrentIndex]['Function'](*CurrentLine)\n                    else:\n                        Log.Warning(f\"{CurrentLine[0]} requires {CurrentFunction['Alias'][CurrentLine[0]]} args\", Caller=f\"Script line {self.Parent.Fields['LineNumber'].Value}\")\n                        self.Parent.Fields['Error'].Value = 1\n                    break\n            else:\n                Log.Warning(f'Unknown function {CurrentLine[0]}', Caller=f\"Script line {self.Parent.Fields['LineNumber'].Value}\")\n                self.Parent.Fields['Error'].Value = 1\n        self.HighestSP = max(self.HighestSP, self.Registers[self.RegisterAliases['sp']])\n        self.Parent.Fields['LineNumber'].Value += 1\n\n    def Instruction_Sin(self, *args):\n",
        "input": "",
        "output": "        Index1 = self.GetArgIndex(args[1])\n        Value1 = self.GetArgValue(args[2])\n        if self.Parent.Fields['Error'].Value == 1:\n            return\n        if Value1 in Constants.NOT_NUMBER_NUMBERS:\n            self.Registers[Index1] = Value1\n            return\n        try:\n            self.Registers[Index1] = math.sin(Value1)\n        except:\n            self.Registers[Index1] = 'NaN'\n    \n",
        "idx": "757"
    },
    {
        "instruction": "# EmulatorFunctions/CodeRunner.py\n\nclass CodeRunner:\n\n    def __init__(self, Parent, FilePath='Configs/Functions.json', DeviceFile: str='Configs/Devices.json'):\n        self.DevicesList = json.loads(open(DeviceFile, 'r').read())\n        self.FunctionMap = json.load(open(FilePath, 'r'))\n        for X, Y in self.FunctionMap['SpecialTypes'].items():\n            Y['ConfirmFunction'] = getattr(self, Y['ConfirmFunction'])\n            Y['GetArgFunction'] = getattr(self, Y['GetArgFunction'])\n        for X, Y in self.FunctionMap['Functions'].items():\n            Y['Function'] = getattr(self, Y['Function'])\n        self.Parent = Parent\n        self.Code = self.Parent.Code.split('\\n')\n        self.Registers = {f'r{X}': 0 for X in range(0, 18)}\n        self.RegisterAliases = copy.copy(Constants.DEFAULT_REGISTER_ALIAS)\n        self.PinAliases = {}\n        if self.Parent.StackEnabled == True:\n            self.Stack = [0 for X in range(self.Parent.StackLength)]\n        self.Constants = copy.copy(Constants.DEFAULT_CONSTANTS)\n        self.ParseCode()\n        self.HighestSP = 0\n\n    def ParseCode(self):\n        self.LogicTypesList = set(['ReferenceId', 'PrefabHash'] + [f'Channel{X}' for X in range(8)])\n        for X, Y in self.DevicesList.items():\n            for A, B in Y['Fields'].items():\n                if B['Read'] or B['Write']:\n                    self.LogicTypesList.add(A)\n        for X, Y in enumerate(self.Code):\n            if '#' in Y:\n                Location = Y.find('#')\n                self.Code[X] = Y[:Location].strip()\n            YTemp = self.Code[X].strip()\n            if ' ' not in YTemp:\n                if YTemp.endswith(':'):\n                    if YTemp not in self.Constants:\n                        self.Constants[YTemp[:-1]] = X\n                    else:\n                        Log.Warning('You cannot declare two lables with the same name', Caller=f\"Script line {self.Parent.Fields['LineNumber'].Value}\")\n                        self.Parent.Fields['Error'].Value = 1\n                    self.Code[X] = ''\n\n    def PrintRegisters(self):\n        Output = ['\\n+------------+-------+\\n|Registers   |       |']\n        for X, Y in self.Registers.items():\n            Output.append(f'|{X:<12}|{Y:<7}|')\n        Log.Info('\\n'.join(Output) + '\\n+------------+-------+')\n\n    def PrintConstants(self):\n        Output = ['\\n+------------+-------+\\n|Constants   |       |']\n        for X, Y in self.Constants.items():\n            Output.append(f'|{X:<12}|{Y:<7}|')\n        Log.Info('\\n'.join(Output) + '\\n+------------+-------+')\n\n    def PrintAlias(self):\n        Output = ['\\n+------------+-------+\\n|Aliases     |       |']\n        for X, Y in self.RegisterAliases.items():\n            Output.append(f'|{X:<12}|{Y:<7}|')\n        for X, Y in self.PinAliases.items():\n            Output.append(f'|{X:<12}|{Y:<7}|')\n        Log.Info('\\n'.join(Output) + '\\n+------------+-------+')\n\n    def PrintStack(self):\n        Output = ['\\n+------------+-------+\\n|Stack       |       |']\n        for X in range(self.HighestSP + 1):\n            Output.append(f'|{X:<12}|{self.Stack[X]:<7}|')\n        Log.Info('\\n'.join(Output) + '\\n+------------+-------+')\n\n    def ScriptLength(self):\n        return len(self.Script)\n\n    def Special_LogicTypes(self, Value, BaseType):\n        return Value in self.LogicTypesList\n\n    def Special_Get_LogicType(self, Value):\n        return Value\n\n    def Special_BatchMode(self, Value, BaseType):\n        if BaseType == 'String':\n            return Value in list(Constants.BATCH_TYPES_VALUES.keys())\n        return True\n\n    def Special_Get_BatchMode(self, Value):\n        if type(Value) == str:\n            if str(Value) in Constants.BATCH_TYPES_VALUES:\n                return Constants.BATCH_TYPES_VALUES[Value]\n        RawValue = self.GetArgValue(Value)\n        if RawValue >= 0 and RawValue < len(Constants.BATCH_TYPES_VALUES):\n            return RawValue\n        else:\n            Log.Warning(f'Batch mode value must bettween greater then or euqal too 0 and less then {len(Constants.BATCH_TYPES_VALUES)}', Caller=f\"Script line {self.Parent.Fields['LineNumber'].Value} \")\n            self.Parent.Fields['Error'].Value = 1\n            return None\n\n    def Special_DeviceHash(self, Value, BaseType):\n        return True\n\n    def Special_Get_DeviceHash(self, Value):\n        return Value\n\n    def Special_NameHash(self, Value, BaseType):\n        return True\n\n    def Special_Get_NameHash(self, Value):\n        return Value\n\n    def Special_ReferenceID(self, Value, BaseType):\n        return True\n\n    def Special_Get_ReferenceID(self, Value):\n        return Value\n\n    def GetArgBaseType(self, Value, TargetTypes=[]):\n        if len(Value) == 0:\n            return 'None'\n        if Value in self.Constants and 'Constant' in TargetTypes:\n            return 'Constant'\n        if Value in self.RegisterAliases and 'Register' in TargetTypes:\n            return 'Register'\n        if Value in self.PinAliases and 'Device' in TargetTypes:\n            return 'Device'\n        if Value[0] == 'd' and len(Value) > 1 and ('Device' in TargetTypes):\n            if 'r' in Value:\n                try:\n                    InValue = int(Value[1:].replace('r', ''))\n                    if InValue >= 0 and InValue < 18:\n                        return 'Device'\n                except:\n                    pass\n            else:\n                try:\n                    DeviceNumberList = [str(X) for X in range(self.Parent.PinsNumber)] + ['b']\n                    if Value[1:] in DeviceNumberList:\n                        return 'Device'\n                except:\n                    pass\n        if Value[0] == 'r' and len(Value) > 1 and ('Register' in TargetTypes):\n            try:\n                InValue = int(Value.replace('r', ''))\n                if InValue >= 0 and InValue < 18:\n                    return 'Register'\n            except:\n                pass\n        if Value.startswith('HASH(\"') and Value.endswith('\")') and ('Hash' in TargetTypes):\n            return 'Hash'\n        if 'Number' in TargetTypes:\n            if Value[0] == '$':\n                try:\n                    int(Value[1:], 16)\n                    return 'Number'\n                except:\n                    pass\n            try:\n                int(Value)\n                return 'Number'\n            except:\n                try:\n                    float(Value)\n                    return 'Number'\n                except:\n                    pass\n        return 'String'\n\n    def GetArgType(self, Value, TargetTypes=[]):\n        IsSpecialType = TargetTypes[0] in self.FunctionMap['SpecialTypes']\n        if IsSpecialType:\n            SpecialType = TargetTypes[0]\n            TargetTypes = self.FunctionMap['SpecialTypes'][SpecialType]['Types'].split('|')\n        BaseType = self.GetArgBaseType(Value, TargetTypes)\n        if IsSpecialType:\n            if BaseType in TargetTypes:\n                Confirmed = self.FunctionMap['SpecialTypes'][SpecialType]['ConfirmFunction'](Value, BaseType)\n                if Confirmed:\n                    return SpecialType\n                else:\n                    return 'None'\n        return BaseType\n\n    def GetArgIndex(self, Value):\n        if Value in self.Constants:\n            Log.Warning('You cannot change a constant value', Caller=f\"Script line {self.Parent.Fields['LineNumber'].Value} \")\n            self.Parent.Fields['Error'].Value = 1\n            return None\n        if Value in self.RegisterAliases:\n            return self.GetArgIndex(self.RegisterAliases[Value])\n        if Value in self.PinAliases:\n            return self.GetArgIndex(self.PinAliases[Value])\n        if Value[0] == 'd':\n            if 'r' in Value:\n                try:\n                    TempValue = Value[1:]\n                    RegisterIndex = int(TempValue.replace('r', ''))\n                    for X in range(TempValue.count('r')):\n                        if RegisterIndex not in Constants.NOT_NUMBER_NUMBERS:\n                            if RegisterIndex >= 0 and RegisterIndex < 18:\n                                RegisterIndex = self.Registers[f'r{RegisterIndex}']\n                            else:\n                                Log.Warning('Indirect device values have to be bettween 0 and 17', Caller=f\"Script line {self.Parent.Fields['LineNumber'].Value}\")\n                                self.Parent.Fields['Error'].Value = 1\n                                return None\n                        else:\n                            Log.Warning('Indirect device values have to be bettween 0 and 17 not NaN', Caller=f\"Script line {self.Parent.Fields['LineNumber'].Value}\")\n                            self.Parent.Fields['Error'].Value = 1\n                            return None\n                    RegisterIndex = f'd{RegisterIndex}'\n                    if RegisterIndex in self.Parent.Pins:\n                        return RegisterIndex\n                    Log.Warning('Indirect device values have to be bettween 0 and 5', Caller=f\"Script line {self.Parent.Fields['LineNumber'].Value}\")\n                    self.Parent.Fields['Error'].Value = 1\n                    return None\n                except:\n                    pass\n            elif Value[0] == 'd' and Value[1:] in [str(X) for X in range(self.Parent.PinsNumber)] + ['b']:\n                return Value\n        if Value[0] == 'r':\n            try:\n                RegisterIndex = int(Value.replace('r', ''))\n                for X in range(Value.count('r') - 1):\n                    if RegisterIndex not in Constants.NOT_NUMBER_NUMBERS:\n                        if RegisterIndex >= 0 and RegisterIndex < 18:\n                            RegisterIndex = self.Registers[f'r{RegisterIndex}']\n                        else:\n                            Log.Warning('Indirect refrences values have to be bettween 0 and 17', Caller=f\"Script line {self.Parent.Fields['LineNumber'].Value}\")\n                            self.Parent.Fields['Error'].Value = 1\n                            return None\n                    else:\n                        Log.Warning('Indirect refrences values have to be bettween 0 and 17 not NaN', Caller=f\"Script line {self.Parent.Fields['LineNumber'].Value}\")\n                        self.Parent.Fields['Error'].Value = 1\n                        return None\n                return f'r{RegisterIndex}'\n            except:\n                pass\n        Log.Warning('Unknown value', Caller=f\"Script line {self.Parent.Fields['LineNumber'].Value}\")\n        self.Parent.Fields['Error'].Value = 1\n        return None\n\n    def GetArgValue(self, Value, TargetType=[]):\n        Value = str(Value)\n        if Value in self.Constants:\n            return self.Constants[Value]\n        if Value[0] == 'r':\n            try:\n                RegisterIndex = int(Value.replace('r', ''))\n                for X in range(Value.count('r') - 1):\n                    if RegisterIndex not in Constants.NOT_NUMBER_NUMBERS:\n                        if RegisterIndex >= 0 and RegisterIndex < 18:\n                            RegisterIndex = self.Registers[f'r{RegisterIndex}']\n                        else:\n                            Log.Warning('Indirect refrences values have to be bettween 0 and 17', Caller=f\"Script line {self.Parent.Fields['LineNumber'].Value}\")\n                            self.Parent.Fields['Error'].Value = 1\n                            return None\n                    else:\n                        Log.Warning('Indirect refrences values have to be bettween 0 and 17 not NaN', Caller=f\"Script line {self.Parent.Fields['LineNumber'].Value}\")\n                        self.Parent.Fields['Error'].Value = 1\n                        return None\n                return self.Registers[f'r{RegisterIndex}']\n            except:\n                pass\n        if Value in self.RegisterAliases:\n            return self.GetArgValue(self.RegisterAliases[Value])\n        if Value[0] == '$':\n            try:\n                return int(Value[1:], 16)\n            except:\n                pass\n        if Value.startswith('HASH(\"') and Value.endswith('\")'):\n            Value = Value[6:-2]\n            return ComputeCRC32(Value)\n        try:\n            return int(Value)\n        except:\n            try:\n                return float(Value)\n            except:\n                pass\n        return str(Value)\n\n    def GetSpecialArgValue(self, Value, Type):\n        if Type in self.FunctionMap['SpecialTypes']:\n            ProcessedValue = self.GetArgValue(Value, Type)\n            if self.Parent.Fields['Error'].Value == 1:\n                return\n            return self.FunctionMap['SpecialTypes'][Type]['GetArgFunction'](ProcessedValue)\n        else:\n            Log.Warning(f'Invalid special arg type', Caller=f\"Script line {self.Parent.Fields['LineNumber'].Value}\")\n            self.Parent.Fields['Error'].Value = 1\n\n    def GetDeviceObject(self, RefID: int, DoError: bool=True):\n        if self.Parent.Fields['Error'].Value == 1:\n            return\n        RefObject = self.Parent.Network.GetDevice(RefID)\n        if RefObject != None:\n            return RefObject\n        elif DoError:\n            Log.Warning(f'Unknown device at reference id {RefID}', Caller=f\"Script line {self.Parent.Fields['LineNumber'].Value}\")\n            self.Parent.Fields['Error'].Value = 1\n        else:\n            return None\n\n    def Instruction_Define(self, *args):\n        Value = int(args[2])\n        if args[1] not in self.Constants:\n            self.Constants[args[1]] = Value\n            if args[1] in self.RegisterAliases:\n                del self.RegisterAliases[args[1]]\n        else:\n            Log.Warning('You cannot change a constant value', Caller=f\"Script line {self.Parent.Fields['LineNumber'].Value}\")\n            if self.Parent.Fields['Error'].Value == 1:\n                return\n\n    def Instruction_Move(self, *args):\n        Index1 = self.GetArgIndex(args[1])\n        Value2 = self.GetArgValue(args[2])\n        if self.Parent.Fields['Error'].Value == 1:\n            return\n        self.Registers[Index1] = Value2\n\n    def Instruction_Alias(self, *args):\n        if self.GetArgType(args[1], ['String']) == 'String':\n            if args[1] not in self.Constants and args[1] not in self.Parent.Pins and (args[1] not in self.Registers):\n                if args[1] in self.RegisterAliases:\n                    del self.RegisterAliases[args[1]]\n                if args[1] in self.PinAliases:\n                    del self.PinAliases[args[1]]\n                if args[2][0] == 'r':\n                    self.RegisterAliases[args[1]] = args[2]\n                elif args[2][0] == 'd':\n                    self.PinAliases[args[1]] = args[2]\n                else:\n                    Log.Error('Unkown alias type not caught by update')\n            else:\n                Log.Warning('Cannot overwrite a constant/builtin register/builtin device index', Caller=f\"Script line {self.Parent.Fields['LineNumber'].Value}\")\n                if self.Parent.Fields['Error'].Value == 1:\n                    return\n        else:\n            Log.Warning('You cannot set a register alias to a device name or a register', Caller=f\"Script line {self.Parent.Fields['LineNumber'].Value}\")\n            self.Parent.Fields['Error'].Value = 1\n\n    def Instruction_Add(self, *args):\n        Index1 = self.GetArgIndex(args[1])\n        Value1 = self.GetArgValue(args[2])\n        Value2 = self.GetArgValue(args[3])\n        if self.Parent.Fields['Error'].Value == 1:\n            return\n        if Value1 in Constants.NOT_NUMBER_NUMBERS:\n            self.Registers[Index1] = Value1\n            return\n        if Value2 in Constants.NOT_NUMBER_NUMBERS:\n            self.Registers[Index1] = Value2\n            return\n        self.Registers[Index1] = Value1 + Value2\n\n    def Instruction_Sub(self, *args):\n        Index1 = self.GetArgIndex(args[1])\n        Value1 = self.GetArgValue(args[2])\n        Value2 = self.GetArgValue(args[3])\n        if self.Parent.Fields['Error'].Value == 1:\n            return\n        if Value1 in Constants.NOT_NUMBER_NUMBERS:\n            self.Registers[Index1] = Value1\n            return\n        if Value2 in Constants.NOT_NUMBER_NUMBERS:\n            self.Registers[Index1] = Value2\n            return\n        self.Registers[Index1] = Value1 - Value2\n\n    def Instruction_Mul(self, *args):\n        Index1 = self.GetArgIndex(args[1])\n        Value1 = self.GetArgValue(args[2])\n        Value2 = self.GetArgValue(args[3])\n        if self.Parent.Fields['Error'].Value == 1:\n            return\n        if Value1 in Constants.NOT_NUMBER_NUMBERS:\n            self.Registers[Index1] = Value1\n            return\n        if Value2 in Constants.NOT_NUMBER_NUMBERS:\n            self.Registers[Index1] = Value2\n            return\n        self.Registers[Index1] = Value1 * Value2\n\n    def Instruction_Div(self, *args):\n        Index1 = self.GetArgIndex(args[1])\n        Value1 = self.GetArgValue(args[2])\n        Value2 = self.GetArgValue(args[3])\n        if self.Parent.Fields['Error'].Value == 1:\n            return\n        if Value1 in Constants.NOT_NUMBER_NUMBERS:\n            self.Registers[Index1] = Value1\n            return\n        if Value2 in Constants.NOT_NUMBER_NUMBERS:\n            self.Registers[Index1] = Value2\n            return\n        if Value2 == 0:\n            self.Registers[Index1] = 'NaN'\n            return\n        self.Registers[Index1] = Value1 / Value2\n\n    def Instruction_Abs(self, *args):\n        Index1 = self.GetArgIndex(args[1])\n        Value1 = self.GetArgValue(args[2])\n        if self.Parent.Fields['Error'].Value == 1:\n            return\n        if Value1 in Constants.NOT_NUMBER_NUMBERS:\n            self.Registers[Index1] = Value1\n            return\n        self.Registers[Index1] = abs(Value1)\n\n    def Instruction_Ceil(self, *args):\n        Index1 = self.GetArgIndex(args[1])\n        Value1 = self.GetArgValue(args[2])\n        if self.Parent.Fields['Error'].Value == 1:\n            return\n        if Value1 in Constants.NOT_NUMBER_NUMBERS:\n            self.Registers[Index1] = Value1\n            return\n        self.Registers[Index1] = math.ceil(Value1)\n\n    def Instruction_Floor(self, *args):\n        Index1 = self.GetArgIndex(args[1])\n        Value1 = self.GetArgValue(args[2])\n        if self.Parent.Fields['Error'].Value == 1:\n            return\n        if Value1 in Constants.NOT_NUMBER_NUMBERS:\n            self.Registers[Index1] = Value1\n            return\n        self.Registers[Index1] = math.floor(Value1)\n\n    def Instruction_Exp(self, *args):\n        Index1 = self.GetArgIndex(args[1])\n        Value1 = self.GetArgValue(args[2])\n        if self.Parent.Fields['Error'].Value == 1:\n            return\n        if Value1 in Constants.NOT_NUMBER_NUMBERS:\n            self.Registers[Index1] = Value1\n            return\n        self.Registers[Index1] = math.e ** Value1\n\n    def Instruction_Log(self, *args):\n        Index1 = self.GetArgIndex(args[1])\n        Value1 = self.GetArgValue(args[2])\n        if self.Parent.Fields['Error'].Value == 1:\n            return\n        if Value1 in Constants.NOT_NUMBER_NUMBERS:\n            self.Registers[Index1] = Value1\n            return\n        self.Registers[Index1] = math.log(Value1)\n\n    def Instruction_Rand(self, *args):\n        Index1 = self.GetArgIndex(args[1])\n        if self.Parent.Fields['Error'].Value == 1:\n            return\n        self.Registers[Index1] = random.random()\n\n    def Instruction_Round(self, *args):\n        Index1 = self.GetArgIndex(args[1])\n        Value1 = self.GetArgValue(args[2])\n        if self.Parent.Fields['Error'].Value == 1:\n            return\n        if Value1 in Constants.NOT_NUMBER_NUMBERS:\n            self.Registers[Index1] = Value1\n            return\n        Decimal = Value1 - math.floor(Value1)\n        if Decimal >= 0.5:\n            self.Registers[Index1] = math.ceil(Value1)\n        else:\n            self.Registers[Index1] = math.floor(Value1)\n\n    def Instruction_Sqrt(self, *args):\n        Index1 = self.GetArgIndex(args[1])\n        Value1 = self.GetArgValue(args[2])\n        if self.Parent.Fields['Error'].Value == 1:\n            return\n        if Value1 in Constants.NOT_NUMBER_NUMBERS:\n            self.Registers[Index1] = Value1\n            return\n        self.Registers[Index1] = math.sqrt(Value1)\n\n    def Instruction_Trunc(self, *args):\n        Index1 = self.GetArgIndex(args[1])\n        Value1 = self.GetArgValue(args[2])\n        if self.Parent.Fields['Error'].Value == 1:\n            return\n        if Value1 in Constants.NOT_NUMBER_NUMBERS:\n            self.Registers[Index1] = Value1\n            return\n        self.Registers[Index1] = math.trunc(Value1)\n\n    def Instruction_Asin(self, *args):\n        Index1 = self.GetArgIndex(args[1])\n        Value1 = self.GetArgValue(args[2])\n        if self.Parent.Fields['Error'].Value == 1:\n            return\n        if Value1 in Constants.NOT_NUMBER_NUMBERS:\n            self.Registers[Index1] = Value1\n            return\n        try:\n            self.Registers[Index1] = math.asin(Value1)\n        except:\n            self.Registers[Index1] = 'NaN'\n\n    def Instruction_Acos(self, *args):\n        Index1 = self.GetArgIndex(args[1])\n        Value1 = self.GetArgValue(args[2])\n        if self.Parent.Fields['Error'].Value == 1:\n            return\n        if Value1 in Constants.NOT_NUMBER_NUMBERS:\n            self.Registers[Index1] = Value1\n            return\n        try:\n            self.Registers[Index1] = math.acos(Value1)\n        except:\n            self.Registers[Index1] = 'NaN'\n\n    def Instruction_Atan(self, *args):\n        Index1 = self.GetArgIndex(args[1])\n        Value1 = self.GetArgValue(args[2])\n        if self.Parent.Fields['Error'].Value == 1:\n            return\n        if Value1 in Constants.NOT_NUMBER_NUMBERS:\n            self.Registers[Index1] = Value1\n            return\n        try:\n            self.Registers[Index1] = math.atan(Value1)\n        except:\n            self.Registers[Index1] = 'NaN'\n\n    def Instruction_Atan2(self, *args):\n        Index1 = self.GetArgIndex(args[1])\n        Value1 = self.GetArgValue(args[2])\n        Value2 = self.GetArgValue(args[3])\n        if self.Parent.Fields['Error'].Value == 1:\n            return\n        if Value1 in Constants.NOT_NUMBER_NUMBERS:\n            self.Registers[Index1] = Value1\n            return\n        if Value2 in Constants.NOT_NUMBER_NUMBERS:\n            self.Registers[Index1] = Value2\n            return\n        try:\n            self.Registers[Index1] = math.atan2(Value1, Value2)\n        except:\n            self.Registers[Index1] = 'NaN'\n\n    def Instruction_Sin(self, *args):\n        Index1 = self.GetArgIndex(args[1])\n        Value1 = self.GetArgValue(args[2])\n        if self.Parent.Fields['Error'].Value == 1:\n            return\n        if Value1 in Constants.NOT_NUMBER_NUMBERS:\n            self.Registers[Index1] = Value1\n            return\n        try:\n            self.Registers[Index1] = math.sin(Value1)\n        except:\n            self.Registers[Index1] = 'NaN'\n\n    def Instruction_Cos(self, *args):\n        Index1 = self.GetArgIndex(args[1])\n        Value1 = self.GetArgValue(args[2])\n        if self.Parent.Fields['Error'].Value == 1:\n            return\n        if Value1 in Constants.NOT_NUMBER_NUMBERS:\n            self.Registers[Index1] = Value1\n            return\n        try:\n            self.Registers[Index1] = math.cos(Value1)\n        except:\n            self.Registers[Index1] = 'NaN'\n\n    def Instruction_Tan(self, *args):\n        Index1 = self.GetArgIndex(args[1])\n        Value1 = self.GetArgValue(args[2])\n        if self.Parent.Fields['Error'].Value == 1:\n            return\n        if Value1 in Constants.NOT_NUMBER_NUMBERS:\n            self.Registers[Index1] = Value1\n            return\n        try:\n            self.Registers[Index1] = math.tan(Value1)\n        except:\n            self.Registers[Index1] = 'NaN'\n\n    def Instruction_Peek(self, *args):\n        Index1 = self.Registers[self.RegisterAliases['sp']]\n        Index2 = self.GetArgIndex(args[1])\n        if self.Parent.Fields['Error'].Value == 1:\n            return\n        if Index1 in Constants.NOT_NUMBER_NUMBERS:\n            Log.Warning('Cannot peek at NaN index', Caller=f\"Script line {self.Parent.Fields['LineNumber'].Value}\")\n            self.Parent.Fields['Error'].Value = 1\n            return\n        if Index1 >= 1 and Index1 <= self.Parent.StackLength:\n            self.Registers[Index2] = self.Stack[Index1 - 1]\n        else:\n            Log.Warning(f'Peek index must be greater then 0 and less then or equal to {self.Parent.StackLength}', Caller=f\"Script line {self.Parent.Fields['LineNumber'].Value}\")\n            self.Parent.Fields['Error'].Value = 1\n\n    def Instruction_Push(self, *args):\n        Index1 = self.Registers[self.RegisterAliases['sp']]\n        Value1 = self.GetArgValue(args[1])\n        if self.Parent.Fields['Error'].Value == 1:\n            return\n        if Index1 in Constants.NOT_NUMBER_NUMBERS:\n            Log.Warning('Cannot push at NaN index', Caller=f\"Script line {self.Parent.Fields['LineNumber'].Value}\")\n            self.Parent.Fields['Error'].Value = 1\n            return\n        if Index1 >= 0 and Index1 < self.Parent.StackLength:\n            self.Stack[Index1] = Value1\n            self.Registers[self.RegisterAliases['sp']] += 1\n        else:\n            Log.Warning(f'Push index must be greater then or euqal to 0 and less then {self.Parent.StackLength}', Caller=f\"Script line {self.Parent.Fields['LineNumber'].Value}\")\n            self.Parent.Fields['Error'].Value = 1\n\n    def Instruction_Pop(self, *args):\n        Index1 = self.Registers[self.RegisterAliases['sp']]\n        Index2 = self.GetArgIndex(args[1])\n        if self.Parent.Fields['Error'].Value == 1:\n            return\n        if Index1 in Constants.NOT_NUMBER_NUMBERS:\n            Log.Warning('Cannot pop at NaN index', Caller=f\"Script line {self.Parent.Fields['LineNumber'].Value}\")\n            self.Parent.Fields['Error'].Value = 1\n            return\n        if Index1 > 0 and Index1 <= self.Parent.StackLength:\n            self.Registers[Index2] = self.Stack[Index1 - 1]\n            self.Registers[self.RegisterAliases['sp']] -= 1\n        else:\n            Log.Warning(f'Pop index must be greater then 0 and less then or equal to {self.Parent.StackLength}', Caller=f\"Script line {self.Parent.Fields['LineNumber'].Value}\")\n            self.Parent.Fields['Error'].Value = 1\n\n    def Instruction_Get(self, *args):\n        Index1 = self.GetArgIndex(args[1])\n        Index2 = self.GetArgIndex(args[2])\n        Index3 = self.GetArgValue(args[3])\n        if self.Parent.Fields['Error'].Value == 1:\n            return\n        if Index2 in self.Parent.Pins:\n            DeviceObject = self.GetDeviceObject(self.Parent.Pins[Index2])\n        else:\n            Log.Warning(f'No device at {Index2}', Caller=f\"Script line {self.Parent.Fields['LineNumber'].Value}\")\n            self.Parent.Fields['Error'].Value = 1\n            return\n        if DeviceObject.StackEnabled == False:\n            Log.Warning(f'Device does not have a stack', Caller=f\"Script line {self.Parent.Fields['LineNumber'].Value}\")\n            self.Parent.Fields['Error'].Value = 1\n            return\n        if Index3 in Constants.NOT_NUMBER_NUMBERS:\n            Log.Warning('Cannot get at NaN index', Caller=f\"Script line {self.Parent.Fields['LineNumber'].Value}\")\n            self.Parent.Fields['Error'].Value = 1\n            return\n        if Index3 >= 1 and Index3 <= DeviceObject.StackLength:\n            self.Registers[Index1] = self.Stack[Index3 - 1]\n            Log.Warning(f'Needs further testing', Caller=f\"Script line {self.Parent.Fields['LineNumber'].Value}\")\n        else:\n            Log.Warning(f'Get must be greater then 0 and less then or equal to {DeviceObject.StackLength}', Caller=f\"Script line {self.Parent.Fields['LineNumber'].Value}\")\n            self.Parent.Fields['Error'].Value = 1\n\n    def Instruction_GetD(self, *args):\n        pass\n\n    def Instruction_Poke(self, *args):\n        Value1 = self.GetArgValue(args[1])\n        Value2 = self.GetArgValue(args[2])\n        if self.Parent.Fields['Error'].Value == 1:\n            return\n        if Value1 in Constants.NOT_NUMBER_NUMBERS:\n            Log.Warning('Cannot poke at NaN index', Caller=f\"Script line {self.Parent.Fields['LineNumber'].Value}\")\n            self.Parent.Fields['Error'].Value = 1\n            return\n        if Value1 >= 0 and Value1 < self.Parent.StackLength:\n            self.Stack[Value1] = Value2\n        else:\n            Log.Warning(f'Pop index must be greater then or equal to 0 and less then {self.Parent.StackLength}', Caller=f\"Script line {self.Parent.Fields['LineNumber'].Value}\")\n            self.Parent.Fields['Error'].Value = 1\n\n    def Instruction_Load(self, *args):\n        Index1 = self.GetArgIndex(args[1])\n        Index2 = self.GetArgIndex(args[2])\n        Value1 = self.GetSpecialArgValue(args[3], 'LogicType')\n        if self.Parent.Fields['Error'].Value == 1:\n            return\n        if Index2 in self.Parent.Pins:\n            DeviceObject = self.GetDeviceObject(self.Parent.Pins[Index2])\n        else:\n            Log.Warning(f'No device at {Index2}', Caller=f\"Script line {self.Parent.Fields['LineNumber'].Value}\")\n            self.Parent.Fields['Error'].Value = 1\n            return\n        if self.Parent.Fields['Error'].Value == 1:\n            return\n        FieldValue = DeviceObject.GetFieldValue(Value1)\n        if FieldValue[0] == None:\n            Log.Warning(FieldValue[1], Caller=f\"Script line {self.Parent.Fields['LineNumber'].Value}\")\n            self.Parent.Fields['Error'].Value = 1\n            return None\n        self.Registers[Index1] = FieldValue[0]\n\n    def ApplyBatchOperation(self, Values, BatchMode):\n        try:\n            BatchMode = int(BatchMode)\n            if BatchMode < 0 or BatchMode >= len(Constants.BATCH_NO_RESPONSE):\n                return 0\n        except:\n            return 0\n        if len(Values) == 0:\n            return Constants.BATCH_NO_RESPONSE[BatchMode]\n        if BatchMode == 0:\n            return sum(Values) / len(Values)\n        elif BatchMode == 1:\n            return sum(Values)\n        elif BatchMode == 2:\n            return min(Values)\n        elif BatchMode == 3:\n            return max(Values)\n        return 'NaN'\n\n    def CollectDevicesValueBatch(self, Devices, Value, BatchMode):\n        Values = []\n        for X in Devices:\n            FieldValue = X.GetFieldValue(Value)\n            if FieldValue[0] != None:\n                Values.append(FieldValue[0])\n        if len(Values) == 0:\n            return Constants.BATCH_NO_RESPONSE[BatchMode]\n        return MakeIntIfClose(self.ApplyBatchOperation(Values, BatchMode))\n\n    def Instruction_LoadBatchNamed(self, *args):\n        Index1 = self.GetArgIndex(args[1])\n        Value1 = self.GetSpecialArgValue(args[2], 'DeviceHash')\n        Value2 = self.GetSpecialArgValue(args[3], 'NameHash')\n        Value3 = self.GetSpecialArgValue(args[4], 'LogicType')\n        Value4 = self.GetSpecialArgValue(args[5], 'BatchMode')\n        if self.Parent.Fields['Error'].Value == 1:\n            return\n        if Value1 in Constants.NOT_NUMBER_NUMBERS:\n            self.Registers[Index1] = 'NaN'\n            return\n        if Value2 in Constants.NOT_NUMBER_NUMBERS:\n            Log.Warning(f'Cannot get a device with a NameHash of NaN', Caller=f\"Script line {self.Parent.Fields['LineNumber'].Value}\")\n            self.Parent.Fields['Error'].Value = 1\n            return\n        Devices = self.Parent.Network.GetBatchDevices(Value1, Value2)\n        Result = self.CollectDevicesValueBatch(Devices, Value3, Value4)\n        self.Registers[Index1] = Result\n\n    def Instruction_Set(self, *args):\n        Index1 = self.GetArgIndex(args[1])\n        Value1 = self.GetSpecialArgValue(args[2], 'LogicType')\n        Value2 = self.GetArgValue(args[3])\n        if self.Parent.Fields['Error'].Value == 1:\n            return\n        if Index1 in self.Parent.Pins:\n            DeviceObject = self.GetDeviceObject(self.Parent.Pins[Index1])\n        else:\n            Log.Warning(f'No device at {Index1}', Caller=f\"Script line {self.Parent.Fields['LineNumber'].Value}\")\n            self.Parent.Fields['Error'].Value = 1\n            return\n        if self.Parent.Fields['Error'].Value == 1:\n            return\n        Result = DeviceObject.SetFieldValue(Value1, Value2)\n        if Result[0] == None:\n            Log.Warning(Result[1], Caller=f\"Script line {self.Parent.Fields['LineNumber'].Value}\")\n            self.Parent.Fields['Error'].Value = 1\n\n    def Instruction_SetBatch(self, *args):\n        Value1 = self.GetSpecialArgValue(args[1], 'DeviceHash')\n        Value2 = self.GetSpecialArgValue(args[2], 'LogicType')\n        Value3 = self.GetArgValue(args[3])\n        if self.Parent.Fields['Error'].Value == 1:\n            return\n        Devices = self.Parent.Network.GetBatchDevices(Value1)\n        for X in Devices:\n            X.SetFieldValue(Value2, Value3)\n\n    def Instruction_SetBatchNamed(self, *args):\n        Value1 = self.GetSpecialArgValue(args[1], 'DeviceHash')\n        Value2 = self.GetSpecialArgValue(args[2], 'NameHash')\n        Value3 = self.GetSpecialArgValue(args[3], 'LogicType')\n        Value4 = self.GetArgValue(args[4])\n        if self.Parent.Fields['Error'].Value == 1:\n            return\n        Devices = self.Parent.Network.GetBatchDevices(Value1, Value2)\n        for X in Devices:\n            X.SetFieldValue(Value3, Value4)\n\n    def Instruction_SetDevice(self, *args):\n        Index1 = self.GetSpecialArgValue(args[1], 'ReferenceID')\n        Value1 = self.GetSpecialArgValue(args[2], 'LogicType')\n        Value2 = self.GetArgValue(args[3])\n        if self.Parent.Fields['Error'].Value == 1:\n            return\n        DeviceObject = self.GetDeviceObject(Index1)\n        if self.Parent.Fields['Error'].Value == 1:\n            return\n        Result = DeviceObject.SetFieldValue(Value1, Value2)\n        if Result[0] == None:\n            Log.Warning(Result[1], Caller=f\"Script line {self.Parent.Fields['LineNumber'].Value}\")\n            self.Parent.Fields['Error'].Value = 1\n\n    def Instruction_LoadDevice(self, *args):\n        Index1 = self.GetArgIndex(args[1])\n        Index2 = self.GetSpecialArgValue(args[2], 'ReferenceID')\n        Value1 = self.GetSpecialArgValue(args[3], 'LogicType')\n        if self.Parent.Fields['Error'].Value == 1:\n            return\n        DeviceObject = self.GetDeviceObject(self.Parent.Pins[Index2])\n        if self.Parent.Fields['Error'].Value == 1:\n            return\n        FieldValue = DeviceObject.GetFieldValue(Value1)\n        if FieldValue[0] == None:\n            Log.Warning(FieldValue[1], Caller=f\"Script line {self.Parent.Fields['LineNumber'].Value}\")\n            self.Parent.Fields['Error'].Value = 1\n            return None\n        self.Registers[Index1] = FieldValue[0]\n\n    def Instruction_Yield(self, *args):\n        return\n\n    def Instruction_Hcf(self, *args):\n        Log.Warning('Hcf triggered', Caller=f\"Script line {self.Parent.Fields['LineNumber'].Value}\")\n        self.Parent.Fields['Error'].Value = 1\n        return\n\n    def Instruction_Jump(self, *args):\n        Line = self.GetArgValue(args[1])\n        if self.Parent.Fields['Error'].Value == 1:\n            return\n        if Line in Constants.NOT_NUMBER_NUMBERS:\n            Log.Warning('You cannot jump to a NaN line', Caller=f\"Script line {self.Parent.Fields['LineNumber'].Value}\")\n            self.Parent.Fields['Error'].Value = 1\n            return\n        self.Parent.Fields['LineNumber'].Value = Line - 1\n\n    def Instruction_JumpAL(self, *args):\n        Line = self.GetArgValue(args[1])\n        if self.Parent.Fields['Error'].Value == 1:\n            return\n        if Line in Constants.NOT_NUMBER_NUMBERS:\n            Log.Warning('You cannot jump to a NaN line', Caller=f\"Script line {self.Parent.Fields['LineNumber'].Value}\")\n            self.Parent.Fields['Error'].Value = 1\n            return\n        self.Registers[self.RegisterAliases['ra']] = self.Parent.Fields['LineNumber'].Value + 1\n        self.Parent.Fields['LineNumber'].Value = Line - 1\n\n    def Instruction_JumpR(self, *args):\n        Line = self.GetArgValue(args[1])\n        if self.Parent.Fields['Error'].Value == 1:\n            return\n        if Line in Constants.NOT_NUMBER_NUMBERS:\n            Log.Warning('You cannot jump relative to a NaN line', Caller=f\"Script line {self.Parent.Fields['LineNumber'].Value}\")\n            self.Parent.Fields['Error'].Value = 1\n            return\n        NewLineNumber = self.Parent.Fields['LineNumber'].Value + Line - 1\n        if NewLineNumber < 0:\n            NewLineNumber = self.Parent.Fields['LineNumber'].Value\n        if NewLineNumber >= len(self.Code) - 1:\n            NewLineNumber = self.Parent.Fields['LineNumber'].Value - 1\n        self.Parent.Fields['LineNumber'].Value = NewLineNumber\n\n    def GetBranchRoot(self, FunctionName):\n        if FunctionName.endswith('al'):\n            StoreNextLine = True\n            FunctionName = FunctionName[:-2]\n        else:\n            StoreNextLine = False\n        if FunctionName.startswith('br'):\n            Relative = True\n            FunctionName = FunctionName[2:]\n        else:\n            Relative = False\n            FunctionName = FunctionName[1:]\n        return (FunctionName, StoreNextLine, Relative)\n\n    def Instruction_Branch(self, *args):\n        global epsilon\n        FunctionName, StoreNextLine, Relative = self.GetBranchRoot(args[0])\n        Values = [self.GetArgValue(X) for X in args[1:]]\n        if self.Parent.Fields['Error'].Value == 1:\n            return\n        Matched = False\n        if FunctionName == 'eq':\n            JumpLine = Values[2]\n            Matched = Values[0] == Values[1]\n        elif FunctionName == 'eqz':\n            JumpLine = Values[1]\n            Matched = Values[0] == 0\n        elif FunctionName == 'ge':\n            JumpLine = Values[2]\n            Matched = Values[0] >= Values[1]\n        elif FunctionName == 'gez':\n            JumpLine = Values[1]\n            Matched = Values[0] >= 0\n        elif FunctionName == 'gt':\n            JumpLine = Values[2]\n            Matched = Values[0] > Values[1]\n        elif FunctionName == 'gtz':\n            JumpLine = Values[1]\n            Matched = Values[0] > 0\n        elif FunctionName == 'le':\n            JumpLine = Values[2]\n            Matched = Values[0] <= Values[1]\n        elif FunctionName == 'lez':\n            JumpLine = Values[1]\n            Matched = Values[0] <= 0\n        elif FunctionName == 'lt':\n            JumpLine = Values[2]\n            Matched = Values[0] < Values[1]\n        elif FunctionName == 'ltz':\n            JumpLine = Values[1]\n            Matched = Values[0] >= 0\n        elif FunctionName == 'ne':\n            JumpLine = Values[2]\n            Matched = Values[0] != Values[1]\n        elif FunctionName == 'nez':\n            JumpLine = Values[1]\n            Matched = Values[0] != 0\n        elif FunctionName == 'nan':\n            JumpLine = Values[1]\n            Matched = Values[0] == 'NaN'\n        elif FunctionName == 'ap':\n            JumpLine = Values[3]\n            Matched = abs(Values[0] - Values[1]) <= max(Values[2] * max(abs(Values[0]), abs(Values[1])), epsilon * 8)\n        elif FunctionName == 'apz':\n            JumpLine = Values[2]\n            Matched = abs(Values[0]) <= max(Values[1] * abs(Values[0]), epsilon * 8)\n        elif FunctionName == 'na':\n            JumpLine = Values[3]\n            Matched = abs(Values[0] - Values[1]) > max(Values[2] * max(abs(Values[0]), abs(Values[1])), epsilon * 8)\n        elif FunctionName == 'naz':\n            JumpLine = Values[2]\n            Matched = abs(Values[0]) > max(Values[1] * abs(Values[0]), epsilon * 8)\n        else:\n            Log.Warning('Unknown branch type', Caller=f\"Script line {self.Parent.Fields['LineNumber'].Value}\")\n            self.Parent.Fields['Error'].Value = 1\n            return\n        if Matched == True:\n            if StoreNextLine == True:\n                self.Registers[self.RegisterAliases['ra']] = self.Parent.Fields['LineNumber'].Value + 1\n            if Relative == True:\n                self.Parent.Fields['LineNumber'].Value += JumpLine - 1\n            else:\n                self.Parent.Fields['LineNumber'].Value = JumpLine - 1\n\n    def Instruction_Branch_Devices(self, *args):\n        global epsilon\n        FunctionName, StoreNextLine, Relative = self.GetBranchRoot(args[0])\n        Index1 = self.GetArgIndex(args[1])\n        JumpLine = self.GetArgValue(args[2])\n        if self.Parent.Fields['Error'].Value == 1:\n            return\n        if Index1 in self.Parent.Pins:\n            Matched = self.GetDeviceObject(self.Parent.Pins[Index1], DoError=False) != None\n        else:\n            Matched = False\n        if FunctionName == 'dns':\n            Matched = not Matched\n        elif FunctionName == 'dse':\n            pass\n        else:\n            Log.Warning('Unknown branch type', Caller=f\"Script line {self.Parent.Fields['LineNumber'].Value}\")\n            self.Parent.Fields['Error'].Value = 1\n            return\n        if Matched == True:\n            if StoreNextLine == True:\n                self.Registers[self.RegisterAliases['ra']] = self.Parent.Fields['LineNumber'].Value + 1\n            if Relative == True:\n                self.Parent.Fields['LineNumber'].Value += JumpLine - 1\n            else:\n                self.Parent.Fields['LineNumber'].Value = JumpLine - 1\n\n    def Instruction_Set_Conditional_Register(self, *args):\n        global epsilon\n        FunctionName, _, _ = self.GetBranchRoot(args[0])\n        Values = [self.GetArgValue(X) for X in args[2:]]\n        Index1 = self.GetArgIndex(args[1])\n        if self.Parent.Fields['Error'].Value == 1:\n            return\n        Matched = False\n        if FunctionName == 'eq':\n            Matched = Values[0] == Values[1]\n        elif FunctionName == 'eqz':\n            Matched = Values[0] == 0\n        elif FunctionName == 'ge':\n            Matched = Values[0] >= Values[1]\n        elif FunctionName == 'gez':\n            Matched = Values[0] >= 0\n        elif FunctionName == 'gt':\n            Matched = Values[0] > Values[1]\n        elif FunctionName == 'gtz':\n            Matched = Values[0] > 0\n        elif FunctionName == 'le':\n            Matched = Values[0] <= Values[1]\n        elif FunctionName == 'lez':\n            Matched = Values[0] <= 0\n        elif FunctionName == 'lt':\n            Matched = Values[0] < Values[1]\n        elif FunctionName == 'ltz':\n            Matched = Values[0] >= 0\n        elif FunctionName == 'ne':\n            Matched = Values[0] != Values[1]\n        elif FunctionName == 'nez':\n            Matched = Values[0] != 0\n        elif FunctionName == 'nan':\n            Matched = Values[0] == 'NaN'\n        elif FunctionName == 'nanz':\n            Matched = Values[0] != 'NaN'\n        elif FunctionName == 'ap':\n            Matched = abs(Values[0] - Values[1]) <= max(Values[2] * max(abs(Values[0]), abs(Values[1])), epsilon * 8)\n        elif FunctionName == 'apz':\n            Matched = abs(Values[0]) <= max(Values[1] * abs(Values[0]), epsilon * 8)\n        elif FunctionName == 'na':\n            Matched = abs(Values[0] - Values[1]) > max(Values[2] * max(abs(Values[0]), abs(Values[1])), epsilon * 8)\n        elif FunctionName == 'naz':\n            Matched = abs(Values[0]) > max(Values[1] * abs(Values[0]), epsilon * 8)\n        else:\n            Log.Warning('Unknown conditional type', Caller=f\"Script line {self.Parent.Fields['LineNumber'].Value}\")\n            self.Parent.Fields['Error'].Value = 1\n            return\n        self.Registers[Index1] = int(Matched)\n\n    def Instruction_Set_Conditional_Register_Devices(self, *args):\n        global epsilon\n        FunctionName, _, _ = self.GetBranchRoot(args[0])\n        Index1 = self.GetArgIndex(args[1])\n        Index2 = self.GetArgIndex(args[2])\n        if self.Parent.Fields['Error'].Value == 1:\n            return\n        if Index2 in self.Parent.Pins:\n            Matched = self.GetDeviceObject(self.Parent.Pins[Index2], DoError=False) != None\n        else:\n            Matched = False\n        if FunctionName == 'dns':\n            Matched = not Matched\n        elif FunctionName == 'dse':\n            pass\n        else:\n            Log.Warning('Unknown conditional type', Caller=f\"Script line {self.Parent.Fields['LineNumber'].Value}\")\n            self.Parent.Fields['Error'].Value = 1\n            return\n        self.Registers[Index1] = int(Matched)\n\n    def Instruction_Select(self, *args):\n        Index1 = self.GetArgIndex(args[1])\n        Value1 = self.GetArgValue(args[2])\n        Value2 = self.GetArgValue(args[3])\n        Value3 = self.GetArgValue(args[4])\n        Output = 0\n        if Value1 != 0:\n            Output = Value2\n        else:\n            Output = Value3\n        self.Registers[Index1] = Output\n\n    def Instruction_Bitwise_And(self, *args):\n        Index1 = self.GetArgIndex(args[1])\n        Value1 = self.GetArgValue(args[2])\n        Value2 = self.GetArgValue(args[3])\n        self.Registers[Index1] = Value1 & Value2\n\n    def Instruction_Bitwise_Nor(self, *args):\n        Index1 = self.GetArgIndex(args[1])\n        Value1 = self.GetArgValue(args[2])\n        Value2 = self.GetArgValue(args[3])\n        Log.Error('DO THIS LOL NOR')\n\n    def Instruction_Bitwise_Not(self, *args):\n        Index1 = self.GetArgIndex(args[1])\n        Value1 = self.GetArgValue(args[2])\n        Value2 = self.GetArgValue(args[3])\n        Log.Error('DO THIS LOL NOT')\n\n    def Instruction_Bitwise_Or(self, *args):\n        Index1 = self.GetArgIndex(args[1])\n        Value1 = self.GetArgValue(args[2])\n        Value2 = self.GetArgValue(args[3])\n        Log.Error('DO THIS LOL OR')\n        self.Registers[Index1] = Value1 | Value2\n\n    def RunUpdate(self):\n        if self.Parent.Fields['LineNumber'].Value >= len(self.Code) or self.Parent.Fields['Error'].Value != 0:\n            return\n        CurrentLine = self.Code[self.Parent.Fields['LineNumber'].Value].strip()\n        if CurrentLine != '':\n            CurrentLine = SplitNotStringSpaces(CurrentLine, ' ')\n            for CurrentIndex, CurrentFunction in self.FunctionMap['Functions'].items():\n                if CurrentLine[0] in CurrentFunction['Alias']:\n                    if len(CurrentLine) - 1 == CurrentFunction['Alias'][CurrentLine[0]]:\n                        for X in range(0, len(CurrentLine) - 1):\n                            TargetArgTypes = CurrentFunction['Args'][X].split('|')\n                            CurrentArgTypes = self.GetArgType(CurrentLine[X + 1], TargetArgTypes)\n                            if CurrentArgTypes not in TargetArgTypes:\n                                print(CurrentArgTypes)\n                                Log.Warning(f\"Arg {X + 1} of {CurrentLine[0]} must be of type {CurrentFunction['Args'][X]}\", Caller=f\"Script line {self.Parent.Fields['LineNumber'].Value}\")\n                                self.Parent.Fields['Error'].Value = 1\n                                break\n                        else:\n                            self.FunctionMap['Functions'][CurrentIndex]['Function'](*CurrentLine)\n                    else:\n                        Log.Warning(f\"{CurrentLine[0]} requires {CurrentFunction['Alias'][CurrentLine[0]]} args\", Caller=f\"Script line {self.Parent.Fields['LineNumber'].Value}\")\n                        self.Parent.Fields['Error'].Value = 1\n                    break\n            else:\n                Log.Warning(f'Unknown function {CurrentLine[0]}', Caller=f\"Script line {self.Parent.Fields['LineNumber'].Value}\")\n                self.Parent.Fields['Error'].Value = 1\n        self.HighestSP = max(self.HighestSP, self.Registers[self.RegisterAliases['sp']])\n        self.Parent.Fields['LineNumber'].Value += 1\n\n    def Instruction_LoadBatch(self, *args):\n",
        "input": "",
        "output": "        Index1 = self.GetArgIndex(args[1])\n        Value1 = self.GetSpecialArgValue(args[2], 'DeviceHash')\n        Value2 = self.GetSpecialArgValue(args[3], 'LogicType')\n        Value3 = self.GetSpecialArgValue(args[4], 'BatchMode')\n        if self.Parent.Fields['Error'].Value == 1:\n            return\n        if Value1 in Constants.NOT_NUMBER_NUMBERS:\n            self.Registers[Index1] = 'Nan'\n            return\n        Devices = self.Parent.Network.GetBatchDevices(Value1)\n        Result = self.CollectDevicesValueBatch(Devices, Value2, Value3)\n        self.Registers[Index1] = Result\n    \n",
        "idx": "758"
    },
    {
        "instruction": "# EmulatorFunctions/CodeRunner.py\n\nclass CodeRunner:\n\n    def __init__(self, Parent, FilePath='Configs/Functions.json', DeviceFile: str='Configs/Devices.json'):\n        self.DevicesList = json.loads(open(DeviceFile, 'r').read())\n        self.FunctionMap = json.load(open(FilePath, 'r'))\n        for X, Y in self.FunctionMap['SpecialTypes'].items():\n            Y['ConfirmFunction'] = getattr(self, Y['ConfirmFunction'])\n            Y['GetArgFunction'] = getattr(self, Y['GetArgFunction'])\n        for X, Y in self.FunctionMap['Functions'].items():\n            Y['Function'] = getattr(self, Y['Function'])\n        self.Parent = Parent\n        self.Code = self.Parent.Code.split('\\n')\n        self.Registers = {f'r{X}': 0 for X in range(0, 18)}\n        self.RegisterAliases = copy.copy(Constants.DEFAULT_REGISTER_ALIAS)\n        self.PinAliases = {}\n        if self.Parent.StackEnabled == True:\n            self.Stack = [0 for X in range(self.Parent.StackLength)]\n        self.Constants = copy.copy(Constants.DEFAULT_CONSTANTS)\n        self.ParseCode()\n        self.HighestSP = 0\n\n    def ParseCode(self):\n        self.LogicTypesList = set(['ReferenceId', 'PrefabHash'] + [f'Channel{X}' for X in range(8)])\n        for X, Y in self.DevicesList.items():\n            for A, B in Y['Fields'].items():\n                if B['Read'] or B['Write']:\n                    self.LogicTypesList.add(A)\n        for X, Y in enumerate(self.Code):\n            if '#' in Y:\n                Location = Y.find('#')\n                self.Code[X] = Y[:Location].strip()\n            YTemp = self.Code[X].strip()\n            if ' ' not in YTemp:\n                if YTemp.endswith(':'):\n                    if YTemp not in self.Constants:\n                        self.Constants[YTemp[:-1]] = X\n                    else:\n                        Log.Warning('You cannot declare two lables with the same name', Caller=f\"Script line {self.Parent.Fields['LineNumber'].Value}\")\n                        self.Parent.Fields['Error'].Value = 1\n                    self.Code[X] = ''\n\n    def PrintRegisters(self):\n        Output = ['\\n+------------+-------+\\n|Registers   |       |']\n        for X, Y in self.Registers.items():\n            Output.append(f'|{X:<12}|{Y:<7}|')\n        Log.Info('\\n'.join(Output) + '\\n+------------+-------+')\n\n    def PrintConstants(self):\n        Output = ['\\n+------------+-------+\\n|Constants   |       |']\n        for X, Y in self.Constants.items():\n            Output.append(f'|{X:<12}|{Y:<7}|')\n        Log.Info('\\n'.join(Output) + '\\n+------------+-------+')\n\n    def PrintAlias(self):\n        Output = ['\\n+------------+-------+\\n|Aliases     |       |']\n        for X, Y in self.RegisterAliases.items():\n            Output.append(f'|{X:<12}|{Y:<7}|')\n        for X, Y in self.PinAliases.items():\n            Output.append(f'|{X:<12}|{Y:<7}|')\n        Log.Info('\\n'.join(Output) + '\\n+------------+-------+')\n\n    def PrintStack(self):\n        Output = ['\\n+------------+-------+\\n|Stack       |       |']\n        for X in range(self.HighestSP + 1):\n            Output.append(f'|{X:<12}|{self.Stack[X]:<7}|')\n        Log.Info('\\n'.join(Output) + '\\n+------------+-------+')\n\n    def ScriptLength(self):\n        return len(self.Script)\n\n    def Special_LogicTypes(self, Value, BaseType):\n        return Value in self.LogicTypesList\n\n    def Special_Get_LogicType(self, Value):\n        return Value\n\n    def Special_BatchMode(self, Value, BaseType):\n        if BaseType == 'String':\n            return Value in list(Constants.BATCH_TYPES_VALUES.keys())\n        return True\n\n    def Special_Get_BatchMode(self, Value):\n        if type(Value) == str:\n            if str(Value) in Constants.BATCH_TYPES_VALUES:\n                return Constants.BATCH_TYPES_VALUES[Value]\n        RawValue = self.GetArgValue(Value)\n        if RawValue >= 0 and RawValue < len(Constants.BATCH_TYPES_VALUES):\n            return RawValue\n        else:\n            Log.Warning(f'Batch mode value must bettween greater then or euqal too 0 and less then {len(Constants.BATCH_TYPES_VALUES)}', Caller=f\"Script line {self.Parent.Fields['LineNumber'].Value} \")\n            self.Parent.Fields['Error'].Value = 1\n            return None\n\n    def Special_DeviceHash(self, Value, BaseType):\n        return True\n\n    def Special_Get_DeviceHash(self, Value):\n        return Value\n\n    def Special_NameHash(self, Value, BaseType):\n        return True\n\n    def Special_Get_NameHash(self, Value):\n        return Value\n\n    def Special_ReferenceID(self, Value, BaseType):\n        return True\n\n    def Special_Get_ReferenceID(self, Value):\n        return Value\n\n    def GetArgBaseType(self, Value, TargetTypes=[]):\n        if len(Value) == 0:\n            return 'None'\n        if Value in self.Constants and 'Constant' in TargetTypes:\n            return 'Constant'\n        if Value in self.RegisterAliases and 'Register' in TargetTypes:\n            return 'Register'\n        if Value in self.PinAliases and 'Device' in TargetTypes:\n            return 'Device'\n        if Value[0] == 'd' and len(Value) > 1 and ('Device' in TargetTypes):\n            if 'r' in Value:\n                try:\n                    InValue = int(Value[1:].replace('r', ''))\n                    if InValue >= 0 and InValue < 18:\n                        return 'Device'\n                except:\n                    pass\n            else:\n                try:\n                    DeviceNumberList = [str(X) for X in range(self.Parent.PinsNumber)] + ['b']\n                    if Value[1:] in DeviceNumberList:\n                        return 'Device'\n                except:\n                    pass\n        if Value[0] == 'r' and len(Value) > 1 and ('Register' in TargetTypes):\n            try:\n                InValue = int(Value.replace('r', ''))\n                if InValue >= 0 and InValue < 18:\n                    return 'Register'\n            except:\n                pass\n        if Value.startswith('HASH(\"') and Value.endswith('\")') and ('Hash' in TargetTypes):\n            return 'Hash'\n        if 'Number' in TargetTypes:\n            if Value[0] == '$':\n                try:\n                    int(Value[1:], 16)\n                    return 'Number'\n                except:\n                    pass\n            try:\n                int(Value)\n                return 'Number'\n            except:\n                try:\n                    float(Value)\n                    return 'Number'\n                except:\n                    pass\n        return 'String'\n\n    def GetArgType(self, Value, TargetTypes=[]):\n        IsSpecialType = TargetTypes[0] in self.FunctionMap['SpecialTypes']\n        if IsSpecialType:\n            SpecialType = TargetTypes[0]\n            TargetTypes = self.FunctionMap['SpecialTypes'][SpecialType]['Types'].split('|')\n        BaseType = self.GetArgBaseType(Value, TargetTypes)\n        if IsSpecialType:\n            if BaseType in TargetTypes:\n                Confirmed = self.FunctionMap['SpecialTypes'][SpecialType]['ConfirmFunction'](Value, BaseType)\n                if Confirmed:\n                    return SpecialType\n                else:\n                    return 'None'\n        return BaseType\n\n    def GetArgIndex(self, Value):\n        if Value in self.Constants:\n            Log.Warning('You cannot change a constant value', Caller=f\"Script line {self.Parent.Fields['LineNumber'].Value} \")\n            self.Parent.Fields['Error'].Value = 1\n            return None\n        if Value in self.RegisterAliases:\n            return self.GetArgIndex(self.RegisterAliases[Value])\n        if Value in self.PinAliases:\n            return self.GetArgIndex(self.PinAliases[Value])\n        if Value[0] == 'd':\n            if 'r' in Value:\n                try:\n                    TempValue = Value[1:]\n                    RegisterIndex = int(TempValue.replace('r', ''))\n                    for X in range(TempValue.count('r')):\n                        if RegisterIndex not in Constants.NOT_NUMBER_NUMBERS:\n                            if RegisterIndex >= 0 and RegisterIndex < 18:\n                                RegisterIndex = self.Registers[f'r{RegisterIndex}']\n                            else:\n                                Log.Warning('Indirect device values have to be bettween 0 and 17', Caller=f\"Script line {self.Parent.Fields['LineNumber'].Value}\")\n                                self.Parent.Fields['Error'].Value = 1\n                                return None\n                        else:\n                            Log.Warning('Indirect device values have to be bettween 0 and 17 not NaN', Caller=f\"Script line {self.Parent.Fields['LineNumber'].Value}\")\n                            self.Parent.Fields['Error'].Value = 1\n                            return None\n                    RegisterIndex = f'd{RegisterIndex}'\n                    if RegisterIndex in self.Parent.Pins:\n                        return RegisterIndex\n                    Log.Warning('Indirect device values have to be bettween 0 and 5', Caller=f\"Script line {self.Parent.Fields['LineNumber'].Value}\")\n                    self.Parent.Fields['Error'].Value = 1\n                    return None\n                except:\n                    pass\n            elif Value[0] == 'd' and Value[1:] in [str(X) for X in range(self.Parent.PinsNumber)] + ['b']:\n                return Value\n        if Value[0] == 'r':\n            try:\n                RegisterIndex = int(Value.replace('r', ''))\n                for X in range(Value.count('r') - 1):\n                    if RegisterIndex not in Constants.NOT_NUMBER_NUMBERS:\n                        if RegisterIndex >= 0 and RegisterIndex < 18:\n                            RegisterIndex = self.Registers[f'r{RegisterIndex}']\n                        else:\n                            Log.Warning('Indirect refrences values have to be bettween 0 and 17', Caller=f\"Script line {self.Parent.Fields['LineNumber'].Value}\")\n                            self.Parent.Fields['Error'].Value = 1\n                            return None\n                    else:\n                        Log.Warning('Indirect refrences values have to be bettween 0 and 17 not NaN', Caller=f\"Script line {self.Parent.Fields['LineNumber'].Value}\")\n                        self.Parent.Fields['Error'].Value = 1\n                        return None\n                return f'r{RegisterIndex}'\n            except:\n                pass\n        Log.Warning('Unknown value', Caller=f\"Script line {self.Parent.Fields['LineNumber'].Value}\")\n        self.Parent.Fields['Error'].Value = 1\n        return None\n\n    def GetArgValue(self, Value, TargetType=[]):\n        Value = str(Value)\n        if Value in self.Constants:\n            return self.Constants[Value]\n        if Value[0] == 'r':\n            try:\n                RegisterIndex = int(Value.replace('r', ''))\n                for X in range(Value.count('r') - 1):\n                    if RegisterIndex not in Constants.NOT_NUMBER_NUMBERS:\n                        if RegisterIndex >= 0 and RegisterIndex < 18:\n                            RegisterIndex = self.Registers[f'r{RegisterIndex}']\n                        else:\n                            Log.Warning('Indirect refrences values have to be bettween 0 and 17', Caller=f\"Script line {self.Parent.Fields['LineNumber'].Value}\")\n                            self.Parent.Fields['Error'].Value = 1\n                            return None\n                    else:\n                        Log.Warning('Indirect refrences values have to be bettween 0 and 17 not NaN', Caller=f\"Script line {self.Parent.Fields['LineNumber'].Value}\")\n                        self.Parent.Fields['Error'].Value = 1\n                        return None\n                return self.Registers[f'r{RegisterIndex}']\n            except:\n                pass\n        if Value in self.RegisterAliases:\n            return self.GetArgValue(self.RegisterAliases[Value])\n        if Value[0] == '$':\n            try:\n                return int(Value[1:], 16)\n            except:\n                pass\n        if Value.startswith('HASH(\"') and Value.endswith('\")'):\n            Value = Value[6:-2]\n            return ComputeCRC32(Value)\n        try:\n            return int(Value)\n        except:\n            try:\n                return float(Value)\n            except:\n                pass\n        return str(Value)\n\n    def GetSpecialArgValue(self, Value, Type):\n        if Type in self.FunctionMap['SpecialTypes']:\n            ProcessedValue = self.GetArgValue(Value, Type)\n            if self.Parent.Fields['Error'].Value == 1:\n                return\n            return self.FunctionMap['SpecialTypes'][Type]['GetArgFunction'](ProcessedValue)\n        else:\n            Log.Warning(f'Invalid special arg type', Caller=f\"Script line {self.Parent.Fields['LineNumber'].Value}\")\n            self.Parent.Fields['Error'].Value = 1\n\n    def GetDeviceObject(self, RefID: int, DoError: bool=True):\n        if self.Parent.Fields['Error'].Value == 1:\n            return\n        RefObject = self.Parent.Network.GetDevice(RefID)\n        if RefObject != None:\n            return RefObject\n        elif DoError:\n            Log.Warning(f'Unknown device at reference id {RefID}', Caller=f\"Script line {self.Parent.Fields['LineNumber'].Value}\")\n            self.Parent.Fields['Error'].Value = 1\n        else:\n            return None\n\n    def Instruction_Define(self, *args):\n        Value = int(args[2])\n        if args[1] not in self.Constants:\n            self.Constants[args[1]] = Value\n            if args[1] in self.RegisterAliases:\n                del self.RegisterAliases[args[1]]\n        else:\n            Log.Warning('You cannot change a constant value', Caller=f\"Script line {self.Parent.Fields['LineNumber'].Value}\")\n            if self.Parent.Fields['Error'].Value == 1:\n                return\n\n    def Instruction_Move(self, *args):\n        Index1 = self.GetArgIndex(args[1])\n        Value2 = self.GetArgValue(args[2])\n        if self.Parent.Fields['Error'].Value == 1:\n            return\n        self.Registers[Index1] = Value2\n\n    def Instruction_Alias(self, *args):\n        if self.GetArgType(args[1], ['String']) == 'String':\n            if args[1] not in self.Constants and args[1] not in self.Parent.Pins and (args[1] not in self.Registers):\n                if args[1] in self.RegisterAliases:\n                    del self.RegisterAliases[args[1]]\n                if args[1] in self.PinAliases:\n                    del self.PinAliases[args[1]]\n                if args[2][0] == 'r':\n                    self.RegisterAliases[args[1]] = args[2]\n                elif args[2][0] == 'd':\n                    self.PinAliases[args[1]] = args[2]\n                else:\n                    Log.Error('Unkown alias type not caught by update')\n            else:\n                Log.Warning('Cannot overwrite a constant/builtin register/builtin device index', Caller=f\"Script line {self.Parent.Fields['LineNumber'].Value}\")\n                if self.Parent.Fields['Error'].Value == 1:\n                    return\n        else:\n            Log.Warning('You cannot set a register alias to a device name or a register', Caller=f\"Script line {self.Parent.Fields['LineNumber'].Value}\")\n            self.Parent.Fields['Error'].Value = 1\n\n    def Instruction_Add(self, *args):\n        Index1 = self.GetArgIndex(args[1])\n        Value1 = self.GetArgValue(args[2])\n        Value2 = self.GetArgValue(args[3])\n        if self.Parent.Fields['Error'].Value == 1:\n            return\n        if Value1 in Constants.NOT_NUMBER_NUMBERS:\n            self.Registers[Index1] = Value1\n            return\n        if Value2 in Constants.NOT_NUMBER_NUMBERS:\n            self.Registers[Index1] = Value2\n            return\n        self.Registers[Index1] = Value1 + Value2\n\n    def Instruction_Sub(self, *args):\n        Index1 = self.GetArgIndex(args[1])\n        Value1 = self.GetArgValue(args[2])\n        Value2 = self.GetArgValue(args[3])\n        if self.Parent.Fields['Error'].Value == 1:\n            return\n        if Value1 in Constants.NOT_NUMBER_NUMBERS:\n            self.Registers[Index1] = Value1\n            return\n        if Value2 in Constants.NOT_NUMBER_NUMBERS:\n            self.Registers[Index1] = Value2\n            return\n        self.Registers[Index1] = Value1 - Value2\n\n    def Instruction_Mul(self, *args):\n        Index1 = self.GetArgIndex(args[1])\n        Value1 = self.GetArgValue(args[2])\n        Value2 = self.GetArgValue(args[3])\n        if self.Parent.Fields['Error'].Value == 1:\n            return\n        if Value1 in Constants.NOT_NUMBER_NUMBERS:\n            self.Registers[Index1] = Value1\n            return\n        if Value2 in Constants.NOT_NUMBER_NUMBERS:\n            self.Registers[Index1] = Value2\n            return\n        self.Registers[Index1] = Value1 * Value2\n\n    def Instruction_Div(self, *args):\n        Index1 = self.GetArgIndex(args[1])\n        Value1 = self.GetArgValue(args[2])\n        Value2 = self.GetArgValue(args[3])\n        if self.Parent.Fields['Error'].Value == 1:\n            return\n        if Value1 in Constants.NOT_NUMBER_NUMBERS:\n            self.Registers[Index1] = Value1\n            return\n        if Value2 in Constants.NOT_NUMBER_NUMBERS:\n            self.Registers[Index1] = Value2\n            return\n        if Value2 == 0:\n            self.Registers[Index1] = 'NaN'\n            return\n        self.Registers[Index1] = Value1 / Value2\n\n    def Instruction_Ceil(self, *args):\n        Index1 = self.GetArgIndex(args[1])\n        Value1 = self.GetArgValue(args[2])\n        if self.Parent.Fields['Error'].Value == 1:\n            return\n        if Value1 in Constants.NOT_NUMBER_NUMBERS:\n            self.Registers[Index1] = Value1\n            return\n        self.Registers[Index1] = math.ceil(Value1)\n\n    def Instruction_Floor(self, *args):\n        Index1 = self.GetArgIndex(args[1])\n        Value1 = self.GetArgValue(args[2])\n        if self.Parent.Fields['Error'].Value == 1:\n            return\n        if Value1 in Constants.NOT_NUMBER_NUMBERS:\n            self.Registers[Index1] = Value1\n            return\n        self.Registers[Index1] = math.floor(Value1)\n\n    def Instruction_Exp(self, *args):\n        Index1 = self.GetArgIndex(args[1])\n        Value1 = self.GetArgValue(args[2])\n        if self.Parent.Fields['Error'].Value == 1:\n            return\n        if Value1 in Constants.NOT_NUMBER_NUMBERS:\n            self.Registers[Index1] = Value1\n            return\n        self.Registers[Index1] = math.e ** Value1\n\n    def Instruction_Log(self, *args):\n        Index1 = self.GetArgIndex(args[1])\n        Value1 = self.GetArgValue(args[2])\n        if self.Parent.Fields['Error'].Value == 1:\n            return\n        if Value1 in Constants.NOT_NUMBER_NUMBERS:\n            self.Registers[Index1] = Value1\n            return\n        self.Registers[Index1] = math.log(Value1)\n\n    def Instruction_Rand(self, *args):\n        Index1 = self.GetArgIndex(args[1])\n        if self.Parent.Fields['Error'].Value == 1:\n            return\n        self.Registers[Index1] = random.random()\n\n    def Instruction_Round(self, *args):\n        Index1 = self.GetArgIndex(args[1])\n        Value1 = self.GetArgValue(args[2])\n        if self.Parent.Fields['Error'].Value == 1:\n            return\n        if Value1 in Constants.NOT_NUMBER_NUMBERS:\n            self.Registers[Index1] = Value1\n            return\n        Decimal = Value1 - math.floor(Value1)\n        if Decimal >= 0.5:\n            self.Registers[Index1] = math.ceil(Value1)\n        else:\n            self.Registers[Index1] = math.floor(Value1)\n\n    def Instruction_Sqrt(self, *args):\n        Index1 = self.GetArgIndex(args[1])\n        Value1 = self.GetArgValue(args[2])\n        if self.Parent.Fields['Error'].Value == 1:\n            return\n        if Value1 in Constants.NOT_NUMBER_NUMBERS:\n            self.Registers[Index1] = Value1\n            return\n        self.Registers[Index1] = math.sqrt(Value1)\n\n    def Instruction_Trunc(self, *args):\n        Index1 = self.GetArgIndex(args[1])\n        Value1 = self.GetArgValue(args[2])\n        if self.Parent.Fields['Error'].Value == 1:\n            return\n        if Value1 in Constants.NOT_NUMBER_NUMBERS:\n            self.Registers[Index1] = Value1\n            return\n        self.Registers[Index1] = math.trunc(Value1)\n\n    def Instruction_Asin(self, *args):\n        Index1 = self.GetArgIndex(args[1])\n        Value1 = self.GetArgValue(args[2])\n        if self.Parent.Fields['Error'].Value == 1:\n            return\n        if Value1 in Constants.NOT_NUMBER_NUMBERS:\n            self.Registers[Index1] = Value1\n            return\n        try:\n            self.Registers[Index1] = math.asin(Value1)\n        except:\n            self.Registers[Index1] = 'NaN'\n\n    def Instruction_Acos(self, *args):\n        Index1 = self.GetArgIndex(args[1])\n        Value1 = self.GetArgValue(args[2])\n        if self.Parent.Fields['Error'].Value == 1:\n            return\n        if Value1 in Constants.NOT_NUMBER_NUMBERS:\n            self.Registers[Index1] = Value1\n            return\n        try:\n            self.Registers[Index1] = math.acos(Value1)\n        except:\n            self.Registers[Index1] = 'NaN'\n\n    def Instruction_Atan(self, *args):\n        Index1 = self.GetArgIndex(args[1])\n        Value1 = self.GetArgValue(args[2])\n        if self.Parent.Fields['Error'].Value == 1:\n            return\n        if Value1 in Constants.NOT_NUMBER_NUMBERS:\n            self.Registers[Index1] = Value1\n            return\n        try:\n            self.Registers[Index1] = math.atan(Value1)\n        except:\n            self.Registers[Index1] = 'NaN'\n\n    def Instruction_Atan2(self, *args):\n        Index1 = self.GetArgIndex(args[1])\n        Value1 = self.GetArgValue(args[2])\n        Value2 = self.GetArgValue(args[3])\n        if self.Parent.Fields['Error'].Value == 1:\n            return\n        if Value1 in Constants.NOT_NUMBER_NUMBERS:\n            self.Registers[Index1] = Value1\n            return\n        if Value2 in Constants.NOT_NUMBER_NUMBERS:\n            self.Registers[Index1] = Value2\n            return\n        try:\n            self.Registers[Index1] = math.atan2(Value1, Value2)\n        except:\n            self.Registers[Index1] = 'NaN'\n\n    def Instruction_Sin(self, *args):\n        Index1 = self.GetArgIndex(args[1])\n        Value1 = self.GetArgValue(args[2])\n        if self.Parent.Fields['Error'].Value == 1:\n            return\n        if Value1 in Constants.NOT_NUMBER_NUMBERS:\n            self.Registers[Index1] = Value1\n            return\n        try:\n            self.Registers[Index1] = math.sin(Value1)\n        except:\n            self.Registers[Index1] = 'NaN'\n\n    def Instruction_Cos(self, *args):\n        Index1 = self.GetArgIndex(args[1])\n        Value1 = self.GetArgValue(args[2])\n        if self.Parent.Fields['Error'].Value == 1:\n            return\n        if Value1 in Constants.NOT_NUMBER_NUMBERS:\n            self.Registers[Index1] = Value1\n            return\n        try:\n            self.Registers[Index1] = math.cos(Value1)\n        except:\n            self.Registers[Index1] = 'NaN'\n\n    def Instruction_Tan(self, *args):\n        Index1 = self.GetArgIndex(args[1])\n        Value1 = self.GetArgValue(args[2])\n        if self.Parent.Fields['Error'].Value == 1:\n            return\n        if Value1 in Constants.NOT_NUMBER_NUMBERS:\n            self.Registers[Index1] = Value1\n            return\n        try:\n            self.Registers[Index1] = math.tan(Value1)\n        except:\n            self.Registers[Index1] = 'NaN'\n\n    def Instruction_Peek(self, *args):\n        Index1 = self.Registers[self.RegisterAliases['sp']]\n        Index2 = self.GetArgIndex(args[1])\n        if self.Parent.Fields['Error'].Value == 1:\n            return\n        if Index1 in Constants.NOT_NUMBER_NUMBERS:\n            Log.Warning('Cannot peek at NaN index', Caller=f\"Script line {self.Parent.Fields['LineNumber'].Value}\")\n            self.Parent.Fields['Error'].Value = 1\n            return\n        if Index1 >= 1 and Index1 <= self.Parent.StackLength:\n            self.Registers[Index2] = self.Stack[Index1 - 1]\n        else:\n            Log.Warning(f'Peek index must be greater then 0 and less then or equal to {self.Parent.StackLength}', Caller=f\"Script line {self.Parent.Fields['LineNumber'].Value}\")\n            self.Parent.Fields['Error'].Value = 1\n\n    def Instruction_Push(self, *args):\n        Index1 = self.Registers[self.RegisterAliases['sp']]\n        Value1 = self.GetArgValue(args[1])\n        if self.Parent.Fields['Error'].Value == 1:\n            return\n        if Index1 in Constants.NOT_NUMBER_NUMBERS:\n            Log.Warning('Cannot push at NaN index', Caller=f\"Script line {self.Parent.Fields['LineNumber'].Value}\")\n            self.Parent.Fields['Error'].Value = 1\n            return\n        if Index1 >= 0 and Index1 < self.Parent.StackLength:\n            self.Stack[Index1] = Value1\n            self.Registers[self.RegisterAliases['sp']] += 1\n        else:\n            Log.Warning(f'Push index must be greater then or euqal to 0 and less then {self.Parent.StackLength}', Caller=f\"Script line {self.Parent.Fields['LineNumber'].Value}\")\n            self.Parent.Fields['Error'].Value = 1\n\n    def Instruction_Pop(self, *args):\n        Index1 = self.Registers[self.RegisterAliases['sp']]\n        Index2 = self.GetArgIndex(args[1])\n        if self.Parent.Fields['Error'].Value == 1:\n            return\n        if Index1 in Constants.NOT_NUMBER_NUMBERS:\n            Log.Warning('Cannot pop at NaN index', Caller=f\"Script line {self.Parent.Fields['LineNumber'].Value}\")\n            self.Parent.Fields['Error'].Value = 1\n            return\n        if Index1 > 0 and Index1 <= self.Parent.StackLength:\n            self.Registers[Index2] = self.Stack[Index1 - 1]\n            self.Registers[self.RegisterAliases['sp']] -= 1\n        else:\n            Log.Warning(f'Pop index must be greater then 0 and less then or equal to {self.Parent.StackLength}', Caller=f\"Script line {self.Parent.Fields['LineNumber'].Value}\")\n            self.Parent.Fields['Error'].Value = 1\n\n    def Instruction_Get(self, *args):\n        Index1 = self.GetArgIndex(args[1])\n        Index2 = self.GetArgIndex(args[2])\n        Index3 = self.GetArgValue(args[3])\n        if self.Parent.Fields['Error'].Value == 1:\n            return\n        if Index2 in self.Parent.Pins:\n            DeviceObject = self.GetDeviceObject(self.Parent.Pins[Index2])\n        else:\n            Log.Warning(f'No device at {Index2}', Caller=f\"Script line {self.Parent.Fields['LineNumber'].Value}\")\n            self.Parent.Fields['Error'].Value = 1\n            return\n        if DeviceObject.StackEnabled == False:\n            Log.Warning(f'Device does not have a stack', Caller=f\"Script line {self.Parent.Fields['LineNumber'].Value}\")\n            self.Parent.Fields['Error'].Value = 1\n            return\n        if Index3 in Constants.NOT_NUMBER_NUMBERS:\n            Log.Warning('Cannot get at NaN index', Caller=f\"Script line {self.Parent.Fields['LineNumber'].Value}\")\n            self.Parent.Fields['Error'].Value = 1\n            return\n        if Index3 >= 1 and Index3 <= DeviceObject.StackLength:\n            self.Registers[Index1] = self.Stack[Index3 - 1]\n            Log.Warning(f'Needs further testing', Caller=f\"Script line {self.Parent.Fields['LineNumber'].Value}\")\n        else:\n            Log.Warning(f'Get must be greater then 0 and less then or equal to {DeviceObject.StackLength}', Caller=f\"Script line {self.Parent.Fields['LineNumber'].Value}\")\n            self.Parent.Fields['Error'].Value = 1\n\n    def Instruction_GetD(self, *args):\n        pass\n\n    def Instruction_Poke(self, *args):\n        Value1 = self.GetArgValue(args[1])\n        Value2 = self.GetArgValue(args[2])\n        if self.Parent.Fields['Error'].Value == 1:\n            return\n        if Value1 in Constants.NOT_NUMBER_NUMBERS:\n            Log.Warning('Cannot poke at NaN index', Caller=f\"Script line {self.Parent.Fields['LineNumber'].Value}\")\n            self.Parent.Fields['Error'].Value = 1\n            return\n        if Value1 >= 0 and Value1 < self.Parent.StackLength:\n            self.Stack[Value1] = Value2\n        else:\n            Log.Warning(f'Pop index must be greater then or equal to 0 and less then {self.Parent.StackLength}', Caller=f\"Script line {self.Parent.Fields['LineNumber'].Value}\")\n            self.Parent.Fields['Error'].Value = 1\n\n    def Instruction_Load(self, *args):\n        Index1 = self.GetArgIndex(args[1])\n        Index2 = self.GetArgIndex(args[2])\n        Value1 = self.GetSpecialArgValue(args[3], 'LogicType')\n        if self.Parent.Fields['Error'].Value == 1:\n            return\n        if Index2 in self.Parent.Pins:\n            DeviceObject = self.GetDeviceObject(self.Parent.Pins[Index2])\n        else:\n            Log.Warning(f'No device at {Index2}', Caller=f\"Script line {self.Parent.Fields['LineNumber'].Value}\")\n            self.Parent.Fields['Error'].Value = 1\n            return\n        if self.Parent.Fields['Error'].Value == 1:\n            return\n        FieldValue = DeviceObject.GetFieldValue(Value1)\n        if FieldValue[0] == None:\n            Log.Warning(FieldValue[1], Caller=f\"Script line {self.Parent.Fields['LineNumber'].Value}\")\n            self.Parent.Fields['Error'].Value = 1\n            return None\n        self.Registers[Index1] = FieldValue[0]\n\n    def ApplyBatchOperation(self, Values, BatchMode):\n        try:\n            BatchMode = int(BatchMode)\n            if BatchMode < 0 or BatchMode >= len(Constants.BATCH_NO_RESPONSE):\n                return 0\n        except:\n            return 0\n        if len(Values) == 0:\n            return Constants.BATCH_NO_RESPONSE[BatchMode]\n        if BatchMode == 0:\n            return sum(Values) / len(Values)\n        elif BatchMode == 1:\n            return sum(Values)\n        elif BatchMode == 2:\n            return min(Values)\n        elif BatchMode == 3:\n            return max(Values)\n        return 'NaN'\n\n    def CollectDevicesValueBatch(self, Devices, Value, BatchMode):\n        Values = []\n        for X in Devices:\n            FieldValue = X.GetFieldValue(Value)\n            if FieldValue[0] != None:\n                Values.append(FieldValue[0])\n        if len(Values) == 0:\n            return Constants.BATCH_NO_RESPONSE[BatchMode]\n        return MakeIntIfClose(self.ApplyBatchOperation(Values, BatchMode))\n\n    def Instruction_LoadBatch(self, *args):\n        Index1 = self.GetArgIndex(args[1])\n        Value1 = self.GetSpecialArgValue(args[2], 'DeviceHash')\n        Value2 = self.GetSpecialArgValue(args[3], 'LogicType')\n        Value3 = self.GetSpecialArgValue(args[4], 'BatchMode')\n        if self.Parent.Fields['Error'].Value == 1:\n            return\n        if Value1 in Constants.NOT_NUMBER_NUMBERS:\n            self.Registers[Index1] = 'Nan'\n            return\n        Devices = self.Parent.Network.GetBatchDevices(Value1)\n        Result = self.CollectDevicesValueBatch(Devices, Value2, Value3)\n        self.Registers[Index1] = Result\n\n    def Instruction_LoadBatchNamed(self, *args):\n        Index1 = self.GetArgIndex(args[1])\n        Value1 = self.GetSpecialArgValue(args[2], 'DeviceHash')\n        Value2 = self.GetSpecialArgValue(args[3], 'NameHash')\n        Value3 = self.GetSpecialArgValue(args[4], 'LogicType')\n        Value4 = self.GetSpecialArgValue(args[5], 'BatchMode')\n        if self.Parent.Fields['Error'].Value == 1:\n            return\n        if Value1 in Constants.NOT_NUMBER_NUMBERS:\n            self.Registers[Index1] = 'NaN'\n            return\n        if Value2 in Constants.NOT_NUMBER_NUMBERS:\n            Log.Warning(f'Cannot get a device with a NameHash of NaN', Caller=f\"Script line {self.Parent.Fields['LineNumber'].Value}\")\n            self.Parent.Fields['Error'].Value = 1\n            return\n        Devices = self.Parent.Network.GetBatchDevices(Value1, Value2)\n        Result = self.CollectDevicesValueBatch(Devices, Value3, Value4)\n        self.Registers[Index1] = Result\n\n    def Instruction_Set(self, *args):\n        Index1 = self.GetArgIndex(args[1])\n        Value1 = self.GetSpecialArgValue(args[2], 'LogicType')\n        Value2 = self.GetArgValue(args[3])\n        if self.Parent.Fields['Error'].Value == 1:\n            return\n        if Index1 in self.Parent.Pins:\n            DeviceObject = self.GetDeviceObject(self.Parent.Pins[Index1])\n        else:\n            Log.Warning(f'No device at {Index1}', Caller=f\"Script line {self.Parent.Fields['LineNumber'].Value}\")\n            self.Parent.Fields['Error'].Value = 1\n            return\n        if self.Parent.Fields['Error'].Value == 1:\n            return\n        Result = DeviceObject.SetFieldValue(Value1, Value2)\n        if Result[0] == None:\n            Log.Warning(Result[1], Caller=f\"Script line {self.Parent.Fields['LineNumber'].Value}\")\n            self.Parent.Fields['Error'].Value = 1\n\n    def Instruction_SetBatch(self, *args):\n        Value1 = self.GetSpecialArgValue(args[1], 'DeviceHash')\n        Value2 = self.GetSpecialArgValue(args[2], 'LogicType')\n        Value3 = self.GetArgValue(args[3])\n        if self.Parent.Fields['Error'].Value == 1:\n            return\n        Devices = self.Parent.Network.GetBatchDevices(Value1)\n        for X in Devices:\n            X.SetFieldValue(Value2, Value3)\n\n    def Instruction_SetBatchNamed(self, *args):\n        Value1 = self.GetSpecialArgValue(args[1], 'DeviceHash')\n        Value2 = self.GetSpecialArgValue(args[2], 'NameHash')\n        Value3 = self.GetSpecialArgValue(args[3], 'LogicType')\n        Value4 = self.GetArgValue(args[4])\n        if self.Parent.Fields['Error'].Value == 1:\n            return\n        Devices = self.Parent.Network.GetBatchDevices(Value1, Value2)\n        for X in Devices:\n            X.SetFieldValue(Value3, Value4)\n\n    def Instruction_SetDevice(self, *args):\n        Index1 = self.GetSpecialArgValue(args[1], 'ReferenceID')\n        Value1 = self.GetSpecialArgValue(args[2], 'LogicType')\n        Value2 = self.GetArgValue(args[3])\n        if self.Parent.Fields['Error'].Value == 1:\n            return\n        DeviceObject = self.GetDeviceObject(Index1)\n        if self.Parent.Fields['Error'].Value == 1:\n            return\n        Result = DeviceObject.SetFieldValue(Value1, Value2)\n        if Result[0] == None:\n            Log.Warning(Result[1], Caller=f\"Script line {self.Parent.Fields['LineNumber'].Value}\")\n            self.Parent.Fields['Error'].Value = 1\n\n    def Instruction_LoadDevice(self, *args):\n        Index1 = self.GetArgIndex(args[1])\n        Index2 = self.GetSpecialArgValue(args[2], 'ReferenceID')\n        Value1 = self.GetSpecialArgValue(args[3], 'LogicType')\n        if self.Parent.Fields['Error'].Value == 1:\n            return\n        DeviceObject = self.GetDeviceObject(self.Parent.Pins[Index2])\n        if self.Parent.Fields['Error'].Value == 1:\n            return\n        FieldValue = DeviceObject.GetFieldValue(Value1)\n        if FieldValue[0] == None:\n            Log.Warning(FieldValue[1], Caller=f\"Script line {self.Parent.Fields['LineNumber'].Value}\")\n            self.Parent.Fields['Error'].Value = 1\n            return None\n        self.Registers[Index1] = FieldValue[0]\n\n    def Instruction_Yield(self, *args):\n        return\n\n    def Instruction_Hcf(self, *args):\n        Log.Warning('Hcf triggered', Caller=f\"Script line {self.Parent.Fields['LineNumber'].Value}\")\n        self.Parent.Fields['Error'].Value = 1\n        return\n\n    def Instruction_Jump(self, *args):\n        Line = self.GetArgValue(args[1])\n        if self.Parent.Fields['Error'].Value == 1:\n            return\n        if Line in Constants.NOT_NUMBER_NUMBERS:\n            Log.Warning('You cannot jump to a NaN line', Caller=f\"Script line {self.Parent.Fields['LineNumber'].Value}\")\n            self.Parent.Fields['Error'].Value = 1\n            return\n        self.Parent.Fields['LineNumber'].Value = Line - 1\n\n    def Instruction_JumpAL(self, *args):\n        Line = self.GetArgValue(args[1])\n        if self.Parent.Fields['Error'].Value == 1:\n            return\n        if Line in Constants.NOT_NUMBER_NUMBERS:\n            Log.Warning('You cannot jump to a NaN line', Caller=f\"Script line {self.Parent.Fields['LineNumber'].Value}\")\n            self.Parent.Fields['Error'].Value = 1\n            return\n        self.Registers[self.RegisterAliases['ra']] = self.Parent.Fields['LineNumber'].Value + 1\n        self.Parent.Fields['LineNumber'].Value = Line - 1\n\n    def Instruction_JumpR(self, *args):\n        Line = self.GetArgValue(args[1])\n        if self.Parent.Fields['Error'].Value == 1:\n            return\n        if Line in Constants.NOT_NUMBER_NUMBERS:\n            Log.Warning('You cannot jump relative to a NaN line', Caller=f\"Script line {self.Parent.Fields['LineNumber'].Value}\")\n            self.Parent.Fields['Error'].Value = 1\n            return\n        NewLineNumber = self.Parent.Fields['LineNumber'].Value + Line - 1\n        if NewLineNumber < 0:\n            NewLineNumber = self.Parent.Fields['LineNumber'].Value\n        if NewLineNumber >= len(self.Code) - 1:\n            NewLineNumber = self.Parent.Fields['LineNumber'].Value - 1\n        self.Parent.Fields['LineNumber'].Value = NewLineNumber\n\n    def GetBranchRoot(self, FunctionName):\n        if FunctionName.endswith('al'):\n            StoreNextLine = True\n            FunctionName = FunctionName[:-2]\n        else:\n            StoreNextLine = False\n        if FunctionName.startswith('br'):\n            Relative = True\n            FunctionName = FunctionName[2:]\n        else:\n            Relative = False\n            FunctionName = FunctionName[1:]\n        return (FunctionName, StoreNextLine, Relative)\n\n    def Instruction_Branch(self, *args):\n        global epsilon\n        FunctionName, StoreNextLine, Relative = self.GetBranchRoot(args[0])\n        Values = [self.GetArgValue(X) for X in args[1:]]\n        if self.Parent.Fields['Error'].Value == 1:\n            return\n        Matched = False\n        if FunctionName == 'eq':\n            JumpLine = Values[2]\n            Matched = Values[0] == Values[1]\n        elif FunctionName == 'eqz':\n            JumpLine = Values[1]\n            Matched = Values[0] == 0\n        elif FunctionName == 'ge':\n            JumpLine = Values[2]\n            Matched = Values[0] >= Values[1]\n        elif FunctionName == 'gez':\n            JumpLine = Values[1]\n            Matched = Values[0] >= 0\n        elif FunctionName == 'gt':\n            JumpLine = Values[2]\n            Matched = Values[0] > Values[1]\n        elif FunctionName == 'gtz':\n            JumpLine = Values[1]\n            Matched = Values[0] > 0\n        elif FunctionName == 'le':\n            JumpLine = Values[2]\n            Matched = Values[0] <= Values[1]\n        elif FunctionName == 'lez':\n            JumpLine = Values[1]\n            Matched = Values[0] <= 0\n        elif FunctionName == 'lt':\n            JumpLine = Values[2]\n            Matched = Values[0] < Values[1]\n        elif FunctionName == 'ltz':\n            JumpLine = Values[1]\n            Matched = Values[0] >= 0\n        elif FunctionName == 'ne':\n            JumpLine = Values[2]\n            Matched = Values[0] != Values[1]\n        elif FunctionName == 'nez':\n            JumpLine = Values[1]\n            Matched = Values[0] != 0\n        elif FunctionName == 'nan':\n            JumpLine = Values[1]\n            Matched = Values[0] == 'NaN'\n        elif FunctionName == 'ap':\n            JumpLine = Values[3]\n            Matched = abs(Values[0] - Values[1]) <= max(Values[2] * max(abs(Values[0]), abs(Values[1])), epsilon * 8)\n        elif FunctionName == 'apz':\n            JumpLine = Values[2]\n            Matched = abs(Values[0]) <= max(Values[1] * abs(Values[0]), epsilon * 8)\n        elif FunctionName == 'na':\n            JumpLine = Values[3]\n            Matched = abs(Values[0] - Values[1]) > max(Values[2] * max(abs(Values[0]), abs(Values[1])), epsilon * 8)\n        elif FunctionName == 'naz':\n            JumpLine = Values[2]\n            Matched = abs(Values[0]) > max(Values[1] * abs(Values[0]), epsilon * 8)\n        else:\n            Log.Warning('Unknown branch type', Caller=f\"Script line {self.Parent.Fields['LineNumber'].Value}\")\n            self.Parent.Fields['Error'].Value = 1\n            return\n        if Matched == True:\n            if StoreNextLine == True:\n                self.Registers[self.RegisterAliases['ra']] = self.Parent.Fields['LineNumber'].Value + 1\n            if Relative == True:\n                self.Parent.Fields['LineNumber'].Value += JumpLine - 1\n            else:\n                self.Parent.Fields['LineNumber'].Value = JumpLine - 1\n\n    def Instruction_Branch_Devices(self, *args):\n        global epsilon\n        FunctionName, StoreNextLine, Relative = self.GetBranchRoot(args[0])\n        Index1 = self.GetArgIndex(args[1])\n        JumpLine = self.GetArgValue(args[2])\n        if self.Parent.Fields['Error'].Value == 1:\n            return\n        if Index1 in self.Parent.Pins:\n            Matched = self.GetDeviceObject(self.Parent.Pins[Index1], DoError=False) != None\n        else:\n            Matched = False\n        if FunctionName == 'dns':\n            Matched = not Matched\n        elif FunctionName == 'dse':\n            pass\n        else:\n            Log.Warning('Unknown branch type', Caller=f\"Script line {self.Parent.Fields['LineNumber'].Value}\")\n            self.Parent.Fields['Error'].Value = 1\n            return\n        if Matched == True:\n            if StoreNextLine == True:\n                self.Registers[self.RegisterAliases['ra']] = self.Parent.Fields['LineNumber'].Value + 1\n            if Relative == True:\n                self.Parent.Fields['LineNumber'].Value += JumpLine - 1\n            else:\n                self.Parent.Fields['LineNumber'].Value = JumpLine - 1\n\n    def Instruction_Set_Conditional_Register(self, *args):\n        global epsilon\n        FunctionName, _, _ = self.GetBranchRoot(args[0])\n        Values = [self.GetArgValue(X) for X in args[2:]]\n        Index1 = self.GetArgIndex(args[1])\n        if self.Parent.Fields['Error'].Value == 1:\n            return\n        Matched = False\n        if FunctionName == 'eq':\n            Matched = Values[0] == Values[1]\n        elif FunctionName == 'eqz':\n            Matched = Values[0] == 0\n        elif FunctionName == 'ge':\n            Matched = Values[0] >= Values[1]\n        elif FunctionName == 'gez':\n            Matched = Values[0] >= 0\n        elif FunctionName == 'gt':\n            Matched = Values[0] > Values[1]\n        elif FunctionName == 'gtz':\n            Matched = Values[0] > 0\n        elif FunctionName == 'le':\n            Matched = Values[0] <= Values[1]\n        elif FunctionName == 'lez':\n            Matched = Values[0] <= 0\n        elif FunctionName == 'lt':\n            Matched = Values[0] < Values[1]\n        elif FunctionName == 'ltz':\n            Matched = Values[0] >= 0\n        elif FunctionName == 'ne':\n            Matched = Values[0] != Values[1]\n        elif FunctionName == 'nez':\n            Matched = Values[0] != 0\n        elif FunctionName == 'nan':\n            Matched = Values[0] == 'NaN'\n        elif FunctionName == 'nanz':\n            Matched = Values[0] != 'NaN'\n        elif FunctionName == 'ap':\n            Matched = abs(Values[0] - Values[1]) <= max(Values[2] * max(abs(Values[0]), abs(Values[1])), epsilon * 8)\n        elif FunctionName == 'apz':\n            Matched = abs(Values[0]) <= max(Values[1] * abs(Values[0]), epsilon * 8)\n        elif FunctionName == 'na':\n            Matched = abs(Values[0] - Values[1]) > max(Values[2] * max(abs(Values[0]), abs(Values[1])), epsilon * 8)\n        elif FunctionName == 'naz':\n            Matched = abs(Values[0]) > max(Values[1] * abs(Values[0]), epsilon * 8)\n        else:\n            Log.Warning('Unknown conditional type', Caller=f\"Script line {self.Parent.Fields['LineNumber'].Value}\")\n            self.Parent.Fields['Error'].Value = 1\n            return\n        self.Registers[Index1] = int(Matched)\n\n    def Instruction_Set_Conditional_Register_Devices(self, *args):\n        global epsilon\n        FunctionName, _, _ = self.GetBranchRoot(args[0])\n        Index1 = self.GetArgIndex(args[1])\n        Index2 = self.GetArgIndex(args[2])\n        if self.Parent.Fields['Error'].Value == 1:\n            return\n        if Index2 in self.Parent.Pins:\n            Matched = self.GetDeviceObject(self.Parent.Pins[Index2], DoError=False) != None\n        else:\n            Matched = False\n        if FunctionName == 'dns':\n            Matched = not Matched\n        elif FunctionName == 'dse':\n            pass\n        else:\n            Log.Warning('Unknown conditional type', Caller=f\"Script line {self.Parent.Fields['LineNumber'].Value}\")\n            self.Parent.Fields['Error'].Value = 1\n            return\n        self.Registers[Index1] = int(Matched)\n\n    def Instruction_Select(self, *args):\n        Index1 = self.GetArgIndex(args[1])\n        Value1 = self.GetArgValue(args[2])\n        Value2 = self.GetArgValue(args[3])\n        Value3 = self.GetArgValue(args[4])\n        Output = 0\n        if Value1 != 0:\n            Output = Value2\n        else:\n            Output = Value3\n        self.Registers[Index1] = Output\n\n    def Instruction_Bitwise_And(self, *args):\n        Index1 = self.GetArgIndex(args[1])\n        Value1 = self.GetArgValue(args[2])\n        Value2 = self.GetArgValue(args[3])\n        self.Registers[Index1] = Value1 & Value2\n\n    def Instruction_Bitwise_Nor(self, *args):\n        Index1 = self.GetArgIndex(args[1])\n        Value1 = self.GetArgValue(args[2])\n        Value2 = self.GetArgValue(args[3])\n        Log.Error('DO THIS LOL NOR')\n\n    def Instruction_Bitwise_Not(self, *args):\n        Index1 = self.GetArgIndex(args[1])\n        Value1 = self.GetArgValue(args[2])\n        Value2 = self.GetArgValue(args[3])\n        Log.Error('DO THIS LOL NOT')\n\n    def Instruction_Bitwise_Or(self, *args):\n        Index1 = self.GetArgIndex(args[1])\n        Value1 = self.GetArgValue(args[2])\n        Value2 = self.GetArgValue(args[3])\n        Log.Error('DO THIS LOL OR')\n        self.Registers[Index1] = Value1 | Value2\n\n    def RunUpdate(self):\n        if self.Parent.Fields['LineNumber'].Value >= len(self.Code) or self.Parent.Fields['Error'].Value != 0:\n            return\n        CurrentLine = self.Code[self.Parent.Fields['LineNumber'].Value].strip()\n        if CurrentLine != '':\n            CurrentLine = SplitNotStringSpaces(CurrentLine, ' ')\n            for CurrentIndex, CurrentFunction in self.FunctionMap['Functions'].items():\n                if CurrentLine[0] in CurrentFunction['Alias']:\n                    if len(CurrentLine) - 1 == CurrentFunction['Alias'][CurrentLine[0]]:\n                        for X in range(0, len(CurrentLine) - 1):\n                            TargetArgTypes = CurrentFunction['Args'][X].split('|')\n                            CurrentArgTypes = self.GetArgType(CurrentLine[X + 1], TargetArgTypes)\n                            if CurrentArgTypes not in TargetArgTypes:\n                                print(CurrentArgTypes)\n                                Log.Warning(f\"Arg {X + 1} of {CurrentLine[0]} must be of type {CurrentFunction['Args'][X]}\", Caller=f\"Script line {self.Parent.Fields['LineNumber'].Value}\")\n                                self.Parent.Fields['Error'].Value = 1\n                                break\n                        else:\n                            self.FunctionMap['Functions'][CurrentIndex]['Function'](*CurrentLine)\n                    else:\n                        Log.Warning(f\"{CurrentLine[0]} requires {CurrentFunction['Alias'][CurrentLine[0]]} args\", Caller=f\"Script line {self.Parent.Fields['LineNumber'].Value}\")\n                        self.Parent.Fields['Error'].Value = 1\n                    break\n            else:\n                Log.Warning(f'Unknown function {CurrentLine[0]}', Caller=f\"Script line {self.Parent.Fields['LineNumber'].Value}\")\n                self.Parent.Fields['Error'].Value = 1\n        self.HighestSP = max(self.HighestSP, self.Registers[self.RegisterAliases['sp']])\n        self.Parent.Fields['LineNumber'].Value += 1\n\n    def Instruction_Abs(self, *args):\n",
        "input": "",
        "output": "        Index1 = self.GetArgIndex(args[1])\n        Value1 = self.GetArgValue(args[2])\n        if self.Parent.Fields['Error'].Value == 1:\n            return\n        if Value1 in Constants.NOT_NUMBER_NUMBERS:\n            self.Registers[Index1] = Value1\n            return\n        self.Registers[Index1] = abs(Value1)\n    \n",
        "idx": "768"
    },
    {
        "instruction": "## k8spulse/db.py\nimport os\n\nfrom jinja2 import Environment, FileSystemLoader\n\nfrom rich.console import Console\n\nconsole = Console()\n\ntemplate_dir = os.path.join(os.path.dirname(__file__), \"templates\")\n\nenv = Environment(loader=FileSystemLoader(template_dir))\n\ndef render_html_report(template_name, context):\n",
        "input": "",
        "output": "    console.log(\"[cyan]Rendering HTML report...[/cyan]\")\n    template = env.get_template(template_name)\n    return template.render(context)\n\n",
        "idx": "771"
    },
    {
        "instruction": "\ndef converter_dolar_para_reais(valor_dolar):\n",
        "input": "",
        "output": "    taxa_conversao = 5.09\n    valor_reais = valor_dolar * taxa_conversao\n    return valor_reais\n\n",
        "idx": "779"
    },
    {
        "instruction": "\ndef calcular_frete(peso_em_gramas):\n",
        "input": "",
        "output": "    taxa_frete_por_100g = 1.99\n    peso_em_kg = peso_em_gramas / 1000\n    valor_frete = peso_em_kg * taxa_frete_por_100g\n    return valor_frete\n\n",
        "idx": "780"
    },
    {
        "instruction": "\ndef build_response(status, content_type, content, connection='keep-alive'):\n",
        "input": "",
        "output": "    response_header = f\"HTTP/1.1 {status}\\r\\n\"\n    response_header += f\"Content-Type: {content_type}\\r\\n\"\n    response_header += f\"Content-Length: {len(content)}\\r\\n\"\n    response_header += f\"Connection: {connection}\\r\\n\\r\\n\"\n    return response_header.encode() + content\n\n",
        "idx": "794"
    },
    {
        "instruction": "\ndef receive_client_id(client_socket, client_address):\n",
        "input": "",
        "output": "    client_id = client_socket.recv(1024).decode(\"utf-8\").strip()\n    print(f\"[{client_address}] Client '{client_id}' connected.\")\n    return client_id\n\n",
        "idx": "795"
    },
    {
        "instruction": "\ndef receive_file_data(client_socket, file_size):\n",
        "input": "",
        "output": "    received_data = b\"\"\n    remaining_size = file_size\n    while remaining_size > 0:\n        chunk = client_socket.recv(min(4096, remaining_size))\n        received_data += chunk\n        remaining_size -= len(chunk)\n    return received_data\n\n",
        "idx": "799"
    },
    {
        "instruction": "# Here are some relevant code fragments from other files of the repo:\n# --------------------------------------------------\n# the below code fragment can be found in:\n# llm.py\n# --------------------------------------------------\n# from langchain_groq import ChatGroq\n# \n# import os\n# \n# llm = ChatGroq(groq_api_key=os.getenv(\"GROQ_API_KEY\"), model_name=\"llama-3.2-90b-text-preview\")\n# \n# --------------------------------------------------\n# the below code fragment can be found in:\n# fewshot.py\n# --------------------------------------------------\n# import pandas as pd\n# \n# import json\n# \n# class FewShot:\n#     def __init__(self, file_paths=None):\n#         self.df = pd.DataFrame()\n#         self.unique_tags = set()\n#         \n#         if file_paths is None:\n#             file_paths = [\"Data/hisham_sarwar_processed.json\",\n#                           \"Data/irfan_malik_processed.json\",\n#                           \"Data/usman_asif_processed.json\"]\n#         \n#         self.load_posts(file_paths)\n# \n#     def load_posts(self, file_paths):\n#         for file_path in file_paths:\n#             with open(file_path, encoding=\"utf-8\") as f:\n#                 posts = json.load(f)\n#                 temp_df = pd.json_normalize(posts)\n#                 temp_df['length'] = temp_df['line_count'].apply(self.categorize_length)\n#                 \n#                 all_tags = temp_df['tags'].apply(lambda x: x).sum()\n#                 self.unique_tags.update(all_tags)\n#                 \n# \n#                 self.df = pd.concat([self.df, temp_df], ignore_index=True)\n# \n#     def get_filtered_posts(self, length, tag):\n#         df_filtered = self.df[\n#             (self.df['tags'].apply(lambda tags: tag in tags)) &  \n#             (self.df['length'] == length)  \n#         ]\n#         return df_filtered.to_dict(orient='records')\n# \n#     def categorize_length(self, line_count):\n#         if line_count < 5:\n#             return \"Short\"\n#         elif 5 <= line_count <= 10:\n#             return \"Medium\"\n#         else:\n#             return \"Long\"\n# \n#     def get_tags(self):\n#         return list(self.unique_tags)\n# \n# --------------------------------------------------\n\n\n## postgenerate.py\nfrom llm import llm\n\nfrom fewshot import FewShot\n\nfew_shot = FewShot()\n\ndef get_length_str(length):\n    if length == \"Short\":\n        return \"1 to 5 lines\"\n    if length == \"Medium\":\n        return \"6 to 10 lines\"\n    if length == \"Long\":\n        return \"11 to 15 lines\"\n\ndef get_prompt(length, tag):\n    length_str = get_length_str(length)\n\n    prompt = f'''\n    Generate a LinkedIn post using the below information. No preamble.\n\n    1) Topic: {tag}\n    2) Length: {length_str}\n    The script for the generated post should always be English.\n    '''\n\n    examples = few_shot.get_filtered_posts(length,tag)\n\n    if len(examples) > 0:\n        prompt += \"4) Use the writing style as per the following examples.\"\n\n    for i, post in enumerate(examples):\n        post_text = post['text']\n        prompt += f'\\n\\n Example {i+1}: \\n\\n {post_text}'\n\n        if i == 1: \n            break\n\n    return prompt\n\ndef generate_post(length, tag):\n",
        "input": "",
        "output": "    prompt = get_prompt(length, tag)\n    response = llm.invoke(prompt)\n    return response.content\n\n",
        "idx": "805"
    },
    {
        "instruction": "## autosubtitles/window/utils_extern.py\nimport tkinter as tk\n\ndef normalize_window_size(root: tk.Misc, geometry: tuple[int, int, int | None, int | None], from_size: tuple[int, int]=(1920, 1080)) -> str:\n",
        "input": "",
        "output": "    x_relation = root.winfo_screenwidth() / from_size[0]\n    y_relation = root.winfo_screenheight() / from_size[1]\n\n    width = round(geometry[0] * x_relation)\n    height = round(geometry[1] * y_relation)\n    x = round(geometry[2] * x_relation) if geometry[2] != None else None\n    y = round(geometry[3] * y_relation) if geometry[3] != None else None\n\n    return f\"{width}x{height}{f'+{x}' if x else ''}{f'+{y}' if y else ''}\"\n\n",
        "idx": "808"
    },
    {
        "instruction": "## client.py\nfrom cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes\n\nfrom cryptography.hazmat.backends import default_backend\n\ndef aes_decrypt(key, ciphertext):\n",
        "input": "",
        "output": "    iv = ciphertext[:16]\n    actual_ciphertext = ciphertext[16:]\n    cipher = Cipher(algorithms.AES(key), modes.CFB(iv), backend=default_backend())\n    decryptor = cipher.decryptor()\n    plaintext = decryptor.update(actual_ciphertext) + decryptor.finalize()\n    return plaintext\n\n",
        "idx": "818"
    },
    {
        "instruction": "## app.py\nfrom cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes\n\nfrom cryptography.hazmat.backends import default_backend\n\ndef aes_decrypt(key, ciphertext):\n",
        "input": "",
        "output": "    iv = ciphertext[:16]\n    actual_ciphertext = ciphertext[16:]\n    cipher = Cipher(algorithms.AES(key), modes.CFB(iv), backend=default_backend())\n    decryptor = cipher.decryptor()\n    plaintext = decryptor.update(actual_ciphertext) + decryptor.finalize()\n    return plaintext\n\n",
        "idx": "821"
    },
    {
        "instruction": "\ndef calcularModa(intervalos, frequencias):\n",
        "input": "",
        "output": "    maiorFrequencia  = 0\n    moda = None\n\n    for i in range(len(frequencias)):\n        if (frequencias[i] > maiorFrequencia):\n            maiorFrequencia = frequencias[i]\n            moda = (intervalos[i][0]+intervalos[i][1])/2\n    return moda\n\n",
        "idx": "823"
    },
    {
        "instruction": "\ndef calcularMediana(intervalos, frequencias):\n",
        "input": "",
        "output": "    totalFreq = 0\n    for f in frequencias:\n        totalFreq += f\n    \n    freqAcumulada = 0\n    mediana = 0\n    for i in range(len(frequencias)):\n        freqAcumulada += frequencias[i]\n        if freqAcumulada >= totalFreq/2:\n            a, b = intervalos[i]\n            mediana = (a+b) / 2\n            break\n\n    return mediana\n\n",
        "idx": "824"
    },
    {
        "instruction": "\ndef calcularMedia(intervalos, frequencias):\n",
        "input": "",
        "output": "    soma = 0 #somatorio dos pontomedios vezes suas frequencias\n    somaFreq = 0 #somatorio das frequencias\n\n    for i in range(len(frequencias)):\n        a, b = intervalos[i]\n        pontoMedio = (a+b)/2\n        freq = frequencias[i]\n        soma += pontoMedio * freq\n        somaFreq += freq\n    \n    if(somaFreq != 0):\n        media = soma/somaFreq\n    else: media = 0\n\n    return media\n\n",
        "idx": "825"
    },
    {
        "instruction": "\ndef separaClasses(intervalos):\n",
        "input": "",
        "output": "    classesSeparadas = []\n    for intervalo in intervalos:\n        classesSeparadas.append(str(intervalo[0]) + \" a \" + str(intervalo[1]))\n    return classesSeparadas\n\n",
        "idx": "828"
    },
    {
        "instruction": "\ndef converterDicionarios(intervalos, frequencias):\n",
        "input": "",
        "output": "    dados = []\n    for i in range(len(intervalos)):\n        classe = f\"{intervalos[i][0]}|-{intervalos[i][1]}\"\n        frequencia = str(frequencias[i])\n        dados.append({\"Classes\": classe, \"Frequencia\": frequencia})\n    return dados\n\n",
        "idx": "829"
    },
    {
        "instruction": "# Here are some relevant code fragments from other files of the repo:\n# --------------------------------------------------\n# the below code fragment can be found in:\n# model_load.py\n# --------------------------------------------------\n# from transformers import GPT2Tokenizer\n# \n# tokenizer = GPT2Tokenizer.from_pretrained('gpt2')\n# \n# --------------------------------------------------\n\n\n## data_load.py\nimport torch\n\nfrom model_load import tokenizer\n\ndef collate_fn(data):\n",
        "input": "",
        "output": "    images, captions = zip(*data)\n    images = torch.stack(images, 0)\n\n    captions = [[tokenizer.bos_token_id] + cap + [tokenizer.eos_token_id] for cap in captions]\n\n    lengths = [len(cap) for cap in captions]\n    targets = torch.zeros(len(captions), max(lengths), dtype=torch.long)\n    # Create attention masks\n    masks = torch.zeros(len(captions), max(lengths), dtype=torch.long)\n\n    for i, cap in enumerate(captions):\n        end = lengths[i]\n        targets[i, :end] = torch.LongTensor(cap)\n        masks[i, :end] = 1\n\n    return images, targets, masks\n\n",
        "idx": "831"
    },
    {
        "instruction": "\ndef parse_nmap_output(nmap_output):\n",
        "input": "",
        "output": "    devices = []\n    lines = nmap_output.split('\\n')\n    current_device = {}\n    for line in lines:\n        if 'Nmap scan report for' in line:\n            if current_device:\n                devices.append(current_device)\n                current_device = {}\n            current_device['ip'] = line.split(' ')[-1]\n        elif 'OS details:' in line:\n            current_device['os'] = line.replace('OS details: ', '').strip()\n        elif 'Device type:' in line:\n            current_device['device_type'] = line.replace('Device type: ', '').strip()\n    if current_device:\n        devices.append(current_device)\n    return devices\n\n",
        "idx": "834"
    },
    {
        "instruction": "\ndef filter_data(df, search_input):\n",
        "input": "",
        "output": "    search_input_parts = search_input.split(\":\")\n    if len(search_input_parts) == 2:\n        start_date, end_date = search_input_parts\n        return df[(df[\"dateAdded\"] >= start_date) & (df[\"dateAdded\"] <= end_date)]\n    return df[(df[\"cveID\"] == search_input) | (df[\"vendorProject\"] == search_input) | (df[\"product\"].str.contains(search_input))]\n\n",
        "idx": "836"
    },
    {
        "instruction": "## kev_scanner.py\nimport subprocess\n\ndef scan_network(network_range):\n    result = subprocess.run(['nmap', '-O', network_range], capture_output=True, text=True)\n    return result.stdout\n\ndef parse_nmap_output(nmap_output):\n    devices = []\n    lines = nmap_output.split('\\n')\n    current_device = {}\n    for line in lines:\n        if 'Nmap scan report for' in line:\n            if current_device:\n                devices.append(current_device)\n                current_device = {}\n            current_device['ip'] = line.split(' ')[-1]\n        elif 'OS details:' in line:\n            current_device['os'] = line.replace('OS details: ', '').strip()\n        elif 'Device type:' in line:\n            current_device['device_type'] = line.replace('Device type: ', '').strip()\n    if current_device:\n        devices.append(current_device)\n    return devices\n\ndef analyze_network(df, network):\n",
        "input": "",
        "output": "    nmap_output = scan_network(network)\n    devices = parse_nmap_output(nmap_output)\n    vulnerable_devices = []\n    for device in devices:\n        vendor = device.get('os', '').split(' ')[0].lower()\n        if vendor:\n            matching_vulns = df[df['vendorProject'] == vendor]\n            if not matching_vulns.empty:\n                vulnerable_devices.append({'ip': device['ip'], 'vendor': vendor, 'vulnerabilities': matching_vulns['cveID'].tolist()})\n    return vulnerable_devices\n\n",
        "idx": "837"
    },
    {
        "instruction": "\ndef selection_sort(arr):\n",
        "input": "",
        "output": "    n=len(arr)\n    \n    for i in range(n):\n        min_idx=i\n        \n        for j in range(i+1,n):\n            if arr[j]<arr[min_idx]:\n                min_idx=j\n        arr[i],arr[min_idx]=arr[min_idx],arr[i]\n        \n    return arr\n\n",
        "idx": "840"
    },
    {
        "instruction": "\ndef insertion_sort(arr):\n",
        "input": "",
        "output": "    n=len(arr)\n    \n    for i in range(1,n):\n        key=arr[i]\n        j=i-1\n        \n        while j>=0 and arr[j]>key:\n            #4 5 3 7 6 1\n            #4 3 5\n            #4 4 5\n            #3 4 5 7 6 1\n            arr[j+1]=arr[j]\n            j-=1\n        arr[j+1]=key\n    return arr\n\n",
        "idx": "841"
    },
    {
        "instruction": "## main.py\nimport requests\n\nimport sys\n\nimport time\n\nfrom io import BytesIO\n\nfrom concurrent.futures import ThreadPoolExecutor\n\nclass ProgressBar:\n    def __init__(self, total: int):\n        self.__total = total\n        self.__current = 0\n        self.__start_time = time.time()\n\n    def increment(self):\n        self.__current += 1\n        self.display()\n\n    def display(self):\n        progress = int((self.__current / self.__total) * 100)\n        sys.stdout.write(f\"\\r\\033[K[{('=' * progress).ljust(100)}] {self.__current}/{self.__total} ({time.time() - self.__start_time:.2f}s)\")\n        sys.stdout.flush()\n\ndef download_url(url: str, progress_bar: ProgressBar) -> BytesIO:\n    response = requests.get(url)\n    progress_bar.increment()\n    return BytesIO(response.content)\n\ndef download_urls(urls) -> list[BytesIO]:\n",
        "input": "",
        "output": "    total = len(urls)\n    progress_bar = ProgressBar(total)\n    data = []\n\n    with ThreadPoolExecutor() as executor:\n        futures = [executor.submit(download_url, url, progress_bar) for url in urls]\n        for future in futures:\n            data.append(future.result())\n    print()\n\n    return data\n\n",
        "idx": "844"
    },
    {
        "instruction": "## gps_simulation/routes/utils.py\nclass NodoArbol: \n    def __init__(self,clave,valor,izquierdo=None,derecho=None,padre=None): #se define el constructor de la clase para inicializar un \u00e1rbol con sus respectivos atributos.\n        self.clave = clave #atributo que va a almacenar la clave del nodo\n        self.cargaUtil = valor #atributo que va a almacenar el valor del nodo\n        self.hijoIzquierdo = izquierdo #hijo izquierdo del nodo\n        self.hijoDerecho = derecho #hijo derecho del nodo\n        self.padre = padre #nodo padre\n        self.factorEquilibrio = 0\n\n    def tieneHijoIzquierdo(self): #m\u00e9todo que verifica si el nodo tiene un hijo izquierdo, devolviendo True o False.\n        return self.hijoIzquierdo \n\n    def tieneHijoDerecho(self): #m\u00e9todo que verifica si el nodo tiene un hijo derecho, devolviendo True o False.\n        return self.hijoDerecho\n\n    def esHijoIzquierdo(self): #m\u00e9todo que verifica si el nodo es hijo izquierdo de su padre.\n        return self.padre and self.padre.hijoIzquierdo == self\n\n    def esHijoDerecho(self): #m\u00e9todo que verifica si el nodo es hijo derecho de su padre.\n        return self.padre and self.padre.hijoDerecho == self\n\n    def esRaiz(self): #m\u00e9todo que verifica si el nodo es la ra\u00edz del \u00e1rbol (no tiene padre)\n        return not self.padre\n\n    def esHoja(self): #m\u00e9todo que verifica si el nodo es una hoja (si no tiene hijos ni izquierdo ni derecho)\n        return not (self.hijoDerecho or self.hijoIzquierdo)\n\n    def tieneAlgunHijo(self): #m\u00e9todo que verifica si el nodo tiene un hijo izquierdo o un hijo derecho\n        return self.hijoDerecho or self.hijoIzquierdo\n\n    def tieneAmbosHijos(self): #m\u00e9todo que verifica si el nodo tiene ambos hijos izquierdo y derecho\n        return self.hijoDerecho and self.hijoIzquierdo\n\n    def reemplazarDatoDeNodo(self, clave, valor, hizq, hder):\n",
        "input": "",
        "output": "        self.clave = clave # Reemplaza la clave del nodo.\n        self.cargaUtil = valor # Reemplaza el valor asociado a la clave.\n        self.hijoIzquierdo = hizq # Reemplaza el hijo izquierdo del nodo.\n        self.hijoDerecho = hder # Reemplaza el hijo derecho del nodo.\n        if self.tieneHijoIzquierdo(): #si el nodo tiene hijo izquierdo, actualiza el padre de ese hijo.\n            self.hijoIzquierdo.padre = self\n        if self.tieneHijoDerecho(): #si el nodo tiene hijo derecho, actualiza el padre de ese hijo.\n            self.hijoDerecho.padre = self\n    \n",
        "idx": "851"
    },
    {
        "instruction": "## gps_simulation/routes/utils.py\nclass NodoArbol: \n    def __init__(self,clave,valor,izquierdo=None,derecho=None,padre=None): #se define el constructor de la clase para inicializar un \u00e1rbol con sus respectivos atributos.\n        self.clave = clave #atributo que va a almacenar la clave del nodo\n        self.cargaUtil = valor #atributo que va a almacenar el valor del nodo\n        self.hijoIzquierdo = izquierdo #hijo izquierdo del nodo\n        self.hijoDerecho = derecho #hijo derecho del nodo\n        self.padre = padre #nodo padre\n        self.factorEquilibrio = 0\n\n    def tieneHijoIzquierdo(self): #m\u00e9todo que verifica si el nodo tiene un hijo izquierdo, devolviendo True o False.\n        return self.hijoIzquierdo \n\n    def tieneHijoDerecho(self): #m\u00e9todo que verifica si el nodo tiene un hijo derecho, devolviendo True o False.\n        return self.hijoDerecho\n\n    def esHijoIzquierdo(self): #m\u00e9todo que verifica si el nodo es hijo izquierdo de su padre.\n        return self.padre and self.padre.hijoIzquierdo == self\n\n    def esHijoDerecho(self): #m\u00e9todo que verifica si el nodo es hijo derecho de su padre.\n        return self.padre and self.padre.hijoDerecho == self\n\n    def esRaiz(self): #m\u00e9todo que verifica si el nodo es la ra\u00edz del \u00e1rbol (no tiene padre)\n        return not self.padre\n\n    def esHoja(self): #m\u00e9todo que verifica si el nodo es una hoja (si no tiene hijos ni izquierdo ni derecho)\n        return not (self.hijoDerecho or self.hijoIzquierdo)\n\n    def tieneAlgunHijo(self): #m\u00e9todo que verifica si el nodo tiene un hijo izquierdo o un hijo derecho\n        return self.hijoDerecho or self.hijoIzquierdo\n\n    def tieneAmbosHijos(self): #m\u00e9todo que verifica si el nodo tiene ambos hijos izquierdo y derecho\n        return self.hijoDerecho and self.hijoIzquierdo\n\n    def reemplazarDatoDeNodo(self,clave,valor,hizq,hder): #m\u00e9todo que reemplaza los datos del nodo (clave, valor) y sus hijos izquierdo y derecho.\n        self.clave = clave # Reemplaza la clave del nodo.\n        self.cargaUtil = valor # Reemplaza el valor asociado a la clave.\n        self.hijoIzquierdo = hizq # Reemplaza el hijo izquierdo del nodo.\n        self.hijoDerecho = hder # Reemplaza el hijo derecho del nodo.\n        if self.tieneHijoIzquierdo(): #si el nodo tiene hijo izquierdo, actualiza el padre de ese hijo.\n            self.hijoIzquierdo.padre = self\n        if self.tieneHijoDerecho(): #si el nodo tiene hijo derecho, actualiza el padre de ese hijo.\n            self.hijoDerecho.padre = self\n\n    def encontrarSucesor(self): #m\u00e9todo que busca el sucesor inorden del nodo (es decir, el nodo con la siguiente clave mayor).\n        suc = None\n        if self.tieneHijoDerecho(): # Si el nodo tiene hijo derecho, el sucesor es el nodo con el valor m\u00ednimo en el sub\u00e1rbol derecho.\n            suc = self.hijoDerecho.encontrarMin()\n        else: # Si no tiene hijo derecho, sube por el \u00e1rbol buscando el primer ancestro que sea hijo izquierdo de su padre.\n            if self.padre:\n                if self.esHijoIzquierdo():\n                    suc = self.padre.encontrarSucesor() # El sucesor es el padre si este nodo es hijo izquierdo.\n                else: # Si el nodo es hijo derecho, sube al padre y busca su sucesor.\n                    self.padre.hijoDerecho = None\n                    suc = self.padre.encontrarSucesor()\n                    self.padre.hijoDerecho = self\n        return suc\n\n    def empalmar(self):\n        # Elimina el nodo del \u00e1rbol, \"empalmando\" sus hijos con su padre.\n        if self.esHoja(): # Si el nodo es una hoja, simplemente elimina la referencia de su padre a \u00e9l.\n            if self.esHijoIzquierdo():\n                self.padre.hijoIzquierdo = None\n            else:\n                self.padre.hijoDerecho = None\n        elif self.tieneAlgunHijo(): # Si el nodo tiene un hijo (izquierdo o derecho), reemplaza el nodo con su \u00fanico hijo.\n            if self.tieneHijoIzquierdo():\n                if self.esHijoIzquierdo():\n                    self.padre.hijoIzquierdo = self.hijoIzquierdo # Si es hijo izquierdo, el padre apunta al hijo izquierdo.\n                else:\n                    self.padre.hijoDerecho = self.hijoIzquierdo # Si es hijo derecho, el padre apunta al hijo izquierdo.\n                self.hijoIzquierdo.padre = self.padre # Actualiza el padre del hijo izquierdo.\n            else:\n                if self.esHijoIzquierdo(): \n                    self.padre.hijoIzquierdo = self.hijoDerecho # Si es hijo izquierdo, el padre apunta al hijo derecho.\n                else:\n                    self.padre.hijoDerecho = self.hijoDerecho # Si es hijo derecho, el padre apunta al hijo derecho.\n                self.hijoDerecho.padre = self.padre # Actualiza el padre del hijo derecho.\n\n    def encontrarMin(self):\n",
        "input": "",
        "output": "        actual = self\n        while actual.tieneHijoIzquierdo():\n            actual = actual.hijoIzquierdo # Baja al hijo izquierdo hasta llegar al nodo m\u00e1s a la izquierda.\n        return actual\n    \n",
        "idx": "852"
    },
    {
        "instruction": "\ndef generate_recommendation(clause, analysis):\n",
        "input": "",
        "output": "    recommendations = []\n    if \"payment\" in analysis:\n        recommendations.append(\n            \"Ensure payment terms are clearly defined and favorable.\"\n        )\n    if \"deadline\" in analysis:\n        recommendations.append(\n            \"Review deadlines to ensure they are realistic and include buffer time.\"\n        )\n    if \"confidentiality\" in analysis:\n        recommendations.append(\n            \"Verify that confidentiality clauses protect your interests adequately.\"\n        )\n    if \"termination\" in analysis:\n        recommendations.append(\n            \"Check termination conditions and ensure they are fair to both parties.\"\n        )\n\n    return (\n        recommendations\n        if recommendations\n        else [\"No specific recommendations. The clause appears standard.\"]\n    )\n\n",
        "idx": "856"
    },
    {
        "instruction": "# Here are some relevant code fragments from other files of the repo:\n# --------------------------------------------------\n# the below code fragment can be found in:\n# src/components/models.py\n# --------------------------------------------------\n# from pydantic import BaseModel, Field\n# \n# class AgentOutput(BaseModel):\n#     \"\"\"Output of each clause agent\"\"\"\n# \n#     analysis: str = Field(\n#         description=\"An analysis of the section in laymen terms\", max_length=256\n#     )\n#     recommendation: str = Field(\n#         description=\"How the current clause deviates from the benchmark documents\",\n#         max_length=256,\n#     )\n# \n# --------------------------------------------------\n# the below code fragment can be found in:\n# src/components/tools.py\n# --------------------------------------------------\n# import os\n# \n# from composio_crewai import Action, App, ComposioToolSet\n# \n# composio_toolset = ComposioToolSet(api_key=os.environ.get(\"COMPOSIO_API_KEY\"))\n# \n# rag_tools = composio_toolset.get_tools(\n#     apps=[App.RAGTOOL],\n#     actions=[\n#         Action.FILETOOL_LIST_FILES,\n#         Action.FILETOOL_CHANGE_WORKING_DIRECTORY,\n#         Action.FILETOOL_FIND_FILE,\n#     ],\n# )\n# \n# rag_query_tools = composio_toolset.get_tools(\n#     apps=[App.RAGTOOL],\n# )\n# \n# --------------------------------------------------\n# the below code fragment can be found in:\n# src/components/clause_agents.py\n# --------------------------------------------------\n# import os\n# \n# from crewai import Agent\n# \n# from langchain_openai import ChatOpenAI\n# \n# from components.tools import rag_query_tools, rag_tools\n# \n# AI_API_KEY_LITELLM = os.environ.get(\"AI_API_KEY_LITELLM\")\n# \n# AI_API_BASE_LITELLM = os.environ.get(\"AI_API_BASE_LITELLM\")\n# \n# AI_MODEL_NAME_LITELLM = os.environ.get(\"AI_MODEL_NAME_LITELLM\")\n# \n# llm = ChatOpenAI(\n#     openai_api_key=AI_API_KEY_LITELLM,\n#     openai_api_base=AI_API_BASE_LITELLM,\n#     model_name=AI_MODEL_NAME_LITELLM,\n#     temperature=0.1,\n# )\n# \n# corporate_lawyer_agent = Agent(\n#     role=\"Corporate Lawyer\",\n#     goal=\"Use the documents you're given and the tools you have to build a knowledge base of NDAs that you can refer later. First, check if the documents have already been added.\",\n#     backstory=\"\"\"You are a corporate lawyer who has vast knowledge of NDAs, different sections within them, and how they are supposed to work.\n#     You also have the ability to call the RAG tool to ingest new documents that using the paths of files given to you and building a knowledge base of NDAs.\"\"\",\n#     # tools=rag_tools,\n#     verbose=True,\n#     llm=llm,\n# )\n# \n# corporate_lawyer_agent.tools = rag_tools\n# \n# parties_corporate_lawyer = Agent(\n#     role=\"Parties Corporate Lawyer\",\n#     goal=\"To compare the current NDA parties clause to the ones in our RAG database and identify how good it is.\",\n#     backstory=\"\"\"You are a corporate lawyer who specialises in identifying who the parties in a certain NDA are.\n#     There's no one who does it as well as you do. Things that others miss, you don't.\"\"\",\n#     # tools=rag_query_tools,\n#     verbose=True,\n#     llm=llm,\n# )\n# \n# parties_corporate_lawyer.tools = rag_query_tools\n# \n# obligation_information_lawyer = Agent(\n#     role=\"Obligations of Receiving Party Lawyer\",\n#     goal=\"To compare the current NDA obligations of receiving party clause to the ones in our RAG database and identify how good it is.\",\n#     backstory=\"\"\"You are an obligations of receiving party lawyer who is an expert in identifying what the obligations of receiving party is in a certain NDA.\n#     You have never failed to identify obligations of receiving party in an NDA. You are a lawyer with many years of experience and know how to identify obligations of receiving party.\n#     \"\"\",\n#     # tools=rag_query_tools,\n#     verbose=True,\n#     llm=llm,\n# )\n# \n# obligation_information_lawyer.tools = rag_query_tools\n# \n# terms_and_termination_lawyer = Agent(\n#     role=\"Terms and Termination Lawyer\",\n#     goal=\"To compare the current NDA terms and termination clause to the ones in our RAG database and identify how good it is.\",\n#     backstory=\"\"\"You are a terms and termination lawyer who is an expert in identifying what the terms and termination is in a certain NDA.\n#     Terms and terminatioin are in your DNA. When given an NDA, you're eyes first go to terms and termination clause and you can identify fallacies well.\n#     \"\"\",\n#     # tools=rag_query_tools,\n#     verbose=True,\n#     llm=llm,\n# )\n# \n# terms_and_termination_lawyer.tools = rag_query_tools\n# \n# remedies_lawyer = Agent(\n#     role=\"Remedies Lawyer\",\n#     goal=\"To compare the current NDA remedies clause to the ones in our RAG database and identify how good it is.\",\n#     backstory=\"\"\"You are a remedies lawyer who is an expert in identifying what the remedies is in a certain NDA.\n#     You craft perfect remedies in an NDA in the case of breach or conflict. You are the go to person for remedies in an NDA.\n#     \"\"\",\n#     # tools=rag_query_tools,\n#     verbose=True,\n#     llm=llm,\n# )\n# \n# remedies_lawyer.tools = rag_query_tools\n# \n# additional_information_lawyer = Agent(\n#     role=\"Additional Important Information Lawyer\",\n#     goal=\"To compare the current NDA additional important information clause to the ones in our RAG database and identify how good it is.\",\n#     backstory=\"\"\"You are an additional important information lawyer who is an expert in identifying what the additional important information is in a certain NDA.\n#     You identify up all the missing information in an NDA. You carefully craft perfect additional important information in an NDA.\n#     \"\"\",\n#     # tools=rag_query_tools,\n#     verbose=True,\n#     llm=llm,\n# )\n# \n# additional_information_lawyer.tools = rag_query_tools\n# \n# --------------------------------------------------\n\n\n## src/components/clause_tasks.py\nfrom crewai import Task\n\nfrom components.clause_agents import (\n    additional_information_lawyer,\n    corporate_lawyer_agent,\n    obligation_information_lawyer,\n    parties_corporate_lawyer,\n    remedies_lawyer,\n    terms_and_termination_lawyer,\n)\n\nfrom components.models import AgentOutput\n\nEXPECTED_TASK_OUTPUT = \"\"\"\nA JSON that has two keys: an `analysis` of the current clause in laymen terms as a paragraph as well as a `recommendation` of how the current clause deviates from the benchmark clauses (in short, numbered points).\"\"\"\n\ndef create_accumulating_task(original_task, key):\n    def accumulating_task(agent, context):\n        result = original_task.function(agent, context)\n        if \"accumulated_results\" not in context:\n            context[\"accumulated_results\"] = {}\n        context[\"accumulated_results\"][key] = result\n        return context[\"accumulated_results\"]\n\n    return Task(\n        description=original_task.description,\n        agent=original_task.agent,\n        function=accumulating_task,\n        expected_output=original_task.expected_output,\n        output_pydantic=original_task.output_pydantic,\n        context=original_task.context,\n    )\n\ndef get_tasks(input_document):\n",
        "input": "",
        "output": "    tasks = []\n    ingest_documents_task = Task(\n        description=\"\"\"Ingest benchmark NDAs that will be used as a yardstick to compare NDAs we will judge later.\n        Check all the files with NDA in their title in the ndas folder inside the current directory and ingest all the documents using the RAG tool.\n        Don't bother with the files inside the uploads folder.\n        Only ingest files with docx, doc, and pdf extensions. You don't need to analyze these documents.\n        If you pass the path of the documents to the RAG tool, it should be able to parse the documents.\"\"\",\n        expected_output=EXPECTED_TASK_OUTPUT,\n        agent=corporate_lawyer_agent,\n    )\n    tasks.append(create_accumulating_task(ingest_documents_task, \"ingest_documents\"))\n\n    identify_parties = Task(\n        description=f\"\"\"Take the current parties clause, which is inside this: `{input_document}`, and compare it with similar clauses in our RAG database to check how good it is.\n    Your task is to identify the parties in our NDA, and see if the current NDA clause abides by all the best practices of similar clauses.\n    There is a party that offers services, and there's a party that consumes services. This should be well defined within the clauses.\"\"\",\n        expected_output=EXPECTED_TASK_OUTPUT,\n        agent=parties_corporate_lawyer,\n        output_pydantic=AgentOutput,\n    )\n    tasks.append(create_accumulating_task(identify_parties, \"identify_parties\"))\n\n    identify_obligations_of_receiving_party = Task(\n        description=f\"\"\"Take the current obligations of receiving party clause, which is inside this: `{input_document}`, and compare it with similar clauses in our RAG database to check how good it is.\n        Your task is to identify the obligations of receiving party in our NDA, and see if the current NDA clause abides by all the best practices of similar clauses.\"\"\",\n        expected_output=EXPECTED_TASK_OUTPUT,\n        agent=obligation_information_lawyer,\n        output_pydantic=AgentOutput,\n    )\n    tasks.append(\n        create_accumulating_task(identify_obligations_of_receiving_party, \"obligations\")\n    )\n\n    identify_terms_and_termination = Task(\n        description=f\"\"\"Take the current terms and termination clause, which is inside this: `{input_document}`, and compare it with similar clauses in our RAG database to check how good it is.\n        Your task is to identify the terms and termination in our NDA, and see if the current NDA clause abides by all the best practices of similar clauses.\"\"\",\n        expected_output=EXPECTED_TASK_OUTPUT,\n        agent=terms_and_termination_lawyer,\n        output_pydantic=AgentOutput,\n    )\n    tasks.append(\n        create_accumulating_task(\n            identify_terms_and_termination, \"terms_and_termination\"\n        )\n    )\n\n    identify_remedies = Task(\n        description=f\"\"\"Take the current remedies clause, which is inside this: `{input_document}`, and compare it with similar clauses in our RAG database to check how good it is.\n        Your task is to identify the remedies in our NDA, and see if the current NDA clause abides by all the best practices of similar clauses.\"\"\",\n        expected_output=EXPECTED_TASK_OUTPUT,\n        agent=remedies_lawyer,\n        output_pydantic=AgentOutput,\n    )\n    tasks.append(create_accumulating_task(identify_remedies, \"remedies\"))\n\n    identify_additional_information = Task(\n        description=f\"\"\"Take the current additional important information clause, which is inside this: `{input_document}`, and compare it with similar clauses in our RAG database to check how good it is.\n        Your task is to identify the additional important information in our NDA, and see if the current NDA clause abides by all the best practices of similar clauses.\"\"\",\n        expected_output=EXPECTED_TASK_OUTPUT,\n        agent=additional_information_lawyer,\n        output_pydantic=AgentOutput,\n    )\n    tasks.append(\n        create_accumulating_task(identify_additional_information, \"additional_info\")\n    )\n\n    return tasks\n\n",
        "idx": "857"
    },
    {
        "instruction": "## lab3.py\nimport numpy as np\n\ndef make_hist_simple(img):\n",
        "input": "",
        "output": "    c_full = np.zeros(256)\n    u, c = np.unique(img, return_counts=True)\n    c_full[u] = c\n\n    c_prob = c_full / np.sum(c_full)\n    return np.linspace(0, 255, 256), c_prob\n\n",
        "idx": "858"
    },
    {
        "instruction": "## lab3.py\nimport numpy as np\n\ndef make_hist(img):\n",
        "input": "",
        "output": "    ur, cr = np.unique(img[:, :, 0], return_counts=True)\n    cr_prob = cr / np.sum(cr)\n\n    ug, cg = np.unique(img[:, :, 1], return_counts=True)\n    cg_prob = cg / np.sum(cg)\n\n    ub, cb = np.unique(img[:, :, 2], return_counts=True)\n    cb_prob = cb / np.sum(cb)\n\n    return ur, cr_prob, ug, cg_prob, ub, cb_prob\n\n",
        "idx": "859"
    },
    {
        "instruction": "## lab1.py\nimport numpy as np\n\ndef task_3(fun, targets: []):\n",
        "input": "",
        "output": "    noise = np.random.normal(size=(fun.shape))\n    fun_noisy = fun + noise\n\n    results = []\n    for number in targets:\n        noisy_signals = []\n        for i in range(number):\n            noise = np.random.normal(size=(fun.shape))\n            noisy_signals.append(noise + fun)\n\n        noisy_signals = np.array(noisy_signals)\n        avg_signal = np.mean(noisy_signals, axis=0)\n        results.append((avg_signal, number))\n\n    return fun_noisy, results\n\n",
        "idx": "861"
    },
    {
        "instruction": "## lab10.py\nimport numpy as np\n\ndef normalize(img):\n",
        "input": "",
        "output": "    img -= np.min(img)\n    img /= np.max(img)\n    return img\n\n",
        "idx": "862"
    },
    {
        "instruction": "## lab10.py\nimport numpy as np\n\ndef make_hist_simple(img):\n",
        "input": "",
        "output": "    c_full = np.zeros(256)\n    u, c = np.unique(img, return_counts=True)\n    c_full[u] = c\n\n    return np.linspace(0, 255, 256), c_full\n\n",
        "idx": "863"
    },
    {
        "instruction": "## lab4.py\nimport numpy as np\n\ndef correlate_kerneln(img, kernel):\n",
        "input": "",
        "output": "    img_x, img_y = img.shape\n    kernel_x, kernel_y = kernel.shape\n\n    pad = int((kernel_x - 1) / 2)\n    img_pad = np.pad(img, pad, 'edge')\n    new_img = np.zeros(img.shape)\n    for x in range(pad, img_x + pad):\n        for y in range(pad, img_y + pad):\n            part = img_pad[x-pad:x + pad + 1, y - pad: y + pad + 1]\n            new_img[x-pad][y-pad] = np.sum(part * kernel)\n    return new_img\n\n",
        "idx": "866"
    },
    {
        "instruction": "## lab6/lab6.py\nimport numpy as np\n\ndef normalize(vector):\n",
        "input": "",
        "output": "    vector -= np.min(vector)\n    vector /= np.max(vector)\n    return vector\n\n",
        "idx": "867"
    },
    {
        "instruction": "## colab.py\nimport pandas as pd\n\ndef convert_time_to_seconds(time_series):\n",
        "input": "",
        "output": "    time_format = '%H:%M:%S.%f'\n    times = pd.to_datetime(time_series, format=time_format)\n    # Get the first (minimum) time to use as the reference point\n    min_time = times.min()\n    # Subtract the minimum time and convert the time differences to seconds\n    time_in_seconds = (times - min_time).dt.total_seconds()\n    return time_in_seconds\n\n",
        "idx": "869"
    },
    {
        "instruction": "\ndef calc_energy(runtime, utilization, P100=61, P0=10, num_cpu=2):\n",
        "input": "",
        "output": "  power = num_cpu*(P0 + (P100-P0)*utilization/100)\n  energy = power*runtime\n  #print('cpu_energy:',cpu_energy, 'Joul')\n  return energy, power\n\n",
        "idx": "870"
    },
    {
        "instruction": "## mainfile.py\nimport unicodedata\n\nimport re\n\ndef unicode_to_ascii(the_file):\n    return ''.join(c for c in unicodedata.normalize('NFD', the_file)\n                   if unicodedata.category(c) != 'MN')\n\ndef preprocess_sentence(w):\n    w = unicode_to_ascii(w.lower().strip())\n    # creating a space between a word and the punctuation following it\n    w = re.sub(r\"([?.!,])\", r\" \\1 \", w)\n\n    # adding a start and an end token to the sentence\n    # so that the model knows when to start and stop predicting\n    w = '<start> ' + w + ' <end>'\n    return w\n\ndef create_dataset(path, num_examples):\n",
        "input": "",
        "output": "    lines = open(path,encoding='UTF-8').read().strip().split('\\n')\n    word_pairs = [[preprocess_sentence(w) for w in l.split('\\t')] for l in lines[:num_examples]]\n    return word_pairs\n\n",
        "idx": "872"
    },
    {
        "instruction": "## mainfile.py\nimport tensorflow as tf\n\nimport numpy as np\n\ndef loss_function(real, pred):\n",
        "input": "",
        "output": "    mask = 1 - np.equal(real, 0)\n    loss_ = tf.nn.sparse_softmax_cross_entropy_with_logits(labels=real, logits=pred) * mask\n    return tf.reduce_mean(loss_)\n\n",
        "idx": "874"
    },
    {
        "instruction": "## app.py\nfrom PIL import Image, ImageDraw, ImageFont, ImageColor\n\nimport io\n\nfrom rembg import remove\n\ndef remove_background(image):\n",
        "input": "",
        "output": "    img_bytes = io.BytesIO()\n    image.save(img_bytes, format=\"PNG\")\n    img_bytes = img_bytes.getvalue()\n    output = remove(img_bytes)\n    return Image.open(io.BytesIO(output))\n\n",
        "idx": "878"
    },
    {
        "instruction": "\ndef superimpose(image_with_text, overlay_image):\n",
        "input": "",
        "output": "    overlay_image = overlay_image.convert(\"RGBA\")\n    image_with_text.paste(overlay_image, (0, 0), overlay_image)\n    return image_with_text\n\n",
        "idx": "879"
    },
    {
        "instruction": "## Netlist2StateSpace.py\nimport sympy as sym\n\ndef createSymbol(symbolList, prefix):\n",
        "input": "",
        "output": "    count = sum(1 for s in symbolList if str(s).startswith(prefix))\n    newSymbol = sym.Symbol(prefix + str(count + 1))\n    symbolList.append(newSymbol)\n    return newSymbol\n\n",
        "idx": "880"
    },
    {
        "instruction": "\ndef parseNetlist(netlist):\n",
        "input": "",
        "output": "    nodes = set()  # Set to store all unique nodes\n    currentSymbols = []  # List to store symbols for currents and inductors\n    currentCount = 0\n    voltageSourceCount = 0\n\n    for line in netlist:\n        parts = line.split()\n        nodes.update(parts[1:3])  # Add nodes from each line\n        element = parts[0]\n        if element in ('L', 'D', 'S', 'E'):  # Elements that require additional equations\n            currentSymbols.append(element)\n            currentCount += 1\n            if element == 'E':  # Count voltage sources separately\n                voltageSourceCount += 1\n\n    if '0' in nodes:  # Remove ground node from node count\n        nodes.remove('0')\n\n    return len(nodes), currentCount, voltageSourceCount, currentSymbols\n\n",
        "idx": "881"
    },
    {
        "instruction": "## aernctrack/period/alg.py\nimport numpy\n\ndef get_period_alg(xs, ys):\n",
        "input": "",
        "output": "    peaks_times = [xs[i] for i in range(1, len(ys) - 1) if ys[i - 1] < ys[i] > ys[i + 1]]\n    if len(peaks_times) > 1:\n        period = numpy.mean([peaks_times[i + 1] - peaks_times[i] for i in range(len(peaks_times) - 1)])\n    else:\n        period = None\n    return period\n\n",
        "idx": "883"
    },
    {
        "instruction": "## aernctrack/period/fft.py\nimport numpy as np\n\ndef get_period_fft(xs, ys):\n",
        "input": "",
        "output": "    if len(xs) != len(ys) or len(xs) < 2:\n        return None\n\n    t = xs[1] - xs[0]  # sample spacing, assumes uniform time spacing\n    fft_values = np.fft.fft(ys)  # fft\n    frequencies = np.fft.fftfreq(len(ys), d=t)  # get the frequencies\n    magnitudes = np.abs(fft_values)\n\n    # exclude the zero frequency and find the dominant frequency\n    magnitudes[0] = 0\n    dominant_frequency = frequencies[np.argmax(magnitudes)]\n\n    # if the dominant frequency is zero, the period is undetermined\n    if dominant_frequency == 0:\n        return None\n\n    # calculate the period as the inverse of the dominant frequency\n    period = 1 / abs(dominant_frequency)\n    return period\n\n",
        "idx": "884"
    },
    {
        "instruction": "## orm_json/utils/checking.py\nfrom typing_extensions import (\n     Any, \n     Sequence, \n     Callable\n)\n\ndef _attrs_data_class(data_class: type | None, name_class: str) -> dict[str, Any]:\n",
        "input": "",
        "output": "     default_values = {\n          'path': 'base.json',\n          'primary': None,\n          'free': False\n     }\n     \n     metadata = {}\n     if not data_class:\n          metadata['tablename'] = name_class\n          metadata['path'] = default_values.get('path')\n          metadata['primary'] = default_values.get('primary')\n          metadata['free'] = default_values.get('free')\n          \n     else:\n          data = data_class.__dict__\n          for keyword in ['path', 'tablename', 'free', 'primary']:\n               if data.get(keyword):\n                    metadata[keyword] = data.get(keyword)\n                    \n               else:\n                    if keyword == 'tablename':\n                         metadata['tablename'] = name_class\n                    \n                    else: metadata[keyword] = default_values.get(keyword)\n     return metadata\n\n",
        "idx": "888"
    },
    {
        "instruction": "# Here are some relevant code fragments from other files of the repo:\n# --------------------------------------------------\n# the below code fragment can be found in:\n# orm_json/utils/exception.py\n# --------------------------------------------------\n# class CallableError(Exception):\n#      def __init__(self, *args: object) -> None:\n#           super().__init__(*args)\n# \n# --------------------------------------------------\n\n\n## orm_json/utils/checking.py\nfrom typing_extensions import (\n     Any, \n     Sequence, \n     Callable\n)\n\nfrom orm_json.utils.exception import (\n     TableNotExists,\n     TableColumnNotExists,\n     RequiredArgument,\n     PrimaryNotExists,\n     JsonFileEmpty,\n     CallableError\n)\n\ndef _custom(data: Sequence, option: Callable) -> tuple[dict[str, dict[str, Any]], list[dict[str, Any]]]:\n",
        "input": "",
        "output": "     if isinstance(data, dict):\n          data = list(data.values())\n          \n     if not callable(option) and not isinstance(option, type):\n          raise CallableError(f\"{option} its not callable object\")\n     return option(), data\n\n",
        "idx": "889"
    },
    {
        "instruction": "## orm_json/utils/checking.py\nfrom typing_extensions import (\n     Any, \n     Sequence, \n     Callable\n)\n\ndef _get_custom_args(data: dict[str, dict[str, Any]], tablename: str) -> tuple:\n",
        "input": "",
        "output": "     arguments = data.get(tablename).get('args')\n     func = data.get(tablename).get('function')\n     return_type = data.get(tablename).get('return_type')\n     \n     return arguments, func, return_type\n\n",
        "idx": "890"
    },
    {
        "instruction": "## project.py\nimport subprocess as sp\n\nclass BtrfsError(Exception):\n    def __init__(self, message):\n        self.message = message\n        super().__init__(self.message)\n\n    def __str__(self):\n        return self.message\n\nclass BtrfsManager:\n    def __init__(self, filesystem_path):\n        self.path = filesystem_path\n\n    # def create_snapshot(self, snapshot_name):\n    #     try:\n    #         command = f\"btrfs subvolume snapshot {self.filesystem_path} {snapshot_name}\"\n    #         sp.run(command, check=True, shell=True)\n    #         return f\"Snapshot '{snapshot_name}' created successfully\"\n    #     except sp.CalledProcessError:\n    #         return f\"Error: Snapshot '{snapshot_name}' creation failed\"\n\n    def list_subvolumes(self):\n",
        "input": "",
        "output": "        command = [\"btrfs\", \"subvolume\", \"list\", self.path]\n\n        result = sp.run(command, capture_output=True)\n        message = result.stdout.decode().strip()\n        if result.returncode != 0:\n            raise BtrfsError(f\"Error: {message}\")\n        return message\n    \n",
        "idx": "898"
    },
    {
        "instruction": "## src/history.py\nfrom datetime import datetime\n\nclass HistoryEntry:\n    def __init__(self, date: int, duration: int, moves: int, win: bool, width: int, height: int, mines: int, remaining_mines: int):\n        self.date = datetime.fromtimestamp(date)\n        self.duration = duration\n        self.moves = moves\n        self.win = win\n        self.width = width\n        self.height = height\n        self.mines = mines\n        self.remaining_mines = remaining_mines\n    \n    def __str__(self):\n        return f\"{int(self.date.timestamp())}, {self.duration}, {self.moves}, {self.win}, {self.width}, {self.height}, {self.mines}, {self.remaining_mines}\"\n    \n    @staticmethod\n    def from_string(s):\n",
        "input": "",
        "output": "        date, duration, moves, win, width, height, mines, remaining_mines = s.split(\", \")\n        return HistoryEntry(int(date), int(duration), int(moves), win == \"True\", int(width), int(height), int(mines), int(remaining_mines))\n    \n",
        "idx": "904"
    },
    {
        "instruction": "## src/l_shape_vis_amcl_test.py\nfrom rclpy.node import Node\n\nfrom geometry_msgs.msg import PoseWithCovarianceStamped\n\nfrom sensor_msgs.msg import LaserScan\n\nimport numpy as np\n\nfrom sklearn.cluster import DBSCAN\n\nimport matplotlib\n\nimport matplotlib.pyplot as plt\n\nimport matplotlib.animation as anim\n\nfrom scipy.spatial.transform import Rotation as R\n\nclass PlotLidar(Node):\n\n    def __init__(self):\n\n        super().__init__('plot_lidar')\n\n        self.declare_parameter(\"lidar_angular_resolution\", 0.00872665)\n        self.lidar_ang_res = self.get_parameter('lidar_angular_resolution').get_parameter_value().double_value\n        self.declare_parameter(\"x_lim\", 5.0)\n        self.declare_parameter(\"y_lim\", 5.0)\n        self.x_lim = self.get_parameter('x_lim').get_parameter_value().double_value\n        self.y_lim = self.get_parameter('y_lim').get_parameter_value().double_value\n\n        self.pose = [0,0,0]\n        self.ranges = []\n        self.create_subscription(PoseWithCovarianceStamped, \"amcl_pose\", self.pose_callback, 10)\n        self.create_subscription(LaserScan, \"scan\", self.scan_callback, 10)\n\n        self.fig, self.ax = plt.subplots()\n\n    def pose_callback(self, pose_msg):\n\n        r = R.from_quat([pose_msg.pose.pose.orientation.x, pose_msg.pose.pose.orientation.y, pose_msg.pose.pose.orientation.z, pose_msg.pose.pose.orientation.w])\n        theta = r.as_rotvec()[-1]\n\n        self.pose = [pose_msg.pose.pose.position.x,\n                    pose_msg.pose.pose.position.y,\n                    theta]\n        \n    def scan_callback(self, scan_msg):\n        \n        self.ranges = []\n\n        for range in scan_msg.ranges:       \n            if range != float(\"+inf\"):\n                self.ranges.append(range)\n\n    def update_plot(self, frame):\n\n        current_lidar_angle = 0\n        points_x = []\n        points_y = []\n\n        for range in self.ranges:\n\n            point_x = self.pose[0] + range*np.cos(self.pose[2] + current_lidar_angle)\n            point_y = self.pose[1] + range*np.sin(self.pose[2] + current_lidar_angle)\n\n            points_x.append(point_x)\n            points_y.append(point_y)\n            \n            current_lidar_angle += self.lidar_ang_res\n        \n        points_x = np.array(points_x).reshape((-1,1))\n        points_y = np.array(points_y).reshape((-1,1))\n\n        if points_x.shape[0] > 0 and points_y.shape[0] > 0:\n\n            ## Clustering\n            lidar_data = np.concatenate((points_x,points_y),axis=1)\n\n            dbscan = DBSCAN(eps=0.1, min_samples=5)\n            labels = dbscan.fit_predict(lidar_data)\n\n            ## Plot Data\n            self.ax.clear()\n            self.ax.autoscale(False)\n            self.ax.set_xlim(-self.x_lim,self.x_lim)\n            self.ax.set_ylim(-self.y_lim,self.y_lim)\n\n            unique_labels = set(labels)\n            core_samples_mask = np.zeros_like(labels, dtype=bool)\n            core_samples_mask[dbscan.core_sample_indices_] = True\n\n            colors = [plt.cm.Spectral(each) for each in np.linspace(0, 1, len(unique_labels))]\n\n            for k, col in zip(unique_labels, colors):\n                if k == -1:\n                    # Black used for noise.\n                    col = [0, 0, 0, 1]\n\n                class_member_mask = labels == k            \n\n                xy = lidar_data[class_member_mask & core_samples_mask]\n                self.ax.scatter(\n                    xy[:, 0],\n                    xy[:, 1],\n                    s=2,\n                    c=np.array([[col]])\n                )\n\n                ## Obtain L-Shapes\n                if k != -1 and xy.shape[0] > 20:\n                    angle, c, pos = self.cal_l_shape(xy)\n                    rect = matplotlib.patches.Rectangle(pos[0], c[2] - c[0], c[3] - c[1], np.rad2deg(angle), color = \"b\", fill = False)\n                    self.ax.add_patch(rect)\n\n                    ## Rectangle center\n                    x_cent = pos[0][0] + ((c[2] - c[0])*np.cos(angle) - (c[3] - c[1])*np.sin(angle))/2\n                    y_cent = pos[0][1] + ((c[2] - c[0])*np.sin(angle) + (c[3] - c[1])*np.cos(angle))/2\n                    self.ax.scatter([x_cent], [y_cent], s=10, c=\"r\", marker=\"x\")\n\n                xy = lidar_data[class_member_mask & ~core_samples_mask]\n                self.ax.scatter(\n                    xy[:, 0],\n                    xy[:, 1],\n                    s=2,\n                    c=np.array([[col]])\n                )\n\n            self.ax.scatter(self.pose[0],self.pose[1],s=14,c='r')       \n\n        return self.ax\n    \n    def variance_criterion(self, C1, C2):\n\n        c1_max = np.max(C1)\n        c1_min = np.min(C1)\n        c2_max = np.max(C2)\n        c2_min = np.min(C2)\n\n        # Calculate distances d1 and d2\n        d1 = np.minimum(np.abs(c1_max - C1), np.abs(C1 - c1_min))\n        d2 = np.minimum(np.abs(c2_max - C2), np.abs(C2 - c2_min))\n\n        e1 = []\n        e2 = []\n\n        # Compare distances\n        for i in range(len(d1)):\n            if d1[i] < d2[i]:\n                e1.append(d1[i])\n            else:\n                e2.append(d2[i])\n\n        v1 = -np.var(e1) if e1 else 0.0\n        v2 = -np.var(e2) if e2 else 0.0\n\n        gamma = v1 + v2\n\n        return gamma\n    \n    def cal_l_shape(self, points):\n\n        Q = []\n        angle_step = 0.0174533\n\n        for search_theta in np.arange(0, np.pi/2 - angle_step, angle_step):\n\n            e1 = np.array([np.cos(search_theta),np.sin(search_theta)]).T\n            e2 = np.array([-np.sin(search_theta),np.cos(search_theta)]).T\n            C1 = np.dot(points,e1)\n            C2 = np.dot(points,e2)\n            q = self.variance_criterion(C1,C2)\n            Q.append([search_theta,q])\n\n        Q = np.array(Q)\n        i = np.argmax(Q[:,1],axis=0)\n        theta_star = Q[i,0]\n\n        C1_star = np.dot(points, np.array([np.cos(theta_star),np.sin(theta_star)]).T)\n        C2_star = np.dot(points, np.array([-np.sin(theta_star),np.cos(theta_star)]).T)\n\n        c1 = np.min(C1_star)\n        c2 = np.min(C2_star)\n        c3 = np.max(C1_star)\n        c4 = np.max(C2_star)\n\n        a1 = np.cos(theta_star)\n        b1 = np.sin(theta_star)\n\n        a2 = -np.sin(theta_star)\n        b2 = np.cos(theta_star)\n\n        a3 = np.cos(theta_star)\n        b3 = np.sin(theta_star)\n\n        a4 = -np.sin(theta_star)\n        b4 = np.cos(theta_star)\n\n        x1 = (b2*c1 - b1*c2)/(b2*a1 - b1*a2)\n        y1 = (c2 - a2*x1)/b2\n\n        x2 = (b4*c1 - b1*c4)/(b4*a1 - b1*a4)\n        y2 = (c4 - a4*x2)/b4\n\n        x3 = (b4*c3 - b3*c4)/(b4*a3 - b3*a4)\n        y3 = (c4 - a4*x3)/b4\n\n        x4 = (b2*c3 - b3*c2)/(b2*a3 - b3*a2)\n        y4 = (c2 - a2*x4)/b2\n\n        return theta_star, [c1,c2,c3,c4], [(x1,y1), (x2,y2), (x3,y3), (x4,y4)]\n    \n    def separate_clusters(self, points, labels):\n",
        "input": "",
        "output": "        unique_labels = set(labels)\n        clusters = []\n\n        for l in unique_labels:\n\n            indices = np.where(labels == l)\n\n            cluster = points[indices[0]]\n            clusters.append(cluster)\n\n        return clusters\n    \n",
        "idx": "911"
    },
    {
        "instruction": "## main.py\nimport hashlib\n\nimport json\n\nfrom time import time\n\nfrom urllib.parse import urlparse\n\nimport requests\n\nclass Blockchain(object):\n    def __init__(self):\n        self.chain = [] # Blockchain\n        self.current_transactions = []\n        self.nodes = set()\n\n        self.new_block(previous_hash=1, proof=1000)\n\n    def new_block(self, proof, previous_hash=None):\n        block = {\n            'index': len(self.chain) + 1,\n            'timestamp': time(),\n            'transactions': self.current_transactions,\n            'proof': proof,\n            'previous_hash': previous_hash or self.hash(self.chain[-1]),\n        }\n\n        self.current_transactions = []\n\n        self.chain.append(block)\n        return block\n\n    def new_transaction(self, sender, recipient, data):\n        self.current_transactions.append({\n            'sender': sender,\n            'recipient': recipient,\n            'data': data,\n        })\n\n        return self.last_block['index'] + 1\n\n    @staticmethod\n    def hash(block):\n",
        "input": "",
        "output": "        block_string = json.dumps(block, sort_keys=True).encode()\n        return hashlib.sha256(block_string).hexdigest()\n    \n",
        "idx": "916"
    },
    {
        "instruction": "## main.py\nimport hashlib\n\nimport json\n\nfrom time import time\n\nfrom urllib.parse import urlparse\n\nimport requests\n\nclass Blockchain(object):\n    def __init__(self):\n        self.chain = [] # Blockchain\n        self.current_transactions = []\n        self.nodes = set()\n\n        self.new_block(previous_hash=1, proof=1000)\n\n    def new_block(self, proof, previous_hash=None):\n        block = {\n            'index': len(self.chain) + 1,\n            'timestamp': time(),\n            'transactions': self.current_transactions,\n            'proof': proof,\n            'previous_hash': previous_hash or self.hash(self.chain[-1]),\n        }\n\n        self.current_transactions = []\n\n        self.chain.append(block)\n        return block\n\n    def new_transaction(self, sender, recipient, data):\n        self.current_transactions.append({\n            'sender': sender,\n            'recipient': recipient,\n            'data': data,\n        })\n\n        return self.last_block['index'] + 1\n\n    @staticmethod\n    def hash(block):\n        block_string = json.dumps(block, sort_keys=True).encode()\n        return hashlib.sha256(block_string).hexdigest()\n\n    @property\n    def last_block(self):\n        return self.chain[-1]\n\n    def proof_of_work(self, last_proof):\n        proof = 0\n        while not self.valid_proof(last_proof, proof):\n            proof += 1\n\n        return proof\n\n    @staticmethod\n    def valid_proof(last_proof, proof):\n",
        "input": "",
        "output": "        guess = f'{last_proof}{proof}'.encode()\n        guess_hash = hashlib.sha256(guess).hexdigest()\n        return guess_hash[:6] == \"000000\"\n    \n",
        "idx": "917"
    },
    {
        "instruction": "# Here are some relevant code fragments from other files of the repo:\n# --------------------------------------------------\n# the below code fragment can be found in:\n# users/models.py\n# --------------------------------------------------\n# from django.contrib.auth.base_user import BaseUserManager\n# \n# from django.utils.translation import gettext_lazy as _\n# \n# from django.contrib.auth.models import AbstractUser\n# \n# from django.db import models\n# \n# class CustomManagerUser(BaseUserManager):\n# \n#     def create_user(self, first_name, last_name, email, password, **extra_fields):\n#         if not first_name:\n#             raise ValueError(_(\"Your first name must be set\"))\n#         if not last_name:\n#             raise ValueError(_(\"Your last name must be set\"))\n#         if not email:\n#             raise ValueError(_(\"The Email must be set\"))\n#         email = self.normalize_email(email)\n#         user = self.model(first_name=first_name,\n#                           last_name= last_name,\n#                           email=email,\n#                           **extra_fields)\n#         user.set_password(password)\n#         user.save()\n#         return user\n#     \n#     def create_superuser(self, first_name, last_name, email, password, **extra_fields):\n# \n#         extra_fields.setdefault(\"is_staff\", True)\n#         extra_fields.setdefault(\"is_superuser\", True)\n#         extra_fields.setdefault(\"is_active\", True)\n# \n#         if extra_fields.get(\"is_staff\") is not True:\n#             raise ValueError(_(\"Superuser must have is_staff=True\"))\n#         if extra_fields.get(\"is_superuser\") is not True:\n#             raise ValueError(_(\"Superuser must have is_superuser=True\"))\n#         return self.create_user(first_name, last_name, email, password, **extra_fields)\n# \n# class CustomUser(AbstractUser):\n#     username = None\n#     first_name = models.CharField(_(\"first name\"), max_length=50)\n#     last_name = models.CharField(_(\"last name\"), max_length=50)\n#     email = models.EmailField(_(\"email address\"), unique=True)\n#     USERNAME_FIELD = \"email\"\n#     REQUIRED_FIELDS = ['first_name', 'last_name',]\n# \n#     objects = CustomManagerUser()\n# \n#     def __str__(self):\n#         return self.email\n# \n# --------------------------------------------------\n\n\n## users/serializers.py\nfrom rest_framework import serializers\n\nfrom .models import CustomUser\n\nclass UserSignupSerializers(serializers.ModelSerializer):\n    password = serializers.CharField(write_only=True, required=True)\n    password2 = serializers.CharField(write_only=True, required=True)\n\n    class Meta:\n        model = CustomUser\n        fields = ('first_name', 'last_name', 'email', 'password', 'password2')\n    \n    def validate(self, attrs):\n",
        "input": "",
        "output": "        if attrs['password'] != attrs['password2']:\n            raise serializers.ValidationError({\"password\": \"password fields didn't match.\"})\n        return attrs\n    \n",
        "idx": "931"
    },
    {
        "instruction": "## booking/booking_report.py\nimport re\n\nfrom selenium.webdriver.common.by import By\n\nfrom selenium.webdriver.remote.webdriver import WebElement\n\nclass BookingReport:\n    def __init__(self, boxes_section_element: WebElement):\n        self.boxes_section_element = boxes_section_element\n        self.deal_boxes = self.pull_deal_boxes()\n\n    def pull_deal_boxes(self):\n",
        "input": "",
        "output": "        deal_boxes = self.boxes_section_element.find_elements(By.XPATH, './/div[@data-testid=\"property-card-container\"]')\n        return deal_boxes\n    \n",
        "idx": "945"
    },
    {
        "instruction": "## booking/booking_filtration.py\nfrom selenium.webdriver.common.by import By\n\nfrom selenium.webdriver.remote.webdriver import WebDriver\n\nimport time\n\nclass BookingFiltration:\n    def __init__(self, driver: WebDriver):\n        self.driver = driver\n        \n\n    def apply_star_rating(self, *star_values):\n",
        "input": "",
        "output": "        for star_value in star_values:\n            star_filtration_box = self.driver.find_elements(By.XPATH, '//div[@data-filters-group=\"class\"]/fieldset//input[@type=\"checkbox\"]')[star_value - 1]\n            star_filtration_box.click()\n            print(f\"Selected {star_value} star(s) rating.\")\n        # wait for the page to load after applying the filtration\n        time.sleep(2)\n        return\n    \n",
        "idx": "947"
    },
    {
        "instruction": "## hito2/api/src/models/usuario_generico.py\nimport re\n\nfrom flask import jsonify\n\nfrom db import mongo\n\nfrom werkzeug.security import generate_password_hash\n\nfrom bson import json_util\n\nfrom bson.objectid import ObjectId\n\nfrom pymongo.errors import PyMongoError\n\nfrom datetime import datetime\n\nclass UsuarioGenerico:\n    def __init__(self, data: dict) -> None:\n        self.nombre = data.get(\"nombre\")\n        self.nombre_usuario = data.get(\"nombre_usuario\")\n        self.password = data.get(\"password\")\n        self.email = data.get(\"email\")\n        self.telefono = data.get(\"telefono\")\n        self.seguidos = data.get(\"seguidos\", [])\n        self.preferencias = data.get(\"preferencias\", [])\n        self.actividades_creadas = data.get(\"actividades_creadas\", [])\n        self.reviews = data.get(\"reviews\", [])\n        self.fecha_nac = data.get(\"fecha_nac\")\n\n    def insertar_usuario_generico(self):\n        try:\n            if not self.correo_es_valido(self.email):\n                raise ValueError(\"Usuario no encontrado\")\n            if self.fecha_nac:\n                if isinstance(self.fecha_nac, str):\n                    self.fecha_nac = datetime.fromisoformat(self.fecha_nac)\n            data_insertar = self.__dict__\n            data_insertar[\"password\"] = generate_password_hash(data_insertar[\"password\"])\n            id = str(mongo.db.usuarios_genericos.insert_one(data_insertar).inserted_id)\n            return {\"message\": \"Usuario creado con \u00e9xito\", \"id\": id}\n        except PyMongoError as e:\n            raise RuntimeError(f\"Error en la base de datos al crear un usuario: {e}\")\n\n    @staticmethod\n    def eliminar_usuario_generico(id):\n        try:\n            usuario_a_eliminar = mongo.db.usuarios_genericos.find_one({\"_id\": ObjectId(id)})\n            if not usuario_a_eliminar:\n                raise ValueError(\"Usuario no encontrado\")\n            resultado = mongo.db.usuarios_genericos.delete_one({\"_id\": ObjectId(id)})\n            if resultado.deleted_count == 0:\n                raise RuntimeError(\"No se pudo eliminar al usuario\")\n            return {\"message\": \"Usuario eliminado con \u00e9xito\"}\n        except PyMongoError as e:\n            raise RuntimeError(f\"Error en la base de datos al eliminar a un usuario: {e}\")\n    \n    @staticmethod\n    def consultar_usuarios():\n        try:\n            usuarios_genericos = mongo.db.usuarios_genericos.find()\n            return json_util.dumps(usuarios_genericos)\n        except PyMongoError as e:\n            raise RuntimeError(f\"Error de base de datos al consultar usuarios genericos de establecimientos: {e}\")\n    \n    @staticmethod\n    def consultar_usuario(id):\n        try:\n            \n            if not ObjectId.is_valid(id):\n                raise ValueError(\"El ID proporcionado no es un ObjectId v\u00e1lido\")\n            \n            \n            usuario = mongo.db.usuarios_genericos.find_one({\"_id\": ObjectId(id)})\n            if not usuario:\n                raise ValueError(\"Usuario no encontrado\")\n            \n            \n            return json_util.dumps(usuario)\n\n        except ValueError as e:\n            return jsonify({\"error\": str(e)}), 404\n        except PyMongoError as e:\n            raise RuntimeError(f\"Error en la base de datos al consultar al usuario: {e}\")\n        \n    @staticmethod\n    def actualizar_usuario(id, data):\n        try:\n            if not ObjectId.is_valid(id):\n                raise ValueError(\"El ID proporcionado no es un ObjectId v\u00e1lido\")\n            \n            data.pop(\"password\", None)\n\n            if 'fecha_nac' in data and isinstance(data['fecha_nac'], str):\n                data['fecha_nac'] = datetime.fromisoformat(data['fecha_nac'])\n\n            if 'preferencias' in data and isinstance(data['preferencias'], str):\n                data['preferencias'] = data['preferencias'].split(',')\n\n            resultado = mongo.db.usuarios_genericos.update_one({\"_id\": ObjectId(id)}, {\"$set\": data})\n\n            if resultado.modified_count == 0:\n                return {\"message\": \"No se realizaron cambios\"}\n\n            return {\"message\": \"Usuario actualizado con \u00e9xito\"}\n        \n        except PyMongoError as e:\n            raise RuntimeError(f\"Error en la base de datos al actualizar al usuario: {e}\")\n\n    @classmethod\n    def correo_es_valido(cls, email):\n",
        "input": "",
        "output": "        patron = r'\\w+@\\w+\\.\\w+'\n        return re.match(patron, email) is not None\n    \n",
        "idx": "950"
    },
    {
        "instruction": "## hito2/api/src/models/administrador_cine.py\nimport re\n\nfrom db import mongo\n\nfrom werkzeug.security import generate_password_hash\n\nfrom bson import json_util\n\nfrom bson.objectid import ObjectId\n\nfrom pymongo.errors import PyMongoError\n\nclass AdministradorCine:\n    def __init__(self, data: dict) -> None:\n        self.nombre = data.get(\"nombre\")\n        self.nombre_usuario = data.get(\"nombre_usuario\")\n        self.password = data.get(\"password\")\n        self.email = data.get(\"email\")\n        self.telefono = data.get(\"telefono\")\n        self.dni = data.get(\"dni\")\n\n    def insertar_administrador_cine(self):\n        try:\n            if not self.correo_es_valido(self.email):\n                raise ValueError(\"Administrador no encontrado\")\n            data_insertar = self.__dict__\n            data_insertar[\"password\"] = generate_password_hash(data_insertar[\"password\"])\n            id = str(mongo.db.administradores_cines.insert_one(data_insertar).inserted_id)\n            return {\"message\": \"Administrador creado con \u00e9xito\", \"id\": id}\n        except PyMongoError as e:\n            raise RuntimeError(f\"Error en la base de datos al crear un administrador: {e}\")\n\n    @staticmethod\n    def eliminar_administrador_cine(id):\n        try:\n            administrador_a_eliminar = mongo.db.administradores_cines.find_one({\"_id\": ObjectId(id)})\n            if not administrador_a_eliminar:\n                raise ValueError(\"administrador no encontrado\")\n            resultado = mongo.db.administradores_cines.delete_one({\"_id\": ObjectId(id)})\n            if resultado.deleted_count == 0:\n                raise RuntimeError(\"No se pudo eliminar al administrador\")\n            return {\"message\": \"administrador eliminado con \u00e9xito\"}\n        except PyMongoError as e:\n            raise RuntimeError(f\"Error en la base de datos al eliminar a un administrador: {e}\")\n    \n    @staticmethod\n    def consultar_administradores_cines():\n        try:\n            administradores_cines = mongo.db.administradores_cines.find()\n            return json_util.dumps(administradores_cines)\n        except PyMongoError as e:\n            raise RuntimeError(f\"Error de base de datos al consultar administradores_cines genericos de establecimientos: {e}\")\n    \n    @staticmethod\n    def consultar_administrador(id):\n        try:\n            \n            if not ObjectId.is_valid(id):\n                raise ValueError(\"El ID proporcionado no es un ObjectId v\u00e1lido\")\n            \n            \n            administrador = mongo.db.administradores_cines.find_one({\"_id\": ObjectId(id)})\n            if not administrador:\n                raise ValueError(\"administrador no encontrado\")\n            \n            \n            return json_util.dumps(administrador)\n        \n        except PyMongoError as e:\n            raise RuntimeError(f\"Error en la base de datos al consultar al administrador: {e}\")\n\n    @staticmethod\n    def actualizar_administrador(id, data):\n        try:\n            if not ObjectId.is_valid(id):\n                raise ValueError(\"El ID proporcionado no es un ObjectId v\u00e1lido\")\n            \n            data.pop(\"password\", None)\n\n            resultado = mongo.db.administradores_cines.update_one({\"_id\": ObjectId(id)}, {\"$set\": data})\n\n            if resultado.modified_count == 0:\n                return {\"message\": \"No se realizaron cambios o administrador no encontrado\"}\n\n            return {\"message\": \"administrador actualizado con \u00e9xito\"}\n        \n        except PyMongoError as e:\n            raise RuntimeError(f\"Error en la base de datos al actualizar al administrador: {e}\")\n\n    @staticmethod\n    def correo_es_valido(email):\n",
        "input": "",
        "output": "        patron = r'\\w+@\\w+\\.\\w+'\n        return re.match(patron, email) is not None\n    \n",
        "idx": "955"
    },
    {
        "instruction": "## src/elin_yar_craft/translate.py\nimport copy\n\nimport re\n\nimport warnings\n\nfrom typing import Any, ClassVar\n\nimport openpyxl\n\nfrom pydantic import BaseModel\n\ndef gen_key_name(lang: str, id: str, name: str) -> str:\n    # \u672b\u5c3e\u304c _q\\d \u304b?\n    suffix_match = re.search(r\"(_q\\d)$\", id)\n    if not suffix_match:\n        return name  # \u30de\u30c3\u30c1\u3057\u306a\u3051\u308c\u3070\u30ea\u30bf\u30fc\u30f3\n\n    # \u30e9\u30f3\u30af\u5206\u3051\n    new_name: str = name + \" \"\n    match suffix_match[0]:\n        case \"_q1\":\n            match lang:\n                case \"cn\":\n                    new_name += \"\u4f18\u8d28\u54c1\"\n                case \"zhtw\":\n                    new_name += \"\u512a\u8cea\u54c1\"\n                case _:\n                    new_name += \"good\"\n        case \"_q2\":\n            match lang:\n                case \"cn\":\n                    new_name += \"\u5947\u8ff9\"\n                case \"zhtw\":\n                    new_name += \"\u5947\u8e5f\"\n                case _:\n                    new_name += \"miracle\"\n        case \"_q3\":\n            match lang:\n                case \"cn\":\n                    new_name += \"\u795e\u5668\"\n                case \"zhtw\":\n                    new_name += \"\u795e\u5668\"\n                case _:\n                    new_name += \"godly\"\n        case \"_q4\":\n            match lang:\n                case \"cn\":\n                    new_name += \"\u7279\u5236\"\n                case \"zhtw\":\n                    new_name += \"\u7279\u88fd\"\n                case _:\n                    new_name += \"special\"\n    return new_name\n\nclass TransThing(BaseModel):\n    key_id: ClassVar[str] = \"id\"\n    key_name: ClassVar[str] = \"name\"\n    key_name_EN: ClassVar[str] = \"name_EN\"  # noqa: N815\n    key_detail: ClassVar[str] = \"detail\"\n    key_unit: ClassVar[str] = \"unit\"\n    key_unknown: ClassVar[str] = \"unknown\"\n    key_roomName: ClassVar[str] = \"roomName\"  # noqa: N815\n    key_name2: ClassVar[str] = \"name2\"\n    trans_list: list[dict[str, Any]] = []\n\n    @classmethod\n    def load(cls, file: str) -> TransThing:\n",
        "input": "",
        "output": "        self = cls()\n        # \u30d5\u30a1\u30a4\u30eb\u8aad\u307f\u8fbc\u307f\n        with warnings.catch_warnings():\n            warnings.simplefilter(\"ignore\")\n            wb = openpyxl.load_workbook(file)\n        ws = wb[\"Thing\"]\n        # 1\u884c\u76ee(\u30d8\u30c3\u30c0)\n        header = ws[1]\n        # 3\u884c\u76ee\u4ee5\u964d(2\u884c\u76ee\u306f\u30b4\u30df)\n        for row in ws.iter_rows(min_row=3):\n            row_dic = {}\n            for k, v in zip(header, row):\n                row_dic[k.value] = v.value\n            self.trans_list.append(row_dic)\n        return self\n    \n",
        "idx": "966"
    },
    {
        "instruction": "## backend/src/tools/migrator.py\nimport sqlite3\n\nimport pandas as pd\n\nfrom pathlib import Path\n\nimport logging\n\nimport time\n\nfrom typing import Optional, Union\n\nclass Migrator:\n    @staticmethod\n    def resolve_db_path(db_path: Union[str, Path]) -> Path:\n",
        "input": "",
        "output": "        db_path = Path(db_path)\n        if db_path.is_absolute():\n            return db_path\n        \n        return Path(__file__).parents[2] / 'db' / db_path\n    \n",
        "idx": "971"
    },
    {
        "instruction": "## src/game.py\nimport pygame\n\nfrom random import *\n\nimport shared\n\nimport math\n\nall_entities = None\n\nentity_size = None\n\ndef find_entity_size(count):\n    area_per_entity = 75000 / count\n    global entity_size\n    entity_size = math.sqrt(area_per_entity)\n\ndef find_winner():\n    potential_winner = all_entities[0]\n    for entity in all_entities:\n        if (entity.type.id != potential_winner.type.id):\n            return None\n    return potential_winner\n\ndef game_tick(events):\n    shared.display_surf.fill(shared.VALTER_VALGE)\n    \n    for entity in all_entities:\n        entity.tick()\n        \n    potential_winner = find_winner()\n    if (potential_winner != None):\n        shared.win_setup(potential_winner.type)\n\ndef game_setup():\n    shared.uireset()\n    \n    find_entity_size(shared.ENTITY_TYPES[0].count + shared.ENTITY_TYPES[1].count + shared.ENTITY_TYPES[2].count)\n    \n    global all_entities\n    all_entities = []\n    \n    for entity_type in shared.ENTITY_TYPES:\n        for i in range(entity_type.count):\n            new_entity = Entity(entity_type)\n            all_entities.append(new_entity)\n    \n    \n    shared.current_tick = game_tick\n\nshared.game_setup = game_setup\n\nclass Entity(pygame.sprite.Sprite): # Entity on kas kivi/paber/k\u00e4\u00e4rid\n\n    def __init__(self, type):\n        super().__init__()\n        \n        self.set_type(type)\n        \n        self.rect = self.image.get_rect()\n        w = self.rect.width\n        h = self.rect.height\n        self.rect.center = (randint(w, shared.SCREEN_WIDTH - w), randint(h, shared.SCREEN_HEIGHT - h))\n        \n        self.dx = randint(-3, 3)\n        self.dy = randint(-3, 3)\n\n    def set_type(self, type):\n        self.type = type\n        \n        self.image = pygame.image.load(type.image())\n        self.image = pygame.transform.scale(self.image, (entity_size, entity_size))\n        \n    \n    def tick(self):\n",
        "input": "",
        "output": "        self.move()\n        self.collide_with_others()\n        self.draw()\n    \n",
        "idx": "978"
    },
    {
        "instruction": "# Here are some relevant code fragments from other files of the repo:\n# --------------------------------------------------\n# the below code fragment can be found in:\n# src/poly.py\n# --------------------------------------------------\n# import numpy as np\n# \n# import os\n# \n# generator_coeffs     = np.array(eval(os.getenv(\"GENERATOR_POLYNOMIAL\")), dtype=np.int8)\n# \n# class GF2Polynomial:\n#     def __init__(self, coeffs):\n#         self.coeffs = np.array(coeffs, dtype=np.int8) & 1\n#         self.trim()\n# \n#     def trim(self):\n#         self.coeffs = np.trim_zeros(self.coeffs, 'f')\n# \n#     def __add__(self, other):\n#         max_len = max(len(self.coeffs), len(other.coeffs))\n#         padded_self = np.pad(self.coeffs, (max_len - len(self.coeffs), 0))\n#         padded_other = np.pad(other.coeffs, (max_len - len(other.coeffs), 0))\n#         result_coeffs = np.bitwise_xor(padded_self, padded_other)\n#         return GF2Polynomial(result_coeffs)\n# \n#     def __mul__(self, other):\n#         result_coeffs = np.zeros(len(self.coeffs) + len(other.coeffs) - 1, dtype=np.int8)\n#         for i in range(len(self.coeffs)):\n#             result_coeffs[i:i + len(other.coeffs)] ^= self.coeffs[i] * other.coeffs\n#         return self.reduce(result_coeffs)\n# \n#     def square(self):\n#         squared_coeffs = np.zeros(2 * len(self.coeffs) - 1, dtype=np.int8)\n#         squared_coeffs[::2] = self.coeffs\n#         return self.reduce(squared_coeffs)\n# \n#     def reduce(self, coeffs):\n#         while len(coeffs) >= len(generator_polynomial.coeffs):\n#             if coeffs[0] == 1:\n#                 coeffs[:len(generator_polynomial.coeffs)] ^= generator_polynomial.coeffs\n#             coeffs = np.trim_zeros(coeffs, 'f')\n#             if coeffs.size == 0:\n#                 coeffs = np.array([0], dtype=np.int8)\n#         return GF2Polynomial(coeffs)\n# \n#     def __repr__(self):\n#         return f\"GF2Polynomial({self.coeffs.tolist()})\"\n#     \n#     def power(self, exp):\n#         result = GF2Polynomial([1])\n#         base = self\n#         \n#         while exp > 0:\n#             if exp % 2 == 1:\n#                 result = result * base\n#             base = base.square()\n#             exp //= 2\n#         \n#         return result\n#     \n#     def trace(self) :\n#         # just need to summarize powers of 2 \n#         pass\n# \n# generator_polynomial = GF2Polynomial(generator_coeffs)\n# \n# --------------------------------------------------\n\n\n## src/test.py\nimport unittest\n\nimport numpy as np\n\nfrom poly import GF2Polynomial\n\nclass TestGF2Polynomial(unittest.TestCase):\n\n    def setUp(self):\n",
        "input": "",
        "output": "        self.poly1 = GF2Polynomial([1, 0, 1])  # x^2 + 1\n        self.poly2 = GF2Polynomial([1, 1])  # x + 1\n        self.poly3 = GF2Polynomial([1, 0, 1, 0])  # x^3 + x + 1\n    \n",
        "idx": "980"
    },
    {
        "instruction": "## src/poly.py\nimport numpy as np\n\nimport os\n\ngenerator_coeffs     = np.array(eval(os.getenv(\"GENERATOR_POLYNOMIAL\")), dtype=np.int8)\n\ngenerator_polynomial = GF2Polynomial(generator_coeffs)\n\nclass GF2Polynomial:\n    def __init__(self, coeffs):\n        self.coeffs = np.array(coeffs, dtype=np.int8) & 1\n        self.trim()\n\n    def trim(self):\n        self.coeffs = np.trim_zeros(self.coeffs, 'f')\n\n    def __add__(self, other):\n        max_len = max(len(self.coeffs), len(other.coeffs))\n        padded_self = np.pad(self.coeffs, (max_len - len(self.coeffs), 0))\n        padded_other = np.pad(other.coeffs, (max_len - len(other.coeffs), 0))\n        result_coeffs = np.bitwise_xor(padded_self, padded_other)\n        return GF2Polynomial(result_coeffs)\n\n    def __mul__(self, other):\n        result_coeffs = np.zeros(len(self.coeffs) + len(other.coeffs) - 1, dtype=np.int8)\n        for i in range(len(self.coeffs)):\n            result_coeffs[i:i + len(other.coeffs)] ^= self.coeffs[i] * other.coeffs\n        return self.reduce(result_coeffs)\n\n    def square(self):\n        squared_coeffs = np.zeros(2 * len(self.coeffs) - 1, dtype=np.int8)\n        squared_coeffs[::2] = self.coeffs\n        return self.reduce(squared_coeffs)\n\n    def reduce(self, coeffs):\n        while len(coeffs) >= len(generator_polynomial.coeffs):\n            if coeffs[0] == 1:\n                coeffs[:len(generator_polynomial.coeffs)] ^= generator_polynomial.coeffs\n            coeffs = np.trim_zeros(coeffs, 'f')\n            if coeffs.size == 0:\n                coeffs = np.array([0], dtype=np.int8)\n        return GF2Polynomial(coeffs)\n\n    def __repr__(self):\n        return f\"GF2Polynomial({self.coeffs.tolist()})\"\n    \n    def power(self, exp):\n",
        "input": "",
        "output": "        result = GF2Polynomial([1])\n        base = self\n        \n        while exp > 0:\n            if exp % 2 == 1:\n                result = result * base\n            base = base.square()\n            exp //= 2\n        \n        return result\n    \n",
        "idx": "982"
    },
    {
        "instruction": "# Here are some relevant code fragments from other files of the repo:\n# --------------------------------------------------\n# the below code fragment can be found in:\n# constants.py\n# --------------------------------------------------\n# PLAYER_RADIUS = 20\n# \n# PLAYER_TURN_SPEED = 300\n# \n# PLAYER_SPEED = 200\n# \n# PLAYER_SHOOT_SPEED = 500\n# \n# PLAYER_SHOOT_COOLDOWN = 0.3\n# \n# SHOT_RADIUS=5\n# \n# --------------------------------------------------\n# the below code fragment can be found in:\n# circleshape.py\n# --------------------------------------------------\n# import pygame as pg\n# \n# class CircleShape(pg.sprite.Sprite):\n#     def __init__(self, x, y, radius):\n#         # we will be using this later\n#         if hasattr(self, \"containers\"):\n#             super().__init__(self.containers)\n#         else:\n#             super().__init__()\n# \n#         self.position = pg.Vector2(x, y)\n#         self.velocity = pg.Vector2(0, 0)\n#         self.radius = radius\n# \n#     def draw(self, screen):\n#         # sub-classes must override\n#         pass\n# \n#     def update(self, dt):\n#         # sub-classes must override\n#         pass\n# \n#     def is_colliding(self, asteroid):\n#         distance = self.position.distance_to(asteroid.position)\n# \n#         if distance <= self.radius + asteroid.radius:\n#             return True\n#         return False\n# \n# --------------------------------------------------\n# the below code fragment can be found in:\n# shot.py\n# --------------------------------------------------\n# import pygame as pg\n# \n# from circleshape import CircleShape\n# \n# from constants import SHOT_RADIUS\n# \n# class Shot(CircleShape):\n#     def __init__(self, x, y):\n#         super().__init__(x, y, SHOT_RADIUS)\n# \n#     def draw(self, screen):\n#         pg.draw.circle(screen, \"white\", self.position, self.radius, width=2)\n# \n#     def update(self, dt):\n#         self.position += self.velocity * dt\n# \n# --------------------------------------------------\n\n\n## player.py\nimport pygame as pg\n\nfrom circleshape import CircleShape\n\nfrom constants import (\n    PLAYER_RADIUS,\n    PLAYER_SHOOT_COOLDOWN,\n    PLAYER_SHOOT_SPEED,\n    PLAYER_SPEED,\n    PLAYER_TURN_SPEED,\n)\n\nfrom shot import Shot\n\nclass Player(CircleShape):\n    def __init__(self, x, y):\n        super().__init__(x, y, PLAYER_RADIUS)\n        self.rotation = 0\n        self.shoot_timer = 0\n    \n    def triangle(self):\n        forward = pg.Vector2(0, 1).rotate(self.rotation)\n        right = pg.Vector2(0, 1).rotate(self.rotation + 90) * self.radius / 1.5\n        a = self.position + forward * self.radius\n        b = self.position - forward * self.radius - right\n        c = self.position - forward * self.radius + right\n        return [a, b, c]\n\n    def draw(self, screen):\n        pg.draw.polygon(screen, \"white\", self.triangle(), width=2)\n\n    def rotate(self, dt):\n        self.rotation += PLAYER_TURN_SPEED * dt\n\n    def move(self, dt):\n        forward = pg.Vector2(0, 1).rotate(self.rotation)\n        self.position += forward * PLAYER_SPEED * dt\n\n    def shoot(self):\n",
        "input": "",
        "output": "        if self.shoot_timer > 0:\n            return\n        self.shoot_timer = PLAYER_SHOOT_COOLDOWN\n        shot = Shot(self.position.x, self.position.y)\n        shot.velocity = pg.Vector2(0, 1).rotate(self.rotation) * \\\n            PLAYER_SHOOT_SPEED\n    \n",
        "idx": "986"
    },
    {
        "instruction": "## CatchTheBall.py\nimport pygame\n\nimport random\n\nRED = (255, 0, 0)\n\nwall_hit_sound = pygame.mixer.Sound(\"wall_hit_sound.wav\")\n\nclass Ball(pygame.sprite.Sprite):\n    def __init__(self):\n        super().__init__()\n        self.image = pygame.Surface((15, 15))\n        self.image.fill(RED)\n        self.rect = self.image.get_rect()\n        self.rect.center = (WIDTH // 2, HEIGHT // 2)\n        self.x_velocity = random.choice([3, -3])\n        self.y_velocity = random.choice([3, -3])\n\n    def update(self):\n",
        "input": "",
        "output": "        self.rect.x += self.x_velocity\n        self.rect.y += self.y_velocity\n\n        if self.rect.left <= 0 or self.rect.right >= WIDTH:\n            self.x_velocity *= -1\n            wall_hit_sound.play()  # Play wall hit sound\n\n        if self.rect.top <= 0 or self.rect.bottom >= HEIGHT:\n            self.y_velocity *= -1\n            wall_hit_sound.play()\n    \n",
        "idx": "989"
    },
    {
        "instruction": "## data_processing/api.py\nimport os\n\nfrom googleapiclient.discovery import build\n\nfrom googleapiclient.errors import HttpError\n\nimport isodate\n\nimport requests\n\nAPI_KEY = os.getenv(\"API_KEY\")\n\nyoutube = build('youtube', 'v3', developerKey=API_KEY)\n\nclass YouTubeAPIClient:\n    \n    \"\"\"\n    The YouTubeAPIClient class interacts with the YouTube API to retrieve video details, comments, playlist videos, and search results. \n    It provides methods to gather comments from specific videos, fetch various statistics like views and likes, retrieve video URLs from \n    playlists, and conduct YouTube search queries. \n    \n    This class requires a video ID or playlist ID as input to operate.\n    \n    \"\"\"\n    def __init__(self, video_id):\n        self.video_id = video_id\n        \n    def get_video_comments(self, max_results=100):\n\n        try:\n            comments = []\n            request = youtube.commentThreads().list(\n                part='snippet',\n                videoId=self.video_id,\n                maxResults=max_results,\n                textFormat='plainText'\n            )\n            \n            while request:\n                response = request.execute()\n            \n                for item in response['items']:\n                    comment = item['snippet']['topLevelComment']['snippet']['textDisplay']\n                    comments.append(comment)\n                    \n                request = youtube.commentThreads().list_next(request, response)\n                \n        except HttpError as e:\n            if e.resp.status == 403 and \"commentsDisabled\" in str(e):\n                print(\"Comments are disabled for this video.\")\n                \n        return comments\n\n    def get_video_details(self):\n\n        request = youtube.videos().list(\n            part=\"snippet,statistics,contentDetails\",\n            id=self.video_id\n        )\n        response = request.execute()\n\n        if response['items']:\n            video_info = response['items'][0]\n            title = video_info['snippet']['title']\n            duration = isodate.parse_duration(video_info['contentDetails'].get('duration', 0))\n            \n            likes = video_info['statistics'].get('likeCount', 0)\n            dislikes = video_info['statistics'].get('dislikeCount', 0)\n            views = video_info['statistics'].get('viewCount', 0)\n            comment_count = video_info['statistics'].get('commentCount', 0)\n\n            results = {\n                'title': title,\n                'likes': likes,\n                'duration': duration,\n                #'dislikes': dislikes,\n                'views': views,\n                'comment_count': comment_count\n            }\n            \n            return results\n        else:\n            return None\n        \n    def get_playlist_videos(self, playlist_id):\n",
        "input": "",
        "output": "        request = youtube.playlistItems().list(\n            part='snippet',\n            playlistId=playlist_id,\n            maxResults=500\n        )\n        \n        response = request.execute()\n\n        video_urls = []\n        for item in response['items']:\n            video_id = item['snippet']['resourceId']['videoId']\n            video_urls.append(f'https://www.youtube.com/watch?v={video_id}')\n        \n        return video_urls\n    \n",
        "idx": "992"
    },
    {
        "instruction": "## src/models.py\nfrom data_processing import processing\n\nimport os\n\nfrom sklearn.feature_extraction.text import TfidfVectorizer\n\nfrom vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer\n\nfrom collections import Counter\n\nimport matplotlib.pyplot as plt\n\nfrom concurrent.futures import ThreadPoolExecutor, as_completed\n\nimport math\n\nclass YouTubeCommentAnalyzer:\n\n    \"\"\"\n    This class contains a set of methods that are used to perform sentiment analysis. It also calculates engagement metrics based on video details \n    and sentiment data to assess the video's potential quality.\n    \n    \"\"\"\n\n    WEIGHT_LIKES_VIEWS = 0.1 \n    WEIGHT_POSITIVE = 1.5  \n    WEIGHT_NEGATIVE = 1.5 \n    WEIGHT_LOG_VIEWS = 0.002 #vievs are not as important as likes or comments \n\n    def __init__(self, video_id):\n\n        self.max_workers = os.cpu_count()\n        self.data_cleanner = processing.DataCleaning(video_id)\n        self.analyser = SentimentIntensityAnalyzer()\n        self.comments = self.data_cleanner.sentence_tokenize() \n        self.sentiment_data = self.analyze_sentiment()\n        self.video_detalis = self.data_cleanner.otherapidata\n        \n\n    def vectorize_data(self, max_features=5000):\n\n        vectorizer = TfidfVectorizer(max_features=max_features)        \n        return vectorizer.fit_transform(self.comments)\n    \n    def analyze_sentiment(self):\n        \n        sentiment_labels = []\n\n        def analyze_comment(comment):\n            sentiment_scores = self.analyser.polarity_scores(comment)\n            if sentiment_scores['compound'] >= 0.05:\n                sentiment_labels.append('positive')\n            elif sentiment_scores['compound'] <= -0.05:\n                sentiment_labels.append('negative')\n            else:\n                sentiment_labels.append('neutral')\n\n        with ThreadPoolExecutor(max_workers=10) as executor:\n            futures = {executor.submit(analyze_comment, comment): comment for comment in self.comments}\n\n            for future in as_completed(futures):\n                try:\n                    result = future.result()  \n                    sentiment_labels.append(result)\n                except Exception as exc:\n                    print(f'Comment generated an exception: {exc}')\n\n        return Counter(sentiment_labels)\n    \n\n    def bar_chart_maker(self):\n\n        sentiment_count = self.sentiment_data\n        sentiments = list(sentiment_count.keys())\n        counts = list(sentiment_count.values())\n\n        plt.figure(figsize=(8, 6))\n        plt.bar(sentiments, counts, color=['red', 'green', 'gray'])\n        plt.title('Sentiment Distribution')\n        plt.xlabel('Sentiment')\n        plt.ylabel('Amount of comments')\n        plt.show()\n        plt.close()\n\n    def data_connector(self):\n",
        "input": "",
        "output": "        data = self.video_detalis\n        data[\"Result\"] = self.sentiment_data\n\n        comment_count = int(data['comment_count']) if int(data['comment_count']) > 0 else 1\n        views = int(data['views']) if int(data['views']) > 0 else 1\n        likes = int(data['likes']) if int(data['likes']) > 0 else 1\n\n        data['Engagement'] = round(((likes / views) * self.WEIGHT_LIKES_VIEWS + \n                                    (int(data['Result'].get('positive', 0)) / comment_count) * self.WEIGHT_POSITIVE + \n                                    (int(data['Result'].get('negative', 0)) / comment_count)) * self.WEIGHT_NEGATIVE + \n                                    math.log(views) * self.WEIGHT_LOG_VIEWS, 5) \n\n        return data\n    \n",
        "idx": "998"
    },
    {
        "instruction": "## subcategory/subcategory.py\nimport requests\n\nimport json\n\nimport os\n\nfrom auth.auth import Auth\n\nfrom utils.logger import configure_logger\n\nlogger = configure_logger()\n\nclass SubcategoryListing:\n    def __init__(self):\n        # Verifica se a vari\u00e1vel de ambiente 'TOKEN' existe e a usa\n        self.token = os.getenv(\"TOKEN\")\n        if not self.token:\n            logger.warning(\n                f\"{os.path.basename(__file__)}: Token n\u00e3o encontrado nas vari\u00e1veis de ambiente.\"\n            )\n            # Tenta obter o token se n\u00e3o houver\n            auth = Auth()\n            self.token = auth.token()\n\n        self.header = {\"Authorization\": f\"{self.token}\"}\n        self.refresh_token()\n\n    def refresh_token(self):\n        # Atualiza o header com o novo token se necess\u00e1rio\n        if not self.token:\n            logger.warning(f\"{os.path.basename(__file__)}: Token n\u00e3o definido.\")\n        else:\n            self.header = {\"Authorization\": f\"{self.token}\"}\n\n    def refresh_new_token(self):\n",
        "input": "",
        "output": "        auth_instance = Auth()\n        new_token = auth_instance.token()\n        if new_token:\n            logger.info(\n                f\"{os.path.basename(__file__)}: Token atualizado com sucesso: {new_token}\"\n            )\n            self.token = new_token\n            self.header = {\"Authorization\": f\"{self.token}\"}\n        else:\n            logger.warning(f\"{os.path.basename(__file__)}: Falha ao obter o token.\")\n    \n",
        "idx": "1002"
    },
    {
        "instruction": "## listing/listing.py\nimport requests\n\nimport json\n\nimport os\n\nfrom auth.auth import Auth\n\nfrom utils.logger import configure_logger\n\nlogger = configure_logger()\n\nclass Listing:\n    def __init__(self):\n        # Verifica se a vari\u00e1vel de ambiente 'TOKEN' existe e a usa\n        self.token = os.getenv(\"TOKEN\")\n        if not self.token:\n            logger.warning(\n                f\"{os.path.basename(__file__)}: Token n\u00e3o encontrado nas vari\u00e1veis de ambiente.\"\n            )\n            # Tenta obter o token se n\u00e3o houver\n            auth = Auth()\n            self.token = auth.token()\n\n        self.header = {\"Authorization\": f\"{self.token}\"}\n        self.refresh_token()\n\n    def refresh_token(self):\n        # Atualiza o header com o novo token se necess\u00e1rio\n        if not self.token:\n            logger.warning(f\"{os.path.basename(__file__)}: Token n\u00e3o definido.\")\n        else:\n            self.header = {\"Authorization\": f\"{self.token}\"}\n\n    def refresh_new_token(self):\n",
        "input": "",
        "output": "        auth_instance = Auth()\n        new_token = auth_instance.token()\n        if new_token:\n            logger.info(\n                f\"{os.path.basename(__file__)}: Token atualizado com sucesso: {new_token}\"\n            )\n            self.token = new_token\n            self.header = {\"Authorization\": f\"{self.token}\"}\n        else:\n            logger.warning(f\"{os.path.basename(__file__)}: Falha ao obter o token.\")\n    \n",
        "idx": "1003"
    },
    {
        "instruction": "# Here are some relevant code fragments from other files of the repo:\n# --------------------------------------------------\n# the below code fragment can be found in:\n# minesweeper/game_state.py\n# --------------------------------------------------\n# from enum import Enum\n# \n# import random\n# \n# class GameState(Enum):\n#     PLAYING = 1\n#     LOST = 2\n#     WON = 3\n# \n# class game_state:\n#     def __init__(self, width = 9, height = 9, mine_count = 10):\n#         self.width = width\n#         self.height = height\n#         self.mines = []\n#         self.flags = []\n#         self.revealed = []\n#         self.cursor = (0,0)\n#         self.game_state = GameState.PLAYING\n#         self._generate_mines(mine_count)\n# \n#     def _generate_mines(self, mine_count):\n#         # Task: Implement the method that generates mines based on width/height/mine_count\n#         # This would involve generating a list of random (x, y) coordinates\n#         rangeX = (0, self.width)\n#         rangeY = (0, self.height)\n# \n#         randPoints = []\n#         current_generated_mines = 0\n#         while current_generated_mines < mine_count:\n#             x = random.randrange(*rangeX)\n#             y = random.randrange(*rangeY)\n#             if (x, y) not in randPoints:\n#                 randPoints.append((x, y))\n#                 current_generated_mines += 1\n#         \n#         self.mines = randPoints\n# \n#     def number_mines(self, x, y):\n#         directions = [(0, 1), (1, 0), (0, -1), (-1, 0), (1, 1), (-1, -1), (1, -1), (-1, 1)]\n# \n#         counted_mines = 0\n# \n#         for dx, dy in directions:\n#             mine_check_x = x + dx\n#             mine_check_y = y + dy\n# \n#             if (mine_check_x, mine_check_y) in self.mines:\n#                 counted_mines += 1\n#                 # self.shown_listed_mines.append((mine_check_x, mine_check_y))\n# \n#         return counted_mines\n# \n# --------------------------------------------------\n# the below code fragment can be found in:\n# minesweeper/ui.py\n# --------------------------------------------------\n# from .game_state import game_state, GameState\n# \n# import os\n# \n# def print_board(game_state: game_state):\n#     # print(f\" TODO print board (mines: {game_state.mines})\")\n#     # Task: Implement the method that prints the board\n#     # 1\ufe0f\u20e32\ufe0f\u20e33\ufe0f\u20e34\ufe0f\u20e35\ufe0f\u20e36\ufe0f\u20e37\ufe0f\u20e38\ufe0f\u20e3\ud83d\udfe8 <-- copy and paste\n#     for y in range(game_state.height):\n#         for x in range(game_state.width):\n#             if (x, y) == game_state.cursor:\n#                 print(\"\ud83d\udfe8\", end=\"\")\n#             elif (x, y) in game_state.mines and game_state.game_state != GameState.PLAYING:\n#                 print(\"\ud83d\udca3\", end=\"\")\n#             elif (x, y) in game_state.flags:\n#                 print(\"\ud83d\udea9\", end=\"\")\n#             elif (x, y) in game_state.revealed:\n#                 number_mines = game_state.number_mines(x, y)\n#                 if number_mines == 0:\n#                     print(\"\ud83d\udfeb\", end=\"\")\n#                 if number_mines == 1:\n#                     print(\"\\u0031\\ufe0f\\u20e3 \", end ='')\n#                 if number_mines == 2:\n#                     print(\"\\u0032\\ufe0f\\u20e3 \", end ='')\n#                 if number_mines == 3:\n#                     print(\"\\u0033\\ufe0f\\u20e3 \", end ='')\n#                 if number_mines == 4:\n#                     print(\"\\u0034\\ufe0f\\u20e3 \", end ='')\n#                 if number_mines == 5:\n#                     print(\"\\u0035\\ufe0f\\u20e3 \", end ='')\n#                 if number_mines == 6:\n#                     print(\"\\u0036\\ufe0f\\u20e3 \", end ='')\n#                 if number_mines == 7:\n#                     print(\"\\u0037\\ufe0f\\u20e3 \", end ='')\n#                 if number_mines == 8:\n#                     print(\"\\u0038\\ufe0f\\u20e3 \", end ='')\n#             else:\n#                 print(\"\ud83d\udfe9\", end=\"\")\n#         print()\n# \n# def clear_console():\n#     # For Windows\n#     if os.name == 'nt':\n#         os.system('cls')\n#     # For macOS and Linux\n#     print('\\n\\n')\n# \n# --------------------------------------------------\n\n\n## minesweeper/game_controller.py\nfrom collections import deque\n\nfrom minesweeper.game_state import game_state, GameState\n\nfrom minesweeper.ui import clear_console, print_board\n\nimport readchar\n\nclass game_controller:\n    def __init__(self, game_state: game_state):\n        self.game_state = game_state\n\n    def play_until_end(self):\n        while self.game_state.game_state == GameState.PLAYING:\n            self.play_game_turn()\n        self.print_end_game()\n\n    def play_game_turn(self):\n        clear_console()\n        print_board(self.game_state)\n        # Task: Implement the method that plays a single turn of the game (including printing the UI)\n        \n        #for now, we'll just loose the game\n        #self.game_state.game_state = GameState.LOST\n        key = readchar.readkey()\n        if key == readchar.key.LEFT:\n            self.game_state.cursor = (max(0, self.game_state.cursor[0] - 1), self.game_state.cursor[1])\n        if key == readchar.key.RIGHT:\n            self.game_state.cursor = (min(self.game_state.width - 1, self.game_state.cursor[0] + 1), self.game_state.cursor[1])\n        if key == readchar.key.DOWN:\n            self.game_state.cursor = (self.game_state.cursor[0], min(self.game_state.height - 1, self.game_state.cursor[1] + 1))\n        if key == readchar.key.UP:\n            self.game_state.cursor = (self.game_state.cursor[0], max( 0, self.game_state.cursor[1] - 1))\n        if key == 'f' or key == 'F':\n            if self.game_state.cursor in self.game_state.flags:\n                self.game_state.flags.remove(self.game_state.cursor)\n            else:   \n                self.game_state.flags.append(self.game_state.cursor)\n        if key == 'r' or key == 'R':\n            if self.game_state.cursor in self.game_state.mines:\n                self.game_state.game_state = 2\n            else:\n                self._reveal(self.game_state.cursor[0], self.game_state.cursor[1])\n\n    def _reveal(self, x, y):\n",
        "input": "",
        "output": "        queue = deque()\n        queue.append((x, y))\n        while len(queue) > 0:\n            item = queue.popleft()\n            if item in self.game_state.revealed:\n                continue\n            self.game_state.revealed.append(item)\n            if self.game_state.number_mines(item[0], item[1]) > 0:\n                continue\n            directions = [(0, 1), (1, 0), (0, -1), (-1, 0), (1, 1), (-1, -1), (1, -1), (-1, 1)]\n\n            for dx, dy in directions:\n                mine_check_x = item[0] + dx\n                mine_check_y = item[1] + dy\n\n                if mine_check_x < 0 or mine_check_x >= self.game_state.width:\n                    continue\n                if mine_check_y < 0 or mine_check_y >= self.game_state.height:\n                    continue\n                queue.append((mine_check_x, mine_check_y))\n    \n",
        "idx": "1007"
    },
    {
        "instruction": "## petstagram_app/accounts/managers.py\nfrom django.contrib.auth.base_user import BaseUserManager\n\nclass AppUserManager(BaseUserManager):\n    def create_user(self, email, password=None, **extra_fields):\n        if not email:\n            raise ValueError('The Email field must be set!')\n        email = self.normalize_email(email)\n        user = self.model(email=email, **extra_fields)\n        user.set_password(password)\n        user.save(using=self._db)\n        return user\n\n    def create_superuser(self, email, password=None, **extra_fields):\n",
        "input": "",
        "output": "        extra_fields.setdefault('is_staff', True)\n        extra_fields.setdefault('is_superuser', True)\n        return self.create_user(email, password, **extra_fields)\n    \n",
        "idx": "1016"
    },
    {
        "instruction": "# Here are some relevant code fragments from other files of the repo:\n# --------------------------------------------------\n# the below code fragment can be found in:\n# src/bioprocess_mlops/utils/utils.py\n# --------------------------------------------------\n# from sklearn.base import BaseEstimator, TransformerMixin\n# \n# class SavitzkyGolayFilter:\n#     ...\n# \n# class SNV(BaseEstimator, TransformerMixin):\n#     def __init__(self):\n#         pass\n# \n#     def fit(self, X, y=None):\n#         pass\n# \n#     def transform(self, X, y=None):\n#         return X\n# \n#     def fit_transform(self, X, y=None):\n#         return X\n# \n# --------------------------------------------------\n# the below code fragment can be found in:\n# src/bioprocess_mlops/utils/__init__.py\n# --------------------------------------------------\n# from .utils import (CustomFormatter,\n#                     load_yaml,\n#                     SavitzkyGolayFilter,\n#                     SNV,\n#                     Metrics)\n# \n# --------------------------------------------------\n# the below code fragment can be found in:\n# src/bioprocess_mlops/config/config.py\n# --------------------------------------------------\n# from dataclasses import dataclass\n# \n# from typing import Any, Dict\n# \n# class PreprocessingConfig:\n#     steps: Dict[str, Dict[str, Any]]\n#     order: list\n#     artifacts_path: Dict[str, str]\n# \n# --------------------------------------------------\n\n\n## src/bioprocess_mlops/components/data_transformation.py\nimport logging\n\nfrom sklearn.preprocessing import StandardScaler, FunctionTransformer\n\nfrom sklearn.pipeline import Pipeline\n\nimport skops.io as sio\n\nfrom typing import List, Tuple, Any\n\nfrom bioprocess_mlops.config.config import PreprocessingConfig\n\nfrom bioprocess_mlops.utils import SavitzkyGolayFilter, SNV\n\nlogger = logging.getLogger(__name__)\n\nclass DataTransformation:\n    def __init__(self,\n                 preprocessing_config: PreprocessingConfig):\n        self.preprocessing_config = preprocessing_config\n\n    def _validate_order_config(self) -> bool:\n",
        "input": "",
        "output": "        enabled_steps = {\n            name for name, config in self.preprocessing_config.steps.items()\n            if config['enabled']\n        }\n        order_steps = self.preprocessing_config.order\n\n        if ((len(enabled_steps) != len(order_steps)) or (enabled_steps !=\n                                                         set(order_steps))):\n            raise ValueError(\n                f\"Mismatch in configuration. Enabled steps: {enabled_steps}, \"\n                f\"Order specified: {self.preprocessing_config.order}\"\n                )\n    \n",
        "idx": "1023"
    },
    {
        "instruction": "## db.py\nimport sqlite3\n\nclass database:\n\n    def __init__(self, db_file):\n        self.connection = sqlite3.connect(db_file, check_same_thread=False)\n        self.cursor = self.connection.cursor()\n        # create a new database table if not exists\n        self.cursor.execute(\"\"\"\nCREATE TABLE IF NOT EXISTS users (\n                            id INTEGER PRIMARY KEY, \n                            user_id INTEGER UNIQUE NOT NULL, \n                            username TEXT, \n                            user_group TEXT, \n                            join_date DATETIME NOT NULL DEFAULT ((DATETIME('now'))), \n                            last_schedule_request_time REAL DEFAULT 0, \n                            last_group_request_time REAL DEFAULT 0,\n                            last_ping_request_time REAL DEFAULT 0)\n\"\"\")\n        # here goes checks for all new columns that were added with updates\n        self.add_column_if_not_exists('last_ping_request_time', 'REAL', 0)\n    \n    # guess what does this do\n    def add_column_if_not_exists(self, c_name: str, c_type: str, c_default=None):\n        # fetch all columns from database\n        columns = [info[1] for info in self.cursor.execute('PRAGMA table_info(users)').fetchall()]\n        # add new column if there is not\n        if c_name not in columns:\n            # DEFAULT is set\n            if c_default is not None:\n                self.cursor.execute(f'ALTER TABLE users ADD COLUMN {c_name} {c_type} DEFAULT {c_default}')\n            # DEFAULT is not set\n            else:\n                self.cursor.execute(f'ALTER TABLE users ADD COLUMN {c_name} {c_type}')\n        return self.connection.commit()\n\n    def user_exists(self, user_id):\n",
        "input": "",
        "output": "        result = self.cursor.execute('SELECT id FROM users WHERE user_id = ?', (user_id,))\n        return bool(len(result.fetchall()))\n    \n",
        "idx": "1024"
    },
    {
        "instruction": "## db.py\nimport sqlite3\n\nclass database:\n\n    def __init__(self, db_file):\n        self.connection = sqlite3.connect(db_file, check_same_thread=False)\n        self.cursor = self.connection.cursor()\n        # create a new database table if not exists\n        self.cursor.execute(\"\"\"\nCREATE TABLE IF NOT EXISTS users (\n                            id INTEGER PRIMARY KEY, \n                            user_id INTEGER UNIQUE NOT NULL, \n                            username TEXT, \n                            user_group TEXT, \n                            join_date DATETIME NOT NULL DEFAULT ((DATETIME('now'))), \n                            last_schedule_request_time REAL DEFAULT 0, \n                            last_group_request_time REAL DEFAULT 0,\n                            last_ping_request_time REAL DEFAULT 0)\n\"\"\")\n        # here goes checks for all new columns that were added with updates\n        self.add_column_if_not_exists('last_ping_request_time', 'REAL', 0)\n    \n    # guess what does this do\n    def add_column_if_not_exists(self, c_name: str, c_type: str, c_default=None):\n        # fetch all columns from database\n        columns = [info[1] for info in self.cursor.execute('PRAGMA table_info(users)').fetchall()]\n        # add new column if there is not\n        if c_name not in columns:\n            # DEFAULT is set\n            if c_default is not None:\n                self.cursor.execute(f'ALTER TABLE users ADD COLUMN {c_name} {c_type} DEFAULT {c_default}')\n            # DEFAULT is not set\n            else:\n                self.cursor.execute(f'ALTER TABLE users ADD COLUMN {c_name} {c_type}')\n        return self.connection.commit()\n\n    # Check if user exists\n    def user_exists(self, user_id):\n        result = self.cursor.execute('SELECT id FROM users WHERE user_id = ?', (user_id,))\n        return bool(len(result.fetchall()))\n    \n    def user_has_group(self, user_id):\n",
        "input": "",
        "output": "        result = self.cursor.execute('SELECT user_group FROM users WHERE user_id = ?', (user_id,))\n        return bool(len(result.fetchall()))\n    \n",
        "idx": "1025"
    },
    {
        "instruction": "## db.py\nimport sqlite3\n\nclass database:\n\n    def __init__(self, db_file):\n        self.connection = sqlite3.connect(db_file, check_same_thread=False)\n        self.cursor = self.connection.cursor()\n        # create a new database table if not exists\n        self.cursor.execute(\"\"\"\nCREATE TABLE IF NOT EXISTS users (\n                            id INTEGER PRIMARY KEY, \n                            user_id INTEGER UNIQUE NOT NULL, \n                            username TEXT, \n                            user_group TEXT, \n                            join_date DATETIME NOT NULL DEFAULT ((DATETIME('now'))), \n                            last_schedule_request_time REAL DEFAULT 0, \n                            last_group_request_time REAL DEFAULT 0,\n                            last_ping_request_time REAL DEFAULT 0)\n\"\"\")\n        # here goes checks for all new columns that were added with updates\n        self.add_column_if_not_exists('last_ping_request_time', 'REAL', 0)\n    \n    # guess what does this do\n    def add_column_if_not_exists(self, c_name: str, c_type: str, c_default=None):\n        # fetch all columns from database\n        columns = [info[1] for info in self.cursor.execute('PRAGMA table_info(users)').fetchall()]\n        # add new column if there is not\n        if c_name not in columns:\n            # DEFAULT is set\n            if c_default is not None:\n                self.cursor.execute(f'ALTER TABLE users ADD COLUMN {c_name} {c_type} DEFAULT {c_default}')\n            # DEFAULT is not set\n            else:\n                self.cursor.execute(f'ALTER TABLE users ADD COLUMN {c_name} {c_type}')\n        return self.connection.commit()\n\n    # Check if user exists\n    def user_exists(self, user_id):\n        result = self.cursor.execute('SELECT id FROM users WHERE user_id = ?', (user_id,))\n        return bool(len(result.fetchall()))\n    \n    # Check if user has group\n    def user_has_group(self, user_id):\n        result = self.cursor.execute('SELECT user_group FROM users WHERE user_id = ?', (user_id,))\n        return bool(len(result.fetchall()))\n    \n    # Add user to database\n    def add_user(self, user_id, username):\n        self.cursor.execute('INSERT INTO users (`user_id`, `username`, `last_schedule_request_time`, `last_group_request_time`) VALUES (?, ?, ?, ?)', (user_id, username, 0, 0))\n        return self.connection.commit()\n    \n    # set value in given column\n    def update_value(self, user_id: int, column: str, value: None):\n        self.cursor.execute(f'UPDATE users SET {column} = \\'{value}\\' WHERE user_id = {user_id}')\n        return self.connection.commit()\n\n    def get_value(self, user_id: int, column: str):\n",
        "input": "",
        "output": "        result = self.cursor.execute(f'SELECT {column} FROM users WHERE user_id = {user_id}')\n        return result.fetchone()[0]\n    \n",
        "idx": "1026"
    },
    {
        "instruction": "## db.py\nimport sqlite3\n\nclass database:\n\n    def __init__(self, db_file):\n        self.connection = sqlite3.connect(db_file, check_same_thread=False)\n        self.cursor = self.connection.cursor()\n        # create a new database table if not exists\n        self.cursor.execute(\"\"\"\nCREATE TABLE IF NOT EXISTS users (\n                            id INTEGER PRIMARY KEY, \n                            user_id INTEGER UNIQUE NOT NULL, \n                            username TEXT, \n                            user_group TEXT, \n                            join_date DATETIME NOT NULL DEFAULT ((DATETIME('now'))), \n                            last_schedule_request_time REAL DEFAULT 0, \n                            last_group_request_time REAL DEFAULT 0,\n                            last_ping_request_time REAL DEFAULT 0)\n\"\"\")\n        # here goes checks for all new columns that were added with updates\n        self.add_column_if_not_exists('last_ping_request_time', 'REAL', 0)\n    \n    # guess what does this do\n    def add_column_if_not_exists(self, c_name: str, c_type: str, c_default=None):\n        # fetch all columns from database\n        columns = [info[1] for info in self.cursor.execute('PRAGMA table_info(users)').fetchall()]\n        # add new column if there is not\n        if c_name not in columns:\n            # DEFAULT is set\n            if c_default is not None:\n                self.cursor.execute(f'ALTER TABLE users ADD COLUMN {c_name} {c_type} DEFAULT {c_default}')\n            # DEFAULT is not set\n            else:\n                self.cursor.execute(f'ALTER TABLE users ADD COLUMN {c_name} {c_type}')\n        return self.connection.commit()\n\n    # Check if user exists\n    def user_exists(self, user_id):\n        result = self.cursor.execute('SELECT id FROM users WHERE user_id = ?', (user_id,))\n        return bool(len(result.fetchall()))\n    \n    # Check if user has group\n    def user_has_group(self, user_id):\n        result = self.cursor.execute('SELECT user_group FROM users WHERE user_id = ?', (user_id,))\n        return bool(len(result.fetchall()))\n    \n    # Add user to database\n    def add_user(self, user_id, username):\n        self.cursor.execute('INSERT INTO users (`user_id`, `username`, `last_schedule_request_time`, `last_group_request_time`) VALUES (?, ?, ?, ?)', (user_id, username, 0, 0))\n        return self.connection.commit()\n    \n    # set value in given column\n    def update_value(self, user_id: int, column: str, value: None):\n        self.cursor.execute(f'UPDATE users SET {column} = \\'{value}\\' WHERE user_id = {user_id}')\n        return self.connection.commit()\n\n    # get value from given column\n    def get_value(self, user_id: int, column: str):\n        result = self.cursor.execute(f'SELECT {column} FROM users WHERE user_id = {user_id}')\n        return result.fetchone()[0]\n\n    def get_all_values(self, column: str):\n",
        "input": "",
        "output": "        result = self.cursor.execute(f'SELECT {column} FROM users')\n        return result.fetchall()\n    \n",
        "idx": "1027"
    },
    {
        "instruction": "## Predator.py\nfrom typing import Callable, List, Dict, Optional\n\nfrom inspect import signature as sig, Parameter, stack as inspect_stack\n\nfrom os import path\n\nfrom asyncio import CancelledError, to_thread, run, sleep, create_task\n\nfrom aiohttp import web, ClientConnectionError\n\nfrom datetime import datetime as dt, timedelta\n\nimport time\n\np = print\n\nclass MyDict:\n    async def init(app, **kwargs):\n        app.__dict__.update(kwargs)\n        return app\n\n    async def get(app):\n        return app.__dict__\n\nclass Stuff:\n    @classmethod\n    async def headers(app, **kwargs):\n        response_headers = {\n            'Server': 'Predator',\n            'Strict-Transport-Security': 'max-age=63072000; includeSubdomains', \n            'X-Frame-Options': 'SAMEORIGIN',\n            'X-XSS-Protection': '1; mode=block',\n            'Referrer-Policy': 'origin-when-cross-origin'\n        }\n\n        if kwargs:\n            response_headers.update(**kwargs)\n\n        return response_headers\n\nclass Error(Exception):\n    def __init__(app, message=None):\n        super().__init__(message)\n        app.message = str(message)\n\n    def __str__(app) -> str:\n        return app.message\n\nclass Abort(Exception):\n    def __init__(app, message=\"Something went wrong\", **kwargs):\n        super().__init__(message)\n        app.message = str(message)\n        app.kwargs = kwargs\n\n    def __str__(app) -> str:\n        return app.message\n\n    async def text(app, r):\n        await Log.out(app.message)\n        response = web.Response(\n            status = app.kwargs.get(\"status\", 403),\n            text = app.message,\n            headers = app.kwargs.get(\"headers\", {})\n        )\n\n        r.response = response\n        return response\n\nclass Pack:\n    @classmethod\n    async def set(app, **kwargs):\n        app = app()\n        app.__dict__.update(kwargs)\n        return app\n\nclass Log:\n    @classmethod\n    async def out_(app, e):\n        try:\n            e = str(e).strip()\n            fname = inspect_stack()[1].function\n            log = False\n\n            known_exceps = [\n                \"transport\",\n                \"Task\",\n                \"Cannot write\",\n                \"closing transport\",\n                \"Cannot write to closing transport\"\n            ]\n            for a in known_exceps:\n                if a in e:\n                    log = False\n                    break\n                else:\n                    log = True\n\n            if log:\n                e = \"[%s]:: %s ::\" % (\n                    fname,\n                    e\n                )\n                print(\"$: %s\" % (e))\n        except Exception as e:\n            print(e)\n    \n    @classmethod\n    async def out(app, e):\n        try:\n            e = str(e).strip()\n            log = False\n\n            known_exceps = [\n                \"transport\",\n                \"Task\",\n                \"Cannot write\",\n                \"closing transport\",\n                \"Cannot write to closing transport\"\n            ]\n            for a in known_exceps:\n                if a in e:\n                    log = False\n                    break\n                else:\n                    log = True\n\n            if log:\n                print(\"$ (%s): %s\" % (dt.now(), e))\n        except Exception as e:\n            print(e)\n\nclass Request:\n    @classmethod\n    async def gen(app, request):\n        app = app() # Immutable dict\n        app.request = request\n        app.json = request.json\n        app.content = request.content\n        app.response = None\n        app.tail = request.path\n        app.params = request.query\n        app.headers = request.headers\n        app.method = request.method\n        app.ip = request.remote\n        app.route_name = request.path\n\n        return app\n\nclass WebApp:\n    environment = \"development\"\n    @classmethod\n    async def init(app, **kwargs):\n        app = app()\n        app.__dict__.update(kwargs)\n        app.web = web\n        app.response_headers = await Stuff.headers()\n        app.dev = 1\n\n        app.routes = await Pack.set()\n        app.ddos_protection = 0\n        app.throttle_at_ram = 0.20\n        app.secure_host = 0\n        app.requests_count = 0\n        app.default_methods = [\"GET\", \"POST\", \"OPTIONS\", \"PUT\", \"PATCH\", \"HEAD\", \"DELETE\"]\n\n        return app\n    \n    def add_route_sync(app, route_name: str, incoming_data: dict):\n",
        "input": "",
        "output": "        if not (func := incoming_data.get(\"func\")):\n            raise Error(\"func is required\")\n        \n        if not isinstance(func, (Callable,)):\n            raise Error(\"func is not Callable\")\n\n        signature = sig(func)\n        params = dict(signature.parameters)\n\n        methods_param = params.get(\"methods\", None)\n        if methods_param:\n            methods = methods_param.default\n        else:\n            methods = app.default_methods\n\n        if isinstance(methods, list):\n            methods = {method: True for method in methods}\n        elif isinstance(methods, str):\n            methods = {methods: True}\n\n        data = {\n            \"func\": func,\n            \"methods\": methods,\n            \"params\": incoming_data.get(\"params\", {})\n        }\n    \n        app.routes.__dict__[route_name] = data\n    \n",
        "idx": "1028"
    },
    {
        "instruction": "## LinkedList/dataStructures.py\nclass Node:\n    def __init__(self, value):\n        self.value = value\n        self.next = None\n\nclass LinkedList:\n    def __init__(self):\n        self.head = None\n\n    def append(self, value):\n        new_node = Node(value)\n\n        if self.head == None:\n            self.head = new_node\n            return\n        else:\n            current = self.head\n\n            while current.next:\n                current = current.next\n            current.next = new_node\n\n    def nodo_de_medio(self, start, end):\n",
        "input": "",
        "output": "        slow = start\n        fast = start\n\n        while fast != end and fast.next != end:\n            slow = slow.next\n            fast = fast.next.next\n\n        return slow\n    \n",
        "idx": "1030"
    },
    {
        "instruction": "## LinkedList/dataStrucutreBinarySearchGraphically.py\nclass Node:\n    def __init__(self, data):\n        self.data = data\n        self.next = None\n\nclass LinkedList:\n    def __init__(self):\n        self.head = None\n\n    def append(self, data):\n",
        "input": "",
        "output": "        new_node = Node(data)\n        if not self.head:\n            self.head = new_node\n            return\n\n        last = self.head\n        while last.next:\n            last = last.next\n        last.next = new_node\n    \n",
        "idx": "1031"
    },
    {
        "instruction": "## LinkedList/dataStrucutreBinarySearchGraphically.py\nclass Node:\n    def __init__(self, data):\n        self.data = data\n        self.next = None\n\nclass LinkedList:\n    def __init__(self):\n        self.head = None\n\n    def append(self, data):\n        new_node = Node(data)\n        if not self.head:\n            self.head = new_node\n            return\n\n        last = self.head\n        while last.next:\n            last = last.next\n        last.next = new_node\n\n    def medio(self, start, end):\n",
        "input": "",
        "output": "        slow = start\n        fast = start\n\n        # Find the middle element between start and end\n        while fast != end and fast.next != end:\n            slow = slow.next\n            fast = fast.next.next\n        return slow\n    \n",
        "idx": "1032"
    },
    {
        "instruction": "## LinkedList/dataStrucutreBinarySearchGraphically.py\nclass Node:\n    def __init__(self, data):\n        self.data = data\n        self.next = None\n\nclass LinkedList:\n    def __init__(self):\n        self.head = None\n\n    def append(self, data):\n        new_node = Node(data)\n        if not self.head:\n            self.head = new_node\n            return\n\n        last = self.head\n        while last.next:\n            last = last.next\n        last.next = new_node\n\n    def medio(self, start, end):\n        slow = start\n        fast = start\n\n        # Find the middle element between start and end\n        while fast != end and fast.next != end:\n            slow = slow.next\n            fast = fast.next.next\n        return slow\n\n    def binary_search(self, start, end, target):\n",
        "input": "",
        "output": "        if start == end:\n            print(\"Reached the end of the search range. Element not found.\")\n            return None\n\n        # Find the middle node\n        middle = self.medio(start, end)\n\n        # Visualization of the current step\n        start_data = start.data if start else \"None\"\n        end_data = end.data if end else \"None\"\n        middle_data = middle.data if middle else \"None\"\n        print(\n            f\"\\nSearching in range: Start={start_data}, Middle={middle_data}, End={end_data}\")\n\n        # Check if the middle node contains the target\n        if middle.data == target:\n            print(f\"Element {target} found at node with value {middle.data}.\")\n            return middle\n        elif middle.data < target:\n            print(\n                f\"Target {target} is greater than {middle.data}. Searching in the right half.\")\n            # Recursively search in the right half\n            return self.binary_search(middle.next, end, target)\n        else:\n            print(\n                f\"Target {target} is less than {middle.data}. Searching in the left half.\")\n            # Recursively search in the left half\n            return self.binary_search(start, middle, target)\n    \n",
        "idx": "1033"
    },
    {
        "instruction": "## LinkedList/linked_list_ayudantia1.py\nclass Node:\n    def __init__(self, value):\n        self.value = value\n        self.next = None\n\nclass LinkedList:\n    def __init__(self):\n        self.head = None\n\n    def append(self, value):\n",
        "input": "",
        "output": "        new_node = Node(value)\n\n        if self.head == None:\n            self.head = new_node\n            return\n    \n        current = self.head\n        while current.next != None:\n            current = current.next\n        \n        current.next = new_node\n    \n",
        "idx": "1034"
    },
    {
        "instruction": "## LinkedList/linked_list_ayudantia1.py\nclass Node:\n    def __init__(self, value):\n        self.value = value\n        self.next = None\n\nclass LinkedList:\n    def __init__(self):\n        self.head = None\n\n    def append(self, value):\n        new_node = Node(value)\n\n        if self.head == None:\n            self.head = new_node\n            return\n    \n        current = self.head\n        while current.next != None:\n            current = current.next\n        \n        current.next = new_node\n\n\n    def append_recursive(self, nodo, value ):\n        if nodo == None:\n            return Node(value)\n        \n        nodo.next = self.append_recursive(nodo.next, value)\n        return nodo\n\n    def print_list(self):\n        if self.head is None:\n            print(\"La lista est\u00e1 vac\u00eda\")\n            return\n\n        current = self.head\n        while current is not None:\n            print(current.value, end=\" -> \")\n            current = current.next\n        print(\"None\")\n\n\n    def print_list_recurive(self, nodo):\n        if nodo == None:\n            print(\"None:\")\n            return\n        print(nodo.value, end=\" -> \")\n        self.print_list_recurive(nodo.next)\n        \n        \n    def buscar_recursivamente(self, nodo, value):\n",
        "input": "",
        "output": "        if nodo == None:\n            return False\n        if nodo.value == value: #4 == 7\n            return True\n        \n        return self.buscar_recursivamente(nodo.next, value)\n    \n",
        "idx": "1037"
    },
    {
        "instruction": "## LinkedList/linked_list_ayudantia1.py\nclass Node:\n    def __init__(self, value):\n        self.value = value\n        self.next = None\n\nclass LinkedList:\n    def __init__(self):\n        self.head = None\n\n    def append(self, value):\n        new_node = Node(value)\n\n        if self.head == None:\n            self.head = new_node\n            return\n    \n        current = self.head\n        while current.next != None:\n            current = current.next\n        \n        current.next = new_node\n\n\n    def append_recursive(self, nodo, value ):\n        if nodo == None:\n            return Node(value)\n        \n        nodo.next = self.append_recursive(nodo.next, value)\n        return nodo\n\n    def print_list(self):\n        if self.head is None:\n            print(\"La lista est\u00e1 vac\u00eda\")\n            return\n\n        current = self.head\n        while current is not None:\n            print(current.value, end=\" -> \")\n            current = current.next\n        print(\"None\")\n\n\n    def print_list_recurive(self, nodo):\n        if nodo == None:\n            print(\"None:\")\n            return\n        print(nodo.value, end=\" -> \")\n        self.print_list_recurive(nodo.next)\n        \n        \n    def buscar_recursivamente(self, nodo, value):\n        if nodo == None:\n            return False\n        if nodo.value == value: #4 == 7\n            return True\n        \n        return self.buscar_recursivamente(nodo.next, value)\n\n\n    def delete_value(self, value):\n        if self.head == None:\n            print(\"La lista no contiene ning\u00f9n nodo\")\n            return\n        \n        if self.head.value == value:\n            self.head = self.head.next\n\n        current = self.head\n        while current.next is not None:\n            if current.next.value == value:\n                current.next = current.next.next\n                return\n            current = current.next\n\n\n    def insertar_valor(self, valor, index):\n        new_node = Node(valor)\n\n        if index == 0:\n            new_node.next = self.head\n            self.head = new_node\n            return\n\n        contador = 0\n        current = self.head\n        while current.next != None and contador < index:\n            current = current.next\n            contador += 1\n\n        if current.next == None:\n            print(\"No es posible ingresa un nuevo nodo con un nuevo valor, puesto que la lista es m\u00e0s peque\u00f1a\")\n            return\n\n\n        new_node.next = current.next\n        current.next = new_node\n        print(\"nodo con su valor agregado correctamente a la lista\")\n        return\n\n    def largo(self):\n        if self.head == None:\n            print(\"La lista esta vacia, no hay nodos\")\n            return\n        \n        contador = 0\n        current = self.head\n        while current.next != None:\n            current = current.next\n            contador += 1\n        print(f\"El largo de la lista es: {contador}\")\n        return\n\n\n    def largo_recursivo(self, nodo):\n        if nodo == None:\n            return 0\n        \n        return 1 + self.largo_recursivo(nodo.next) # 1 + (1 + (1 + (1 +(1 + (1 + (0))))))\n\n\n    def encontrar_mayor(self):\n",
        "input": "",
        "output": "        if self.head == None:\n            return None\n\n        mayor = self.head.value\n\n        current = self.head.next\n\n        while current != None:\n            if current.value > mayor:\n                mayor = current.value\n\n            current = current.next\n\n        return mayor\n    \n",
        "idx": "1041"
    }
]