import unittest2
import os
import tempfile

import top
from top.utils.files import (copy_file,
                             remove_files,
                             get_directory_files_list)

class TestExporterDaemon(unittest2.TestCase):

    @classmethod
    def setUpClass(cls):
        cls._ed = top.ExporterDaemon(pidfile=None)
        cls._ed.set_business_units({'priority': 1, 'fast': 2, 'ipec': 3})
        cls._ed._config = top.ExporterB2CConfig()
        cls._ed._config.set_cond({'tolp': '000100000000010110',
                                  'tolf': '000101100000010110',
                                  'toli': '100010000000010110'})
        cls._ed._config.set_file_bu({'tolp': 1,
                                     'tolf': 2,
                                     'tolf_nsw': 2,
                                     'tolf_vic': 2,
                                     'tolf_qld': 2,
                                     'tolf_sa': 2,
                                     'tolf_wa': 2,
                                     'tolf_act': 2,
                                     'toli': 3})

        # Signature dir.
        cls._signature_dir = tempfile.mkdtemp()
        cls._ed._config.set_signature_dir(cls._signature_dir)
        cls._sig_files = ['1.ps', '1.png', '5.ps', '5.png']
        for f in cls._sig_files:
            fh = open(os.path.join(cls._signature_dir, f), 'w')
            fh.close()

        # Exporter file closure dirs.
        cls._exporter_dir = tempfile.mkdtemp()
        cls._ed._config.set_exporter_dirs([cls._exporter_dir])
        cls._ed._config.set_exporter_file_formats(['.*_RE[PIF]_\d{14}\.txt$'])

        # Staging base.
        cls._staging_dir = tempfile.mkdtemp()
        cls._ed._config.set_staging_base(cls._staging_dir)

        # Archive directory.
        cls._archive_dir = tempfile.mkdtemp()
        cls._ed._config.set_archive_dir(cls._archive_dir)

        cls._ed.emailer.set_template_base(os.path.join('top', 'templates'))

        # Call up front to pre-load the DB.
        cls._ed._exporter = top.Exporter(**(cls._ed.exporter_kwargs))
        cls._ed.set_exporter_fields({'tolp': '0,1,2,3,4,5,6',
                                     'tolf': '0,1,2,3,4,5,6',
                                     'toli': '0,1,2,3,4,5,6,7'})

        db = cls._ed._exporter.db
        fixture_dir = os.path.join('top', 'tests', 'fixtures')
        fixtures = [{'db': db.agent, 'fixture': 'agents.py'},
                    {'db': db.identity_type,
                     'fixture': 'identity_type.py'},
                    {'db': db.job, 'fixture': 'jobs.py'},
                    {'db': db.jobitem, 'fixture': 'jobitems.py'}]
        for i in fixtures:
            fixture_file = os.path.join(fixture_dir, i['fixture'])
            db.load_fixture(i['db'], fixture_file)

        db.commit()

    def test_init(self):
        """Intialise a ExporterDaemon object.
        """
        msg = 'Not a top.ExporterDaemon object'
        self.assertIsInstance(self._ed, top.ExporterDaemon, msg)

    def test_start(self):
        """Start dry loop.
        """
        old_dry = self._ed.dry

        self._ed.set_dry()
        self._ed._start(self._ed.exit_event)

        # Clean up.
        self._ed.set_dry(old_dry)
        self._ed.exit_event.clear()

    def test_start_non_dry(self):
        """Start non-dry loop.
        """
        dry = False

        old_dry = self._ed.dry
        old_batch = self._ed.batch
        old_support_emails = list(self._ed.support_emails)

        test_file_dir = os.path.join('top', 'tests', 'files')
        file = 'VIC_VANA_REP_20140214120000.txt'
        copy_file(os.path.join(test_file_dir, file),
                  os.path.join(self._exporter_dir, file))

        # Start processing.
        self._ed.set_dry(dry)
        self._ed.set_batch()
        # Add valid email address here if you want to verify support comms.
        self._ed.set_support_emails(None)
        self._ed._start(self._ed.exit_event)

        # Clean up.
        self._ed.set_support_emails(old_support_emails)
        self._ed.set_dry(old_dry)
        self._ed.set_batch(old_batch)
        self._ed.exit_event.clear()

    @classmethod
    def tearDownClass(cls):
        del cls._ed
        # Hardwired for now until we can think of a better way ...
        sig_dir_1 = os.path.join(cls._archive_dir,
                                 'signature',
                                 'c4',
                                 'c4ca',
                                 'c4ca42',
                                 'c4ca4238')
        remove_files(get_directory_files_list(sig_dir_1))
        sig_dir_5 = os.path.join(cls._archive_dir,
                                 'signature',
                                 'e4',
                                 'e4da',
                                 'e4da3b',
                                 'e4da3b7f')
        remove_files(get_directory_files_list(sig_dir_5))
        os.removedirs(sig_dir_1)
        os.removedirs(sig_dir_5)
        os.removedirs(cls._exporter_dir)
        for dir in ['priority', 'fast', 'ipec']:
            out_dir = os.path.join(cls._staging_dir, dir, 'out')
            remove_files(get_directory_files_list(out_dir))
            os.removedirs(out_dir)


# Import os to set API key
import os
# Import OpenAI as main LLM service
from langchain.llms import OpenAI
from langchain.embeddings import OpenAIEmbeddings
# Bring in streamlit for UI/app interface
import streamlit as st

# Read the markdown content from a file
with open("styles.md", "r") as f:
    markdown_content = f.read()
st.markdown(markdown_content, unsafe_allow_html=True)

# Import PDF document loaders...there's other ones as well!
from langchain.document_loaders import PyPDFLoader
# Import chroma as the vector store
from langchain.vectorstores import Chroma

# Import vector store stuff
from langchain.agents.agent_toolkits import (
    create_vectorstore_agent,
    VectorStoreToolkit,
    VectorStoreInfo
)

# Set APIkey for OpenAI Service
with open("api_key.txt", "r") as file:
    api_key = file.read().strip()
os.environ['OPENAI_API_KEY'] = api_key

# Create instance of OpenAI LLM
llm = OpenAI(temperature=0.1, verbose=True)
embeddings = OpenAIEmbeddings()

# Create and load PDF Loader
loader = PyPDFLoader('FinanceReport.pdf')
# Split pages from pdf
pages = loader.load_and_split()
# Load documents into vector database aka ChromaDB
store = Chroma.from_documents(pages, embeddings, collection_name='Report2023')

# Create vectorstore info object - metadata repo?
vectorstore_info = VectorStoreInfo(
    name="finance_report",
    description="a finance report as a pdf",
    vectorstore=store
)
# Convert the document store into a langchain toolkit
toolkit = VectorStoreToolkit(vectorstore_info=vectorstore_info)

# Add the toolkit to an end-to-end LC
agent_executor = create_vectorstore_agent(
    llm=llm,
    toolkit=toolkit,
    verbose=True
)

# Create a text input box for the user
prompt = st.text_input('Input your request here')

# If the user hits enter
if prompt:
    # Then pass the prompt to the LLM
    response = agent_executor.run(prompt)
    # ...and write it out to the screen
    st.write(response)


#setting initial value of variable
score = 0
score = int(score)

#Ask user for their name
name = input("What is your name?")
name = name.title()
print("""Hello {}, welcome to the classification algorithm for risk prediction!
You will be presented with 2 questions regarding your age and profession.
Enter the appropriate number or letter to answer the question
Good luck!""".format(name))

#Question1
print("""What is your age category?
1. 13-35
2. 36-50
3. 51-69
4. 70-100""")

answer1 = "1"
answer2 = "2"
answer3 = "3"
answer4 = "4"

response1 = input("Your answer is:")

if response1 == answer1:
    score += 2
elif response1 == answer2:
    score += 3
elif response1 == answer3:
    score += 4
else:
    score += 5

print("Your current score is " + str(score))

#Question 2
print("""What sector of profession are you in?
a. Student/School
b. Public workers (chefs, labourers, bartenders etc)
c. Education (teachers, professors)
d. Healthcare (doctors, nurses)""")

answertwo1 = "a"
answertwo2 = "b"
answertwo3 = "c"
answertwo4 = "d"

response2 = input("Your answer is:")

if response2 == answertwo1:
    score += 2
elif response2 == answertwo2:
    score += 3
elif response2 == answertwo3:
    score += 4
else:
    score += 5

#Printing the final results
print("Your current score is " + str(score))

print("Your total score is " + str(score))
if score >= 7:
    print("You fall in the higher risk end and hence will be prioritized to get vaccinated!")

print("Thank you for taking part in this {}!".format(name))


from PyQt5.QtWidgets import QWidget, QVBoxLayout, QLabel, QPushButton

from pizza.controller.ControllorePizza import ControllorePizza

class VistaEliminaPizza(QWidget):
    def __init__(self, pizza, elimina_pizza, elimina_callback, parent=None):
        super(VistaEliminaPizza, self).__init__(parent)
        self.controllore = ControllorePizza(pizza)
        self.elimina_pizza = elimina_pizza
        self.elimina_callback = elimina_callback

        v_layout = QVBoxLayout()
        label = QLabel("Vuoi eliminare la pizza " + pizza.nome + "?")
        font = label.font()
        font.setPointSize(18)
        label.setFont(font)
        v_layout.addWidget(label)

        delete_btn = QPushButton("Elimina")
        delete_btn.clicked.connect(self.elimina)
        v_layout.addWidget(delete_btn)

        self.setLayout(v_layout)
        self.resize(150, 300)
        self.setWindowTitle("Elimina pizza")

    def elimina(self):
        self.elimina_pizza()
        self.elimina_callback()
        self.close()


from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

from collections import namedtuple

import tensorflow as tf
import tensorflow.contrib.slim as slim

class Block(namedtuple('Block', ['scope', 'unit_fn', 'args'])):
    """A named tuple describing a ResNet block.

    Its parts are:
        scope: The scope of the `Block`.
        unit_fn: The ResNet unit function which takes as input a `Tensor` and returns another `Tensor` with the output of the ResNet unit.
        args: A list of length equal to the number of units in the `Block`. The list contains one (depth, depth_bottleneck, stride) tuple for each unit in the block to serve as argument to unit_fn.
    """

def subsample(inputs, factor, scope=None):
    if factor == 1:
        return inputs
    else:
        return slim.max_pool2d(inputs, [1, 1], stride=factor, scope=scope)  # padding='VALID'

def conv2d_same(inputs, num_outputs, kernel_size, stride, rate=1, scope=None):
    if stride == 1:
        return slim.conv2d(inputs, num_outputs, kernel_size, stride=1, rate=rate, padding='SAME', scope=scope)
    else:
        kernel_size_effective = kernel_size+(kernel_size-1)*(rate-1)
        pad_total = kernel_size_effective-1
        pad_beg = pad_total//2
        pad_end = pad_total-pad_beg
        inputs = tf.pad(inputs, [[0, 0], [pad_beg, pad_end], [pad_beg, pad_end], [0, 0]])  # zero padding
        return slim.conv2d(inputs, num_outputs, kernel_size, stride=stride, rate=rate, padding='VALID', scope=scope)

