import os
import re

from pandas_datareader.base import _DailyBaseReader

class QuandlReader(_DailyBaseReader):
    """
    Returns DataFrame of historical stock prices from symbol, over date
    range, start to end.

    .. versionadded:: 0.5.0

    Parameters
    ----------
    symbols : string
        Possible formats:
        1. DB/SYM: The Quandl 'codes': DB is the database name,
        SYM is a ticker-symbol-like Quandl abbreviation
        for a particular security.
        2. SYM.CC: SYM is the same symbol and CC is an ISO country code,
        will try to map to the best single Quandl database for that country.
        Beware of ambiguous symbols (different securities per country)!
        Note: Cannot use more than a single string because of the inflexible
        way the URL is composed of url and _get_params in the superclass
    start : string, int, date, datetime, Timestamp
        Starting date. Parses many different kind of date
        representations (e.g., 'JAN-01-2010', '1/1/10', 'Jan, 1, 1980'). Defaults to
        20 years before current date.
    end : string, int, date, datetime, Timestamp
        Ending date
    retry_count : int, default 3
        Number of times to retry query request.
    pause : int, default 0.1
        Time, in seconds, to pause between consecutive queries of chunks. If
        single value given for symbol, represents the pause between retries.
    chunksize : int, default 25
        Number of symbols to download consecutively before initiating pause.
    session : Session, default None
        requests.sessions.Session instance to be used
    api_key : str, optional
        Quandl API key . If not provided the environmental variable
        QUANDL_API_KEY is read. The API key is *required*.
    """

    _BASE_URL = "https://www.quandl.com/api/v3/datasets/"

    def __init__(
        self,
        symbols,
        start=None,
        end=None,
        retry_count=3,
        pause=0.1,
        session=None,
        chunksize=25,
        api_key=None,
    ):
        super().__init__(symbols, start, end, retry_count, pause, session, chunksize)
        if api_key is None:
            api_key = os.getenv("QUANDL_API_KEY")
        if not api_key or not isinstance(api_key, str):
            raise ValueError(
                "The Quandl API key must be provided either "
                "through the api_key variable or through the "
                "environmental variable QUANDL_API_KEY."
            )
        self.api_key = api_key

    @property
    def url(self):
        """API URL"""
        symbol = self.symbols if isinstance(self.symbols, str) else self.symbols[0]
        mm = self._fullmatch(r"([A-Z0-9]+)(([/\.])([A-Z0-9_]+))?", symbol)
        assert mm, "Symbol '%s' must conform to Quandl convention 'DB/SYM'" % symbol
        datasetname = "WIKI"
        if not mm.group(2):
            # bare symbol:
            datasetname = "WIKI"  # default; symbol stays itself
        elif mm.group(3) == "/":
            # --- normal Quandl DB/SYM convention:
            symbol = mm.group(4)
            datasetname = mm.group(1)
        elif mm.group(3) == ".":
            # secondary convention SYM.CountryCode:
            symbol = mm.group(1)
            datasetname = self._db_from_countrycode(mm.group(4))
        params = {
            "start_date": self.start.strftime("%Y-%m-%d"),
            "end_date": self.end.strftime("%Y-%m-%d"),
            "order": "asc",
            "api_key": self.api_key,
        }
        paramstring = "&".join([f"{k}={v}" for k, v in params.items()])
        url = "{url}{dataset}/{symbol}.csv?{params}"
        return url.format(
            url=self._BASE_URL, dataset=datasetname, symbol=symbol, params=paramstring
        )

    def _fullmatch(self, regex, string, flags=0):
        """Emulate python-3.4 re.fullmatch()."""
        return re.match("(?:" + regex + r")\Z", string, flags=flags)

    _COUNTRYCODE_TO_DATASET = dict(
        # https://www.quandl.com/data/EURONEXT-Euronext-Stock-Exchange
        BE="EURONEXT",
        # https://www.quandl.com/data/HKEX-Hong-Kong-Exchange
        CN="HKEX",
        # https://www.quandl.com/data/SSE-Boerse-Stuttgart
        DE="SSE",
        FR="EURONEXT",
        # https://www.quandl.com/data/NSE-National-Stock-Exchange-of-India
        IN="NSE",
        # https://www.quandl.com/data/TSE-Tokyo-Stock-Exchange
        JP="TSE",
        NL="EURONEXT",
        PT="EURONEXT",
        # https://www.quandl.com/data/LSE-London-Stock-Exchange
        UK="LSE",
        # https://www.quandl.com/data/WIKI-Wiki-EOD-Stock-Prices
        US="WIKI",
    )

    def _db_from_countrycode(self, code):
        assert code in self._COUNTRYCODE_TO_DATASET, (
            "No Quandl dataset known for country code '%s'" % code
        )
        return self._COUNTRYCODE_TO_DATASET[code]

    def _get_params(self, symbol):
        return {}

    def read(self):
        """Read data"""
        df = super().read()
        df.rename(
            columns=lambda n: n.replace(" ", "")
            .replace(".", "")
            .replace("/", "")
            .replace("%", "")
            .replace("(", "")
            .replace(")", "")
            .replace("'", "")
            .replace("-", ""),
            inplace=True,
        )
        return df


import re

pattern = "подпишитесь|лайкните|поставьте лайк|ищу|оставите реакцию|помогите|нужна помощь|инстаграм|в профиле|" \
          "instagram|подписывайтесь|прайс|подпиской|комментариями|комментарий|лайки|в директ|\.by|https|http|\.ru|" \
          "мастер-класс|практики|для записи|цена"

def check_message_for_buzz_words(message: str):

    # # Combine the patterns into a single regular expression
    # regex = re.compile('|'.join(patterns), re.IGNORECASE)

    # Find matches in the text
    matches = re.findall(pattern, message.lower())

    return matches

def add_name_to_message(message, name):
    # Extract the last number from the string
    print(message)
    numbers = re.findall(r'\n(\d+)\.', message)
    print(numbers)
    if numbers:
        last_number = numbers[-1]

        # Increment the last number and add the next name
        next_number = int(last_number) + 1

        # Append the new number and name to the string
        new_string = message + f"\n{next_number}. {name}"

    else:
        new_string = message + f"\n\nУже помогли:\n1. {name}"

    return new_string

def replace_numbers(match, number_to_delete):
    number = int(match.group(1))
    if number > number_to_delete:
        number -= 1
    return f"\n{number}."

def remove_name_from_message(message, name):
    # Find the row with the specified name
    name_pattern = fr"\n(\d+)\.\s{re.escape(name)}(?!\w)"
    matches = re.findall(name_pattern, message)

    if matches:
        # Remove the row with the specified name
        number_to_delete = int(matches[0])
        new_string = re.sub(name_pattern, "", message)

        # Update the numbers of the remaining rows
        number_pattern = r"\n(\d+)\."

        new_string = re.sub(number_pattern, lambda match: replace_numbers(match, number_to_delete), new_string)

        number_pattern_for_find = r"1\."

        has_people = re.findall(number_pattern_for_find, new_string)
        print(has_people, 'has people')

        if not has_people:
            print('inside')
            new_string = new_string.replace('Уже помогли:', '')

        return new_string
    else:
        return message

# def create_patterns(words: list[str]):
#     res = []
#     for word in words:
#         for letter in word:
#             res.append(r'\b' + word.replace(letter, '.', 1) + r'\b')
#         res.append(r'\b' + word[:-1] + '.' + r'\b')
#         res.append(r'\b' + word + '.' + r'\b')
#         res.append(r'\b' + '.' + word + r'\b')
#     print(set(res))
#     return list(set(res))

# create_patterns(['сметана'])

# print(check_message_for_buzz_words('см*тана Смметана Пароль сметана*'))
# print(check_message_for_buzz_words("""14 июня, сегодня, 19. 00
# На сцене Молодёжного театра эстрады.
# Билеты в кассе театра и на kvitki.by"""))

if __name__ == '__main__':
    # print(add_name_to_message('1. Антон', 'Дима'))
    print(remove_name_from_message('1. Антон\n2. Дима', 'Дима'))


import os
from setuptools import setup

dir_path = os.path.dirname(os.path.abspath(__file__))

description = """pyfred"""
package_name = "pyfred"
requirements = open(os.path.join(dir_path, "requirements.txt")).read()
test_requirements = open(os.path.join(dir_path, "test_requirements.txt")).read()
version = open(os.path.join(dir_path, "VERSION")).read().strip()

def package_files():
    paths = []
    for (path, directories, filenames) in os.walk(package_name):
        for filename in filenames:
            paths.append(os.path.join('..', path, filename))
    return paths

setup(
    name=package_name,
    version=version,
    description=description,
    install_requires=requirements,
    extras_require={
        'test':  test_requirements,
    },
    packages=[package_name],
    package_data={'': package_files()},
    entry_points={

    },
    author="Jason Darnell",
    email="jasdarnell@gmail.com",
    license="MIT",
    url=""
)


from base_tree import TreeNode

class Codec:

    def serialize(self, root):
        """Encodes a tree to a single string.

        :type root: TreeNode
        :rtype: str
        """
        res = []
        def dfs(root):
            if not root:
                res.append("#")
                return
            res.append(str(root.val))
            dfs(root.left)
            dfs(root.right)
        dfs(root)
        return ",".join(res)

    def deserialize(self, data):
        """Decodes your encoded data to tree.

        :type data: str
        :rtype: TreeNode
        """
        data = data.split(",")
        def dfs(data):
            val = data.pop(0)
            if val == "#":
                return
            root = TreeNode(val)
            root.left = dfs(data)
            root.right = dfs(data)
            return root
        return dfs(data)

if __name__ == "__main__":
    tree = TreeNode(1, left=TreeNode(2, left=TreeNode(4), right=TreeNode(5)),
                    right=TreeNode(3, left=TreeNode(6), right=TreeNode(7)))

    solution = Codec()
    my_serialize = solution.serialize(tree)
    print(my_serialize)
    my_deserialize = solution.deserialize(my_serialize)
    print(my_deserialize)

二叉树/二叉树的序列化与反序列化.py

二叉树的序列化与反序列化.py


from guardian.shortcuts import assign_perm

from kitsune.access.utils import has_perm
from kitsune.forums.tests import ForumFactory
from kitsune.sumo.tests import TestCase
from kitsune.users.tests import UserFactory, GroupFactory