@slim.add_arg_scope
def stack_blocks_dense(net, blocks, output_stride=None, store_non_strided_activations=False, outputs_collections=None):
    current_stride = 1
    rate = 1

    for block in blocks:
        with tf.variable_scope(block.scope, 'block', [net]) as sc:
            block_stride = 1
            for i, unit in enumerate(block.args):
                if store_non_strided_activations and i == len(block.args)-1:
                    block_stride = unit.get('stride', 1)
                    unit = dict(unit, stride=1)
                with tf.variable_scope('unit_%d' % (i+1), values=[net]):
                    if output_stride is not None and current_stride == output_stride:
                        net = block.unit_fn(net, rate=rate, **dict(unit, stride=1))
                        rate *= unit.get('stride', 1)
                    else:
                        net = block.unit_fn(net, rate=1, **unit)
                        current_stride *= unit.get('stride', 1)
                        if output_stride is not None and current_stride > output_stride:
                            raise ValueError('The target output_stride cannot be reached.')
            net = slim.utils.collect_named_outputs(outputs_collections, sc.name, net)

            if output_stride is not None and current_stride == output_stride:
                rate *= block_stride
            else:
                net = subsample(net, block_stride)
                current_stride *= block_stride
                if output_stride is not None and current_stride > output_stride:
                    raise ValueError('The target output_stride cannot be reached.')
    if output_stride is not None and current_stride != output_stride:
        raise ValueError('The target output_stride cannot be reached.')
    return net

def resnet_arg_scope(weight_decay=0.0001,
                     batch_norm_decay=0.9,
                     batch_norm_epsilon=2e-5,
                     batch_norm_scale=True,
                     activation_fn=tf.nn.leaky_relu,
                     use_batch_norm=True,
                     batch_norm_updates_collections=tf.GraphKeys.UPDATE_OPS):
    batch_norm_params = {
      'decay': batch_norm_decay,
      'epsilon': batch_norm_epsilon,
      'scale': batch_norm_scale,
      'updates_collections': batch_norm_updates_collections,
      'fused': None,  # Use fused batch norm if possible.
      'param_regularizers': {'gamma': slim.l2_regularizer(weight_decay)},
    }

    with slim.arg_scope(
        [slim.conv2d],
        weights_regularizer=slim.l2_regularizer(weight_decay),
        weights_initializer=tf.contrib.layers.xavier_initializer(uniform=False),
        activation_fn=activation_fn,
        normalizer_fn=slim.batch_norm if use_batch_norm else None,
        normalizer_params=batch_norm_params):
        with slim.arg_scope([slim.batch_norm], **batch_norm_params):
            with slim.arg_scope([slim.max_pool2d], padding='SAME') as arg_sc:
                return arg_sc


import logging
import boto3
class SESService():

    def __init__(self):
        self.client = boto3.client(
            'ses',
            aws_access_key_id="INPUT YOUR ACESS KEY FROM AWS",
            aws_secret_access_key="INPUT YOUR SECRET ACESS KEY FROM AWS",
            region_name="INPUT YOUR REGION",
        )

    @staticmethod
    def __verify_status(*email):
        approved_message = 'We are happy to inform you that your application was approved'
        rejected_message = 'We regret to inform you that your application was rejected'
        application = 'Thank you for applying. We will get back to you as soon as possible!'
        status = application
        if len(email) > 1 and email[1] == 'Approved':
            status = approved_message
        elif len(email) > 1 and email[1] == 'Rejected':
            status = rejected_message
        return status

    def send_email(self, *email):
        message = self.__verify_status(*email)
        response = self.client.send_email(
            Source='bignightmare1@gmail.com',
            Destination={
                'ToAddresses': [
                    email[0],
                ],

            },
            Message={
                'Subject': {
                    'Data': f'Welcome to Interview Management System {email[0]}!',
                    'Charset': 'UTF-8'
                },

                'Body': {
                    'Text': {

                        'Data': f'{message}',
                        'Charset': 'UTF-8'
                    }

                }
            },
        )
        logging.info(f'Email sent {response}')


def solution(n):
    answer = 0

    for i in range(1, n+1):
        answer += 1 if is_prime(i) else 0

    return answer

def is_prime(n):
    if n == 1 or (n != 2 and n % 2 == 0):
        return False
    elif n == 2:
        return True
    e = round(n ** 0.5) + 1
    for i in range(3, e, 2):
        if n % i == 0:
            return False
    return True

print(solution(10))


import numpy as np
import math

# Python 3 program for the
# haversine formula
def haversine(lat1, lon1, lat2, lon2):

    # distance between latitudes
    # and longitudes
    dLat = (lat2 - lat1) * math.pi / 180.0
    dLon = (lon2 - lon1) * math.pi / 180.0

    # convert to radians
    lat1 = (lat1) * math.pi / 180.0
    lat2 = (lat2) * math.pi / 180.0

    # apply formulae
    a = (pow(math.sin(dLat / 2), 2) +
         pow(math.sin(dLon / 2), 2) *
             math.cos(lat1) * math.cos(lat2));
    rad = 6371
    c = 2 * math.asin(math.sqrt(a))
    return rad * c

def find_best_school(houses,schools):
    output=[]
    for i in range(len(houses)):
        lat1=houses[i][0]
        lon1=houses[i][1]
        a=[]
        for j in range(len(schools)):
            lat2=schools[j][0]
            lon2=schools[j][1]
            result=haversine(lat1,lon1,lat2,lon2)
            a.append(result)
        print(a)
        output.append(a.index(min(a)))

    print(output)
    return output

def basic_test(my_function):
    houses=[(28.1,78),(13,78),(13,26),(28,76)]
    schools=[(28,77),(13,77),(20,68)]
    output=my_function(houses,schools)
    answer=[0,1,2,0]
    try:
        print("Basic Score : {:0.2%}".format((np.array(answer)==output).mean()))
    except:
        print("Error : give the index of nearest school for each house in the list")

basic_test(find_best_school)


from __future__ import annotations

import os
import typing as t
import logging
import pathlib
from typing import TYPE_CHECKING

import yaml
import pytest

import bentoml
from bentoml._internal.utils import bentoml_cattr
from bentoml._internal.models import ModelStore
from bentoml._internal.models import ModelContext
from bentoml._internal.bento.build_config import BentoBuildConfig

if TYPE_CHECKING:
    from _pytest.python import Metafunc

TEST_MODEL_CONTEXT = ModelContext(
    framework_name="testing", framework_versions={"testing": "v1"}
)

def pytest_generate_tests(metafunc: Metafunc) -> None:
    from bentoml._internal.utils import analytics

    analytics.usage_stats.do_not_track.cache_clear()
    analytics.usage_stats._usage_event_debugging.cache_clear()  # type: ignore (private warning)

    # used for local testing, on CI we already set DO_NOT_TRACK
    os.environ["__BENTOML_DEBUG_USAGE"] = "False"
    os.environ["BENTOML_DO_NOT_TRACK"] = "True"

@pytest.fixture(scope="function")
def noop_service(dummy_model_store: ModelStore) -> bentoml.Service:
    import cloudpickle

    from bentoml.io import Text

    class NoopModel:
        def predict(self, data: t.Any) -> t.Any:
            return data

    with bentoml.models.create(
        "noop_model",
        context=TEST_MODEL_CONTEXT,
        module=__name__,
        signatures={"predict": {"batchable": True}},
        _model_store=dummy_model_store,
    ) as model:
        with open(model.path_of("test.pkl"), "wb") as f:
            cloudpickle.dump(NoopModel(), f)

    ref = bentoml.models.get("noop_model", _model_store=dummy_model_store)

    class NoopRunnable(bentoml.Runnable):
        SUPPORTED_RESOURCES = ("cpu",)
        SUPPORTS_CPU_MULTI_THREADING = True

        def __init__(self):
            self._model: NoopModel = bentoml.picklable_model.load_model(ref)

        @bentoml.Runnable.method(batchable=True)
        def predict(self, data: t.Any) -> t.Any:
            return self._model.predict(data)

    svc = bentoml.Service(
        name="noop_service",
        runners=[bentoml.Runner(NoopRunnable, models=[ref])],
    )

    @svc.api(input=Text(), output=Text())
    def noop_sync(data: str) -> str:  # type: ignore
        return data

    return svc

@pytest.fixture(scope="function", autouse=True, name="propagate_logs")
def fixture_propagate_logs() -> t.Generator[None, None, None]:
    logger = logging.getLogger("bentoml")
    # bentoml sets propagate to False by default, so we need to set it to True
    # for pytest caplog to recognize logs
    logger.propagate = True
    yield
    # restore propagate to False after tests
    logger.propagate = False

@pytest.fixture(scope="function")
def reload_directory(
    request: pytest.FixtureRequest, tmp_path_factory: pytest.TempPathFactory
) -> t.Generator[pathlib.Path, None, None]:
    """
    This fixture will create an example bentoml working file directory
    and yield the results directory
    ./
    ├── models/  # mock default bentoml home models directory
    ├── [fdir, fdir_one, fdir_two]/
    │   ├── README.md
        ├── subdir/
        │   ├── README.md
    │   │   └── app.py
    │   ├── somerust.rs
    │   └── app.py
    ├── README.md
    ├── .bentoignore
    ├── bentofile.yaml
    ├── fname.ipynb
    ├── requirements.txt
    ├── service.py
    └── train.py
    """
    root = tmp_path_factory.mktemp("reload_directory")
    # create a models directory
    root.joinpath("models").mkdir()

    # enable this fixture to use with unittest.TestCase
    if request.cls is not None:
        request.cls.reload_directory = root

    root_file = [
        "README.md",
        "requirements.txt",
        "service.py",
        "train.py",
        "fname.ipynb",
    ]
    for f in root_file:
        p = root.joinpath(f)
        p.touch()

    build_config = BentoBuildConfig(
        service="service.py:svc",
        description="A mock service",
        exclude=["*.rs"],
    ).with_defaults()
    bentofile = root / "bentofile.yaml"
    bentofile.touch()
    with bentofile.open("w", encoding="utf-8") as f:
        yaml.safe_dump(bentoml_cattr.unstructure(build_config), f)

    custom_library = ["fdir", "fdir_one", "fdir_two"]
    for app in custom_library:
        ap = root.joinpath(app)
        ap.mkdir()
        dir_files: list[tuple[str, list[t.Any]]] = [
            ("README.md", []),
            ("subdir", ["README.md", "app.py"]),
            ("lib.rs", []),
            ("app.py", []),
        ]
        for name, maybe_files in dir_files:
            if maybe_files:
                dpath = ap.joinpath(name)
                dpath.mkdir()
                for f in maybe_files:
                    p = dpath.joinpath(f)
                    p.touch()
            else:
                p = ap.joinpath(name)
                p.touch()

    yield root

@pytest.fixture(scope="function", name="change_test_dir")
def fixture_change_test_dir(
    request: pytest.FixtureRequest,
) -> t.Generator[None, None, None]:
    os.chdir(request.fspath.dirname)  # type: ignore (bad pytest stubs)
    yield
    os.chdir(request.config.invocation_dir)  # type: ignore (bad pytest stubs)

@pytest.fixture(scope="session", name="dummy_model_store")
def fixture_dummy_model_store(tmpdir_factory: "pytest.TempPathFactory") -> ModelStore:
    store = ModelStore(tmpdir_factory.mktemp("models"))
    with bentoml.models.create(
        "testmodel",
        module=__name__,
        signatures={},
        context=TEST_MODEL_CONTEXT,
        _model_store=store,
    ):
        pass
    with bentoml.models.create(
        "testmodel",
        module=__name__,
        signatures={},
        context=TEST_MODEL_CONTEXT,
        _model_store=store,
    ):
        pass
    with bentoml.models.create(
        "anothermodel",
        module=__name__,
        signatures={},
        context=TEST_MODEL_CONTEXT,
        _model_store=store,
    ):
        pass

    return store


'''
https://leetcode.com/problems/minimum-height-trees/description/
'''

from collections import defaultdict, deque

# there can only be at most two roots in MHT, which are the mid points of the longest path
# find leaves, remove leaves from neighbours
# keep doing as long as num of nodes is > 2
# ones remaining are the root
def findMinHeightTrees(n, edges):
    """
    :type n: int
    :type edges: List[List[int]]
    :rtype: List[int]
    """
    adjlist = defaultdict(set)
    for u,v in edges:
        adjlist[u].add(v)
        adjlist[v].add(u)

    nodes = set(range(n)) # {0, 1, 2, 3}
    while len(nodes) > 2:
        leaves = {i for i in nodes if len(adjlist[i]) == 1}
        nodes -= leaves # remove set of leaves from nodes
        for i in leaves:
            for edge in adjlist[i]: # moving up one level
                adjlist[edge].remove(i)
    return list(nodes)

print(findMinHeightTrees(6, [[0, 3], [1, 3], [2, 3], [4, 3], [5, 4]])) # [3, 4]

# runs faster due to one lesser for loop, and no set comprehension
def find_min_height_faster(n, edges):
    adjlist = defaultdict(set)
    for u,v in edges:
        adjlist[u].add(v)
        adjlist[v].add(u)
    nodes = set(range(n)) # {0, 1, 2, 3}
    leaves = {i for i in nodes if len(adjlist[i]) == 1}

    while len(nodes) > 2:
        newleaves = set()
        nodes -= leaves
        for i in leaves:
            j = adjlist[i].pop()
            adjlist[j].remove(i)
            print(adjlist)
            if len(adjlist[j]) == 1:
                newleaves.add(j)
        leaves = newleaves
    return list(nodes)

# bfs, O(n^2), TLE
# do bfs on each node to find minheight of each node
def findMinHeightTrees(n, edges):
    """
    :type n: int
    :type edges: List[List[int]]
    :rtype: List[int]
    """
    adjlist = defaultdict(list)
    for u,v in edges:
        adjlist[u].append(v)
        adjlist[v].append(u)

    levels, ans, minheight = {}, [], float('inf')
    for i in range(n):
        visited, queue = set(), deque([(i, 0)])
        level, height = 0, float('-inf')

        while queue:
            curr, level = queue.popleft()
            visited.add(curr)
            for edge in adjlist[curr]:
                if edge not in visited:
                    queue.append((edge, level+1))
        levels[i] = level
        minheight = min(minheight, level)

    for key, val in levels.items():
        if val == minheight:
            ans.append(key)
    return ans

print(findMinHeightTrees(4, [[1, 0], [1, 2], [1, 3]])) # [1]


#!/usr/bin/python

import json
import os
import sys

config = sys.argv[-1]

# load json content from config file
def load_json():
    with open(config) as components:
        return json.load(components)

json = load_json()

# helper function for creating folders
def create_folder(folder_name,prev = None):
    if prev is None:
        new_folder_path = os.path.join(os.getcwd(),folder_name)
        if not os.path.exists(new_folder_path):
            os.mkdir(new_folder_path)
        return new_folder_path

    new_folder_pathh = os.path.join(prev,folder_name)
    if not os.path.exists(new_folder_pathh):
        os.mkdir(new_folder_pathh)

# create all the respective subfolders folders specified for each component
def create_directories():
    parent = create_folder(json['path'])
    for component in json['components']:
        create_folder(component,parent)

path = create_directories()

# react code template
code_template = """// libraries
import React from "react"

// other components

// style

// utils

const {} = () => {{
    return (

This is the {} component

    );
}};

export default {};"""

# create javascript files in respective folders
# fill each file with code template
def create_js():
    for component in json['components']:
        filename = component.capitalize() + ".js"
        full_file_path = os.path.join("components",component,filename)
        with open(full_file_path,"w") as file:
            file.write(code_template.format(component.capitalize(),component,component.capitalize()))

create_js()


from LinkedList import LinkedList

def find_middle(linked_list):
  fast_tracker = linked_list.head_node
  slow_tracker = linked_list.head_node

    #iterate fast_tracker normally
  while fast_tracker:
    fast_tracker = fast_tracker.get_next_node()
    if fast_tracker:
        #iterate fast tracker twice for every one slow_tracker
        # to get the middle node by the time fast_tracker reaches the end
      fast_tracker = fast_tracker.get_next_node()
      slow_tracker = slow_tracker.get_next_node()

  return slow_tracker

  #an alternative method
#   def find_middle_alt(linked_list):
    #   count = 0
    #   fast = linked_list.head_node
    #   slow = linked_list.head_node
    #   while fast:
    #     fast = fast.get_next_node()
    #     if count % 2 != 0:
    #       slow = slow.get_next_node()
    #     count += 1
#       return slow

def generate_test_linked_list(length):
  linked_list = LinkedList()
  for i in range(length, 0, -1):
    linked_list.insert_beginning(i)
  return linked_list

# Use this to test your code:
test_list = generate_test_linked_list(7)
print(test_list.stringify_list())
middle_node = find_middle(test_list)
print(middle_node.value)

dataStructuresAndAlgorithms/2 - Linked Lists/fastSlowTrackerReturnMiddle.py


import pandas as pd
import rpy2.robjects.packages as rpackages
from rpy2.robjects.vectors import StrVector
import xlsxwriter

def add_feature_metadata(df_target, df_feature_metadata, df_target_fn_col=None):
    """Adds feature metadata columns to df_target.

    Args:
        df_target - a DataFrame; must contain feature names somewhere
        df_feature_metadata - a DataFrame containing feature metadata,
            as loaded by fst.py's self.feature_metadata
        df_target_fn_col - the name of the column in df_target that contains
            the feature names, or None if it's the index of df_target that
            contains the feature names

    Returns:
        a copy of df_target with the feature metadata added
    """
    original_index = df_target.index
    if df_target_fn_col is not None:
        df_target.index = df_target[df_target_fn_col]
    df_joined = df_target.join(df_feature_metadata)
    # add groups for shadow features
    s_group = df_joined['group']
    feature_names = s_group.index.values
    s_non_shadows = pd.Series(
        [not fname.startswith('shadow_') for fname in feature_names],
        index=feature_names)
    s_group = s_group.where(s_non_shadows, 'Shadow')
    df_joined['group'] = s_group
    # handle any remaining NaN groups
    df_joined['group'].fillna('NA')
    # restore index
    df_target.index = original_index

    return df_joined

def create_refuse_xlsx(df_refuse_table, df_feature_metadata, outpath):
    """Creates an Excel spreadsheet containing the REFUSE Table data,
    annotated with the feature metadata, saved to the given outpath."""

    # merge data
    df_complete = add_feature_metadata(df_refuse_table, df_feature_metadata)
    df_complete['Feature Name'] = df_complete.index.values # easier to iterate

    # sort by VIM_mean
    df_complete.sort(columns='VIM_mean', ascending=False, inplace=True)

    # create spreadsheet
    workbook = xlsxwriter.Workbook(outpath)
    worksheet = workbook.add_worksheet()

    # start from first cell (zero-indexed)
    row = 0
    col = 0

    # styles
    title_style = workbook.add_format({
        'font_size': 12,
        'font_color': 'white',
        'bg_color': '#808080'
        })
    relevant_style = workbook.add_format({
        'font_size': 12,
        'bg_color': '#EBF1DE'
        })
    default_style = workbook.add_format({
        'font_size': 12})

    # these columns should always come first
    column_order = ['Feature Name', 'VIM_mean', 'p_val', 'VIM_var', 'group']
    # there may be user-defined columns to follow
    additional_columns = [x for x in df_complete.columns.values
        if x not in column_order]
    # final order
    column_order += additional_columns

    # some columns get user-friendly names
    column_titles = {
        'VIM_mean': 'Rank (higher=better)',
        'p_val': 'Likelihood of Relevance',
        'VIM_var': 'Variance of Rank',
        'group': 'Group Name'}

    for column in column_order:
        row = 0
        title = column
        if column in column_titles:
            title = column_titles[column]
        worksheet.write(row, col, title, title_style)
        for cell in df_complete[column]:
            row += 1
            style = default_style
            if column == 'p_val' and cell > 0.5:
                style = relevant_style
            worksheet.write(row, col, cell, style)
        col += 1

    # set column widths
    worksheet.set_column(0, len(column_order)-1, 30)

    workbook.close()

def check_r_packages():
    """Ensures required R packages are installed."""
    # import R's utility package
    utils = rpackages.importr('utils')
    # R package names
    packnames = ('classInt',
        'minerva', # should already be installed in dockerfile
        'randomForest', #should already be installed in dockerfile
        #'ggplot2', #used by FST commands that generate PDFs, which aren't currently
        #           #used, and this package doesn't install properly due to versioning problems
        'MASS',
        'gplots')

    # R vector of strings
    for x in packnames:
        print('$$$ ensuring installation of R package: ' + str(x))
        if rpackages.isinstalled(x):
            print('$$$  already installed')
        else:
            print('$$$  INSTALLING: ' + x)
            utils.install_packages(StrVector([x]), verbose=True, quiet=False, dependencies=True, repos="https://cran.rstudio.com", method="curl")
            print('$$$  reported as now installed? ' + str(rpackages.isinstalled(x)) + ' for ' + x)

    #R likes to fail silently, so double check.
    failed_installs = list()
    for x in packnames:
        if not rpackages.isinstalled(x):
            failed_installs.append(x)
    if not len(failed_installs) == 0:
        raise Exception('rpackages claims to have installed these packages, but did not: ' + str(failed_installs))


import time
import numpy as np
import smbus

from ugly.drivers.base import Driver
from ugly.drivers.hardware.i2c import Register, BankedRegister

CONFIG_BANK = 0x0b
BANK_REGISTER = 0xfd

PICTURE_MODE = 0x00
AUTOPLAY_MODE = 0x08
AUDIOPLAY_MODE = 0x18

class IS31FL3731(Driver):

    bank = Register(BANK_REGISTER)

    mode = BankedRegister(BANK_REGISTER, CONFIG_BANK, 0x00)
    frame = BankedRegister(BANK_REGISTER, CONFIG_BANK, 0x01)
    audiosync = BankedRegister(BANK_REGISTER, CONFIG_BANK, 0x06)
    shutdown = BankedRegister(BANK_REGISTER, CONFIG_BANK, 0x0a)

    enable = Register(0x00)
    blink = Register(0x12)
    pwm = Register(0x24)

    def __init__(self, rawbuf, map, bus=1, address=0x74, name='IS31FL3731'):
        super().__init__(rawbuf, 8, name)
        self._bus = smbus.SMBus(bus)
        self._address = address
        self.__current_frame = 0
        self.__map = map

        self.reset()

        self.mode = PICTURE_MODE
        self.audiosync = 0
        self.frame = self.__current_frame

        enable_pattern = np.packbits(self.__map.reshape(-1, 8)[:,::-1] >= 0)

        for bank in range(8):
            self.bank = bank
            self.enable = enable_pattern.tolist()

    def show(self):
        self.__current_frame += 1
        self.__current_frame %= 8 # use all the banks...

        self.bank = self.__current_frame
        self.pwm = self.gammabuf.flatten().take(self.__map, mode='clip').tolist()
        self.frame = self.__current_frame
        super().show()

    def reset(self):
        self.sleep(True)
        time.sleep(0.00001)
        self.sleep(False)

    def sleep(self, value):
        self.shutdown = not value