class ForumTestPermissions(TestCase):
    """Make sure access helpers work on the forums."""

    def setUp(self):
        self.group = GroupFactory()

        # Set up forum_1
        self.forum_1 = ForumFactory()
        permission_names = [
            "forums.delete_forum_thread",
            "forums.edit_forum_thread",
            "forums.move_forum_thread",
            "forums.sticky_forum_thread",
            "forums.delete_forum_thread_post",
            "forums.edit_forum_thread_post",
        ]
        for name in permission_names:
            assign_perm(name, self.group, self.forum_1)

        # Set up forum_2
        self.forum_2 = ForumFactory()
        assign_perm("forums.move_forum_thread", self.group, self.forum_2)

    def test_has_perm_thread_edit(self):
        """User in group can edit thread in forum_1, but not in forum_2."""
        user = UserFactory()
        self.group.user_set.add(user)
        self.assertTrue(has_perm(user, "forums.edit_forum_thread", self.forum_1))
        self.assertFalse(has_perm(user, "forums.edit_forum_thread", self.forum_2))

    def test_has_perm_thread_delete(self):
        """User in group can delete thread in forum_1, but not in forum_2."""
        user = UserFactory()
        self.group.user_set.add(user)
        self.assertTrue(has_perm(user, "forums.delete_forum_thread", self.forum_1))
        self.assertFalse(has_perm(user, "forums.delete_forum_thread", self.forum_2))

    def test_has_perm_thread_sticky(self):
        """
        User in group can change sticky status of thread in forum_1, but not in forum_2.
        """
        user = UserFactory()
        self.group.user_set.add(user)
        self.assertTrue(has_perm(user, "forums.sticky_forum_thread", self.forum_1))
        self.assertFalse(has_perm(user, "forums.sticky_forum_thread", self.forum_2))

    def test_has_perm_thread_locked(self):
        """User in group has no permission to change locked status in forum_1."""
        user = UserFactory()
        self.group.user_set.add(user)
        self.assertFalse(has_perm(user, "forums.lock_forum_thread", self.forum_1))

    def test_has_perm_post_edit(self):
        """User in group can edit any post in forum_1, but not in forum_2."""
        user = UserFactory()
        self.group.user_set.add(user)
        self.assertTrue(has_perm(user, "forums.edit_forum_thread_post", self.forum_1))
        self.assertFalse(has_perm(user, "forums.edit_forum_thread_post", self.forum_2))

    def test_has_perm_post_delete(self):
        """User in group can delete posts in forum_1, but not in forum_2."""
        user = UserFactory()
        self.group.user_set.add(user)
        self.assertTrue(has_perm(user, "forums.delete_forum_thread_post", self.forum_1))
        self.assertFalse(has_perm(user, "forums.delete_forum_thread_post", self.forum_2))

    def test_no_perm_thread_delete(self):
        """User not in group cannot delete thread in any forum."""
        user = UserFactory()
        self.assertFalse(has_perm(user, "forums.delete_forum_thread", self.forum_1))
        self.assertFalse(has_perm(user, "forums.delete_forum_thread", self.forum_2))


# importing formatting packages
import re
import os
import json
import pandas as pd
import numpy as np
import xlsxwriter
import copy
import ctypes

def getInputJson(json_path):
    with open(json_path, 'r+') as f:
        text = f.read()
        text = re.sub('[0-9]{2}_', '', text)
        f.seek(0)
        f.write(text)
        f.truncate()
    with open(json_path) as file:
        data = json.load(file)

    return data

def normalizeJson(data):

    nodes = pd.json_normalize(data, 'nodes')

    nodes.rename(columns=lambda x: x.replace('data.', ''), inplace=True)
    nodes.rename(columns=lambda x: x.replace('properties.', ''), inplace=True)
    nodes.rename(columns=lambda x: x.replace('attributes.', ''), inplace=True)
    nodes.drop(['x', 'y', 'color', 'radius', 'shape'], axis=1, inplace=True)

    edges = pd.json_normalize(data, 'edges')
    edges.rename(columns=lambda x: x.replace('data.', ''), inplace=True)
    edges.rename(columns={'properties.Source': 'Data Source'}, inplace=True)
    edges.rename(columns=lambda x: x.replace('properties.', ''), inplace=True)
    edges.rename(columns=lambda x: x.replace('attributes.', ''), inplace=True)
    edges.drop(['color', 'width'], axis=1, inplace=True)

    nodes = nodes.replace(np.nan, 'NA', regex=True)
    edges = edges.replace(np.nan, 'NA', regex=True)
    #nodes = nodes.astype(str)
    #edges = edges.astype(str)

    return nodes, edges

def getAvailableSeed(nodes):

    ava_seed_node = nodes[['PAN', 'Name']].loc[nodes['PAN'] != 'NA']
    ava_seed_node.rename(columns={"Name": "PAN Name"}, inplace=True)
    return ava_seed_node

def flattenData(nodes, edges):
    nodes['source'] = nodes['id']
    nodes['target'] = nodes['id']

    """"related_nodes = nodes[['id', 'Name', 'categories', 'Pincode', 'Financial Year',
                           'Pan Allotment Date', 'Person Of Interest flags',
                           'Last AY for which ITR filed', 'Income Range', 'Income Tax Ward/Circle',
                           'Turnover Range', 'Mobile Number', 'Date Of Birth/Incorporation',
                           'Address', 'Pincode Category', 'Nature Of Business', 'Email', 'PAN',
                           'Gender', 'latitude', 'longitude', 'Other Income Category']]

    related_links = edges.merge(nodes[['source', 'Name', 'PAN']], on='source', how='left')
    related_links.rename(columns={"Name": "Source-Name", "PAN": "Source-PAN"}, inplace=True)
    related_links = related_links.merge(nodes[['target', 'Name', 'PAN']], on='target', how='left')
    related_links.rename(columns={"Name": "Target-Name", "PAN": "Target-PAN"}, inplace=True)

    related_links = related_links[
        ['id', 'source', 'Source-Name', 'Source-PAN', 'target', 'Target-Name', 'Target-PAN', 'text', 'type',
         'Financial Year', 'Tax',
         'Transaction Amount']]

    return related_nodes, related_links"""

#Function for auto-fitting the column width

def get_col_widths2(related_nodes):
    # First we find the maximum length of the index column
    idx_max = max([len(str(s)) for s in related_nodes.index.values] + [len(str(related_nodes.index.name))])
    # Then, we concatenate this to the max of the lengths of column name and its values for each column, left to right
    return [idx_max] + [max([len(str(s)) for s in related_nodes[col].values] + [len(col)]) for col in related_nodes.columns]

# Function for auto-fitting the column width

def get_col_widths(related_links):
        # First we find the maximum length of the index column
        idx_max = max([len(str(s)) for s in related_links.index.values] + [len(str(related_links.index.name))])
        # Then, we concatenate this to the max of the lengths of column name and its values for each column, left to right
        return [idx_max] + [max([len(str(s)) for s in related_links[col].values] + [len(col)]) for col in
                            related_links.columns]

def generateXLS(seed_pan, module, nodes, edges,img_path):

    related_nodes = copy.deepcopy(nodes)
    #pdb.set_trace()
    #print(seed_pan)
    seed_node = nodes[['PAN', 'Name']].loc[nodes['Name'] == seed_pan]
    seed_node.rename(columns={"Name": "PAN Name"}, inplace=True)
    #print(seed_node)

    # Converting all date columns to Datetime format
    related_nodes[[col for col in related_nodes.columns if "Date" in col]] = related_nodes[
        [col for col in related_nodes.columns if "Date" in col]].apply(pd.to_datetime, format='%d-%b-%Y',
                                                                       errors='coerce')
    edges[[col for col in edges.columns if "Date" in col]] = edges[[col for col in edges.columns if "Date" in col]] = \
    edges[[col for col in edges.columns if "Date" in col]].apply(pd.to_datetime, format='%d%b%Y:%H:%M:%S',
                                                                 errors='coerce')

    if "TDS" in module:
        related_links = edges.merge(nodes[['source', 'text', 'PAN', 'TAN']], on='source', how='left')
        related_links.rename(columns={"text_y": "Source-Name", "PAN": "Source-PAN", 'TAN': "Source-TAN"}, inplace=True)
        related_links = related_links.merge(nodes[['target', 'text', 'PAN', 'TAN']], on='target', how='left')
        related_links.rename(columns={"text": "Target-Name", "PAN": "Target-PAN", 'TAN': "Target-TAN"}, inplace=True)
        #print("TDS")
    else:
        related_links = edges.merge(nodes[['source', 'Name', 'PAN']], on='source', how='left')
        related_links.rename(columns={"Name": "Source-Name", "PAN": "Source-PAN"}, inplace=True)
        related_links = related_links.merge(nodes[['target', 'Name', 'PAN']], on='target', how='left')
        related_links.rename(columns={"Name": "Target-Name", "PAN": "Target-PAN"}, inplace=True)
        #print('No TDS')

    #print(related_links)

    # Merging additional info columns into one column for Relation module
    if "Relation" in module:
        cols = [col for col in related_links.columns if "Additional" in col]
        related_links['Additional Relationships Info'] = related_links[cols].apply(
            lambda row: ', '.join(row.values.astype(str)), axis=1)
        related_links['Additional Relationships Info'] = related_links['Additional Relationships Info'].str.replace(
            "NA,", "")
        related_links.drop(cols, axis=1, inplace=True)
    else:
        pass
    #print(related_links)

    # Re-ordering the columns
    if "TDS" in module:
        cols_to_order = ['Source-Name', 'Source-PAN', 'Source-TAN', 'Target-Name', 'Target-PAN', 'Target-TAN']
        new_columns = cols_to_order + (related_links.columns.drop(cols_to_order).tolist())
        related_links = related_links[new_columns]
    elif "Relation" in module:
        cols_to_order = ['Source-Name', 'Source-PAN', 'Target-Name', 'Target-PAN']
        new_columns = cols_to_order + (related_links.columns.drop(cols_to_order).tolist())
        related_links = related_links[new_columns]
    else:
        cols_to_order = ['Target-Name', 'Target-PAN', 'Source-Name', 'Source-PAN']
        new_columns = cols_to_order + (related_links.columns.drop(cols_to_order).tolist())
        related_links = related_links[new_columns]
    #print(related_links)

    cols_to_order_nodes = ['Name', 'text', 'PAN', 'Pincode', 'Pincode Category', 'Address', 'Mobile Number', 'Email']
    new_columns_nodes = cols_to_order_nodes + (related_nodes.columns.drop(cols_to_order_nodes).tolist())
    related_nodes = related_nodes[new_columns_nodes]
    #print(related_nodes)

    if "TDS" in module:
        related_links.rename(
            columns={'Source-PAN': 'Deductee PAN', 'Target-PAN': 'Deductor PAN', 'Source-Name': 'Deductee Name',
                     'Target-Name': 'Deductor Name', 'Target-TAN': 'Deductor TAN', 'Source-TAN': 'Deductee TAN',
                     'type': 'TDS Type'}, inplace=True)
        related_links['TDS Type'] = related_links['TDS Type'].str.replace(u"Â", "")
        related_links['Deductee Name'], related_links['Deductor Name'] = np.where(
            related_links['TDS Type'].astype(str).str.contains('receiver') == True,
            (related_links['Deductor Name'], related_links['Deductee Name']),
            (related_links['Deductee Name'], related_links['Deductor Name']))
        related_links['Deductee PAN'], related_links['Deductor PAN'] = np.where(
            related_links['TDS Type'].astype(str).str.contains('receiver') == True,
            (related_links['Deductor PAN'], related_links['Deductee PAN']),
            (related_links['Deductee PAN'], related_links['Deductor PAN']))
        related_links.drop(['id', 'source', 'target', 'text_x', 'Financial Year', 'Deductee TAN'], axis=1, inplace=True)
        related_links['Amount Of Transaction'] = related_links['Amount Of Transaction'].map('{:,.0f}'.format)
        related_links['TDS Deducted'] = related_links['TDS Deducted'].map('{:,.0f}'.format)
    elif "Share" in module:
        related_links.rename(
            columns={'Source-PAN': 'Entity PAN', 'Target-PAN': 'Shareholder PAN', 'Source-Name': 'Entity Name',
                     'Target-Name': 'Shareholder Name'}, inplace=True)
        related_links.drop(['id', 'source', 'target', 'text', 'type', 'Financial Year'], axis=1, inplace=True)

    elif "Relation" in module:
        related_links.rename(
            columns={'Source-PAN': 'Seed Node PAN', 'Target-PAN': 'Related Entity PAN', 'Source-Name': 'Seed Node Name',
                     'Target-Name': 'Related Entity Name', 'type': 'Relationship Type'}, inplace=True)
        related_links.drop(['id', 'source', 'target', 'text', 'Financial Year', 'EDGE_ID', 'Relationship Score',
                            'PRIMARY_RELATIONSHIP'], axis=1, inplace=True)

    else:
        related_links.rename(
            columns={'Source-PAN': 'Seller PAN', 'Target-PAN': 'Purchaser PAN', 'Source-Name': 'Seller Name',
                     'Target-Name': 'Purchaser Name'}, inplace=True)
        related_links.drop(['id', 'source', 'target', 'text', 'type', 'Financial Year'], axis=1, inplace=True)
        related_links['Transaction Amount'] = related_links['Transaction Amount'].map('{:,.0f}'.format)
        related_links['Tax'] = related_links['Tax'].map('{:,.0f}'.format)

    Financial_Year = related_nodes.iloc[0]['Financial Year']

    if "TDS" in module:
        related_nodes.drop(['id', 'source', 'target', 'Name', 'Financial Year'], axis=1, inplace=True)
        related_nodes.rename(columns={'categories': 'Categories', "text": "Name"}, inplace=True)

    else:
        related_nodes.rename(columns={'categories': 'Categories'}, inplace=True)
        related_nodes.drop(['id', 'source', 'target', 'text', 'Financial Year'], axis=1, inplace=True)

    # POI Nodes
    POI_Nodes = related_nodes.loc[
        related_nodes['Categories'].apply(str).str.contains('Person Of Interest')].reset_index(drop=True)
    POI_Nodes['Risk Flags'] = POI_Nodes['Person Of Interest flags'].apply(lambda x: len(x.split(',')))
    POI_Nodes = POI_Nodes[['PAN', 'Name', 'Risk Flags', 'Person Of Interest flags']]

    # Red flags segregation
    POI_red_flags = POI_Nodes[['Name', 'PAN', 'Person Of Interest flags']]
    POI_red_flags.rename(columns={'Person Of Interest flags': 'Risk_Flag'}, inplace=True)
    POI_red_flags = POI_red_flags.assign(Risk_Flag=POI_red_flags['Risk_Flag'].str.split(',')).explode(
        'Risk_Flag').reset_index(drop=True)
    POI_red_flags = POI_red_flags[['PAN', 'Name', 'Risk_Flag']]

    # POI Relationships
    if "TDS" in module:
        POI_related_links = related_links.loc[(related_links['Deductee PAN'].isin(POI_red_flags['PAN'])) | (
            related_links['Deductor PAN'].isin(POI_red_flags['PAN']))].reset_index(drop=True)
        POI_related_links.drop(['Deductor PAN'], axis=1, inplace=True)
        related_links.drop(['Deductor PAN'], axis=1, inplace=True)
    elif "Share" in module:
        POI_related_links = related_links.loc[(related_links['Shareholder PAN'].isin(POI_red_flags['PAN'])) | (
            related_links['Entity PAN'].isin(POI_red_flags['PAN']))].reset_index(drop=True)
    elif "Relation" in module:
        POI_related_links = related_links.loc[(related_links['Related Entity PAN'].isin(POI_red_flags['PAN'])) | (
            related_links['Seed Node PAN'].isin(POI_red_flags['PAN']))].reset_index(drop=True)
    else:
        POI_related_links = related_links.loc[(related_links['Purchaser PAN'].isin(POI_red_flags['PAN'])) | (
            related_links['Seller PAN'].isin(POI_red_flags['PAN']))].reset_index(drop=True)

    writer = pd.ExcelWriter(r'./Link_Analysis_'+module+'_'+seed_node.iloc[0]['PAN']+'.xlsx', engine='xlsxwriter')

    len1 = len(seed_node) + 20

    # len2 = len(seed_node) + len(related_nodes)+24

    # Write all nodes and edges data to an excel
    # seed_node.to_excel(writer, sheet_name=module, startrow=2, index=False, header=False)
    related_links.to_excel(writer, sheet_name='All Relationships', startrow=len1, index=False)
    related_nodes.to_excel(writer, sheet_name='All Nodes', startrow=2, index=False)

    # Write Person of Interest data to an excel
    POI_Nodes.to_excel(writer, sheet_name='Person of Interest', startrow=2, index=False)
    POI_red_flags.to_excel(writer, sheet_name='Person of Interest', startrow=len(POI_Nodes) + 5, index=False)
    POI_related_links.to_excel(writer, sheet_name='Person of Interest',
                               startrow=len(POI_Nodes) + len(POI_red_flags) + 8, index=False)

    # Get workbook
    workbook = writer.book

    title_format = workbook.add_format({
        'bold': False,
        'valign': 'top',
        'fg_color': '#F1FF7C',
        'border': 1})

    # Get Sheet1
    worksheet = writer.sheets['All Relationships']
    worksheet_nodes = writer.sheets['All Nodes']
    worksheet_POI = writer.sheets['Person of Interest']
    # worksheet.hide_gridlines(2)

    # worksheet.write(0,0, 'Seed Node',title_format)
    merge_format = workbook.add_format({
        'bold': 1,
        'border': 1,
        'align': 'center',
        'valign': 'vcenter',
        'fg_color': 'yellow'})

    worksheet.merge_range(0, 0, 0, 5,
                          module + ' Analysis for ' + seed_node.iloc[0]['PAN Name'] + " (" + seed_node.iloc[0][
                              'PAN'] + ") for FY " + Financial_Year, merge_format)
    worksheet_nodes.merge_range(0, 0, 0, 1, module + ' - All Nodes', merge_format)
    worksheet_POI.merge_range(0, 0, 0, 2, 'Person of Interest Analysis for ' + seed_node.iloc[0]['PAN Name'] + " (" +
                              seed_node.iloc[0]['PAN'] + ")", merge_format)

    worksheet.insert_image(1 + 1, 1, img_path,
                           {'x_scale': 0.46, 'y_scale': 0.46, 'object_position': 3})

    worksheet.merge_range(len1 - 1, 0, len1 - 1, 2, module + ' - All Relationships', merge_format)
    worksheet_POI.merge_range(len(POI_Nodes) + 4, 0, len(POI_Nodes) + 4, 1, 'Person of Interest Flags', merge_format)
    worksheet_POI.merge_range(len(POI_Nodes) + len(POI_red_flags) + 7, 0, len(POI_Nodes) + len(POI_red_flags) + 7, 1,
                              'Relationships ', merge_format)

    # Add a header format.
    header_format = workbook.add_format({
        'bold': False,
        'valign': 'left',
        'fg_color': '#d9e1f2',
        'border': 1})

    # Write the column headers with the defined format.
    for col_num, value in enumerate(related_links.columns.values):
        worksheet.write(len1, col_num, value, header_format)

    for col_num, value in enumerate(related_nodes.columns.values):
        worksheet_nodes.write(2, col_num, value, header_format)

    for col_num, value in enumerate(POI_Nodes.columns.values):
        worksheet_POI.write(2, col_num, value, header_format)

    for col_num, value in enumerate(POI_red_flags.columns.values):
        worksheet_POI.write(len(POI_Nodes) + 5, col_num, value, header_format)

    for col_num, value in enumerate(POI_related_links.columns.values):
        worksheet_POI.write(len(POI_Nodes) + len(POI_red_flags) + 8, col_num, value, header_format)

    # Applying function to auto-fit the width of columns
    for i, width in enumerate(get_col_widths(related_links)):
        worksheet.set_column(i, i, width)
    for i, width in enumerate(get_col_widths(related_nodes)):
        worksheet_nodes.set_column(i, i, width)
    for i, width in enumerate(get_col_widths(POI_red_flags)):
        worksheet_POI.set_column(i, i, width)

    writer.save()
    writer.close()
    return True

def main():
    modules = ["Relationship", "TDS Payments", "GST Payments", "Shareholding Details"]
    data = getInputJson("sandbox.json")
    nodes, edges = normalizeJson(data)
    seed_list = getAvailableSeed(nodes)
    #print(seed_list)
    #flattenData(nodes, edges)

if __name__ == "__main__":
    main()


from csr.dev.fw.firmware_component import FirmwareComponent
from csr.dev.env.env_helpers import InvalidDereference
from csr.dev.model import interface

class Gaa(FirmwareComponent):
    """
    Gaa Voice Assistant analysis class
    """

    def __init__(self, env, core, parent=None):
        FirmwareComponent.__init__(self, env, core, parent=parent)
        try:
            self._gaa = env.econst.voice_ui_provider_gaa
        except AttributeError:
            raise self.NotDetected()

    @property
    def active(self):
        try:
            active_va = self.env.vars['active_va'].deref.voice_assistant.deref.va_provider.value
            return active_va == self._gaa
        except InvalidDereference:
            return False

    def _convert_binary_to_fp64(self, value):
        if(value == '0b0'):
            fp64_value = 0.0
        else:
            # Bit 64
            sign = int(value[2:3], 2)
            # Bit 63-53
            exponent = int(value[3:14], 2)
            offset = 1023

            if(exponent):
                exponent = 2 ** (exponent-offset)
            else:
                exponent = 2 ** (offset-1)

            # Bit 52-0
            fraction = int(value[14:], 2)

            if sign == 0:
                exponent = exponent * -1

            fp64_value = float(str(exponent) + '.' + str(fraction))
        return fp64_value

    def _create_device_actions_group(self):
        try:
            command_table = self.env.vars['command_table']
        except KeyError:
            return None

        device_actions_grp = interface.Group("Gaa device actions")

        device_actions_storage_ptr_tbl = interface.Table(["all", "battery_details", "noise_cancellation", "ambient_mode"])
        device_actions_storage_ptr_tbl.add_row([self.env.vars['update_all_storage'],
                                                self.env.vars['battery_level_device_action'].update.storage,
                                                self.env.vars['noise_cancellation_device_action'].update.storage,
                                                self.env.vars['ambient_mode_device_action'].update.storage])
        device_actions_grp.append(device_actions_storage_ptr_tbl)

        device_actions_command_tbl = interface.Table(["Command", "Value Kind", "Value"])
        with command_table.footprint_prefetched():
            for i in range(10):
                value_kind = command_table[i].value_kind
                if value_kind.value == self.env.econst.EXECUTION_VALUE__KIND_NULL_VALUE:
                    value = command_table[i].u.null_value.value
                elif value_kind.value == self.env.econst.EXECUTION_VALUE__KIND_NUMBER_VALUE:
                    value = self._convert_binary_to_fp64(bin(command_table[i].u.number_value.value))
                elif value_kind.value == self.env.econst.EXECUTION_VALUE__KIND_STRING_VALUE:
                    value = command_table[i].u.string_value.value
                elif value_kind.value == self.env.econst.EXECUTION_VALUE__KIND_BOOL_VALUE:
                    value = "TRUE" if command_table[i].u.bool_value.value else "FALSE"
                else:
                    value = 'No value found!'

                device_actions_command_tbl.add_row([command_table[i].command,
                                                    value_kind,
                                                    value])

        device_actions_grp.append(device_actions_command_tbl)

        device_actions_update_tbl = interface.Table(["Update", "Value"])
        for i in range(10):
            device_actions_update_tbl.add_row([self.env.vars['update_table'][i].update,
                                               self.env.vars['update_table'][i].value.value])
        device_actions_grp.append(device_actions_update_tbl)

        return device_actions_grp

    def _generate_report_body_elements(self):

        content = []

        grp = interface.Group("Gaa status")
        tbl = interface.Table(["Active"])
        tbl.add_row([
            "Y" if self.active else "N"
        ])
        grp.append(tbl)
        content.append(grp)

        device_actions_grp = self._create_device_actions_group()
        content.append(device_actions_grp)

        return content


import numpy as np
from scipy.misc import logsumexp

def input_and_show_tables():
    print('Copy-and-paste L0 and S0 from s0_grids, as a dict {"L0": [[...]], "S0": [[...]]}. ')
    print('Press ^D when done.')
    s0_dict_lines = []
    while True:
        try:
            line = raw_input('')
        except EOFError:
            break
        s0_dict_lines.append(line)
    s0_dict = eval(''.join(line.strip() for line in s0_dict_lines))

    utts_str = raw_input('Enter rows of the table to select utts from, separated by comma:\n')
    utts = [int(i) for i in utts_str.strip().split(',')]
    cols_str = raw_input('Enter order of cols of the table separated by comma:\n')
    cols = [int(i) for i in cols_str.strip().split(',')]
    show_tables(s0_dict, utts, cols)