class ScrollPhatHD(IS31FL3731):

    map = np.array([
        110,  93,  76,  59,  42,  25,   8,  -1,   9,  26,  43,  60,  77,  94, 111,  -1,
        109,  92,  75,  58,  41,  24,   7,  -1,  10,  27,  44,  61,  78,  95, 112,  -1,
        108,  91,  74,  57,  40,  23,   6,  -1,  11,  28,  45,  62,  79,  96, 113,  -1,
        107,  90,  73,  56,  39,  22,   5,  -1,  12,  29,  46,  63,  80,  97, 114,  -1,
        106,  89,  72,  55,  38,  21,   4,  -1,  13,  30,  47,  64,  81,  98, 115,  -1,
        105,  88,  71,  54,  37,  20,   3,  -1,  14,  31,  48,  65,  82,  99, 116,  -1,
        104,  87,  70,  53,  36,  19,   2,  -1,  15,  32,  49,  66,  83, 100, 117,  -1,
        103,  86,  69,  52,  35,  18,   1,  -1,  16,  33,  50,  67,  84, 101, 118,  -1,
        102,  85,  68,  51,  34,  17,   0,  -1,  -1,  -1,  -1,  -1,  -1,  -1,  -1,  -1,
    ], dtype=np.int16)

    def __init__(self, bus=1, name='ScrollPhatHD'):
        super().__init__(np.zeros((7, 17, 1), dtype=np.uint8), self.map, bus=bus, name=name)


"""Management of per-player info."""
from functools import partial

from PyQt5.QtCore import Qt
from PyQt5.QtGui import QIntValidator, QPalette, QColor
from PyQt5.QtWidgets import (
    QFormLayout,
    QGroupBox,
    QGridLayout,
    QHBoxLayout,
    QLabel,
    QLineEdit,
    QPushButton,
    QWidget,
)

from table.scorer import Phase, dress_value

class Player(QGroupBox):
    """A widget for managing player info."""

    def __init__(self, name, dress_cb, drop_cb):
        """Initialise with name and a callback for board dressing."""
        super().__init__(name)
        self.name = name
        self.setAlignment(Qt.AlignCenter)

        layout = QFormLayout()

        self.count = QLabel("")
        layout.addRow("Count:", self.count)

        self.cards = QLineEdit()
        self.cards.setValidator(QIntValidator())
        layout.addRow("Cards:", self.cards)

        self.dress = QPushButton("Dress")
        self.dress.clicked.connect(partial(dress_cb, self))
        self.drop = QPushButton("Go Out")
        self.drop.clicked.connect(partial(drop_cb, self))
        self.drop.hide()
        buttons = QHBoxLayout()
        buttons.addWidget(self.dress)
        buttons.addWidget(self.drop)
        layout.setLayout(2, QFormLayout.SpanningRole, buttons)

        self.setLayout(layout)

    def set_color(self, color):
        """Set the color palette."""
        for button in (self.dress, self.drop):
            col = QColor(color)
            if not button.isEnabled():
                col.setAlpha(150)
            pal = button.palette()
            pal.setColor(self.backgroundRole(), col)
            pal.setColor(QPalette.ButtonText, col.darker())
            button.setPalette(pal)

    def set_bold_italic(self, bold_italic):
        """Set whether the font should be both bold and italic or not."""
        font = self.font()
        font.setBold(bold_italic)
        font.setItalic(bold_italic)
        self.setFont(font)

    def refresh(self, phase, is_in_game, is_dresser, balance):
        """Refresh the widget based on the game state."""

        # Update player scores
        self.count.setText(str(balance))

        # Clear card counts
        self.cards.setText("")

        # Deduce other flags
        must_dress = is_dresser and (phase == Phase.DRESSING)
        cannot_dress = balance < dress_value()
        out_of_counters = (must_dress and cannot_dress) or (balance < 0)

        # Update widget availability based on the game state
        self.setEnabled(is_in_game)
        self.cards.setEnabled(phase == Phase.SCORING)
        self.dress.setEnabled(must_dress)
        self.drop.setEnabled(out_of_counters)
        if out_of_counters:
            self.drop.show()
        else:
            self.drop.hide()

        # Update colour based on game state
        if not is_in_game:
            self.set_color(Qt.lightGray)
        elif out_of_counters:
            self.set_color(Qt.red)
        elif cannot_dress:
            self.set_color(Qt.yellow)
        elif must_dress:
            self.set_color(Qt.green)
        else:
            self.set_color(Qt.darkGray)

        # Update font based on whether the player is the dresser
        self.set_bold_italic(is_dresser)

    @property
    def cards_left(self):
        """Get the number of cards remaining."""
        try:
            return int(self.cards.text())
        except ValueError:
            return 0