def show_tables(s0_dict, utts, cols):
    sw = 0.608
    bw = -0.15
    alpha = 0.544
    gamma = 0.509

    l0 = np.array(s0_dict['L0']).T[utts, :][:, cols]
    print('L0:\n{}'.format(friendly(l0)))
    print('')

    scaled = l0 * alpha
    s1 = norm(scaled, axis=0)
    print('S1:\n{}'.format(friendly(s1)))
    print('')

    l2 = norm(s1)
    print('L2:\n{}'.format(friendly(l2)))
    print('')

    s0 = np.array(s0_dict['S0']).T[0][cols]
    print('S0:\n{}'.format(np.exp(s0)))
    print('')

    l1 = norm(s0)
    print('L1:\n{}'.format(friendly(l1)))
    print('')

    la = norm((1-sw) * l0[0] + sw * l1)
    print('La:\n{}'.format(friendly(la)))
    print('')

    lb = norm(bw * l0[0] + (1-bw) * l2[0])
    print('Lb:\n{}'.format(friendly(lb)))
    print('')

    le = norm(gamma * lb + (1-gamma) * la)
    print('Le:\n{}'.format(friendly(le)))
    print('')

def friendly(arr):
    return np.round(np.exp(arr), 3)

def norm(arr, axis=-1):
    return arr - logsumexp(arr, axis=axis, keepdims=True)

if __name__ == '__main__':
    input_and_show_tables()


import sys
import subprocess
import os
import traceback

class WrongFileType(Exception):
    """Raised when the input file is not supported"""
    pass

def split(droppedFile,mode,debug):
    ''' Dropped file as mp3 or wav , Mode 1 = analyze Mode 2 = normalize Mode 3 = Split only Mode 4 = Split with silence removal
     debug = 0/1 keeps terminal open '''

    # create new Output folder if missing
    try:
        os.makedirs((os.getcwd()+'/output'), exist_ok=False)
    except OSError:
        pass

    try:
        extension = os.path.splitext(droppedFile)[1]    # Get file extension

        if not extension in [".wav",".mp3"]:            # Raise exeption if other than .wav file dragged.
            raise WrongFileType

        inputfile = (droppedFile.replace('\\', '/'))    # Fixing correct filepath style

        full_filename = os.path.basename(inputfile)
        filename = os.path.splitext(full_filename)[0]

        if not (filename[:2].isdigit()):                   # Checking if file doesnt have index number.
            file_number = "01"
            new_filename = "_" + filename

        else :
            file_number = filename[:2]                  # Gettings first 2 characters from filename to file_numbers
            new_filename = filename[2:]                 # Creating new filename without first 2 characters.

        # Creating ffmpeg command parameters for
        # Removing silence from end and begining
        # Splitting audio files and create right filenumbers for new ones
        # Converting to 32KHz 16bit Mono .wav file

        if mode == 1:
            # Analyze audio file
            cmd = analyze_cmd = (
            "ffmpeg -hide_banner \
            -i {} \
            -af volumedetect -vn -sn -dn -f null NUL".format(inputfile))

            print("Analyzing...")

        if mode == 2:
            # Split only
            cmd = split_cmd = (
            "ffmpeg -hide_banner \
            -i {}  \
            -f segment -segment_time 2 -segment_start_number {} -map_metadata -1 -bitexact\
            -acodec pcm_s16le -ac 1 -ar 32000 output/%02d{}.wav"
            .format(inputfile,file_number,new_filename))

            print("Splitting...")

        if mode == 3:
            # Split with silence removal
            #  buggy
            cmd = split_silence= (
            "ffmpeg -hide_banner \
            -i {}  \
            -af silenceremove=start_periods=1:detection=peak:start_duration=1:start_silence=0.05:start_threshold=0.02:stop_periods=1:stop_duration=1:stop_silence=0.05:stop_threshold=0.02\
            -f -segment_time 2 -segment_start_number {} -map_metadata -1 -bitexact\
            -acodec pcm_s16le -ac 1 -ar 32000 output/%02d{}.wav"
            .format(inputfile,file_number,new_filename))

            print("Deleting silence and splitting...")

        subprocess.run(cmd,shell=True, check=True)

    #Error catching to keep terminal in case of errors.
    except WrongFileType:
        print("Wrong file type. Only [.wav .mp3] files are supported.")
        print("\nPress enter to exit.")
        input()
        sys.exit(1)

    except subprocess.CalledProcessError as e:
        print("\nPress enter to exit.")
        input()
        sys.exit(1)

    except BaseException:
        print ("\n",sys.exc_info()[0])
        print("\n",traceback.format_exc())
        input()
        sys.exit(1)

    print("\nExited without errors.")

    if debug:
        print("\nPress enter to exit.")
        input()


#nome=input('Qual o seu nome ? ');
#aniversario=int(input('Qual o ano do seu aniversario? '));
#print('Seu nome é {} e sua idade é {}'.format(nome,2022-aniversario))
#======================================================================#

numero=int(input('Qual o numero ? '));
i=1
for i in range(10):
    print(numero,' X ', i+1 ,' = ', ((i+1)*numero))


import os

class MyCorpus:
    cambridgePath=os.path.abspath("my_corpus/cambridge_words.txt")
    wordListPath=os.path.abspath("my_corpus/wordList.txt")
    bigramPath=os.path.abspath("my_corpus/bigrams.txt")

    wordList=set()
    bigrams=set()
    debug=False

    def __init__(self, debug=False):
        self.loadWordList()
        self.loadBigrams()
        self.loadCambridgeWords()
        self.debug=debug
        print("MyCorpus initiated :)\n")

    def saveAll(self):
        self.saveWordList()
        self.saveBigrams()

    def addWord(self, word):
        self.wordList.add(word)

    def addBigram(self, word):
        self.bigrams.add(word)

    def saveWordList(self):
        try:
            wf=open(self.wordListPath, "w", encoding="utf-8")
        except:
            raise IOError("Can't save wordlist in file.")
        for word in self.wordList:
            wf.write(word+"\n")
        wf.close()

    def saveBigrams(self):
        try:
            wf=open(self.bigramPath, "w", encoding="utf-8")
        except:
            raise IOError("Can't save wordlist in file.")
        for line in self.bigrams:
            wf.write(line[0]+" "+line[1]+"\n")
        wf.close()

    def printAllWords(self):
        print("Printing wordList: {}".format("<Empty>" if not self.wordList else ""))
        for i, word in enumerate(self.wordList):
            print(str(i+1), word)

    def printAllBigrams(self):
        print("Printing bigrams: {}".format("<Empty>" if not self.bigrams else ""))
        for i, bigram in enumerate(self.bigrams):
            print(str(i+1), bigram[0], bigram[1])

    def loadCambridgeWords(self):
        print("Fetching Cambridge Words...")
        try:
            wf=open(self.cambridgePath, "r", encoding="utf-8")
        except:
            open(self.wordListPath, "w").close()
            wf=open(self.cambridgePath, "r", encoding="utf-8")

        for word in wf:
            for w in word.split():
                self.wordList.add(w)
        wf.close()

        if self.debug: self.printAllWords()
        print("Loaded Cambridge Words\n")

    def loadWordList(self):
        print("Fetching Wordlist...")
        try:
            wf=open(self.wordListPath, "r", encoding="utf-8")
        except:
            open(self.wordListPath, "w").close()
            wf=open(self.wordListPath, "r", encoding="utf-8")

        for word in wf:
            for w in word.split():
                self.wordList.add(w)
        wf.close()

        if self.debug: self.printAllWords()
        print("Loaded WordList\n")

    def loadBigrams(self):
        print("Fetching Bigrams...")
        try:
            bf=open(self.bigramPath, "r", encoding="utf-8")
        except:
            open(self.bigramPath, "w").close()
            bf=open(self.bigramPath, "r", encoding="utf-8")

        for line in bf:
            a, b = line.split()
            self.bigrams.add((a, b))
        bf.close()

        if self.debug: self.printAllBigrams()
        print("Loaded Bigrams\n")


from rest_framework import mixins, viewsets

from teams_be.base import response
from teams_be.base.apis.mixins import MultipleSerializerMixin
from teams_be.tasks.models import Task
from teams_be.tasks.serializers import TaskSerializer, TaskResponseSerializer

class TaskViewSet(
    MultipleSerializerMixin,
    mixins.ListModelMixin,
    mixins.DestroyModelMixin,
    mixins.RetrieveModelMixin,
    mixins.UpdateModelMixin,
    viewsets.GenericViewSet,
):
    serializer_class = TaskResponseSerializer
    queryset = Task.objects.all()

    serializer_classes = {
        "create": TaskSerializer,
        "update": TaskSerializer,
    }

    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        task_obj = serializer.save()
        response_serializer = self.serializer_class(
            task_obj, context=self.get_serializer_context()
        )
        return response.Created(response_serializer.data)


from termcolor import cprint

class Set_Skin:
    def __init__(self,command,manager,inventory_data):

        # format: set weanpon_name skin_name level chroma
        if len(command) < 3:
            cprint("command missing required params", "red")
            return
        weapon_name = str(command[1])
        skin_name = str(command[2]).replace("-"," ")

        weapon_data = ()
        skin_data = ()
        level_data = ()
        chroma_data = ()
        for uuid,weapon in inventory_data.items():
            if weapon["display_name"] == weapon_name:
                weapon_data = (uuid,weapon)

        for uuid,skin in weapon_data[1]["skins"].items():
            if skin["display_name"] == skin_name:
                skin_data = (uuid,skin)

        if len(command) < 4:
            # missing level
            level_data = (list(skin_data[1]["levels"].keys())[-1],skin_data[1]["levels"][list(skin_data[1]["levels"].keys())[-1]])
            if len(skin_data[1]["levels"]) > 1:
                cprint(f"no level provided, using default ({level_data[1]['display_name']})", "yellow")
        else:
            level_name = command[3].replace("-"," ")
            for uuid,level in skin_data[1]["levels"].items():
                if level['display_name'] == level_name:
                    level_data = (uuid,level)

        if len(command) < 5:
            # missing chroma
            chroma_data = (list(skin_data[1]["chromas"].keys())[-1],skin_data[1]["chromas"][list(skin_data[1]["chromas"].keys())[-1]])
            if len(skin_data[1]["chromas"]) > 1:
                cprint(f"no chroma provided, using default ({chroma_data[1]['display_name']})", "yellow")
        else:
            chroma_name = command[4].replace("-"," ")
            for uuid,chroma in skin_data[1]["chromas"].items():
                if chroma['display_name'] == chroma_name:
                    chroma_data = (uuid,chroma)

        manager.modify_skin(weapon_data[0], skin_data[0], level_data[0], chroma_data[0])
        cprint(f"{weapon_data[1]['display_name']} -> {skin_data[1]['display_name']} ({level_data[1]['display_name']}/{chroma_data[1]['display_name']})", "green", attrs=["bold"])


import json
import os
import struct
from collections import OrderedDict

import pandas as pd
from mpi4py import MPI

from spykshrk.realtime.realtime_logging import PrintableMessage

class TimingSystemError(Exception):
    def __init__(self, value, **kwargs):
        self.value = value
        self.data = kwargs

    def __str__(self):
        return repr(self.value) + '\n' + repr(self.data)

class TimingMessage(PrintableMessage):
    msgheader_format = '=12sqi'
    msgheader_format_size = struct.calcsize(msgheader_format)
    timept_format = '=id'
    timept_format_size = struct.calcsize(timept_format)

    def __init__(self, label, timestamp=0, start_rank=-1, timing_data=None):
        """

        Args:
            label:
            start_rank:
        """

        if len(label) > 12:
            raise TimingSystemError('Timing label {}: label must be 10 characters or less.'.format(label))

        if isinstance(label, str):
            self._label = bytes(label, 'utf-8')
        elif isinstance(label, bytes) or isinstance(label, bytearray):
            self._label = label

        self._timestamp = timestamp

        if timing_data is None:
            self._timing_data = [(start_rank, MPI.Wtime())]
        else:
            self._timing_data = timing_data

    def record_time(self, rank):
        self._timing_data.append((rank, MPI.Wtime()))

    @classmethod
    def unpack(cls, message_bytes):
        """

        Args:
            message_bytes:

        Returns:
            TimingMessage: The de-serialized TimingMessage object.
        """

        label, timestamp, num_time_pt = struct.unpack(cls.msgheader_format,
                                                      message_bytes[0:cls.msgheader_format_size])

        num_time_pt = int(num_time_pt)
        unpacked = struct.unpack(cls.timept_format[0] + cls.timept_format[1:] *
                                 num_time_pt, message_bytes[cls.msgheader_format_size:
                                                            cls.msgheader_format_size +
                                                            cls.timept_format_size*num_time_pt])

        timing_data = []
        for pt_ii in range(num_time_pt):
            timing_data.append((unpacked[pt_ii*2], unpacked[pt_ii*2+1]))

        return cls(label=label, timestamp=timestamp, timing_data=timing_data)

    def pack(self):
        return struct.pack(self.msgheader_format + self.timept_format[1:] * len(self._timing_data),
                           self._label, self._timestamp, len(self._timing_data),
                           *[it for sub in self._timing_data for it in sub])

    @property
    def label(self):
        return self._label.split(b'\0', 1)[0].decode()

    @label.setter
    def label(self, label):
        raise TimingSystemError('Cannot modify TimingMessage label.')

    @property
    def timestamp(self):
        return self._timestamp

    @timestamp.setter
    def timestamp(self, label):
        raise TimingSystemError('Cannot modify TimingMessage timestamp.')

    @property
    def timing_data(self):
        return self._timing_data

    @timing_data.setter
    def timing_data(self, timing_data):
        raise TimingSystemError('Cannot modify TimingMessage timing_data.')

    def __eq__(self, other):
        return ((self.label == other.label) and
                (self.timestamp == other.timestamp) and
                (self.timing_data == other.timing_data))

class CreateTimingFileMessage(PrintableMessage):
    def __init__(self, save_dir, file_prefix, file_postfix):
        self.save_dir = save_dir
        self.file_prefix = file_prefix
        self.file_postfix = file_postfix

class TimingFileWriter:

    header_format = '=Qi'

    @staticmethod
    def format_full_path(save_dir, file_prefix, mpi_rank, file_postfix):
        file_path = os.path.join(save_dir, '{}.{:02d}.{}'.format(file_prefix, mpi_rank,
                                                                 file_postfix))

        return file_path

    def __init__(self, save_dir, file_prefix, mpi_rank, file_postfix):
        self._save_dir = save_dir
        self._file_prefix = file_prefix
        self._mpi_rank = mpi_rank
        self._file_postfix = file_postfix

        self._file_path = self.format_full_path(save_dir=self._save_dir, file_prefix=self._file_prefix,
                                                mpi_rank=self._mpi_rank, file_postfix=self._file_postfix)

        self._header_json = json.dumps(OrderedDict([('file_type', 'timing'),
                                                    ('file_prefix', self._file_prefix),
                                                    ('mpi_rank', self._mpi_rank),
                                                    ('header_fmt', self.header_format),
                                                    ('msgheader_fmt', TimingMessage.msgheader_format),
                                                    ('timept_fmt', TimingMessage.timept_format)
                                                    ]))

        self._file_handle = open(self._file_path, 'wb')

        self._file_handle.write(bytearray(self._header_json, encoding='utf-8'))

        self._rec_counter = 0

    @classmethod
    def create_from_mesage(cls, create_message: CreateTimingFileMessage, rank):
        return cls(save_dir=create_message.save_dir,
                   file_prefix=create_message.file_prefix,
                   mpi_rank=rank,
                   file_postfix=create_message.file_postfix)

    def write_timing_message(self, timing_msg: TimingMessage):
        msg_bytes = timing_msg.pack()
        header_bytes = struct.pack(self.header_format, self._rec_counter, len(msg_bytes))
        self._file_handle.write(header_bytes + msg_bytes)

        self._rec_counter += 1

    def __del__(self):
        self._file_handle.close()

    @property
    def closed(self):
        return self._file_handle.closed

    def close(self):
        self._file_handle.close()

class TimingFileReader:
    def __init__(self, save_dir, file_prefix, mpi_rank, file_postfix):
        self._save_dir = save_dir
        self._file_prefix = file_prefix
        self._mpi_rank = mpi_rank
        self._file_postfix = file_postfix

        self._file_path = TimingFileWriter.format_full_path(save_dir=self._save_dir, file_prefix=self._file_prefix,
                                                            mpi_rank=self._mpi_rank, file_postfix=self._file_postfix)

        self._file_handle = open(self._file_path, 'rb')

        self._header_bytes = None
        self._data_start_byte = None
        self._extract_json_header()
        self._header = json.loads(self._header_bytes.decode('utf-8'))

    def _extract_json_header(self):
        self._file_handle.seek(0)
        self._header_bytes = bytearray()

        read_byte = self._file_handle.read(1)
        if read_byte != b'{':
            raise TimingSystemError('Not a Binary Records file, JSON header not found at first byte.',
                                    file_path=self._file_path)

        level = 0
        while read_byte:
            self._header_bytes.append(ord(read_byte))
            if read_byte == b'{':
                level += 1
            elif read_byte == b'}':
                level -= 1

            if level == 0:
                break
            elif len(self._header_bytes) >= 1000:
                raise TimingSystemError('Could not find end of JSON header before 1000 byte header limit.',
                                        file_path=self._file_path)

            # read next byte
            read_byte = self._file_handle.read(1)

        if level != 0:
            raise TimingSystemError('Could not find end of JSON header before end of file.',
                                    file_path=self._file_path)

        self._data_start_byte = self._file_handle.tell()

        self.rec_id = -1

    def __iter__(self):
        return self

    def __next__(self):
        return_rec = self._read_record()
        if return_rec is None:
            raise StopIteration()
        else:
            return return_rec

    def _read_record(self):

        header_bytes = self._file_handle.read(struct.calcsize(self._header['header_fmt']))

        if not header_bytes:
            return None

        try:
            self.rec_id, msg_len = struct.unpack(self._header['header_fmt'], header_bytes)

            msg_bytes = self._file_handle.read(msg_len)
            msg = TimingMessage.unpack(msg_bytes)

        except struct.error as ex:
            raise TimingSystemError('File might be corrupted, record does not match format or unexpected EOF.',
                                    file_path=self._file_path, last_rec_id=self.rec_id)

        return self.rec_id, msg

    def convert_panda_labels(self):
        timing_labels = {}
        msg_id_labels = {}

        return_rec = self._read_record()
        while return_rec is not None:

            msg_id, msg = return_rec

            id_data = msg_id_labels.setdefault(msg.label, [])
            timing_data = timing_labels.setdefault(msg.label, [])

            id_data.append(msg_id)
            id_data_unrolled = [it for sublist in msg.timing_data for it in sublist]
            timing_data.append(id_data_unrolled)

            return_rec = self._read_record()

        timing_df_labels = {}
        for label in timing_labels.keys():
            data_id = msg_id_labels[label]
            timing_data = timing_labels[label]

            num_measurements = len(timing_data[0])/2
            if not num_measurements.is_integer():
                raise TimingSystemError('Timing data columns is not even (rank, time). Data is corrupted.')
            num_measurements = int(num_measurements)

            column_names = []
            for measurement_id in range(num_measurements):
                column_names.append('rank{}'.format(measurement_id))
                column_names.append('time{}'.format(measurement_id))

            timing_df_labels[label] = pd.DataFrame(data=timing_data, index=data_id, columns=column_names)

        return timing_df_labels


from pathlib import Path
import sys

parent_dir = Path(__file__).parent
file_name = Path(__file__).stem

sys.stdin = open(f"{parent_dir}\{file_name} input.txt")
input = sys.stdin.readline

def permutation(cols, depth, N, cur_sum):
    global arr
    global min_sum

    if depth < N:
        for c in range(depth, N):
            # 가지치기 부분
            # 기준이 될 수 있는 곳들마다 값을 구해서 기존 합에 더함
            # 그 값이 최소 합보다 커지면 넘김
            new_base_val = arr[depth][cols[c]]
            if cur_sum + new_base_val > min_sum:
                continue

            # 기준을 바꿔줬으므로, 이 값을 기존 합에 더해서 넘김
            cols[depth], cols[c] = cols[c], cols[depth]
            permutation(cols, depth + 1, N, cur_sum + new_base_val)
            cols[depth], cols[c] = cols[c], cols[depth]
    else:
        # 위에서 최소 합보다 크면 넘어가게 했으므로
        # 끝까지 도착한 건 최소 합보다 작거나 같음
        min_sum = cur_sum

T = int(input())
for test_case in range(1, T + 1):
    N = int(input())
    arr = [list(map(int, input().split())) for _ in range(N)]
    cols = list(range(N))
    # 10 미만의 정수 * N 행이므로, 최댓값은 10 * N
    min_sum = 10 * N

    permutation(cols, 0, len(cols), 0)

    print("#{} {}".format(test_case, min_sum))

problems/SW_Expert_Academy/0824/11883. 배열 최소 합.py


#! /usr/bin/env python3
'''
Extract data into game folders from a VGCollect dump
'''
from json import load as jload
from os import makedirs
from sys import argv

# main program
if __name__ == "__main__":
    if len(argv) != 2:
        print("USAGE: %s <vgcollect_dump.json>" % argv[0]); exit(1)
    data = jload(open(argv[1]))
    for serial in data:
        game_path = '../../games/%s' % serial
        makedirs(game_path, exist_ok=True)
        for k in data[serial]:
            f = open('%s/%s.txt' % (game_path, k), 'w'); f.write('%s\n' % data[serial][k]); f.close()


#!/usr/bin/env python

import sys, getopt
from dreampy3.redshift.netcdf import RedshiftNetCDFFile
import matplotlib.pyplot as pl
from data_lmt import data_lmt

def main(argv):
    # defaults
    date = '2014-02-22'
    scan = '16667'
    chassis = '2'
    band = 0

    # get options
    try:
        opts, arg = getopt.getopt(argv,"hc:d:s:b:",["chassis=","date=","scan=","band="])
    except getopt.GetoptError:
        print('bad argument: usage: look_map.py')
        sys.exit(2)
    for opt, arg in opts:
        if opt == '-h':
            print('usage: look_map.py')
            print('-c chassis')
            print('-d date in yyyy-mm-dd format')
            print('-s OBSNUM')
            print('-b band (or board) to view')
            sys.exit()
        elif opt in ("-c","--chassis"):
            chassis = arg
        elif opt in ("-d","--date"):
            date = arg
        elif opt in ("-s","--scan"):
            scan = arg
        elif opt in ("-b","--band"):
            band = eval(arg)

    filename = make_filename(date,scan,chassis)
    nc = RedshiftNetCDFFile(filename)
    pl.ion()
    pl.clf()
    pl.figure(1)
    pl.plot(nc.hdu.data.AccAverage[:,band])
    print('Gains= ',nc.hdu.header.Gain)
    pl.show()

def make_filename(date,scan,chassis):
    # makes a filename from date and obnum
    filename = data_lmt() + '/RedshiftChassis%s/RedshiftChassis%s_%s_%06d_01_0001.nc' % (chassis, chassis, date, eval(scan))
    return filename

main(sys.argv[1:])