class PlayerPanel(QWidget):
    """A panel of widgets for managing player info."""

    N_ROWS = 4

    def __init__(self, players, dress_cb, drop_cb):
        """Initialise from a list of names and board dressing callback."""
        super().__init__()
        layout = QGridLayout()

        self.players = {}
        for i, name in enumerate(players):
            player = Player(name, dress_cb, drop_cb)
            self.players[name] = player
            row = 2 * (i % self.N_ROWS)
            col = (i // self.N_ROWS)
            layout.addWidget(player, row, col)
            layout.setRowStretch(row + 1, 1)

        self.setLayout(layout)

    def __getitem__(self, key):
        """Return the requested player widget."""
        return self.players[key]

    def __iter__(self):
        """Return iterator through player widgets."""
        return iter(self.players.values())

    def refresh(self, phase, players, dresser, balance):
        """Refresh the player score displays based on the game state."""

        for name, player in self.players.items():
            player.refresh(phase,
                           name in players,
                           name == dresser,
                           balance[name])


# (11564번 / 아스키 코드 / B5)

# 값 입력
value = input()

# value의 type이 str이라면 ord() 함수를 통해 아스키 코드 출력
if(str(type(value)) == "<class 'str'>") :
    print(ord(value))

# value의 type이 int라면 chr() 함수를 통해 아스키 코드 출력
else :
    print(chr(value))


#!/usr/bin/env python
import random
import logging
import datetime
import cPickle
from time import time

class GeneticAlgorithm(object):
    """Runs genetic algorithm, contains chromosomes and applies fitness,
    selection, recombination and mutation methods to them."""
    def __init__(self,
                 population_size,
                 survivors_per_round,
                 generations,
                 mutation_rate,
                 peptide_length,
                 fitness_function,
                 selection_function,
                 recombination_function,
                 chromosome_type,
                 chromosome_elements):
        self.population_size = population_size
        self.survivors_per_round = survivors_per_round
        self.generations = generations
        self.mutation_rate = mutation_rate
        self.chromosome_length = peptide_length
        self.current_generation = 0
        self.population = None
        self.selection_func = selection_function
        self.fitness_function = fitness_function
        self.recombination_function = recombination_function
        self.chromosome_type = chromosome_type
        self.elements = chromosome_elements
        self.run_record = []
        self.do_logging = True
        self._init_time = time()
        self._setup_ga()

    def run(self, do_logging=True):
        if do_logging:
            self.do_logging = True
            logging.info("-----RUNNING-GA-----")
        while self.current_generation < self.generations:
            self._run_selection_round()
        if self.do_logging:
            logging.info("-----FINISHED------")
            self.log_status()
        self.final_summary()

    def log_status(self):
        ave_fitness = lambda:sum(c.fitness for c in
                                 self.population)/self.population_size
        logging.info("\n\n..........")
        logging.info("Population size: %d" % self.population_size)
        logging.info("Survivors per round: %d" % self.survivors_per_round)
        logging.info("Current round %d/%d" % (self.current_generation,
                                              self.generations))
        time_elapsed = datetime.timedelta(seconds=round(time()-self._init_time))
        logging.info("Time elapsed %s" % str(time_elapsed))
        logging.info("Average Fitness %f" % ave_fitness())
        logging.info("..........\n\n")

    @classmethod
    def load_run(cls, f):
        with open(f) as data:
            return cPickle.load(data)

    def save(self):
        pickle_fname = "round%d.pkl" % self.current_generation
        with open(pickle_fname, 'wb') as f:
            cPickle.dump(self, f)

    def _setup_ga(self):
        assert self.survivors_per_round >= 2
        assert self.survivors_per_round < self.population_size
        assert 0.0 < self.mutation_rate < 1.0
        if self.do_logging:
            logging.info("\n\n\n-----BEGINNING-GA-RUN-----")
            logging.info("-----CALCULATING-INITIAL-GA-FITNESSES-----")
        self._random_initial_population()

    def _random_initial_population(self):
        random_chromosome = self.chromosome_type.random_chromosome
        self.population = []
        while len(self.population) < self.population_size:
            new_chromosome = random_chromosome(self.chromosome_length,
                                               self.mutation_rate,
                                               elements=self.elements)
            assert new_chromosome, "Failed to construct chromosome"
            if new_chromosome not in self.population:
                self.population.append(new_chromosome)
        self._calc_population_fitness()
        initial_statistics = {'initial_population': [(c.idx_name, c.fitness)
                                                     for c in self.population]}
        self.run_record.append(initial_statistics)

    def _calc_population_fitness(self):
        fitnesses = self.fitness_function(self.population)
        for chromosome, fitness in zip(self.population, fitnesses):
            #Fitness function modifies chromosome fitness in place
            chromosome.fitness = fitness

    def _run_selection_round(self):
        round_statistics = {'selected': [], 'children': []}
        seqs_as_str = lambda l: ", ".join(c.idx_name for c in l)
        if self.do_logging:
            self.log_status()
            logging.info("-----RUNNING-SELECTION-ROUND-----")
        self.current_generation += 1
        selected = []
        #Select survivors
        while len(selected) < self.survivors_per_round:
            selected_chromosomes = self.selection_func(self.population)
            assert [s in self.population for s in selected_chromosomes]
            selected.extend(selected_chromosomes)
            #Delete chosen chromosomes from selection pool (i.e. population)
            for selected_chromosome in selected_chromosomes:
                self.population.remove(selected_chromosome)
        if self.do_logging:
            logging.info("SELECTED CHROMOSOMES: %s" % seqs_as_str(selected))
        round_statistics['selected'] = [(c.idx_name, c.fitness)
                                        for c in selected]
        #Recombination of survivors to make children
        #Randomly select pairs of parents until there are enough children
        children = []
        while len(children) < self.population_size:
            p1, p2 = _random_choose_two(selected)
            new_sequence = self.recombination_function(p1.sequence, p2.sequence)
            #Random mutation of children
            child = self.chromosome_type(new_sequence, self.mutation_rate,
                                         elements=self.elements)
            child.mutate()
            #Do not add duplicate sequences
            if child.sequence not in [c.sequence for c in children]:
                children.append(child)
        if self.do_logging:
            logging.info("NEXT GENERATION: %s" % seqs_as_str(children))
        num_unique_sequences = len(set(c.sequence for c in children))
        assert num_unique_sequences == self.population_size
        self.population = children
        self._calc_population_fitness()
        round_statistics['children'] = [(c.idx_name, c.fitness)
                                        for c in self.population]
        self.run_record.append(round_statistics)
        self.save()

    def final_summary(self):
        with open('ga-summary.txt', 'w') as out:
            line = "Name: %s, Fitness %s"
            print>>out, "Initial Population:"
            for (name, fitness) in self.run_record[0]['initial_population']:
                print>>out, line % (name, fitness)
            print>>out, '\n'
            for i, ga_round in enumerate(self.run_record[1:]):
                print>>out, "Round %d" % (i+1)
                for step in ('selected', 'children'):
                    print>>out, step
                    for (name, fitness) in ga_round[step]:
                        print>>out, line % (name, fitness)
                print>>out

def _random_choose_two(seq):
    a = random.choice(seq)
    b = random.choice(seq)
    while b is not a:
        b = random.choice(seq)
    return a, b


n = list()
for c in range (0, 5):
    p = 0
    n.append(int(input('Digite um valor: ')))
    while p < c:
        if n[p] > n[c]:
            aux = n[p]
            n[p] = n[c]
            n[c] = aux
        p += 1
print(n)


import glob
import cv2
import pandas as pd
import openpyxl
from openpyxl.utils.dataframe import dataframe_to_rows
from skimage.metrics import structural_similarity as ssim
import os
import sys

def SearchExtFiles(fpath, ext, lst):
    try:
        flist = os.listdir(fpath)
    except:
        return
    for f in flist:
        next = os.path.join(fpath, f)
        if(os.path.splitext(next)[-1] == ext):
            lst.append(next)
        if os.path.isdir(next):
            SearchExtFiles(next,ext,lst)

# 열 너비 자동 맞춤
def AutoFitColumnSize(worksheet, columns=None, margin=2):
    for i, column_cells in enumerate(worksheet.columns):
        is_ok = False
        if columns == None:
            is_ok = True
        elif isinstance(columns, list) and i in columns:
            is_ok = True

        if is_ok:
            length = max(len(str(cell.value)) for cell in column_cells)
            worksheet.column_dimensions[column_cells[0].column_letter].width = length + margin

def image_compare():
    # 통합 문서 객체 생성
    wb = openpyxl.Workbook()
    # 시트 선택
    ws = wb.active
    ws.append(['index', 'Similarity', 'different image'])
    refLst = []
    SearchExtFiles(sys.argv[1],'.bmp',refLst)   # main 있는 자리에 이미지가 있으면 경로 지정할 때 ./ 으로 놓기  (경로는 edit_Configuration 에서 parameter 바꾸기)
    compLst = []
    SearchExtFiles(sys.argv[2],'.bmp', compLst)

    # 파일 전체 읽기 위해 glob 함수 사용
    ref_img_list = refLst
    compare_img_list = compLst

    for i in range(len(ref_img_list)):

        imageA = cv2.imread(ref_img_list[i])
        imageB = cv2.imread(compare_img_list[i])
        imageC = imageA.copy()
        if (ref_img_list[i] == compare_img_list[i]):
            tempDiff = cv2.subtract(imageA, imageB)

        grayA = cv2.cvtColor(imageA, cv2.COLOR_BGR2GRAY)
        grayB = cv2.cvtColor(imageB, cv2.COLOR_BGR2GRAY)

        (score, diff) = ssim(grayA, grayB, full=True)
        diff = (diff * 255).astype("uint8")
        print(f"Similarity: {score:.5f}")
        if (score == 1):
            print("같음")
        # 다를 땐 엑셀로 이미지 파일 이름 뽑기
        else:
            diff_image = ref_img_list[i]
            print(diff_image)
            df = pd.DataFrame([[score, diff_image]], index=[ws.max_row/2+0.5], columns=['Similarity', 'different image'])
            # df = pd.DataFrame([[score, diff_image]])
            # 시트에 데이터프레임 삽입
            for r in dataframe_to_rows(df, index=True, header=False):  # True 면 변경 가능 False면 변경 불가능
                ws.append(r)
            print("다름")

        # assert 함수는 디버깅 모드에서 개발자가 오류가 생기면 치명적일 것이라는 곳에 심어 놓는 에러 검출용 코드
        assert score, "다른 점 찾을 수 없음"

    df = df.reset_index(inplace=True)

    AutoFitColumnSize(ws)
    # df.index=df.index+1
    # 엑셀 파일에 저장
    wb.save("./test.xlsx")

    # 아무 키나 눌러서 종료하기
    cv2.waitKey(0)

# Press the green button in the gutter to run the script.
if __name__ == '__main__':
    image_compare()


import json
import argparse
import shutil

import nbt
import os

def main():
    parser = argparse.ArgumentParser(description='修改玩家座標')
    parser.add_argument("username", help="Player name", type=str)
    parser.add_argument("dim", help="Target dim", type=int)
    parser.add_argument("x", help="Target x", type=float)
    parser.add_argument("y", help="Target y", type=float)
    parser.add_argument("z", help="Target z", type=float)
    args = parser.parse_args()

    with open('usernamecache.json') as f:
        uuid_to_username = json.load(f)

    target_uuid = None
    for uuid, username in uuid_to_username.items():
        if username == args.username:
            target_uuid = uuid

    print('Player uuid: ' + target_uuid)

    filename = os.path.join('world', 'playerdata', target_uuid + '.dat')
    shutil.copy(filename, filename + '.bak')

    player_dat = nbt.nbt.NBTFile(filename, 'rb')
    player_dat['Dimension'].value = args.dim
    player_dat['Pos'][0].value = args.x
    player_dat['Pos'][1].value = args.y
    player_dat['Pos'][2].value = args.z

    player_dat.write_file(filename)
    print('Done')

if __name__ == '__main__':
    main()


# -*- coding: utf-8 -*-
"""
Created on Wed Apr 24 11:26:01 2019

@author: soura
"""
import hashtag
import query
import username
import json
import decider
import pandas as pd

class Transfer:
    def __init__(self):
        self.file_mapping = {"query":"query_results.json", "username":"username_results.json","hashtag":"hashtag_results.json"}
        self.predictor=decider.Decider(mode="test")
    def set_mode(self, mode):
        self.mode = mode
    def fetch_predict(self, data):
        filename = self.file_mapping[self.mode]
        if self.mode=="query":
            query.fetch_queries(data)
        elif self.mode=="username":
            username.get_tweets(data)
        else:
            hashtag.get_tweets(data)
        data=json.load(open(filename,'r'))
        tweets=[]
        for obj in data:
            tweets.append(obj['tweet'])
        predictions=[self.predictor.predict(tweets[i])[0] for i in range(len(tweets))]
        return pd.DataFrame({"Tweets":tweets,"Prediction":predictions})


import numpy as np

class Sudoku:
    def __init__(
        self, arr: np.array = np.zeros((9, 9)), possibilities: np.array = None
    ):
        """Create a new Sudoku instance, by providing a 9 by 9 array that holds
        the starting position. Empty fields should be set to 0.

        :param arr: Input sudoku, 9×9 array-like object.
        :param possibilities: Mainly used to clone a sudoku directly.
        """

        self.possibilities = (
            np.array(
                [
                    [np.full(fill_value=True, shape=9) for _ in range(9)]
                    for __ in range(9)
                ]
            )
            if possibilities is None
            else possibilities
        )

        for i in range(9):
            for j in range(9):
                if arr[i, j] > 0:
                    self.setval(j, i, arr[i, j])

    def setval(self, x: int, y: int, num: int):
        """Set a value at (x, y)."""
        # remove option from all bounded numbers
        self.possibilities[y, :, num - 1] = 0
        self.possibilities[:, x, num - 1] = 0
        self.possibilities[
            y - y % 3 : y - y % 3 + 3, x - x % 3 : x - x % 3 + 3, num - 1
        ] = 0

        # set value itself
        self.possibilities[y, x] = np.array(
            [True if i == num - 1 else False for i in range(9)]
        )

    def update(self):
        """Update internal possibility array, following the sudoku rules."""
        while True:
            precount = np.sum(self.possibility_count())
            for y, x in np.argwhere(self.possibility_count() == 1):
                if self.is_valid():
                    self.setval(x, y, self.get_possibilities(x, y)[0])
                else:
                    return None

            if precount == np.sum(self.possibility_count()):
                break

    def __str__(self) -> str:
        """Nicely print the current state of the sudoku."""
        out = ""
        for row in self.possibilities:
            for col in row:
                if col.sum() == 1:
                    out += f"{np.arange(1, 10)[col][0]} "
                else:
                    out += "  "
            out += "\n"
        return out

    def possibility_count(self):
        """Returns number of options at each field."""
        return self.possibilities.sum(axis=2)

    def count_filled(self):
        """Total number of filled in fields."""
        return np.sum(self.possibility_count() == 1)

    def is_finished(self):
        """Returns wheter the sudoku is solved yet."""
        return np.all(self.possibility_count() == 1)

    def is_valid(self):
        """Checks if sudoku is still following the rules (and thus solveable)."""
        return 0 not in self.possibility_count()

    def get_possibilities(self, x, y):
        """Returns the possible numbers at (x,y) in the sudoku."""
        return np.arange(1, 10)[self.possibilities[y, x]]

    def copy(self):
        return Sudoku(possibilities=self.possibilities.copy())

def solve(sudoku: Sudoku, maxdepth: int = None, depth: int = 0) -> Sudoku:
    """Recursively solve a given sudoku until it is solved.

    :param sudoku: The unsolve Sudoku
    :param maxdepth: If set, the recursive solving will not go deeper than this
    :param depth: Recursive depth, mainly for debugging puposes.
    :return: The solved sudoku
    """

    # escape if solved
    if sudoku.is_finished():
        return sudoku

    # stop if maxdepth is reached
    if maxdepth is not None:
        if depth > maxdepth:
            return None

    if sudoku.is_valid():
        # loop through unsolved fields least choices first
        for y, x in np.argwhere(
            sudoku.possibility_count() == np.unique(sudoku.possibility_count())[1]
        ):
            for choice in sudoku.get_possibilities(x, y):
                # clone current state, to preserve if fails
                new_sudoku = sudoku.copy()
                new_sudoku.setval(x, y, choice)
                new_sudoku.update()

                # recursive solve
                solution = solve(new_sudoku, maxdepth=maxdepth, depth=depth + 1)
                if solution:
                    return solution

## GENERATE SUDOKUS
def generate(n: int = 10) -> Sudoku:
    """Generates a solvable, non-filled sudoku with n prefilled fields.

    The algorithms is rather naive, and a single solution is not garanteed.

    :param n: number of prefilled-fields, defaults to 10
    :type n: int, optional
    :return: Solveable sudoku
    :rtype: Sudoku
    """
    new_sudoku = generate_filled()

    while True:
        # pick n random positions
        random_positions = np.array([(x, y) for x in range(9) for y in range(9)])[
            np.random.choice(np.arange(81), n, replace=False)
        ]
        # create new test sudoku, with the numbers of new_sudoku at these positions
        test_sudoku = Sudoku()
        for (x, y) in random_positions:
            test_sudoku.possibilities[x, y] = new_sudoku.possibilities[x, y]
        # if the resulting sudoku is solvable, return it
        if solve(test_sudoku, maxdepth=10) is not None:
            return test_sudoku

def generate_filled() -> Sudoku:
    """Generates a randomly filled sudoku.

    It works by randomly setting the blocks on the first diagonal, and then it
    returns the first solution.

    :return: The filled sudoku.
    :rtpye: Sudoku
    """
    # create empty sudoku
    s = np.zeros((9, 9), dtype=np.uint8)
    # randomly fill blocks on diagonal, as they are independant, no danger for invalid sudokus
    rand_block = np.arange(1, 10).reshape((3, 3))
    np.random.shuffle(rand_block)
    s[:3, :3] = rand_block
    np.random.shuffle(rand_block)
    s[6:, 6:] = rand_block
    np.random.shuffle(rand_block)
    s[3:6, 3:6] = rand_block

    # Put in new Sudoku instance, and return first solution
    new_sudoku = Sudoku(s)
    return solve(new_sudoku)

if __name__ == "__main__":
    print(generate(15))
    test_sudoku = Sudoku(
        np.array(
            [
                [1, 0, 0, 0, 0, 0, 0, 0, 6],
                [0, 0, 6, 0, 2, 0, 7, 0, 0],
                [7, 8, 9, 4, 5, 0, 1, 0, 3],
                [0, 0, 0, 8, 0, 7, 0, 0, 4],
                [0, 0, 0, 0, 3, 0, 0, 0, 0],
                [0, 9, 0, 0, 0, 4, 2, 0, 1],
                [3, 1, 2, 9, 7, 0, 0, 4, 0],
                [0, 4, 0, 0, 1, 2, 0, 7, 8],
                [9, 0, 8, 0, 0, 0, 0, 0, 0],
            ]
        )
    )
    test_sudoku.update()
    print(test_sudoku)

    diff_sudoku = Sudoku(
        np.array(
            [
                [0, 0, 0, 0, 0, 0, 0, 0, 0],
                [2, 0, 0, 0, 0, 0, 0, 0, 0],
                [9, 6, 0, 0, 5, 8, 0, 0, 0],
                [0, 0, 3, 4, 0, 0, 0, 7, 0],
                [0, 0, 8, 0, 0, 0, 0, 0, 2],
                [0, 2, 0, 0, 6, 7, 5, 0, 0],
                [4, 0, 0, 9, 1, 0, 7, 5, 0],
                [0, 0, 0, 0, 0, 6, 0, 8, 0],
                [0, 0, 0, 0, 0, 5, 4, 0, 3],
            ]
        )
    )
    print(solve(diff_sudoku))


"""
Helpers for processing JUnit evaluations.
"""
import os
import stat
import patoolib
import glob
import subprocess32 as subprocess
from application import app
from application.models import TestResult, TestCase
from flask import render_template
from shutil import move
import xml.etree.ElementTree as ET
from shutil import rmtree
from tempfile import mkdtemp

class Enumerator(object):

    """Simple enumerator for the lowercase ascii alphabet."""

    def __init__(self, banned_words_list):
        self.token = ['a']
        self.symbol_table = set()
        for word in banned_words_list:
            self.symbol_table.add(word)

    def get_token(self):
        while "".join(self.token) in self.symbol_table:
            self.increment_token()
        token = "".join(self.token)
        self.symbol_table.add(token)
        self.increment_token()
        return token

    def increment_token(self):
        if self.token[-1] != 'z':
            self.token[-1] = chr(ord(self.token[-1]) + 1)
        elif len(self.token) == 1:
            self.token = ['a', 'a']
        else:
            # Either all chars are 'z' or one can be
            if all([x == 'z' for x in self.token]):
                self.token.append('a')
            else:
                # Go back recursively
                self.increment_helper()

    def increment_helper(self):
        if self.token[-1] != 'z':
            self.token[-1] = chr(ord(self.token[-1]) + 1)
            self.token.append('a')
        else:
            self.token = self.token[:-1]
            self.increment_helper()

class DirectoryError(Exception):

    def __init__(self, value):
        self.value = value
        super(DirectoryError, self).__init__()

class SRCError(Exception):

    def __init__(self, value):
        self.value = value
        super(SRCError, self).__init__()

def copy_junit_tests(project, working_directory, buffer_size):
    """
    Creates JUNIT directory structure in ANT_TESTS_DIR_NAME
    and extract the project tests in it.
    @param project the project to run, we extract the tests in it
    @param working_directory is a random folder name for this run of the project
    @buffer_size is provided by FILE_BUFFER_SIZE in config
    """
    tests_dir = os.path.join(
        working_directory, app.config['ANT_TESTS_DIR_NAME'])
    app.logger.info('using {0} as test directory initially'.format(tests_dir))
    os.mkdir(tests_dir)
    # Write each junit in the project to the tests dir
    for junit in project.tests:
        with open(os.path.join(tests_dir, junit.filename), "wb") as outfile:
            buff = junit.read(buffer_size)
            while len(buff) != 0:
                outfile.write(buff)
                buff = junit.read(buffer_size)

def prepare_for_source(submission, enumerator, in_use_names, working_directory):
    """
    Makes sure the source archive can be written without overwriting any existing files.
    returns dict of renamed files.
    Doesn't rename source archive.
    """
    renamed_files = {}
    src_arch_name = submission.code.get().filename
    src_arch_name_split = src_arch_name.split('.')
    arch_no_ext_nm = src_arch_name_split[0]
    abs_arch_no_ext_nm = os.path.join(working_directory, arch_no_ext_nm)
    if arch_no_ext_nm in in_use_names:
        renamed_files[arch_no_ext_nm] = enumerator.get_token()
        move(abs_arch_no_ext_nm, os.path.join(
            working_directory, renamed_files[arch_no_ext_nm]))
    if src_arch_name in in_use_names and src_arch_name != arch_no_ext_nm:
        renamed_files[src_arch_name] = enumerator.get_token()
        move(abs_arch_no_ext_nm, os.path.join(
            working_directory, renamed_files[src_arch_name]))
    return renamed_files

def extract_source(submission, working_directory, buffer_size):
    """Writes the source archive and extracts it."""
    # Copy archive
    abs_arch_name = os.path.join(
        working_directory, submission.code.get().filename)
    prev_entry_count = len(os.listdir(working_directory))
    with open(abs_arch_name, "wb") as archive_out:
        buff = submission.code.read(buffer_size)
        while len(buff) != 0:
            archive_out.write(buff)
            buff = submission.code.read(buffer_size)
    after_entry_count = len(os.listdir(working_directory))
    if after_entry_count < prev_entry_count + 1:
        message = 'Working directory entry count assertion failed. Before write {0} after write {1}'.format(
            prev_entry_count, after_entry_count)
        app.logger.error(message)
        raise DirectoryError(message)
    # Extract archive
    prev_entry_count = after_entry_count
    patoolib.extract_archive(abs_arch_name, outdir=working_directory)
    after_entry_count = len(os.listdir(working_directory))
    os.remove(abs_arch_name)
    if after_entry_count < prev_entry_count + 1:
        message = 'Working directory entry count assertion failed. Before extraction {0} after extraction {1}'.format(
            prev_entry_count, after_entry_count)
        app.logger.error(message)
        raise DirectoryError(message)

def determine_src_dir(in_use_names, renamed_files, working_directory):
    """Attempts to determine source directory name"""
    candidates = [entry for entry in os.listdir(working_directory)
                  if (entry not in in_use_names) and (entry not in renamed_files.values())]

    if len(candidates) != 1:
        message = 'Could not determine working directory. Candidates {0},\ndirectory entries{1},\nrenamed_files {2},\nin_use_names: {1}'
        message = message.format(','.join(candidates), ','.join(os.listdir(
            working_directory)), ','.join(renamed_files.items()), ','.join(in_use_names))
        app.logger.error(message)
        raise SRCError(message)
    else:
        return candidates[0]

def create_ant_build_file(project, in_use_names, renamed_files, working_directory):
    """Creates ant build file."""
    src_dir = determine_src_dir(in_use_names, renamed_files, working_directory)
    # Paths in build.xml are relative not absolute.
    context = {
        "src_dir": src_dir,
        "tests_dir": renamed_files.get(app.config['ANT_TESTS_DIR_NAME'], app.config['ANT_TESTS_DIR_NAME']),
        "plain_format": False,
        "xml_format": True,
        "build_dir": renamed_files.get(app.config['ANT_BUILD_DIR_NAME'], app.config['ANT_BUILD_DIR_NAME']),
        "has_tests": project.has_tests,
        "has_class_files": project.has_class_files,
        "working_directory": working_directory,
        "test_files": [test.filename for test in project.tests]
    }
    if project.has_class_files:
        context["test_classes"] =\
         [test.filename for
            test in project.tests if test.filename.endswith(".class")]
    else:
        context["test_classes"] =\
         [test.filename.replace('.java', '.class') for test in project.tests]

    ant_build_template = render_template('runner/build.xml', **context)
    build_abs_fname = os.path.join(
        working_directory, renamed_files.get(app.config['ANT_BUILD_FILE_NAME'], app.config['ANT_BUILD_FILE_NAME']))
    with open(build_abs_fname, "w") as script_file:
        script_file.write(ant_build_template)

def create_ant_script_file(project, in_use_names, renamed_files, working_directory):
    """Creates ant script runner"""
    script_abs_fname = os.path.join(working_directory, renamed_files.get(
        app.config['ANT_RUN_FILE_NAME'], app.config['ANT_RUN_FILE_NAME']))
    context = {
        'buildfile_name': renamed_files.get(app.config['ANT_BUILD_FILE_NAME'], app.config['ANT_BUILD_FILE_NAME']),
        "has_class_files": project.has_class_files,
        'has_tests': project.has_tests,
        'test_timeout': project.test_timeout_seconds
    }
    rendered_script = render_template('runner/ant_script.sh', **context)
    with open(script_abs_fname, "w") as script_file:
        script_file.write(rendered_script)
    script_st = os.stat(script_abs_fname)
    os.chmod(script_abs_fname, script_st.st_mode | stat.S_IEXEC)

def setup_directory(submission, project, working_directory):
    """
    Sets up the directory layout.
    """
    BUFFER_SIZE = app.config['FILE_BUFFER_SIZE']
    if project.has_tests:
        copy_junit_tests(project, working_directory, BUFFER_SIZE)

    # Check if archive clashes
    in_use_names = os.listdir(working_directory) + [app.config[
        'ANT_BUILD_FILE_NAME'] + app.config['ANT_RUN_FILE_NAME'] + app.config['ANT_BUILD_DIR_NAME']]
    enumerator = Enumerator(in_use_names)
    renamed_files = prepare_for_source(
        submission, enumerator, in_use_names, working_directory)
    extract_source(submission, working_directory, BUFFER_SIZE)
    app.logger.info('Directory after extraction:[{0}]'.format(
        ','.join(os.listdir(working_directory))))
    before_ant_scripts = len(os.listdir(working_directory))
    create_ant_build_file(
        project, in_use_names, renamed_files, working_directory)
    create_ant_script_file(
        project, in_use_names, renamed_files, working_directory)
    after_ant_scripts = len(os.listdir(working_directory))
    if after_ant_scripts != before_ant_scripts + 1:
        message = 'Failed before and after sanity check for ant scripts entries: {0}'.format(
            ','.join(os.listdir(working_directory)))
        app.logger.error(message)
    return renamed_files

def parse_junit_results(test_res_dir, subm):
    """
    Parses XML output. Creates embedded TestResult and TestCase documents.
    Doesn't save submission.
    param: ters_res_dir path to directory where reports are.
    param: subm submission document instance.
    """
    files = glob.glob(os.path.join(test_res_dir, '*.xml'))
    test_results = {}
    for junit_report in files:
        # Process each junit report
        tree = ET.parse(junit_report)
        for test_case_elm in tree.iterfind('testcase'):
            # Process each test case in a junit file
            class_name = test_case_elm.attrib['classname']
            # class name is something like FooTest which is the class
            # the tests were declared at
            if class_name not in test_results:
                # Create new result if needed
                test_results[class_name] = TestResult(
                    name=class_name, success=True)
            # Populate case
            case = TestCase(
                name=test_case_elm.attrib['name'], passed=True, detail='')
            for failure in test_case_elm.iterfind('failure'):
                # If it has a failure child then it failed.
                case.passed = False
                case.detail += failure.text + '\n'
            for err in test_case_elm.iterfind('error'):
                # If it has an error child then it failed.
                case.passed = False
                case.error = True
                case.detail += err.text + '\n'
            case.save()
            test_results[class_name].cases.append(case)
            test_results[class_name].success &= case.passed

    subm.test_results = test_results.values()
    for r in subm.test_results:
        r.save()
    subm.save()

def run_sandbox(working_directory, selinux_directory, renamed_files, submission):
    """Initiates SELinux Sanbox."""
    command = ['sandbox', '-M', '-H', working_directory, '-T',
               selinux_directory, 'bash',
               renamed_files.get(app.config['ANT_RUN_FILE_NAME'], app.config['ANT_RUN_FILE_NAME'])]
    app.logger.info('Lauching {0}'.format(' '.join(command)))
    process = subprocess.Popen(
        command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    stdout, stderr = process.communicate()
    submission.compile_status = ('THE SOURCE WAS COMPILED SUCCESFULLY'
        in stderr or 'THE SOURCE WAS COMPILED SUCCESFULLY' in stdout)
    app.logger.info(stderr)
    app.logger.info(stdout)
    submission.compiler_out = stderr + '\n' + stdout
    ant_build_dir_name = renamed_files.get(
        app.config['ANT_BUILD_DIR_NAME'], app.config['ANT_BUILD_DIR_NAME'])
    if submission.compile_status and not ant_build_dir_name in os.listdir(working_directory):
        app.logger.error('Error unknown reason for compilation faliure.')
    submission.compile_status &= ant_build_dir_name in os.listdir(
        working_directory)

def extract_team_grade_submissions(grades):
    """
    write all submissions to disk then zip them in one archive file
    return that file for downlaod

    """
    # First we need to create the temporary directories
    class TempDirectories(object):

        def __enter__(self):
            self.dirs = mkdtemp()
            return self.dirs

        def __exit__(self, type, value, traceback):
            if app.config['CLEAN_TEMP_DIRS']:
                # rmtree(self.dirs[0])
                pass

    buffer_size = app.config['FILE_BUFFER_SIZE']
    working_directory = ''
    with TempDirectories() as directories:
        try:
            working_directory = directories
            arch_dir = os.path.join(working_directory, 'arch')
            os.mkdir(arch_dir)
            app.logger.info('using {0} as directory'.format(working_directory))
            # Populate directory
            for grade in grades:
                submission = grade.best_submission
                src_arch_name = submission.code.get().filename
                src_arch_name_split = src_arch_name.split('.')
                arch_ext = src_arch_name_split[-1]
                arch_nm = "Team_" + grade.team_id + "." + arch_ext
                abs_arch_name = os.path.join(arch_dir, arch_nm)

                prev_entry_count = len(os.listdir(arch_dir))

                with open(abs_arch_name, "wb") as archive_out:
                    buff = submission.code.read(buffer_size)
                    while len(buff) != 0:
                        archive_out.write(buff)
                        buff = submission.code.read(buffer_size)

                after_entry_count = len(os.listdir(arch_dir))

                if after_entry_count < prev_entry_count + 1:
                    message = 'Working directory entry count assertion failed. Before write {0} after write {1}'.format(
                        prev_entry_count, after_entry_count)
                    app.logger.error(message)
                    raise DirectoryError(message)

        except DirectoryError as de:
            print(de.value)
            pass
        print(working_directory)
    return working_directory

def junit_submission(submission, project):
    # First we need to create the temporary directories

    class TempDirectories(object):

        def __enter__(self):
            self.dirs = mkdtemp(), mkdtemp()
            return self.dirs

        def __exit__(self, type, value, traceback):
            if app.config['CLEAN_TEMP_DIRS']:
                rmtree(self.dirs[0])
                rmtree(self.dirs[1])

    with TempDirectories() as directories:
        try:
            working_directory, selinux_directory = directories
            app.logger.info('using {0} and {1} as directories'.format(working_directory, selinux_directory))
            # Populate directory
            renamed_files = setup_directory(
                submission, project, working_directory)
            run_sandbox(
                working_directory, selinux_directory, renamed_files, submission)
            if submission.compile_status and project.has_tests:
                tests_dir = os.path.join(working_directory,
                    renamed_files.get(app.config['ANT_BUILD_DIR_NAME'], app.config['ANT_BUILD_DIR_NAME']))
                tests_dir = os.path.join(tests_dir, 'tests')
                parse_junit_results(tests_dir, submission)
            submission.processed = True
            submission.save()
        except DirectoryError as de:
            submission.compile_status = False
            submission.processed = True
            submission.compiler_out = de.value
            submission.save()
        except SRCError as se:
            submission.compile_status = False
            submission.compiler_out = se.value
            submission.processed = True
            submission.save()


from .vars import *
from .utils.utils import *
import re

def checkAttempt(lines):
    recordingStarts = search('== Recording Start ==', lines)
    streamingStarts = search('== Streaming Start ==', lines)
    replaybufferStarts = search('== Replay Buffer Start ==', lines)
    if (len(recordingStarts) + len(streamingStarts) + len(replaybufferStarts) == 0):
        return [LEVEL_INFO, "No Output Session",
                "Your log contains no recording or streaming session. Results of this log analysis are limited. Please post a link to a clean log file. " + cleanLog]

def checkMP4(lines):
    writtenFiles = search('Writing file ', lines)
    mp4 = search('.mp4', writtenFiles)
    mov = search('.mov', writtenFiles)
    fragmentedFlag = search('movflags=frag_keyframe+empty_moov+delay_moov', lines)
    if (mp4 or mov) and not fragmentedFlag:
        return [LEVEL_CRITICAL, "MP4/MOV Recording",
                "Record to FLV or MKV. If you record to MP4 or MOV and the recording is interrupted, the file will be corrupted and unrecoverable.

If you require MP4 files for some other purpose like editing, remux them afterwards by selecting File > Remux Recordings in the main OBS Studio window."]

def checkPreset(lines):
    encoderLines = search('x264 encoder:', lines)
    presets = search('preset: ', lines)
    sensiblePreset = True
    for ln in presets:
        if (not (('veryfast' in ln) or ('superfast' in ln) or ('ultrafast' in ln))):
            sensiblePreset = False

    if ((len(encoderLines) > 0) and (not sensiblePreset)):
        return [LEVEL_INFO, "Non-Default x264 Preset",
                "A slower x264 preset than 'veryfast' is in use. It is recommended to leave this value on veryfast, as there are significant diminishing returns to setting it lower. It can also result in very poor gaming performance on the system if you're not using a 2 PC setup."]

def checkCustom(lines):
    encoderLines = search("'adv_ffmpeg_output':", lines)
    if (len(encoderLines) > 0):
        return [LEVEL_WARNING, "Custom FFMPEG Output",
                """Custom FFMPEG output is in use. Only absolute professionals should use this. If you got your settings from a YouTube video advertising "Absolute best OBS settings" then we recommend using one of the presets in Simple output mode instead."""]

def checkStreamSettingsX264(lines):
    streamingSessions = []
    for i, s in enumerate(lines):
        if "[x264 encoder: 'simple_h264_stream'] settings:" in s:
            streamingSessions.append(i)

    if (len(streamingSessions) > 0):
        bitrate = float(lines[streamingSessions[-1] + 2].split()[-1])
        fps_num = float(lines[streamingSessions[-1] + 5].split()[-1])
        fps_den = float(lines[streamingSessions[-1] + 6].split()[-1])
        width = float(lines[streamingSessions[-1] + 7].split()[-1])
        height = float(lines[streamingSessions[-1] + 8].split()[-1])

        bitrateEstimate = (width * height * fps_num / fps_den) / 20000
        if (bitrate < bitrateEstimate):
            return [LEVEL_INFO, "Low Stream Bitrate",
                    "Your stream encoder is set to a video bitrate that is too low. This will lower picture quality especially in high motion scenes like fast paced games. Use the Auto-Config Wizard to adjust your settings to the optimum for your situation. It can be accessed from the Tools menu in OBS, and then just follow the on-screen directions."]

def checkNVENC(lines):
    msgs = search("Failed to open NVENC codec", lines)
    if (len(msgs) > 0):
        # TODO Check whether the user is on Windows before suggesting Windows-specific solutions
        return [LEVEL_WARNING, "NVENC Start Failure",
                """The NVENC Encoder failed to start due of a variety of possible reasons. Make sure that Windows Game Bar and Windows Game DVR are disabled and that your GPU drivers are up to date.

You can perform a clean driver installation for your GPU by following the instructions at  Clean GPU driver installation.
If this doesn't solve the issue, then it's possible your graphics card doesn't support NVENC. You can change to a different Encoder in Settings > Output."""]

def checkStreamSettingsNVENC(lines):
    videoSettings = []
    fps_num, fps_den = 0, 1
    for i, s in enumerate(lines):
        if "video settings reset:" in s:
            videoSettings.append(i)
    if (len(videoSettings) > 0):
        for i in range(7):
            chunks = lines[videoSettings[-1] + i].split()
            if (chunks[-2] == 'fps:'):
                fps_num, fps_den = (int(x) for x in chunks[-1].split('/'))
    streamingSessions = []
    for i, s in enumerate(lines):
        if "[NVENC encoder: 'streaming_h264'] settings:" in s:
            streamingSessions.append(i)
    if (len(streamingSessions) > 0):
        bitrate = 0
        width = 0
        height = 0
        for i in range(12):
            chunks = lines[streamingSessions[-1] + i].split()
            if (chunks[-2] == 'bitrate:'):
                bitrate = float(chunks[-1])
            elif (chunks[-2] == 'width:'):
                width = float(chunks[-1])
            elif (chunks[-2] == 'height:'):
                height = float(chunks[-1])
        bitrateEstimate = (width * height * fps_num / fps_den) / 20000
        if (bitrate < bitrateEstimate):
            return [LEVEL_INFO, "Low Stream Bitrate",
                    "Your stream encoder is set to a video bitrate that is too low. This will lower picture quality especially in high motion scenes like fast paced games. Use the Auto-Config Wizard to adjust your settings to the optimum for your situation. It can be accessed from the Tools menu in OBS, and then just follow the on-screen directions."]

def checkEncodeError(lines):
    if (len(search('Error encoding with encoder', lines)) > 0):
        return [LEVEL_INFO, "Encoder start error",
                """An encoder failed to start. This could result in a bitrate stuck at 0 or OBS stuck on "Stopping Recording". Depending on your encoder, try updating your drivers. If you're using QSV, make sure your iGPU is enabled. If that still doesn't help, try switching to a different encoder in Settings -> Output."""]

def checkEncoding(lines):
    hasx264 = len(search('[x264 encoder:', lines))
    hasNVENC = (len(search('[jim-nvenc:', lines)) + len(search('[NVENC encoder:', lines)))
    hasAMD = (len(search('[AMF] [H264]', lines)) + len(search('[AMF] [H265]', lines)))
    hasQSV = len(search('[qsv encoder:', lines))
    hasAPPLE = (len(search('[VideoToolbox recording_h264:', lines)) + len(search('[VideoToolbox streaming_h264:', lines)))
    drops = search('skipped frames', lines)
    val = 0
    severity = 9000
    for drop in drops:
        v = float(drop[drop.find("(") + 1: drop.find(")")
                       ].strip('%').replace(",", "."))
        if (v > val):
            val = v
    if (val != 0):
        if (val >= 15):
            severity = LEVEL_CRITICAL
        elif (15 > val and val >= 5):
            severity = LEVEL_WARNING
        else:
            severity = LEVEL_INFO
        if (hasx264 > 0 and (hasAMD + hasQSV + hasNVENC + hasAPPLE) > 0):
            return [severity, "{}% Encoder Overload".format(val),
                    """Encoder overload may be related to your CPU or GPU being overloaded, depending on the encoder in question. If you are using a software encoder (x264) please see the CPU Overload Guide. If you are using a hardware encoder (AMF, QSV/Quicksync, NVENC) please see the GPU Overload Guide."""]
        elif (hasx264 > 0):
            return [severity, "{}% CPU Encoder Overload".format(val),
                    """The encoder is skipping frames because of CPU overload. Read about General Performance and Encoding Issues."""]
        elif ((hasNVENC + hasAMD + hasQSV + hasAPPLE) > 0):
            return [severity, "{}% GPU Encoder Overload".format(val),
                    """The encoder is skipping frames because of GPU overload. Read about troubleshooting tips in our GPU Overload Guide."""]
        else:
            return [severity, "{}% Encoder Overload".format(val),
                    """Encoder overload may be related to your CPU or GPU being overloaded, depending on the encoder in question. If you are using a software encoder (x264) please see the CPU Overload Guide. If you are using a hardware encoder (AMF, QSV/Quicksync, NVENC) please see the GPU Overload Guide."""]

unknownenc_re = re.compile(r"Encoder\sID\s'(?P<name>.+)'\snot\sfound")

def checkUnknownEncoder(lines):
    encLines = search('Encoder ID', lines)
    outdatedEncMac = ['vt_h264_sw', 'vt_h264_hw']
    if (len(encLines) > 0):
        for i in encLines:
            m = unknownenc_re.search(i)
            if m:
                encName = m.group("name")
                if encName in outdatedEncMac:
                    return [LEVEL_CRITICAL, "Outdated Encoder Set",
                            "In OBS v27, the Apple VT encoder was changed to better support the Apple M1 platform, which resulted in the existing encoder becoming unrecognised. Manually navigate to Settings -> Output and set the 'Encoder' to fix this."]
                return [LEVEL_WARNING, "Unrecognised Encoder",
                        "One of the configured encoders is not recognised. This can result in failure to go live or to record. To fix this, go to Settings -> Output and change the 'Encoder' option."]


"""Kernel computation for gravity and magnetics."""
import numpy as np
from pygimli.utils import ProgressBar

def SolveGravMagHolstein(mesh, pnts, cmp, igrf=None, foot=np.inf):
    """Solve gravity and/or magnetics problem after Holstein (1997).

    Parameters
    ----------
    mesh : pygimli:mesh
        tetrahedral or hexahedral mesh
    pnts : list|array of (x, y, z)
        measuring points
    cmp : list of str
        component list of: gx, gy, gz, TFA, Bx, By, Bz, Bxy, Bxz, Byy, Byz, Bzz
    igrf : list|array of size 3 or 7
        international geomagnetic reference field, either
        [D, I, H, X, Y, Z, F] - declination, inclination, horizontal field,
                               X/Y/Z components, total field OR
        [X, Y, Z] - X/Y/Z components

    Returns
    -------
    out : ndarray (nPoints x nComponents x nCells)
        kernel matrix to be multiplied with density or susceptibility
    """
    if pnts is None:
        pnts = [[0.0, 0.0]]

    doG = np.any([c[0] == "g" for c in cmp])
    doB = np.any([c[0] == "B" and len(c) == 2 for c in cmp]) or "TFA" in cmp
    doBT = np.any([c[0] == "B" and len(c) == 3 for c in cmp])
    B_tens = None

    kernel = np.zeros((mesh.cellCount(), len(pnts), len(cmp)))
    if igrf:
        if len(igrf) == 3:  # an X, Y, Z vector
            F = np.linalg.norm(igrf)
            fakt = F / (4*np.pi)
            B_dir = np.array(igrf) / F
        elif len(igrf) == 7:  # an IGRF vector (D, I, H, X, Y, Z, F)
            fakt = igrf[6] / (4*np.pi)
            myigrf = np.array(igrf[3:6])
            B_dir = myigrf / np.linalg.norm(myigrf)
        else:
            raise Exception("Could not use IGRF vector. Len must be 3 or 7!")
    elif doB or doB:
        raise Exception("Specify IGRF!")

    b_list, c_list = [], []
    for bd in mesh.boundaries():
        b_list.append([n.id() for n in bd.allNodes()])
        c_list.append([bd.leftCell(), bd.rightCell()])

    b_list = np.array(b_list)
    lb = b_list.shape

    n_list = np.array([n.pos() for n in mesh.nodes()])

    cl, cr = [], []
    for i, c in enumerate(c_list):
        if c[0]:
            cl.append([i, c[0].id()])
        if c[1]:
            cr.append([i, c[1].id()])

    cl = np.array(cl)
    cr = np.array(cr)

    rr = range(0, mesh.cellCount())
    rs = np.roll(range(0, lb[1]), -1)

    temp = np.zeros((len(pnts), lb[0], len(cmp)))
    pBar = ProgressBar(its=len(pnts), width=40, sign='+')
    nb = n_list[b_list]
    for i, p in enumerate(pnts):
        r1 = nb - p
        r2 = r1[:, rs, :]
        r0 = r2 - r1
        u = np.sum(np.cross(r1, r2), 1)
        u = u / np.expand_dims(np.linalg.norm(u, axis=1), axis=1)
        ut = np.tile(u, lb[1]).reshape((lb[0], lb[1], 3))
        ll = np.linalg.norm(r0, axis=2)
        t = r0/np.expand_dims(ll, axis=2)
        lm = (np.sum(r1*t, 2) + np.sum(r2*t, 2)) / 2
        h = np.cross(t, ut)
        hn = np.sum(h*r1, 2)
        v = np.sum(ut*r1, 2)
        r1n = np.linalg.norm(r1, axis=2)
        r2n = np.linalg.norm(r2, axis=2)
        rm = (r1n+r2n)/2
        lumbda = ll/(2*rm)

        jj = 0
        if doG: # gravitational field
            g = hn*np.arctanh(lumbda)-np.sign(v)*v*np.arctan2(
                hn*lumbda, (rm*(1-lumbda**2)+abs(v)))
            g_vec = 2 * u * np.expand_dims(np.sum(g, 1), axis=1)

            if 'g' in cmp:
                temp[i, :, jj] = g
                jj += 0

            if 'gx' in cmp:
                temp[i, :, jj] = g_vec[:, 0]
                jj += 1

            if 'gy' in cmp:
                temp[i, :, jj] = g_vec[:, 1]
                jj += 1

            if 'gz' in cmp:
                temp[i, :, jj] = g_vec[:, 2]
                jj += 1

            # if 'gxx' in cmp:
            #     temp[:, jj]=G_tens[:, 0, 0]
            # if 'gxy' in cmp:
            #     temp[:, jj]=G_tens[:, 0, 1]
            # if 'gxz' in cmp:
            #     temp[:, jj]=G_tens[:, 0, 2]
            # if 'gyy' in cmp:
            #     temp[:, jj]=G_tens[:, 1, 1]
            # if 'gyz' in cmp:
            #     temp[:, jj]=G_tens[:, 1, 2]
            # if 'gzz' in cmp:
            #     temp[:, jj]=G_tens[:, 2, 2]

        if doB or doBT:
            # magnetic field vector and gravity gradient tensor
            b = h*np.expand_dims(np.arctanh(lumbda), axis=2) - \
                ut*np.expand_dims(np.sign(v)*np.arctan2(
                    hn*lumbda, (rm*(1-lumbda**2)+abs(v))), axis=2)
            P = np.dot(u, B_dir)
            B_vec = np.expand_dims(P, 1) * np.sum(b, 1)
            B_vec = 2 * np.expand_dims(P, 1) * np.sum(b, 1)

            if 'TFA' in cmp:
                temp[i, :, jj] = fakt*B_vec.dot(B_dir)
                jj += 1

            if 'Bx' in cmp:
                temp[i, :, jj] = fakt*B_vec[:, 0]
                jj += 1

            if 'By' in cmp:
                temp[i, :, jj] = fakt*B_vec[:, 1]
                jj += 1

            if 'Bz' in cmp:
                temp[i, :, jj] = fakt*B_vec[:, 2]
                jj += 1

            if doBT:  # magnetic gradient tensor
                d = (-2*lumbda*hn) / (r1n*r2n*(1-lumbda**2))
                e = (-2*lumbda*lm) / (r1n*r2n)
                f = (-2*lumbda*v) / (r1n*r2n*(1-lumbda**2))

                h1 = np.expand_dims(h, axis=3)
                h2 = np.swapaxes(h1, 2, 3)
                t1 = np.expand_dims(t, axis=3)
                t2 = np.swapaxes(t1, 2, 3)
                u1 = np.expand_dims(ut, axis=3)
                u2 = np.swapaxes(u1, 2, 3)

                B = (h1*h2-u1*u2)*np.expand_dims(d, (2, 3)) + \
                    (t1*h2+h1*t2)*np.expand_dims(e, (2, 3))/2 + \
                    (h1*u2+u1*h2)*np.expand_dims(f, (2, 3))

                B_tens = np.expand_dims(P, (1, 2)) * np.sum(B, 1)

                if 'Bxx' in cmp:
                    temp[i, :, jj] = fakt*B_tens[:, 0, 0]
                    jj += 1

                if 'Bxy' in cmp:
                    temp[i, :, jj] = fakt*B_tens[:, 0, 1]
                    jj += 1

                if 'Bxz' in cmp:
                    temp[i, :, jj] = fakt*B_tens[:, 0, 2]
                    jj += 1

                if 'Byy' in cmp:
                    temp[i, :, jj] = fakt*B_tens[:, 1, 1]
                    jj += 1

                if 'Byz' in cmp:
                    temp[i, :, jj] = fakt*B_tens[:, 1, 2]
                    jj += 1

                if 'Bzz' in cmp:
                    temp[i, :, jj] = fakt * B_tens[:, 2, 2]
                    jj += 1

    pBar.update(i)
    kernel += np.array([np.sum(temp[:, cl[cl[:, 1] == j, 0]], 1) for j in rr])
    kernel -= np.array([np.sum(temp[:, cr[cr[:, 1] == j, 0]], 1) for j in rr])

    return kernel.transpose([1, 2, 0])