from Myro import *

#makeRobot("ROSARDrone", "myip", "ROSip")

speak("Please prepare for liftoff")
for i in range(10, 0, -1):
    speak(str(i))

reset()
show(takePicture())
takeoff()

lst = []
for t in timer(10):
    p = takePicture()
    lst.append(p)
    show(p)
land()

savePicture(lst, "119animation.gif")


# 解説AC
n, k = map(int, input().split())
a = list(map(int, input().split()))
x = 0
cnt = {}  # {あまり : i}
lst = []  # i番目のxの値
for i in range(k):
    rem = x % n
    if rem in cnt:
        rem_pst = cnt[rem]
        cycle = x - lst[rem_pst]
        size = i - rem_pst
        ans = lst[rem_pst] + (k - rem_pst) // (i - rem_pst) * cycle
        now = rem_pst + (k - rem_pst) // size * size
        for j in range(now, k):
            ans += a[ans % n]
        exit(print(ans))
    cnt[rem] = i
    lst.append(x)
    x += a[x % n]
print(x)


import math

def main():
    can_sizes = [
        ["#1 Picnic", 6.83, 10.16, 0.28],
        ["#1 Tall", 7.78, 11.91, 0.43],
        ["#2", 8.73, 11.59, 0.45],
        ["#2.5", 10.32, 11.91, 0.61],
        ["#3 Cylinder", 10.79, 17.78, 0.86],
        ["#5", 13.02, 14.29, 0.83],
        ["#6Z", 5.4, 8.89, 0.22],
        ["#8Z short", 6.83, 7.62, 0.26],
        ["#10", 15.72, 17.78, 1.53],
        ["#211", 6.83, 12.38, 0.34],
        ["#300", 7.62, 11.27, 0.38],
        ["#303", 8.1, 11.11, 0.42]
    ]

    best_store = None
    best_cost = None
    max_store_eff = -1
    max_cost_eff = -1

    # For each can in the can_sizes list, unpack the values
    # into the variables name, radius, height, and cost.
    for name, radius, height, cost in can_sizes:

        # Call the storage_efficiency and cost_efficiency functions.
        store_eff = storage_efficiency(radius, height)
        cost_eff =  cost_efficiency(radius, height, cost)

        # Print the can size name, storage
        # efficiency, and cost efficiency.
        print(f"{name} {store_eff:.1f} {cost_eff:.0f}")

        if store_eff > max_store_eff:
            best_store = name
            max_store_eff = store_eff

        if cost_eff > max_cost_eff:
            best_cost = name
            max_cost_eff = cost_eff

    # Print the best storage and cost efficiencies.
    print("Best can size in storage efficiency:", best_store)
    print("Best can size in cost efficiency:", best_cost)

def storage_efficiency(radius, height):

    volume = cylinder_volume(radius, height)
    surf_area = cylinder_surface_area(radius, height)
    efficiency = volume / surf_area
    return efficiency

def cost_efficiency(radius, height, cost):

    volume = cylinder_volume(radius, height)
    efficiency = volume / cost
    return efficiency

def cylinder_volume(radius, height):

    volume = math.pi * radius**2 * height
    return volume

def cylinder_surface_area(radius, height):

    surf_area = 2 * math.pi * radius * (radius + height)
    return surf_area

# Start this program by
# calling the main function.
main()


import zipfile
import pandas as pd
import io
import requests
import os
import logging
from scipy.spatial import cKDTree
import math
import numpy as np

from .GtfsDataframe import GtfsDataframe

def process_gtfs_zipfile_obj(gtfs_zip: zipfile.ZipFile, version_id: str) -> pd.DataFrame:
    dfs = []
    for item in gtfs_zip.namelist():
        if item.endswith('/'): # Check if the item is a directory
            branch_id = item.strip('/')
            google_transit_zip_path = f"{branch_id}/google_transit.zip"
            with gtfs_zip.open(google_transit_zip_path) as google_transit_file:
                with zipfile.ZipFile(google_transit_file, 'r') as transit_zip:
                    nested_file_list = transit_zip.namelist()
                    for nested_file_name in nested_file_list:
                        if nested_file_name.endswith('.txt'):

                            table_name = nested_file_name.removesuffix('.txt')
                            logging.info(f"Processing {branch_id} {table_name} {version_id}")

                            with transit_zip.open(nested_file_name) as nested_file:

                                df = pd.read_csv(nested_file, keep_default_na=False, low_memory=False, na_values=[''])

                                df_gtfs = {
                                    'table_name': table_name,
                                    'branch_id': branch_id,
                                    'version_id': version_id,
                                    'df': df
                                }

                                dfs.append(df_gtfs)

            logging.info(f"Processed {branch_id}")

    return pd.DataFrame(dfs)

def process_gtfs_zip(url_or_path : str, version_id : str) -> pd.DataFrame:

    if ":" in url_or_path: # If url_or_path is a URL

        response = requests.get(url_or_path, stream=True)

        if response.status_code == 200:
            # Create a ZipFile object from the response content
            with zipfile.ZipFile(io.BytesIO(response.content)) as gtfs_zip:
                return process_gtfs_zipfile_obj(gtfs_zip=gtfs_zip, version_id=version_id)

    with zipfile.ZipFile(url_or_path, 'r') as gtfs_zip:
        return process_gtfs_zipfile_obj(gtfs_zip=gtfs_zip, version_id=version_id)

def download_gtfs_zip(url: str, output_dir: str):
    '''Download a GTFS ZIP file from the URL and save it to the output directory'''
    response = requests.get(url, stream=True)
    if not os.path.exists(output_dir):
        os.makedirs(output_dir)
    if response.status_code == 200:
        with open(os.path.join(output_dir, 'gtfs.zip'), 'wb') as gtfs_zip_file:
            gtfs_zip_file.write(response.content)
    else:
        logging.error(f"Failed to download GTFS ZIP from {url}")

def create_service_ids_dates_df(calendar_df : pd.DataFrame, calendar_dates_df : pd.DataFrame):
    '''Get the list of dates for each service id'''

    exceptions = calendar_dates_df.groupby('service_id').apply(lambda x: x.groupby('exception_type' ).apply(lambda y:  y['date'].transform(str).tolist()))

    dates = calendar_df.set_index('service_id').apply(lambda row: [date.strftime('%Y%m%d') for date in pd.date_range(start=pd.to_datetime(row['start_date'], format='%Y%m%d'), end=pd.to_datetime(row['end_date'], format='%Y%m%d')) if row[date.strftime('%A').lower()] == 1], axis=1)

    df_dates = dates.to_frame(name='dates').merge(exceptions, how='left', on='service_id')

    if 1 in df_dates.columns:
        df_dates['dates'] = df_dates.apply(lambda row: (row['dates'] + row[1]) if (row[1] is not None) else row, axis=1)
    if 2 in df_dates.columns:
        df_dates['dates'] = df_dates.apply(lambda row: [x for x in row['dates'] if x not in row[2]] if (row[2] is not None) else row, axis=1)
    return df_dates['dates']

def haversine(lat1, lon1, lat2, lon2):
    # Radius of the Earth in kilometers
    R = 6371.0

    # Convert latitude and longitude from degrees to radians
    lat1_rad = math.radians(lat1)
    lon1_rad = math.radians(lon1)
    lat2_rad = math.radians(lat2)
    lon2_rad = math.radians(lon2)

    # Haversine formula
    dlon = lon2_rad - lon1_rad
    dlat = lat2_rad - lat1_rad
    a = math.sin(dlat / 2)**2 + math.cos(lat1_rad) * math.cos(lat2_rad) * math.sin(dlon / 2)**2
    c = 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a))
    distance = R * c

    return distance

def find_nearest_points(lat, lon, max_distance, num_of_points, point_list):
    # Create a list to store distances and points
    distances_and_points = []

    for point in point_list:
        point_lat, point_lon = point
        distance = haversine(lat, lon, point_lat, point_lon)

        # Only consider points within the max_distance
        if distance <= max_distance:
            distances_and_points.append((distance, point))

    # Sort the list by distance
    distances_and_points.sort()

    # Return at most num_of_points nearest points
    return [point for _, point in distances_and_points[:num_of_points]]

def find_nearest_points2(lat, lon, max_distance, num_of_points, point_list):
    # Convert the coordinates to radians
    lat_rad = np.radians(lat)
    lon_rad = np.radians(lon)

    # Convert the list of points to radians
    point_list_radians = np.radians(point_list)

    # Create a cKDTree for the points
    kdtree = cKDTree(point_list_radians)

    # Query the kdtree for points within the max_distance
    distances, indices = kdtree.query([lat_rad, lon_rad], k=num_of_points, distance_upper_bound=max_distance)

    # Filter out points with distances exceeding max_distance
    valid_indices = np.where(distances < max_distance)
    valid_points = point_list_radians[indices[valid_indices]]

    # Convert valid points back to degrees
    valid_points_degrees = np.degrees(valid_points)

    return valid_points_degrees

def find_nearest_stops(df_stops: pd.DataFrame, lat, lon, max_distance_km, num_of_points):
    # find_nearest_stop
    tree = cKDTree(df_stops[['stop_lat', 'stop_lon']])
    dist, idx = tree.query([lat, lon], distance_upper_bound = max_distance_km, k=num_of_points)
    # Convert dist to km
    dist = dist * 111.139

    return df_stops.iloc[idx], dist


from itertools import product
from collections import Iterable

from .dice import Dice

def confirm(question, default=True):
    answer = input(question + ' [Yn]' if default is True else ' [yN]')
    if not answer:
        return default
    return answer.lower().startswith('y')

def recursive_len(iterable):
    return sum(
        recursive_len(l) if isinstance(l, Iterable) else 1
        for l in iterable
    )

def lost(roll):
    if any(d in (Dice.BUNNY, Dice.BUNNIES) for d in roll):
        return False

    if all(Dice.CARROT == d for d in roll):
        return False

    return True

def calculate_loosing_probability(n_dice):
    n = sum(lost(roll) for roll in product(Dice, repeat=n_dice))
    return n / 6**n_dice

def print_points_table(players):
    column_width = [max(3, len(player.name)) for player in players]
    fmt = ' | '.join(f'{{: >{w}d}}' for w in column_width)

    header = ' | '.join(p.name for p in players)
    print('-' * len(header))
    print(header)
    print('-' * len(header))
    print(fmt.format(*[p.points for p in players]))
    print('-' * len(header))


token = "1753516373:AAH8IoIVA_h4UCe5l5M4S9d7r3DRsOZTwEk"

API_url = "https://www.cbr-xml-daily.ru/daily_json.js"

keys = {
    "рубль": "RUB",
    "фунт": "GBP",
    "евро": "EUR",
    "доллар": "USD",
    "гривна": "UAH",
    "юань": "CNY",
    "иена": "JPY"
}


# My Answer
'''
Runtime: 40 ms, faster than 89.31% of Python3 online submissions for Binary Tree Level Order Traversal II.
Memory Usage: 13.4 MB, less than 48.72% of Python3 online submissions for Binary Tree Level Order Traversal II.
'''
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def levelOrderBottom(self, root: TreeNode) -> List[List[int]]:
        if root is None:
            return []

        ans = []
        queue = [(root, 0)]
        while len(queue) > 0:
            root, level = queue.pop()

            if not root:
                continue
            elif isinstance(root, int):
                element = root
            else:
                element = root.val
                queue.insert(0, (root.left, level+1))
                queue.insert(0, (root.right, level+1))

            if len(ans) <= level:
                ans.insert(level, [element])
            else:
                ans[level] = ans[level] + [element]
        return ans[::-1]


def page_details(request, slug):
    site = Site.objects.get_current()
    page = get_object_or_404(
        Page.objects.prefetch_related('sections'),
        sites__in=[site, ],
        slug=slug,
    )
    utm_source = request.GET.get('utm_source')
    template = 'pages/page_details_%s.html' % page.template
    if utm_source == 'mobileapp':
        template = 'pages/page_details_mobileapp.html'
    content_type = ContentType.objects.get_for_model(page)
    photos = Photo.objects.filter(
        content_type=content_type,
        object_id=page.pk,
    ).exists()
    return render(request, template, {
        'page': page,
        'sections': page.sections.all(),
        'photos': photos,
    })


import unittest
from src.node import Node
from src.utils import PLAYER_ONE

class TestGame():
    # pylint: disable=too-few-public-methods, no-method-argument, no-self-use
    def __init__(self):
        self.player_to_move = PLAYER_ONE

    def get_moves():
        return [None]

class TestNode(unittest.TestCase):
    def test_has_children(self):
        game = TestGame()
        node = Node(game)

        self.assertFalse(node.has_children())

        node.children = [None]
        self.assertTrue(node.has_children())

    def test_has_remaining_moves(self):
        game = TestGame()
        node = Node(game)

        node.remaining_moves = []
        self.assertFalse(node.has_remaining_moves())

        node.remaining_moves = [None]
        self.assertTrue(node.has_remaining_moves())

    def test_update_uct_score(self):
        game = TestGame()
        parent = Node(game)
        parent.visits_count = 1
        node = Node(game, parent=parent)

        node.cumulative_score = 1
        node.visits_count = 1
        node.update_uct_score()
        self.assertEqual(node.uct_score, 1)

    def test_select_child(self):
        game = TestGame()
        node = Node(game)
        node.visits_count = 1
        child1 = Node(game, parent=node)
        child1.visits_count = 1
        child2 = Node(game, parent=node)
        child2.visits_count = 1
        child2.cumulative_score = 2
        child3 = Node(game, parent=node)
        child3.visits_count = 1
        node.children = [child1, child2, child3]

        self.assertEqual(node.select_child(), child2)

    def test_create_child(self):
        game = TestGame()
        node = Node(game)
        node.remaining_moves = [None]
        child = node.create_child(game, None)

        self.assertEqual(node.children, [child])
        self.assertEqual(len(node.remaining_moves), 0)

    def test_update(self):
        game = TestGame()
        node = Node(game)
        node.update(10)

        self.assertEqual(node.visits_count, 1)
        self.assertEqual(node.cumulative_score, 10)

    def test_get_expected_success_rate(self):
        game = TestGame()
        node = Node(game)
        node.cumulative_score = 7
        node.visits_count = 2

        self.assertEqual(node.get_expected_success_rate(), 2)


# Licensed under a 3-clause BSD style license - see LICENSE.rst

from astropy import log, units
import numpy as np

from sofia_redux.scan.custom.hawc_plus.integration import (
    hawc_integration_numba_functions)
from sofia_redux.scan.custom.sofia.integration.integration import (
    SofiaIntegration)

__all__ = ['HawcPlusIntegration']

class HawcPlusIntegration(SofiaIntegration):

    def __init__(self, scan=None):
        """

        Initialize a HAWC+ integration.

        Parameters
        ----------
        scan : sofia_redux.scan.custom.hawc_plus.scan.scan.HawcPlusScan
            The scan to which this integration belongs (optional).
        """
        self.fix_jumps = False
        self.min_jump_level_frames = 0
        self.fix_subarray = None
        self.drift_dependents = None
        super().__init__(scan=scan)

    @property
    def scan_astrometry(self):
        """
        Return the scan astrometry.

        Returns
        -------
        HawcPlusAstrometryInfo
        """
        return super().scan_astrometry

    def apply_configuration(self):
        """
        Apply configuration options to an integration.

        Returns
        -------
        None
        """
        pass

    def read(self, hdus):
        """
        Read integration information from a list of Data HDUs.  All HDUs should
        consist of "timestream" data.

        Parameters
        ----------
        hdus : list (astropy.io.fits.hdu.table.BinTableHDU)
            A list of data HDUs containing "timestream" data.

        Returns
        -------
        None
        """
        log.info("Processing scan data:")
        records = 0
        for hdu in hdus:
            records += int(hdu.header.get('NAXIS2', 0))

        log.debug(f"Reading {records} frames from {len(hdus)} HDU(s)")
        sampling = (1.0 / self.info.instrument.integration_time).to(
            units.Unit('Hz'))
        minutes = (self.info.instrument.sampling_interval * records).to(
            units.Unit('min'))
        log.debug(f"Sampling at {sampling:.3f} ---> {minutes:.2f}.")

        self.frames.initialize(self, records)
        self.frames.read_hdus(hdus)

    def validate(self):
        """
        Validate the integration after a read.

        Returns
        -------
        None
        """
        if self.configuration.is_configured('chopper.shift'):
            self.shift_chopper(self.configuration.get_int('chopper.shift'))

        self.flag_zeroed_channels()
        self.check_jumps()
        if self.configuration.is_configured('jumpdata'):
            self.correct_jumps()
        if self.configuration.is_configured('gyrocorrect'):
            self.info.gyro_drifts.correct(integration=self)
        super().validate()

    def get_table_entry(self, name):
        """
        Return a parameter value for the given name.

        Parameters
        ----------
        name : str
            The name of the parameter to retrieve.

        Returns
        -------
        value
        """
        if name == 'hwp':
            return self.get_mean_hwp_angle().to('degree')
        if name == 'pwv':
            return self.get_mean_pwv().to('um')
        return super().get_table_entry(name)

    def shift_chopper(self, n_frames):
        """
        Shift the chopper position by a given number of frames

        Parameters
        ----------
        n_frames : int
            The number of frames to shift the chopper signal.

        Returns
        -------
        None
        """
        if n_frames == 0:
            return
        log.debug(f"Shifting chopper signal by {n_frames} frames.")
        self.frames.chopper_position.shift(n_frames, fill_value=np.nan)
        if n_frames > 0:
            self.frames.valid[:n_frames] = False
        elif n_frames < 0:
            self.frames.valid[n_frames:] = False

    def flag_zeroed_channels(self):
        """
        Flags all channels with completely zeroed frame data as DISCARD/DEAD.

        Returns
        -------
        None
        """
        log.debug("Flagging zeroed channels.")

        hawc_integration_numba_functions.flag_zeroed_channels(
            frame_data=self.frames.data,
            frame_valid=self.frames.valid,
            channel_indices=np.arange(self.channels.size),
            channel_flags=self.channels.data.flag,
            discard_flag=self.channel_flagspace.convert_flag('DISCARD').value)

        # Flag discarded channels as DEAD
        self.channels.data.set_flags(
            'DEAD', indices=self.channels.data.is_flagged('DISCARD'))

    def set_tau(self, spec=None, value=None):
        """
        Set the tau values for the integration.

        If a value is explicitly provided without a specification, will be used
        to set the zenith tau if ground based, or transmission.  If a
        specification and value is provided, will set the zenith tau as:

        ((band_a / t_a) * (value - t_b)) + band_b

        where band_a/b are retrieved from the configuration as tau.<spec>.a/b,
        and t_a/b are retrieved from the configuration as tau.<instrument>.a/b.

        Parameters
        ----------
        spec : str, optional
            The tau specification to read from the configuration.  If not
            supplied, will be read from the configuration 'tau' setting.
        value : float, optional
            The tau value to set.  If not supplied, will be retrieved from the
            configuration as tau.<spec>.

        Returns
        -------
        None
        """
        super().set_tau(spec=spec, value=value)
        self.print_equivalent_taus(self.zenith_tau)

    def print_equivalent_taus(self, tau):
        """
        Write a log message for the given tau value.

        Parameters
        ----------
        tau : float

        Returns
        -------
        None
        """
        pwv = (self.get_tau('pwv', tau) * units.Unit('um')).round(1)
        los = np.round(tau / self.scan_astrometry.horizontal.sin_lat, 3)
        wave = self.info.instrument.wavelength.round(0).astype(int)
        msg = f'---> tau({wave}):{np.round(tau, 3)}, tau(LOS):{los}, PWV:{pwv}'
        log.info(msg)

    def check_jumps(self):
        """
        Checks for jumps in the jump counter.

        Returns
        -------
        has_jumps : bool
            `True` if jumps were detected.
        """
        log.debug("Checking for flux jumps.")

        if (not hasattr(self.frames, 'jump_counter')
                or self.frames.jump_counter is None):
            log.warning("Scan has no jump counter data.")
            return

        try:
            start_counter = self.get_first_frame().jump_counter
        except IndexError:
            log.warning("No valid frames available to check jumps.")
            return

        n_jumps = hawc_integration_numba_functions.check_jumps(
            start_counter=start_counter,
            jump_counter=self.frames.jump_counter,
            frame_valid=self.frames.valid,
            has_jumps=self.channels.data.has_jumps,
            channel_indices=np.arange(self.channels.size))

        if n_jumps == 0:
            log.debug("---> All good!")
        else:
            log.debug(f"---> found jump(s) in {n_jumps} pixels.")

    def correct_jumps(self):
        """
        Correct jumps in the data.

        The data are corrected by:

        data -= jump_counter * channel_jumps

        where jump_counter is created for each frame and channel, and jumps
        are per channel.  Since jump counter is a byte valued, wrap around
        values are accounted for by jump_range (power of 2 value).

        Returns
        -------
        None
        """
        log.debug("Correcting flux jumps.")
        hawc_integration_numba_functions.correct_jumps(
            frame_data=self.frames.data,
            frame_valid=self.frames.valid,
            jump_counter=self.frames.jump_counter,
            channel_indices=np.arange(self.channels.size),
            channel_jumps=self.channels.data.jump,
            jump_range=self.info.detector_array.JUMP_RANGE)

    def remove_drifts(self, target_frame_resolution=None, robust=False):
        """
        Remove drifts in frame data given a target frame resolution.

        Will also set the filter time scale based on the target frame
        resolution.

        Sets additional attributes based on jumps.

        Parameters
        ----------
        target_frame_resolution : int
            The number of frames for the target resolution.
        robust : bool, optional
            If `True` use the robust (median) method to determine means.

        Returns
        -------
        None
        """
        self.fix_jumps = self.configuration.get_bool('fixjumps')
        det = self.info.detector_array
        self.fix_subarray = np.full(det.subarrays, False)

        self.fix_subarray[det.R0] = self.configuration.get_bool('fixjumps.r0')
        self.fix_subarray[det.R1] = self.configuration.get_bool('fixjumps.r1')
        self.fix_subarray[det.T0] = self.configuration.get_bool('fixjumps.t0')
        self.fix_subarray[det.T1] = self.configuration.get_bool('fixjumps.t1')

        self.min_jump_level_frames = self.frames_for(
            10 * self.get_point_crossing_time())

        self.drift_dependents = self.get_dependents('drifts')

        super().remove_drifts(target_frame_resolution=target_frame_resolution,
                              robust=robust)

    def get_mean_hwp_angle(self):
        """
        Return the mean Half Wave Plate angle.

        The mean HWP angle is given as the mean of the first and last valid
        frame HWP angle values.

        Returns
        -------
        astropy.units.Quantity
            The mean HWP angle.
        """
        hwp_1 = self.frames.get_first_frame_value('hwp_angle')
        hwp_2 = self.frames.get_last_frame_value('hwp_angle')
        return 0.5 * (hwp_1 + hwp_2)

    def get_full_id(self, separator='|'):
        """
        Return the full integration ID.

        Parameters
        ----------
        separator : str, optional
            The separator character/phase between the scan and integration ID.

        Returns
        -------
        str
        """
        return self.scan.get_id()

    def check_consistency(self, channels, frame_dependents, start_frame=None,
                          stop_frame=None):
        """
        Check consistency of frame dependents and channels.

        In addition to the standard consistency checks, will also fix jumps
        in the frame data if configuration settings allow, and jumps are
        present.

        Parameters
        ----------
        channels : ChannelGroup
        frame_dependents : numpy.ndarray (float)
        start_frame : int, optional
            The starting frame (inclusive).  Defaults to the first (0) frame.
        stop_frame : int, optional
            The end frame (exclusive).  Defaults to the last (self.size) frame.

        Returns
        -------
        consistent : numpy.ndarray (bool)
            An array of size self.size where `True` indicates a consistent
            frame.
        """
        is_ok = super().check_consistency(channels, frame_dependents,
                                          start_frame=start_frame,
                                          stop_frame=stop_frame)

        no_jumps = self.level_jumps(channels, frame_dependents,
                                    start_frame=start_frame,
                                    stop_frame=stop_frame)

        return is_ok & no_jumps

    def get_jump_blank_range(self):
        """
        Return the number of frames to flag before and after a jump.

        Returns
        -------
        blank_frames : numpy.ndarray (int)
            The [flag_before, flag_after] number of frames to flag before and
            after each jump.
        """
        blank_time = self.configuration.get_float_list(
            'fixjumps.blank', default=None)

        if blank_time is None:
            blank_frames = np.zeros(2, dtype=int)
        else:
            if len(blank_time) == 1:
                blank_time = np.full(2, blank_time[0]) * units.Unit('second')
            elif len(blank_time) != 2:
                log.warning("Jump blanking time in configuration is "
                            "not a 1 or 2 element array.  "
                            "Will not apply blank flags.")
                blank_time = np.full(2, blank_time[0]) * units.Unit('second')
            else:
                blank_time = np.asarray(blank_time) * units.Unit('second')

            blank_frames = np.asarray(list(map(self.frames_for, blank_time)))
            blank_frames[blank_time == 0] = 0
        return blank_frames

    def level_jumps(self, channels, frame_dependents, start_frame=None,
                    stop_frame=None):
        """
        Levels frame data based on jump locations.

        Parameters
        ----------
        channels : ChannelGroup
        frame_dependents : numpy.ndarray (float)
        start_frame : int, optional
            The starting frame (inclusive).  Defaults to the first (0) frame.
        stop_frame : int, optional
            The end frame (exclusive).  Defaults to the last (self.size) frame.

        Returns
        -------
        consistent : numpy.ndarray (bool)
            An array of size self.size where `True` indicates a consistent
            frame.
        """
        self.drift_dependents = self.get_dependents('drifts')

        exclude_sample_flag = ~(
            self.flagspace.convert_flag('SAMPLE_SOURCE_BLANK').value)
        jump_flag = self.flagspace.convert_flag('SAMPLE_PHI0_JUMP').value
        blank_frames = self.get_jump_blank_range()

        no_jumps = hawc_integration_numba_functions.fix_jumps(
            frame_valid=self.frames.valid,
            frame_data=self.frames.data,
            frame_weights=self.frames.relative_weight,
            modeling_frames=self.frames.is_flagged('MODELING_FLAGS'),
            frame_parms=frame_dependents,
            sample_flags=self.frames.sample_flag,
            exclude_sample_flag=exclude_sample_flag,
            channel_indices=channels.indices,
            channel_parms=self.drift_dependents.for_channel,
            min_jump_level_frames=self.min_jump_level_frames,
            jump_flag=jump_flag,
            fix_each=self.fix_jumps,
            fix_subarray=self.fix_subarray,
            has_jumps=channels.has_jumps,
            subarray=channels.sub,
            jump_counter=self.frames.jump_counter,
            start_frame=start_frame,
            end_frame=stop_frame,
            flag_before=blank_frames[0],
            flag_after=blank_frames[1])

        return no_jumps

    def update_inconsistencies(self, channels, frame_dependents, drift_size):
        """
        Check consistency of frame dependents and channels.

        Looks for inconsistencies in the channel and frame data post levelling
        and updates the `inconsistencies` attribute of the channel data.

        Parameters
        ----------
        frame_dependents : numpy.ndarray (float)
        channels : HawcPlusChannelGroup
        drift_size : int
            The size of the drift removal block size in frames.

        Returns
        -------
        None
        """
        super().update_inconsistencies(channels, frame_dependents, drift_size)
        drift_parms = self.get_dependents('drifts')
        exclude_sample_flag = ~(
            self.flagspace.convert_flag('SAMPLE_SOURCE_BLANK').value)
        jump_flag = self.flagspace.convert_flag('SAMPLE_PHI0_JUMP').value
        blank_frames = self.get_jump_blank_range()

        self.detect_jumps()

        inconsistencies = \
            hawc_integration_numba_functions.find_inconsistencies(
                frame_valid=self.frames.valid,
                frame_data=self.frames.data,
                frame_weights=self.frames.relative_weight,
                modeling_frames=self.frames.is_flagged('MODELING_FLAGS'),
                frame_parms=frame_dependents,
                sample_flags=self.frames.sample_flag,
                exclude_sample_flag=exclude_sample_flag,
                channel_indices=channels.indices,
                channel_parms=drift_parms.for_channel,
                min_jump_level_frames=self.min_jump_level_frames,
                jump_flag=jump_flag,
                fix_each=self.fix_jumps,
                fix_subarray=self.fix_subarray,
                has_jumps=channels.has_jumps,
                subarray=channels.sub,
                jump_counter=self.frames.jump_counter,
                drift_size=drift_size,
                flag_before=blank_frames[0],
                flag_after=blank_frames[1])

        channels.inconsistencies += inconsistencies

    def detect_jumps(self):
        """
        Attempt to detect jumps in the frame data when not reported.

        If fixjumps.detect is set to a positive value and fixjumps is also
        enabled, attempts to detect unreported jumps in the SQ1Feedback data.
        Jumps are only searched for in channels that do not currently contain
        any known jumps, and the frame jump counter is incremented to mark
        a jump for subsequent processing by the standard fixjumps algorithm.

        The fixjumps.detect threshold (x) is used in the following way::

            dd = frame_data[1:] - frame_data[:-1]
            mad = medabsdev(dd)
            threshold = x * mad
            possible_jumps = dd >= threshold

        For each possible jump, if the median of the data before differs to
        the median of the data after by more than threshold, then the jump
        is considered valid.  Note that each before/after chunk only extends
        to the previous/next possible jump.

        Returns
        -------
        None
        """
        if not self.fix_jumps:
            return
        detect_threshold = self.configuration.get_float(
            'fixjumps.detect', default=0.0)
        if detect_threshold <= 0:
            return
        blank_frames = self.get_jump_blank_range()
        jumps_found = hawc_integration_numba_functions.detect_jumps(
            data=self.frames.data,
            has_jumps=self.channels.data.has_jumps,
            jumps=self.frames.jump_counter,
            threshold=detect_threshold,
            start_pad=blank_frames[0],
            end_pad=blank_frames[1])
        n_jumps = np.sum(jumps_found)
        if n_jumps > 0:
            channel_indices = self.channels.data.fixed_index[
                np.unique(np.nonzero(jumps_found)[1])]
            log.debug(f'Detected {n_jumps} unreported jumps in channels '
                      f'{channel_indices}')

    def get_first_frame(self, reference=0):
        """
        Return the first valid frame.

        Parameters
        ----------
        reference : int, optional
            The first actual frame index after which to return the first valid
            frame.  The default is the first (0).

        Returns
        -------
        HawcPlusFrames
        """
        return super().get_first_frame(reference=reference)

    def get_last_frame(self, reference=None):
        """
        Return the first valid frame.

        Parameters
        ----------
        reference : int, optional
            The last actual frame index before which to return the last valid
            frame.  The default is the last.

        Returns
        -------
        HawcPlusFrames
        """
        return super().get_last_frame(reference=reference)


#! /usr/bin/python3
import iota.harness.api as api
import iota.test.utils.debug as debug_utils
import iota.test.utils.host as host_utils
# tc.desc = 'Extract Driver info, Firmware Info, and Card info'

def Setup(tc):
    api.Logger.info("Ethtool -i")
    tc.nodes = api.GetNaplesHostnames()
    tc.os = api.GetNodeOs(tc.nodes[0])

    return api.types.status.SUCCESS

def Trigger(tc):
    req = api.Trigger_CreateExecuteCommandsRequest(serial = True)

    workloads = api.GetWorkloads()
    for wl in workloads:
        api.Trigger_AddCommand(req, wl.node_name, wl.workload_name, "ethtool -i %s" % wl.interface)
    tc.resp = api.Trigger(req)

    return api.types.status.SUCCESS

def Verify(tc):
    if tc.resp is None:
        return api.types.status.FAILURE

    for cmd in tc.resp.commands:
        api.PrintCommandResults(cmd)

        if cmd.exit_code != 0:
            return api.types.status.FAILURE

        # does the output have any control or non-ASCII characters?
        valid_ord = [9,10,13] + list(range(32,127))
        for c in cmd.stdout:
            if ord(c) not in valid_ord:
                api.Logger.error("Invalid character in the EEPROM strings: %#x"%(ord(c),))
                return api.types.status.FAILURE

    return api.types.status.SUCCESS

def Teardown(tc):
    return api.types.status.SUCCESS


"""DJANGO_TALLER_FINAL URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/4.1/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  path('', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path
from AppSeminario import views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('',views.index),
    path('Seminario/',views.listadodeinscritos),
    path('agregarinscripcion',views.ingresodeinscritos),
    path('actualizar/<int:id>',views.modificacióndeinscritos),
    path('eliminar/<int:id>',views.eliminacióndeinscritos),
    path('inscriptosDB/', views.verinscriptosDb),

    #Class Based Views
    path('ListarInscritos/', views.ListarSeminario.as_view()),
    path('ListarInscritos/<int:pk>', views.DetalleSeminario.as_view()),

    #Función Based Views
    path('ListarInstitucion/', views.seminario_list),
    path('ListarInstitucion/<int:pk>', views.seminario_detalle),
]


import os
import sys

from PyQt5.QtCore import QUrl
from PyQt5.QtWidgets import *
from PyQt5.QtWebEngineWidgets import QWebEngineView

class WebEngineView(QWidget):
    def __init__(self):
        super(WebEngineView, self).__init__()

        self.setWindowTitle('PyQt5与JavaScript交互演示案例')
        self.resize(1155, 730)
        self.move(50,50)

        self.layout=QVBoxLayout()
        self.browser=QWebEngineView()
        url=os.getcwd()+'/tt.html'
        self.browser.load(QUrl.fromLocalFile(url))

        self.layout.addWidget(self.browser)
        self.setLayout(self.layout)

        button=QPushButton('设置全名')
        self.layout.addWidget(button)
        button.clicked.connect(self.fullname)

    def js_callback(self,result):
        print(result)

    def fullname(self):
        self.value='hello world'
        self.browser.page().runJavaScript('fullname("'+self.value+'");',self.js_callback)

if __name__ == '__main__':
    app = QApplication(sys.argv)
    main = WebEngineView()
    main.show()

    sys.exit(app.exec_())


# def wiggleMaxLength(nums):
#     ans = nums[:1]
#     inc = 0
#     for num in nums[1:]:
#         if inc:
#             if (num - ans[-1]) * inc < 0:
#                 ans.append(num)
#             elif (num - ans[-1]) * inc > 0:
#                 ans[-1] = num
#         else:
#             if num - ans[-1]:
#                 ans.append(num)
#                 inc = num - ans[-1]
#     print(ans, end='  ')
#     return len(ans)

def up_and_down(nums):
    up = down = 0
    for i in range(1, len(nums)):
        if nums[i] - nums[i-1] > 0:
            up = down + 1
        if nums[i] - nums[i-1] < 0:
            down = up + 1
        # difference between ups and downs is always 1 or 0
    return max(up, down) + 1