# importing necessary libraries
import pandas as pd
import numpy as np
import re
import string
import nltk
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.model_selection import train_test_split
from sklearn.naive_bayes import GaussianNB
from sklearn.metrics import classification_report, confusion_matrix, f1_score, roc_auc_score, accuracy_score

# loading the date into data frame from the classified email data set which was generated using main,py module
emails = pd.read_csv("email_classify.csv")

# seggregate the dataset
def parse_into_emails(messages):
    emails = [parse_raw_message(message) for message in messages]
    return {
        'body': map_to_list(emails, 'body'),
        'to': map_to_list(emails, 'to'),
        'from_': map_to_list(emails, 'from')
    }

# cleaning
def parse_raw_message(raw_message):
    lines = raw_message.split('\n')
    email = {}
    message = ''
    keys_to_extract = ['from', 'to']
    for line in lines:
        if ':' not in line:
            message += line.strip()
            email['body'] = message
        else:
            pairs = line.split(':')
            key = pairs[0].lower()
            val = pairs[1].strip()
            if key in keys_to_extract:
                email[key] = val
    return email

def map_to_list(emails, key):
    results = []
    for email in emails:
        if key not in email:
            results.append('')
        else:
            results.append(email[key])
    return results

email_df = pd.DataFrame(parse_into_emails(emails.message))
email_data=pd.concat([email_df['body'],emails['State']],axis=1)

#data cleaning
stopwords = nltk.corpus.stopwords.words('english')
ps = nltk.PorterStemmer()
def clean_text(text):
    text = "".join([word.lower() for word in text if word not in string.punctuation])
    tokens = re.split('\W+', text)
    text = [ps.stem(word) for word in tokens if word not in stopwords]
    return text

email_data['clean_body']=email_data['body'].apply(lambda x : clean_text(x))
email_data

# Intializing tfidf vector
tfidf_vect = TfidfVectorizer(analyzer=clean_text)
tfidf_vect_fit = tfidf_vect.fit_transform(email_data['clean_body'])
tfidf_vect_fit

#split the data into train and test data set by 4:1 ratio
X_train, X_test, y_train, y_test = train_test_split(tfidf_vect_fit.toarray(), email_data['State'], test_size=0.2)

#applying the Gaussian model
gnb=GaussianNB()
y_pred2 = gnb.fit(X_train, y_train).predict(X_test)

#Metrics calculation
print("Accuracy score :", accuracy_score(y_test,y_pred2))
print("Confussion matrix :\n",confusion_matrix(y_test,y_pred2))
print("Classification report :\n", classification_report(y_test,y_pred2))


"""
Author: Prathyush Ravula, psravula@purdue.edu
Assignment: 06.1 - Math Quiz
Date: 3/19/2022

Description:
    This program outputs random integers and quizzes the user on
    the addition of the two integers.

Contributors:
    Prathyush Ravula, psravula@purdue.edu [repeat for each]

My contributor(s) helped me:
    [ ] understand the assignment expectations without
        telling me how they will approach it.
    [ ] understand different ways to think about a solution
        without helping me plan my solution.
    [ ] think through the meaning of a specific error or
        bug present in my code without looking at my code.
    Note that if you helped somebody else with their code, you
    have to list that person as a contributor.

Academic Integrity Statement:
    I have not used source code obtained from any unauthorized
    source, either modified or unmodified; nor have I provided
    another student access to my code.  The project I am
    submitting is my own original work.
"""

"""Import additional modules below this line (starting with unit 6)."""
#Random number import
from random import randint

"""Write new functions below this line (starting with unit 4)."""
#Function to retrieve random numbers
def random_number(digits):
    if digits == 2:
        num = randint(10, 99)
    if digits == 3:
        num = randint(100, 999)
    return num

def main():
    """Write your mainline logic below this line (then delete this line)."""
    #Calls random number function to generate numbers
    twodigit = random_number(2)
    threedigit = random_number(3)
    sum = twodigit + threedigit

    #Prints initial setup statements
    print(f"   {twodigit}")
    print(f"+ {threedigit}")
    print("-----")
    userinput = int(input("= "))

    #Conditional to check if user input matches sum
    if userinput != sum:
        print(f"Incorrect. The correct answer is {sum}.")
    else:
        print("Correct -- Good Work!")

"""Do not change anything below this line."""
if __name__ == "__main__":
    main()


#!/usr/bin/env python3
#!/usr/bin/env python2
import socket

# Se crea un objeto socket UDP
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
# Se enlaza al socket especificado
s.bind(('localhost', 1200))

status = True

# Mientras ninguno de los clientes se desconecten:
while(status):
    # Espera a recibir un mensaje del cliente 1 y lo imprime
    print("Esperando el mensaje de la persona 1")
    mensaje1 = s.recvfrom(1024)
    print("Recibido de Persona 1:["+ str(mensaje1[0]) +"]")
    # Reenvía el mensaje del cliente 1 al cliente 2
    s.sendto(mensaje1[0], ('localhost', 1202))
    # Si el mensaje indicaba que el cliente 1 se ha desconectado,
    # el servidor también se desconecta
    if str(mensaje1[0])=="b'desconectado'":
        status=False
    # Si el cliente 1 no se ha desconectado:
    else:
        # El servidor espera a recibir la respuesta del cliente 2
        print("Esperando el mensaje de la persona 2")
        mensaje2 = s.recvfrom(1024)
        print("Recibo de Persona 2:["+ str(mensaje2[0]) +"]")
        # Reenvía la respuesta del cliente 2 al cliente 1
        s.sendto(mensaje2[0], ('localhost', 1201))

        # Si el cliente 2 se ha desconectado, el servidor también
        if str(mensaje2[0])=="b'desconectado'":
            status=False

# Cierra la conexión
s.close()
print("Desconectado")


selection = 13

def mainMenu():
    print("1. Show all records.")
    print("2. Show one record.")
    print("3. Create new record")
    print("4. Update record")
    print("5. Delete record.")
    print("6. Exit Program.")
    selection = int(input("Enter choice: "))

    while selection != 6:

        if selection == 1:
            showAll()
        elif selection == 2:
            showOne()
        elif selection == 3:
            createNew()
        elif selection == 4:
            update()
        elif selection == 5:
            delete()
        else:
            print("Enter a valid selection")
            mainMenu()

def showAll():
    print("Showing all records")

    mainMenu()

def showOne():
    print("Showing one record")
    mainMenu()

def createNew():
    print("Creating a new record")
    mainMenu()

def update():
    print("Updating record")
    mainMenu()

def delete():
    print("Deleting record")
    mainMenu()

mainMenu()


# 导入通用模块
import tensorflow as tf
from dataLoader.DataLoader import DataGenerator
from utils.parse import process_config
from utils.makeDirs import makeDirs
from utils.logger import Logger
from utils.getArgs import getArgs

# 导入需重写的模块
from models.exampleModel import ExampleModel
from trainers.exampleTrainer import ExampleTrainer
from testers.exampleTester import ExampleTester

def main():
    # capture the config path from the run arguments
    # then process the json configuration file
    try:
        args = getArgs()
        print("args got")
        config = process_config(args.config)

    except:
        print("missing or invalid arguments")
        exit(0)

    if config.mode == "train":

        # create the experiments dirs
        makeDirs([config.summary_dir, config.checkpoint_dir])
        # create tensorflow session
        sess = tf.Session()
        # create your data generator
        data = DataGenerator(config)
        # create an instance of the model
        model = ExampleModel(config)
        # create tensorboard logger
        logger = Logger(sess, config)
        # create trainer and pass all the previous components to it
        trainer = ExampleTrainer(sess, model, data, config, logger)
        # load model if exists
        model.load(sess)
        # train model
        trainer.train()

    if config.mode == "test":
        # create the experiments dirs
        makeDirs([config.summary_dir, config.checkpoint_dir])
        # create tensorflow session
        sess = tf.Session()
        # create your data generator
        data = DataGenerator(config)
        # create an instance of the model
        model = ExampleModel(config)
        # create trainer and pass all the previous components to it
        tester = ExampleTester(sess, model, data, config)
        # train model
        tester.test()

    else:
        print("invalid mode")
        exit(0)

if __name__ == '__main__':
    main()


import contextlib
import io
import itertools
import typing
import warnings
from os import PathLike, fspath
from typing import (
    BinaryIO,
    Container,
    Dict,
    Iterable,
    Iterator,
    Mapping,
    MutableMapping,
    Optional,
    Sized,
    Union,
)

from . import relationship
from .entity import Entity, EntityData
from .logic.lineage import Lineage
from .metadata import Metadata
from .relationship import Relationship, RelationshipData
from .synonym import SynonymType
from .term import Term, TermData
from .utils.io import decompress, get_handle, get_location
from .utils.iter import SizedIterator
from .utils.meta import roundrepr, typechecked

__all__ = ["Ontology"]
_D = typing.TypeVar("_D", bound=EntityData)

class _DataGraph(typing.Generic[_D], typing.Mapping[str, _D]):
    """A private data storage for a type of entity.

    This class is equivalent to a graph storing nodes in the ``entities``
    attribute, and directed edges corresponding to the sub-entity
    relationship between entities in the ``lineage`` attribute.
    """

    entities: MutableMapping[str, _D]
    lineage: MutableMapping[str, Lineage]

    def __init__(self, entities=None, lineage=None):
        self.entities = entities or {}
        self.lineage = lineage or {}

    def __contains__(self, key: object) -> bool:
        return key in self.entities

    def __len__(self) -> int:
        return len(self.entities)

    def __iter__(self):
        return iter(self.entities)

    def __getitem__(self, key: str) -> _D:
        return self.entities[key]

class _OntologyTerms(Sized, Container, Iterable[Term]):
    """A convenience wrapper over the terms of an ontology."""

    def __init__(self, ontology: "Ontology") -> None:
        self.__ontology = ontology

    def __len__(self) -> int:
        return sum(len(ref.terms()) for ref in self.__ontology.imports.values()) + len(
            self.__ontology._terms.entities
        )

    def __iter__(self) -> Iterator[Term]:
        return itertools.chain(
            (
                Term(self.__ontology, t._data())
                for ref in self.__ontology.imports.values()
                for t in ref.terms()
            ),
            (
                Term(self.__ontology, tdata)
                for tdata in self.__ontology._terms.entities.values()
            ),
        )

    def __contains__(self, item: object) -> bool:
        if isinstance(item, str):
            return (
                any(item in ref for ref in self.__ontology.imports.values())
                or item in self.__ontology._terms
            )
        return False

class _OntologyRelationships(Sized, Container, Iterable[Relationship]):
    """A convenience wrapper over the relationships of an ontology."""

    def __init__(self, ontology: "Ontology"):
        self.__ontology = ontology

    def __len__(self) -> int:
        return sum(
            len(ref.relationships()) for ref in self.__ontology.imports.values()
        ) + len(self.__ontology._relationships.entities)

    def __iter__(self) -> Iterator[Relationship]:
        return itertools.chain(
            (
                Relationship(self.__ontology, r._data())
                for ref in self.__ontology.imports.values()
                for r in ref.relationships()
            ),
            (
                Relationship(self.__ontology, rdata)
                for rdata in self.__ontology._relationships.entities.values()
            ),
        )

    def __contains__(self, item: object) -> bool:
        if isinstance(item, str):
            return (
                any(item in ref for ref in self.__ontology.imports.values())
                or item in self.__ontology._relationships
            )
        return False

class Ontology(Mapping[str, Union[Term, Relationship]]):
    """An ontology storing terms and the relationships between them.

    Ontologies can be loaded with ``pronto`` if they are serialized in any of
    the following ontology languages and formats at the moment:

    - `Ontology Web Language 2 <https://www.w3.org/TR/owl2-overview/>`_
      in `RDF/XML format
      <https://www.w3.org/TR/2012/REC-owl2-mapping-to-rdf-20121211/>`_.
    - `Open Biomedical Ontologies 1.4
      <http://owlcollab.github.io/oboformat/doc/obo-syntax.html>`_.
    - `OBO graphs <https://github.com/geneontology/obographs>`_ in
      `JSON <http://json.org/>`_ format.

    Attributes:
        metadata (Metadata): A data structure storing the metadata about the
            current ontology, either extracted from the ``owl:Ontology`` XML
            element or from the header of the OBO file.
        timeout (int): The timeout in seconds to use when performing network
            I/O, for instance when connecting to the OBO library to download
            imports. This is kept for reference, as it is not used after the
            initialization of the ontology.
        imports (~typing.Dict[str, Ontology]): A dictionary mapping references
            found in the import section of the metadata to resolved `Ontology`
            instances.

    """

    # Public attributes
    import_depth: int
    timeout: int
    imports: Dict[str, "Ontology"]
    path: Optional[str]
    handle: Optional[BinaryIO]

    # Private attributes
    _terms: _DataGraph[TermData]
    _relationships: _DataGraph[RelationshipData]

    # --- Constructors -------------------------------------------------------

    @classmethod
    def from_obo_library(
        cls,
        slug: str,
        import_depth: int = -1,
        timeout: int = 5,
        threads: Optional[int] = None,
    ) -> "Ontology":
        """Create an `Ontology` from a file in the OBO Library.

        This is basically just a shortcut constructor to avoid typing the full
        OBO Library URL each time.

        Arguments:
            slug (str): The filename of the ontology release to download from
                the OBO Library, including the file extension (should be one
                of ``.obo``, ``.owl`` or ``.json``).
            import_depth (int): The maximum depth of imports to resolve in the
                ontology tree. *Note that the library may not behave correctly
                when not importing the complete dependency tree, so you should
                probably use the default value and import everything*.
            timeout (int): The timeout in seconds to use when performing
                network I/O, for instance when connecting to the OBO library
                to download imports.
            threads (int): The number of threads to use when parsing, for
                parsers that support multithreading. Give `None` to autodetect
                the number of CPUs on the host machine.

        Example:
            >>> apo = pronto.Ontology.from_obo_library("apo.obo")
            >>> apo.metadata.ontology
            'apo'
            >>> apo.path
            'http://purl.obolibrary.org/obo/apo.obo'

        """
        return cls(
            f"http://purl.obolibrary.org/obo/{slug}", import_depth, timeout, threads
        )

    def __init__(
        self,
        handle: Union[BinaryIO, str, PathLike, None] = None,
        import_depth: int = -1,
        timeout: int = 5,
        threads: Optional[int] = None,
    ):
        """Create a new `Ontology` instance.

        Arguments:
            handle (str, ~typing.BinaryIO, ~os.PathLike, or None): Either the
                path to a file or a binary file handle that contains a
                serialized version of the ontology. If `None` is given, an
                empty `Ontology` is returned and can be populated manually.
            import_depth (int): The maximum depth of imports to resolve in the
                ontology tree. *Note that the library may not behave correctly
                when not importing the complete dependency tree, so you should
                probably use the default value and import everything*.
            timeout (int): The timeout in seconds to use when performing
                network I/O, for instance when connecting to the OBO library
                to download imports.
            threads (int): The number of threads to use when parsing, for
                parsers that support multithreading. Give `None` to autodetect
                the number of CPUs on the host machine.

        Raises:
            TypeError: When the given ``handle`` could not be used to parse
                and ontology.
            ValueError: When the given ``handle`` contains a serialized
                ontology not supported by any of the builtin parsers.

        """
        from .parsers import BaseParser

        with contextlib.ExitStack() as ctx:
            self.import_depth = import_depth
            self.timeout = timeout
            self.imports = dict()

            # self._inheritance = dict()
            # self._terms: Dict[str, TermData] = {}
            # self._relationships: Dict[str, RelationshipData] = {}
            self._terms = _DataGraph(entities={}, lineage={})
            self._relationships = _DataGraph(entities={}, lineage={})

            # Creating an ontology from scratch is supported
            if handle is None:
                self.metadata = Metadata()
                self.path = self.handle = None
                return

            # Get the path and the handle from arguments
            if isinstance(handle, (str, PathLike)):
                self.path = handle = fspath(handle)
                self.handle = ctx.enter_context(get_handle(handle, timeout))
                _handle = ctx.enter_context(decompress(self.handle))
                _detach = False
            elif hasattr(handle, "read"):
                self.path = get_location(handle)
                self.handle = handle
                _handle = decompress(self.handle)
                _detach = True
            else:
                raise TypeError(f"could not parse ontology from {handle!r}")

            # check value of `threads`
            if threads is not None and not threads > 0:
                raise ValueError("`threads` must be None or strictly positive")

            # Parse the ontology using the appropriate parser
            buffer = _handle.peek(io.DEFAULT_BUFFER_SIZE)
            for cls in BaseParser.__subclasses__():
                if cls.can_parse(typing.cast(str, self.path), buffer):
                    cls(self).parse_from(_handle)  # type: ignore
                    break
            else:
                raise ValueError(f"could not find a parser to parse {handle!r}")

            if _detach:
                _handle.detach()

    # --- Magic Methods ------------------------------------------------------

    def __len__(self) -> int:
        """Return the number of entities in the ontology.

        This method takes into accounts the terms and the relationships defined
        in the current ontology as well as all of its imports. To only count
        terms or relationships, use `len` on the iterator returned by the
        dedicated methods (e.g. ``len(ontology.terms())``).

        Example:
            >>> ms = pronto.Ontology.from_obo_library("ms.obo")
            >>> len(ms)
            6023
            >>> len(ms.terms())
            5995

        """
        return (
            len(self._terms.entities)
            + len(self._relationships.entities)
            + sum(map(len, self.imports.values()))
        )

    def __iter__(self) -> SizedIterator[str]:
        """Yield the identifiers of all the entities part of the ontology."""
        terms, relationships = self.terms(), self.relationships()
        entities: typing.Iterable[Entity] = itertools.chain(terms, relationships)
        return SizedIterator(
            (entity.id for entity in entities),
            length=len(terms) + len(relationships),
        )

    def __contains__(self, item: object) -> bool:
        if isinstance(item, str):
            # TODO: remove in v3.0.0
            if item in self._relationships or item in relationship._BUILTINS:
                warnings.warn(
                    "checking if an ontology contains a relationship with "
                    "`<id> in Ontology` will not be supported in future "
                    "versions, use `<id> in Ontology.relationships()`.",
                    category=DeprecationWarning,
                    stacklevel=2,
                )
                return True
            return any(item in i for i in self.imports.values()) or item in self._terms
        return False

    def __getitem__(self, id: str) -> Union[Term, Relationship]:
        """Get any entity in the ontology graph with the given identifier."""
        # TODO: remove block in v3.0.0
        try:
            entity = self.get_relationship(id)
        except KeyError:
            pass
        else:
            warnings.warn(
                "indexing an ontology to retrieve a relationship will not be "
                "supported in future versions, use `Ontology.get_relationship` "
                "directly.",
                category=DeprecationWarning,
                stacklevel=2,
            )
            return entity

        try:
            return self.get_term(id)
        except KeyError:
            pass

        raise KeyError(id)

    def __repr__(self):
        """Return a textual representation of `self` that should roundtrip."""
        if self.path is not None:
            args = (self.path,)
        elif self.handle is not None:
            args = (self.handle,)
        else:
            args = ()
        kwargs = {"timeout": (self.timeout, 5)}
        if self.import_depth > 0:
            kwargs["import_depth"] = (self.import_depth, -1)
        return roundrepr.make("Ontology", *args, **kwargs)

    def __getstate__(self):
        state = self.__dict__.copy()
        state["handle"] = None
        return state

    def __setstate__(self, state):
        self.__dict__ = state

    # --- Serialization utils ------------------------------------------------

    def dump(self, file: BinaryIO, format: str = "obo"):
        """Serialize the ontology to a given file-handle.

        Arguments:
            file (~typing.BinaryIO): A binary file handle open in reading mode
                to write the serialized ontology into.
            format (str): The serialization format to use. Currently supported
                formats are: **obo**, **json**.

        Example:
            >>> ms = pronto.Ontology.from_obo_library("ms.obo")
            >>> with open("ms.json", "wb") as f:
            ...     ms.dump(f, format="json")

        """
        from .serializers import BaseSerializer

        for cls in BaseSerializer.__subclasses__():
            if cls.format == format:
                cls(self).dump(file)  # type: ignore
                break
        else:
            raise ValueError(f"could not find a serializer to handle {format!r}")

    def dumps(self, format: str = "obo") -> str:
        """Get a textual representation of the serialization ontology.

        Example:
            >>> go = pronto.Ontology("go.obo")
            >>> print(go.dumps())
            format-version: 1.2
            data-version: releases/2019-07-01
            ...

        """
        s = io.BytesIO()
        self.dump(s, format=format)
        return s.getvalue().decode("utf-8")

    # --- Data accessors -----------------------------------------------------

    def synonym_types(self) -> SizedIterator[SynonymType]:
        """Iterate over the synonym types of the ontology graph."""
        sources = [i.synonym_types() for i in self.imports.values()]
        sources.append(self.metadata.synonymtypedefs)  # type: ignore
        length = sum(map(len, sources))
        return SizedIterator(itertools.chain.from_iterable(sources), length)

    def terms(self) -> _OntologyTerms:
        """Query the terms of an ontology.

        Example:
            >>> pato = pronto.Ontology.from_obo_library("pato.obo")
            >>> len(pato.terms())
            2661
            >>> "PATO:0000186" in pato.terms()
            True
            >>> for term in sorted(pato.terms()):
            ...     print(term)
            Term('PATO:0000000', name='obsolete pato')
            Term('PATO:0000001', name='quality')
            ...

        """
        return _OntologyTerms(self)

    def relationships(self) -> _OntologyRelationships:
        """Query the relationships of an ontology.

        Example:
            >>> pato = pronto.Ontology.from_obo_library("pato.obo")
            >>> len(pato.relationships())
            24
            >>> "reciprocal_of" in pato.relationships()
            True
            >>> for relationship in pato.relationships():
            ...     print(relationship)
            Relationship('correlates_with', ...)
            Relationship('decreased_in_magnitude_relative_to', ...)
            ...

        """
        return _OntologyRelationships(self)

    @typechecked()
    def create_term(self, id: str) -> Term:
        """Create a new term with the given identifier.

        Returns:
            `Term`: the newly created term view, which attributes can the be
            modified directly.

        Raises:
            ValueError: if the provided ``id`` already identifies an entity
                in the ontology graph, or if it is not a valid OBO identifier.

        """
        if id in self:
            raise ValueError(f"identifier already in use: {id} ({self[id]})")
        self._terms.entities[id] = termdata = TermData(id)
        self._terms.lineage[id] = Lineage()
        return Term(self, termdata)

    @typechecked()
    def create_relationship(self, id: str) -> Relationship:
        """Create a new relationship with the given identifier.

        Raises:
            ValueError: if the provided ``id`` already identifies an entity
                in the ontology graph.

        """
        if id in self:
            raise ValueError(f"identifier already in use: {id} ({self[id]})")
        self._relationships.entities[id] = reldata = RelationshipData(id)
        self._relationships.lineage[id] = Lineage()
        return Relationship(self, reldata)

    @typechecked()
    def get_term(self, id: str) -> Term:
        """Get a term in the ontology graph from the given identifier.

        Raises:
            KeyError: if the provided ``id`` cannot be found in the terms of
                the ontology graph.

        """
        try:
            return Term(self, self._terms[id])
        except KeyError:
            pass
        for dep in self.imports.values():
            try:
                return Term(self, dep.get_term(id)._data())
            except KeyError:
                pass
        raise KeyError(id)

    @typechecked()
    def get_relationship(self, id: str) -> Relationship:
        """Get a relationship in the ontology graph from the given identifier.

        Builtin ontologies (``is_a`` and ``has_subclass``) can be accessed
        with this method.

        Raises:
            KeyError: if the provided ``id`` cannot be found in the
                relationships of the ontology graph.

        """
        # TODO: remove block in v3.0.0
        if id in relationship._BUILTINS:
            warnings.warn(
                "using the `is_a` relationship not be supported in future versions, "
                "use `superclasses` and `subclasses` API of entities instead.",
                category=DeprecationWarning,
                stacklevel=2,
            )
            return Relationship(self, relationship._BUILTINS[id])

        try:
            return Relationship(self, self._relationships[id])
        except KeyError:
            pass

        for dep in self.imports.values():
            try:
                return Relationship(self, dep.get_relationship(id)._data())
            except KeyError:
                pass

        raise KeyError(id)

    @typechecked()
    def get_synonym_type(self, id: str) -> SynonymType:
        """Get a synonym type in the ontology graph from the given identifier.

        Raises:
            KeyError: if the provided ``id`` does not resolve to a synonym type
                declared in this `Ontology` or one of its imports.

        """
        ty = next((ty for ty in self.metadata.synonymtypedefs if ty.id == id), None)
        if ty is not None:
            return ty
        for dep in self.imports.values():
            try:
                return dep.get_synonym_type(id)
            except KeyError:
                pass
        raise KeyError(id)


import service.globals as global_variables
import component.filesystem_item as filesystem_item
import dialogs.add_filesystem as add_filesystem
import pybookeeping.core.operation.filesystem as filesystem
import PySide.QtGui as QtGui
import PySide.QtCore as QtCore
import json
import functools

class FilesystemList(QtGui.QListWidget):
	_stylesheet = """
		QListWidget {
			font-family: "Lucida Grande", Verdana, Helvetica, Arial, sans-serif;
			font-size: 14px;
			background-color: #a6a6a6;
		}

		QListWidget::item {
			color: #a6a6a6;
			background-color: white;
			padding-top: 10px;
			padding-bottom: 10px;
			border-bottom: 1px solid black;
		}

		QListWidget::item:selected {
			color: white;
			background-color: #5abae1;
		}

		QListWidget::item:focus {
			border: 0px;
		}
	"""

	def __init__(self, entity):
		QtGui.QListWidget.__init__(self, entity)
		self.setSortingEnabled(True)
		self.setStyleSheet(self._stylesheet)
		self.setFocusPolicy(QtCore.Qt.NoFocus)

		global_variables.twig_signal.add_filesystem.connect(self.create_new)
		global_variables.twig_signal.view_changed.connect(self.item_changed)
		self.itemSelectionChanged.connect(self.item_changed)

		self.filesystem = filesystem.Filesystem(global_variables.bookeeping_connection)
		self.display_children()

	def display_children(self):
		for filesystem_info in self.filesystem.get_all_filesystem(global_variables.userid)[1]:
			item_tooltip = json.dumps(filesystem_info, indent = 8)
			item = filesystem_item.FilesytemItem(filesystem_info, self)
			item.setToolTip(item_tooltip)

	def remove_children(self):
		while self.count() > 0:
			self.takeItem(0)

	def contextMenuEvent(self, event):
		menu = QtGui.QMenu()

		item = self.itemAt(event.x(), event.y())
		if item is None:
			menu.addAction(QtGui.QAction("Add Filesystem", menu, triggered = self.create_new))
		else:
			menu.addAction(QtGui.QAction("Show Changes", menu, triggered = functools.partial(item.filesystem_changes)))
			menu.addAction(QtGui.QAction("Commit", menu, triggered = functools.partial(item.commit_changes)))

		menu.exec_(QtGui.QCursor.pos())

	def create_new(self):
		add_dialog = add_filesystem.AddFilesystem()
		if add_dialog.exec_() == QtGui.QDialog.Accepted:
			self.remove_children()
			self.display_children()

	def item_changed(self):
		current_item = self.currentItem()
		if current_item is not None:
			current_filesytem_info = self.currentItem().filesystem_info
			global_variables.twig_signal.filesystem_list_changed.emit(current_filesytem_info)


from datetime import datetime

from celery.decorators import task
from celery.utils.log import get_task_logger
from django.conf import settings
from django.template.loader import render_to_string
from djangoRT import rtUtil

from glanceclient import Client as glance_client
from novaclient import client as nova_client
from ironicclient import client as ironic_client
from blazarclient import client as blazar_client
from chameleon.keystone_auth import admin_session, admin_ks_client
from projects.models import Project
from util.keycloak_client import KeycloakClient
from dateutil import parser

LOG = get_task_logger(__name__)

class OpenstackDataError(Exception):
    def __init__(self, messages=[]):
        self.messages = messages
        super(OpenstackDataError, self).__init__(messages)

@task(bind=True)
def add_openstack_data(self, **kwargs):
    ticket_id = kwargs.get("ticket_id")
    username = kwargs.get("username")

    messages = []
    bound_task = self

    def write_message(progress_pct, message):
        LOG.info(message)
        messages.append(message)
        bound_task.update_state(
            state="PROGRESS",
            meta={
                "messages": messages,
                "progress_pct": progress_pct,
            },
        )

    try:
        if username:
            keycloak_client = KeycloakClient()
            projects = keycloak_client.get_full_user_projects_by_username(username)

            regions = list(settings.OPENSTACK_AUTH_REGIONS.keys())
            region_list = []
            for i, region in enumerate(regions):
                try:
                    factor = (1.0 / len(regions)) * 100
                    write_message(factor * i, f'Processing region "{region}"')
                    region_list.append(get_openstack_data(username, region, projects))
                except Exception as err:
                    LOG.error(
                        f"Failed to get OpenStack data for region {region}: {err}"
                    )
            openstack_user_data = remove_empty_lines(
                render_to_string(
                    "djangoRT/project_details.txt", {"regions": region_list}
                )
            )
        else:
            openstack_user_data = "No openstack data for anonymous user."
        rt = rtUtil.DjangoRt()
        rt.commentOnTicket(ticket_id, openstack_user_data)
    except Exception as exc:
        LOG.exception("Failed to gather data")
        exc_message = getattr(exc, "message", None)
        if exc_message:
            messages.append(exc_message)
        raise OpenstackDataError(messages=messages) from exc
    # Return current state as last action
    return {
        "messages": messages,
        "progress_pct": 100.0,
    }

def get_openstack_data(username, region, projects):
    admin_client = admin_ks_client(region)
    admin_sess = admin_session(region)

    current_region = {}
    current_region["name"] = region
    current_region["projects"] = []

    # we know there is only going to be one domain
    domains = list(admin_client.domains.list(name="chameleon"))
    if not domains:
        LOG.error('Didn\'t find the domain "chameleon", skipping this site')
        return current_region
    domain_id = domains[0].id

    ks_users_list = list(admin_client.users.list(name=username, domain=domain_id))
    if len(ks_users_list) > 1:
        LOG.warning(
            f"Found {len(ks_users_list)} users for {username}, using the first."
        )
    ks_user = ks_users_list[0]

    all_ks_projects = {
        ks_p.name: ks_p for ks_p in admin_client.projects.list(domain=domain_id)
    }
    for project in projects:
        charge_code = project["name"]
        # Project doesn't exist for this region
        if charge_code not in all_ks_projects:
            continue
        ks_project_id = all_ks_projects[charge_code].id
        project_qs = Project.objects.filter(charge_code=charge_code)
        project_list = list(project_qs)
        if len(project_list) > 1:
            raise Exception(
                f"More than one project found with charge code {charge_code}"
            )
        project = project_list[0]

        current_project = {}
        current_project["charge_code"] = project.charge_code
        current_project["id"] = ks_project_id
        current_region["projects"].append(current_project)

        try:
            current_project["leases"] = get_lease_info(
                admin_sess, ks_user.id, ks_project_id
            )
        except Exception as err:
            current_project["lease_error"] = True
            LOG.error(f"Failed to get leases in {region} for {project.title}: {err}")
        try:
            current_project["servers"] = get_server_info(admin_sess, ks_project_id)
        except Exception as err:
            current_project["server_error"] = True
            LOG.error(
                f"Failed to get active servers in {region} for {project.title}: {err}"
            )

    return current_region

def get_lease_info(sess, user_id, project_id):
    lease_list = []
    blazar = blazar_client.Client(
        "1", service_type="reservation", interface="publicURL", session=sess
    )
    ironic = ironic_client.Client("1", session=sess)
    leases = blazar.lease.list()
    for lease in leases:
        if lease.get("user_id") != user_id or lease.get("project_id") != project_id:
            continue

        # Ignore if more than 3 days out of date
        end_date = parser.parse(lease.get("end_date"))
        date_diff = datetime.utcnow() - end_date
        if date_diff.days > 3:
            continue

        lease_dict = {}
        lease_dict["name"] = lease.get("name")
        lease_dict["status"] = lease.get("status")
        lease_dict["start_date"] = str(parser.parse(lease.get("start_date")))
        lease_dict["end_date"] = str(end_date)
        lease_dict["id"] = lease.get("id")

        lease_dict["hosts"] = []
        resource_map = {r["id"]: r for r in blazar.host.list()}
        for blazar_host in blazar.host.list_allocations():
            if any(
                res["lease_id"] == lease_dict["id"]
                for res in blazar_host["reservations"]
            ):
                resource_host = resource_map[blazar_host["resource_id"]]
                host = {
                    "node_name": resource_host["node_name"],
                    "uid": resource_host["uid"],
                    "node_type": resource_host["node_type"],
                }
                node = ironic.node.get(resource_host["uid"])
                host["provision_state"] = node.provision_state
                host["instance_uuid"] = node.instance_uuid
                host["last_error"] = node.last_error
                lease_dict["hosts"].append(host)

        lease_dict["networks"] = []
        resource_map = {r["id"]: r for r in blazar.network.list()}
        for network in blazar.network.list_allocations():
            if any(
                res["lease_id"] == lease_dict["id"] for res in network["reservations"]
            ):
                lease_dict["networks"].append(resource_map[network["resource_id"]])
        lease_list.append(lease_dict)
    return lease_list

def remove_empty_lines(string):
    return "\n".join([line for line in string.split("\n") if len(line.strip()) > 0])

def get_server_info(sess, project_id):
    server_list = []
    nova = nova_client.Client("2", session=sess)
    glance = glance_client("2", service_type="image", session=sess)
    servers = nova.servers.list(search_opts={"all_tenants": True})
    for server in servers:
        if server.tenant_id != project_id:
            continue
        server_dict = {}
        server_dict["name"] = server.name
        server_dict["status"] = str(server.status)
        server_dict["created_date"] = str(parser.parse(server.created))
        server_dict["id"] = server.id
        server_dict["networks"] = []
        for network in server.addresses.keys():
            network_dict = {"name": network, "addresses": []}
            for address in server.addresses[network]:
                network_dict["addresses"].append(
                    {
                        "addr": address["addr"],
                        "type": address["OS-EXT-IPS:type"],
                    }
                )
            server_dict["networks"].append(network_dict)
        image = glance.images.get(str(server.image["id"]))
        server_dict["image_name"] = str(image.name)
        server_dict["image_id"] = str(image.id)
        server_list.append(server_dict)
    return server_list


from pylab import * #importing several functions from pylab, including numpy and pyplot
import numpy as np
import math
from math import pi
from numpy.lib import scimath as SM #used for the square root of the enveloping section of algorithm

def noise_algorithm(total_time,reals,site,dt,Sko,Wko):
    #Constants over the whole procedure
    k = 8.6173303E-5 #boltzmann constant in eV/K
    T = 300 #Temperature in K
    hbar = 0.658211951 # in eV-fs
    #N = (int(total_time/dt)+1)*site #+1 to account for the dt/dt that we need if  we want to have our time and Noise exactly finish at total_time
    N = (int(total_time/dt)+1)
    Gammak =  0.00062/hbar #9.4196*10**(-4) #rad/fs

    #array with all the frequencies and S
    Sk = array(Sko) #only for the first peak #27th April: before was array([Sk]), now Sk and Wk need to be passed already as [] since I want to pass it on RunNise code
    #Sk = array([0.007, 0.018])
    #Wk = array([568, 770])*1.23984*10**(-4)/hbar
    Wk = array(Wko)*1.23984*10**(-4)/hbar #only for the first peak

    #this contains the noise generation algorithm
    def spectral(w): #drude spectral density
        #converting the frequencies to angular frequencies. Update: done already on the definition as requested by professor
        S = 0
        for i in range(len(Wk)):
            S += hbar*4*k*T*Sk[i]*Wk[i]**3*Gammak/((Wk[i]**2-w**2)**2+(w**2*Gammak**2))
        return S

    def generate_noise(mean, var,N,reals,site,dt):
        white_noise = np.random.normal(mean, var, size=(reals*site,N)) #generates matrix with white noise. Shape = reals x N. Here, mean = 0 and var = 1
        freq = np.fft.fft(white_noise)*1/sqrt(dt) #fourier transform of the white noise: W
        freq_bins = np.fft.fftfreq(N,dt)*2*pi #frequencies associated to fft(white noise)
        freq_enveloped = SM.sqrt(spectral(freq_bins)) * freq #sqrt(S)*W
        return np.real(np.fft.ifft(freq_enveloped))

    OldNoise = generate_noise(0, 1, N, reals,site,dt)

    print(shape(OldNoise)) #returns noise matrix of size (reals x N). N:= (length/dt + 1)*site

    #N2 = int(total_time/dt)+1  #15th April: basically here is N because 1st axis is the longer one

    NewNoise = np.zeros((reals,N,site))#NEmpty 3D array with correct dimensions
                                        # first dimension: realizations
                                        # second dimension: total_time + 1
                                        # third dimension: number of sites
    print(shape(NewNoise))

    for j in range(0,site):
        print(j)
        #NewNoise[:,:,j//2] = OldNoise[:,j*N2:(j+1)*N2] #assigning to each site N2 elements := total_time/dt + 1
        #NewNoise[:,:,j//2] = OldNoise[j*reals:(j+1)*reals,0:N2] #taking only alternating blocks: Y,N
        NewNoise[:,:,j] = OldNoise[j*reals:(j+1)*reals,0:N]
        print(shape(NewNoise[:,:,j]))
    #assigning the noise values to each site
    #Explanation: for each site j we are going from the j*Nth element to the (j+1)*Nth element.
    #Recall: for slicing the last element is not taken into account. Example, site = 4, N = 101, reals= 100:
    #j = 1: 0-->100, 101-->201, 202-->302, 303-->403. Each of them has N elements. 404th element is called by 403.

    print('Finished algorithm properly')
    return NewNoise

def main():
    print('You are using this script as your main')

if __name__=='__main__':
    main()


""" Enumeration of all the differents types of possible pawn on the board"""
from enum import Enum
from src.utils.PrintGomoku import print_gomoku
from sys import platform

class pawnType(Enum):
    EMPTY = 0
    BRAIN = 1
    MANAGER = 2

class GomokuBoard:
    """ Class Constructor, taking a board Size for the Game"""

    def __init__(self, boardSize):
        if boardSize < 5:
            raise RuntimeError("The given value can't be a Gomoku board size")
        self.__boardSize = boardSize
        self.boardMap = [[]]
        self.reset_board()

    def __check_pos(self, x: int, y: int) -> bool:
        """ Private Method, useful to check if the given coordinates are allowed """
        if x >= self.__boardSize or x < 0:
            return False
        if y >= self.__boardSize or y < 0:
            return False
        return True

    def __is_empty(self, x: int, y: int) -> bool:
        """ Private Method, check if the pawn on the given coordinates is empty """
        if not self.__check_pos(x, y):
            return False
        if self.boardMap[y][x] != pawnType.EMPTY:
            return False
        return True

    def __add_pawn(self, x: int, y: int, type):
        """ Add a pawn at the given coordinates """
        if not self.__check_pos(x, y):
            raise RuntimeError('Invalid Coordinate')
        if not self.__is_empty(x, y):
            raise RuntimeError('Cell is not empty')
        self.boardMap[y][x] = type

    def duplicate_pawn(self, x, y, type):
        """ TO USE ONLY IN ADD AND DUPLICATE """
        self.__add_pawn(x, y, type)

    def add_brain_pawn(self, x: int, y: int, display=True):
        """ Add a Brain Pawn at the given coordinates """
        self.__add_pawn(x, y, pawnType.BRAIN)
        if display:
            print_gomoku(f"{x},{y}")

    def add_manager_pawn(self, x: int, y: int):
        """ Add a Manager Pawn at the given coordinates"""
        self.__add_pawn(x, y, pawnType.MANAGER)

    def reset_board(self, boardSize: int = -1):
        """ Reset completly the board, setting all the cells to empty state """
        if boardSize == -1:
            boardSize = self.__boardSize
        self.__boardSize = boardSize
        self.boardMap = [[pawnType.EMPTY] *
                         boardSize for i in range(boardSize)]

    def get_pawn(self, x: int, y: int):
        """ Get the Pawn at the given coordinates """
        if not self.__check_pos(x, y):
            raise RuntimeError("The pawn can't be get with the given coordinates")
        return self.boardMap[y][x]

    def get_board_size(self) -> int:
        """ Get the Board Size """
        return self.__boardSize

    def get_cols_rows(self):
        """ Get all the diagonals"""
        max_col = len(self.boardMap[0])
        max_row = len(self.boardMap)
        cols = [[] for _ in range(max_col)]
        rows = [[] for _ in range(max_row)]
        for x in range(max_col):
            for y in range(max_row):
                cols[x].append(self.boardMap[x][y])
                rows[y].append(self.boardMap[x][y])
        return cols, rows

    def get_reverse_diagonal(self, x: int, y: int) -> list:
        """ Get the reverse diagonal of the given coordinates """
        if not self.__check_pos(x, y):
            return RuntimeError("The pawn can't be get with the given coordinates")
        diagonal = []
        for i in range(0, self.__boardSize):
            diagonal.append(self.boardMap[i][self.__boardSize - i - 1])
        return diagonal

    def __str__(self):
        BLUE = ''
        RED = ''
        WHITE = ''
        if platform == "linux" or platform == "linux2" or platform == "darwin":
            BLUE = '\033[94m'
            RED = "\033[1;31;40m"
            WHITE = "\033[0;37;40m"
        elif platform == "win32":
            pass

        """ Pass the board as string to be displayed """
        toPrint: str = f"DEBUG - Current board (size {self.__boardSize}):\n"
        toPrint += "DEBUG - 0 is Empty / 1 is Brain / 2 is Manager\n"
        for lines in self.boardMap:
            toPrint += 'DEBUG - '
            for cell in lines:
                value: str = f'[{cell.value}]' + WHITE
                if cell == pawnType.BRAIN:
                    value = RED + value
                if cell == pawnType.MANAGER:
                    value = BLUE + value
                toPrint += f'{value}'
            toPrint += '\n'
        toPrint = toPrint[:-1]
        return toPrint


import cv2
import numpy as np
import matplotlib.pyplot as plt
from feature_matching import match
from homography import solve_homography
import glob

def read_img_list(dir):
    # dir = '../data/data2/'
    image_lst = glob.glob(dir + '*.JPG')

    print(image_lst)

    nums = len(image_lst)
    images = [cv2.imread(f) for f in image_lst]

    center = nums / 2
    print("center index: %d" % center)

    left_list = []
    right_list = []
    for i in range(nums):
        if (i <= center):
            left_list.append(images[i])
        else:
            right_list.append(images[i])
    # left_list = images

    return left_list, right_list

def left_shift(left_list, right_list):
    # left_list = list(reversed(left_list))
    img_pre = left_list[0]
    for img_append in left_list[1:]:
        H = match_H(img_pre, img_append)
        print(H)
        Ht = np.linalg.inv(H)

        bottom_right = np.dot(Ht, np.array([img_pre.shape[1], img_pre.shape[0], 1]))
        top_left = np.dot(Ht, np.array([0, 0, 1]))
        bottom_left = np.dot(Ht, np.array([0, img_pre.shape[0], 1]))
        top_right = np.dot(Ht, np.array([img_pre.shape[1], 0, 1]))

        bottom_right /= bottom_right[-1]
        top_left /= top_left[-1]
        bottom_left /= bottom_left[-1]
        top_right /= top_right[-1]

        cx = int(max([0, img_pre.shape[1], top_left[0], bottom_left[0], top_right[0], bottom_right[0]]))
        cy = int(max([0, img_pre.shape[0], top_left[1], bottom_left[1], top_right[1], bottom_right[1]]))
        offset = [abs(int(min([0, img_pre.shape[1], top_left[0], bottom_left[0], top_right[0], bottom_right[0]]))),
                    abs(int(min([0, img_pre.shape[0], top_left[1], bottom_left[1], top_right[1], bottom_right[1]])))]
        dsize = (cx + offset[0], cy + offset[1])

        top_left[0:2] += offset
        bottom_left[0:2] += offset
        top_right[0:2] += offset
        bottom_right[0:2] += offset

        dstpoints = np.array([top_left, bottom_left, top_right, bottom_right])
        srcpoints = np.array([[0, 0], [0, img_pre.shape[0]], [img_pre.shape[1], 0], [img_pre.shape[1], img_pre.shape[0]]])

        H_offset, _ = cv2.findHomography(srcpoints, dstpoints)

        warped_img2 = cv2.warpPerspective(img_pre, H_offset, dsize)
        # cv2.imwrite("warped1.jpg", warped_img2)

        warped_img1 = np.zeros([dsize[1], dsize[0], 3], np.uint8)
        warped_img1[offset[1]:img_append.shape[0] + offset[1], offset[0]:img_append.shape[1] + offset[0]] = img_append
        tmp = blend_linear(warped_img1, warped_img2)
        img_pre = tmp

    left_image = tmp

    # right_list = list(reversed(right_list))
    for img_append in right_list:
        H = match_H(left_image, img_append)
        print(H)

        bottom_right = np.dot(H, np.array([img_append.shape[1], img_append.shape[0], 1]))
        top_left = np.dot(H, np.array([0, 0, 1]))
        bottom_left = np.dot(H, np.array([0, img_append.shape[0], 1]))
        top_right = np.dot(H, np.array([img_append.shape[1], 0, 1]))

        bottom_right /= bottom_right[-1]
        top_left /= top_left[-1]
        bottom_left /= bottom_left[-1]
        top_right /= top_right[-1]

        cx = int(max([0, left_image.shape[1], top_left[0], bottom_left[0], top_right[0], bottom_right[0]]))
        cy = int(max([0, left_image.shape[0], top_left[1], bottom_left[1], top_right[1], bottom_right[1]]))
        offset = [abs(int(min([0, left_image.shape[1], top_left[0], bottom_left[0], top_right[0], bottom_right[0]]))),
                    abs(int(min([0, left_image.shape[0], top_left[1], bottom_left[1], top_right[1], bottom_right[1]])))]
        dsize = (cx + offset[0], cy + offset[1])

        top_left[0:2] += offset
        bottom_left[0:2] += offset
        top_right[0:2] += offset
        bottom_right[0:2] += offset

        dstpoints = np.array([top_left, bottom_left, top_right, bottom_right])
        srcpoints = np.array([[0, 0], [0, img_append.shape[0]], [img_append.shape[1], 0], [img_append.shape[1], img_append.shape[0]]])

        H_offset, _ = cv2.findHomography(dstpoints, srcpoints)

        warped_img2 = cv2.warpPerspective(img_append, H_offset, dsize, flags=cv2.WARP_INVERSE_MAP)
        # cv2.imwrite("warped2.jpg", warped_img2)
        warped_img1 = np.zeros([dsize[1], dsize[0], 3], np.uint8)
        warped_img1[offset[1]:left_image.shape[0] + offset[1], offset[0]:left_image.shape[1] + offset[0]] = left_image
        tmp = blend_linear(warped_img1, warped_img2)
        left_image = tmp

    return left_image

def blend_linear(img1, img2):
    mask1 = ((img1[:,:,0] | img1[:,:,1] | img1[:,:,2]) > 0)
    mask2 = ((img2[:,:,0] | img2[:,:,1] | img2[:,:,2]) > 0)

    r,c = np.nonzero(mask1)
    center1 = [np.mean(r), np.mean(c)]

    r,c = np.nonzero(mask2)
    center2 = [np.mean(r), np.mean(c)]

    vec = np.array(center2) - np.array(center1)
    intsct_mask = mask1 & mask2

    r,c = np.nonzero(intsct_mask)

    out_wmask = np.zeros(mask2.shape[:2])
    proj_val = (r - center1[0]) * vec[0] + (c - center1[1]) * vec[1]
    # FIXME: proj_val is empty

    out_wmask[r,c] = (proj_val - (min(proj_val)+(1e-3))) / ((max(proj_val)-(1e-3)) - (min(proj_val)+(1e-3)))

    # blending
    mask1 = mask1 & (out_wmask == 0)
    mask2 = out_wmask
    mask3 = mask2 & (out_wmask == 0)

    out = np.zeros(img1.shape)
    for i in range(3):
        out[:,:,i] = img1[:,:,i] * (mask1 + (1 - mask2) * (mask2 != 0)) + img2[:,:,i] * (mask2 + mask3)

    return np.uint8(out)

def match_H(img1, img2, mode='sift', k=2, r=0.7, threshold=5.0, max_iters=2000, is_default=True, is_show=False):
    kp1, kp2, matches = match(img1, img2, mode=mode, k=k, r=r, is_default=True)
    H, _ = solve_homography(kp1, kp2, matches, threshold=threshold, max_iters=max_iters, is_default=True)

    return H

def main(dir, out):
    left_list, right_list = read_img_list(dir)
    res = left_shift(left_list, right_list)

    cv2.imwrite(out, res)

if __name__ == '__main__':
    main('../data/data1/', '../res/data1.jpg')
    main('../data/data2/', '../res/data2.jpg')
    main('../data/data3/', '../res/data3.jpg')
    main('../data/data4/', '../res/data4.jpg')


"""Author: Samuel DeLaughter
12/6/14

This program graphs the probability of landing on each integer in a given interval for a 1D random-walk simulation
If called with a -i flag, it will prompt for user input on the following variables:
	Boundary numbers, starting position, number of steps per simulation, number of simulations

"""

import sys
import random
import numpy as np
import matplotlib.pyplot as plt

#Set default values for the variables
MIN_POSITION = -10
MAX_POSITION = 10
START_POSITION = 0
NSTEPS = 12
NSIMS = 1000

if('-i' in sys.argv):
#Get user input for variables if called with the -i argument
	MIN_POSITION = int(raw_input("Enter lower boundary: ") or MIN_POSITION)
	MAX_POSITION = int(raw_input("Enter upper boundary: ") or MAX_POSITION)

	#If the upper boundary is smaller than the lower boundary, swap them
	sorted_bounds = sorted((MIN_POSITION, MAX_POSITION))
	MIN_POSITION = sorted_bounds[0]
	MAX_POSITION = sorted_bounds[1]

	#If the two boundaries are equivalent, increment the upper bound
	if(MIN_POSITION == MAX_POSITION):
		MAX_POSITION+=1

	START_POSITION = int(raw_input("Enter starting position: ") or START_POSITION)
	#Make sure the starting position is within the min/max bounds

	START_POSITION=sorted((MIN_POSITION, START_POSITION, MAX_POSITION))[1]

	NSTEPS = int(raw_input("Enter number of steps for each simulation: ") or NSTEPS)
	NSIMS = int(raw_input("Enter number of simulations to run: ") or NSIMS)

def move(position):
#Change the current position
	if(position == MAX_POSITION):
		#If you're at the upper boundary, either stay put or decrease
		step=random.randint(-1, 0)
	elif(position == MIN_POSITION):
		#If you're at the lower boundary, either stay put or increase
		step=random.randint(0, 1)
	else:
		#If you're within the boundaries, either stay put, decrease, or increase
		step=random.randint(-1, 1)
	position += step
	return position

def sim():
#Run a simulation
	position=START_POSITION
	for i in range(NSTEPS):
		position=move(position)
	return position

def main():
	results=[]
	for i in range(NSIMS):
		results.append(sim())
	counts=[]
	for i in range(MIN_POSITION, (MAX_POSITION+1)):
		counts.append(results.count(i))

	plt.plot(range(MIN_POSITION, (MAX_POSITION+1)), counts, 'ro')
	#Set axis intervals
	plt.xticks(np.arange(MIN_POSITION, (MAX_POSITION + 1), 1.0))
	#plt.yticks(np.arange(0, max(counts), 100))
	#Display gridlines
	plt.grid(b=True, which=u'major', axis=u'both')
	plt.show()

	#Make the plot window visible
	wm = plt.get_current_fig_manager()
	wm.window.attributes('-topmost', 0)

if __name__ == '__main__':
    main()


from setuptools import setup
import json

with open("metadata.json", encoding="utf-8") as fp:
    metadata = json.load(fp)

setup(
    name="lexibank_wangbai",
    description=metadata["title"],
    license=metadata.get("license", ""),
    url=metadata.get("url", ""),
    py_modules=["lexibank_wangbai"],
    include_package_data=True,
    zip_safe=False,
    entry_points={
        "lexibank.dataset": ["wangbai=lexibank_wangbai:Dataset"],
        "cldfbench.commands": ["wangbai=wangbaicommands"],
    },
    install_requires=["pylexibank>=3.0"],
    extras_require={"wangbai": ["sinopy", "lingrex", "python-igraph"]},
)


# Example of backtracking pattern to solve problems such as: find all subsets, permutations, combinations, etc.

from typing import List

# ref: https://leetcode.com/problems/combinations/solutions/844096/backtracking-cheatsheet-simple-solution/?orderBy=most_votes&languageTags=python

# Template:

class BacktrackingTemplate():
  def __init__(self, data):
    self.data = data
    self.result = []

  def subsets(self, nums: List[int]) -> List[List[int]]:
    res, path = [], []
    self.dfs(0, res, path, nums)
    return res

  def dfs(self, index, res, path, nums):
    res.append(list(path))
    for i in range(index, len(nums)):
      path.append(nums[i])
      self.dfs(i+1, res, path, nums)
      path.pop()


from torchvision import transforms, datasets
import numpy as np
from torch.utils.data import DataLoader
from torch.utils.data.sampler import SubsetRandomSampler

def get_image_dataset(project, preprocessing, signal_length, figtype, image_size=224):

    fig_path = (project.images_dir / preprocessing /
                figtype / signal_length).__str__()

    dataset = datasets.ImageFolder(root=fig_path,
                                   transform=transforms.Compose([
                                       transforms.Resize(image_size),
                                       transforms.ToTensor(),
                                       transforms.Normalize((0.5, 0.5, 0.5),
                                                            (0.5, 0.5, 0.5))
                                   ])
                                   )
    return dataset

def get_image_dataloaders(project, preprocessing, signal_length, figtype, image_size=224,
                          train_split=0.8, batch_size=8, workers=1, ngpu=1, random_seed=42):

    dataset = get_image_dataset(project, preprocessing, signal_length, figtype)

    dataset_size = len(dataset)
    indices = list(range(dataset_size))
    trainsplit = int(np.floor(train_split * dataset_size))

    np.random.seed(random_seed)
    np.random.shuffle(indices)

    train_indices, val_indices = indices[:trainsplit], indices[trainsplit:]
    trainset_size = len(train_indices)
    valset_size = len(val_indices)

    train_sampler = SubsetRandomSampler(train_indices)
    valid_sampler = SubsetRandomSampler(val_indices)

    train_loader = DataLoader(dataset, batch_size=batch_size, sampler=train_sampler,
                              num_workers=workers)
    validation_loader = DataLoader(dataset, batch_size=batch_size, sampler=valid_sampler,
                                   num_workers=workers)

    dataloaders = {"train": train_loader, "val": validation_loader}

    dataset_sizes = {"train": len(train_indices), "val": len(val_indices)}

    return dataloaders, dataset_sizes


def _action():
    global _user_str
    _user_str = input('введите строку ')
    _int_func(_user_str)
def _int_func(txt):
    txt_list = txt.split()
    n=0
    new_txt = ""
    while n<len(txt_list):
        new_txt =new_txt + txt_list[n].title() + ' '
        n=n+1
    print(str(new_txt))

_action()


"""
Data preparation for Titanic data. Includes train-test split and creating of features and labels.
"""
from typing import Tuple

import pandas as pd
from numpy import array
from sklearn.model_selection import train_test_split

from src.data_prep.categorical import lowercase_column, extract_title
from src.data_prep.continuous import fill_numeric

title_mapping = {'mme': 'mrs',
                 'ms': 'miss',
                 'mlle': 'miss',
                 'lady': 'rare',
                 'countess': 'rare',
                 'capt': 'rare',
                 'col': 'rare',
                 'don': 'rare',
                 'dr': 'rare',
                 'major': 'rare',
                 'rev': 'rare',
                 'sir': 'rare',
                 'jonkheer': 'rare',
                 'dona': 'rare'}
title_to_int = {'mr': 1, 'mrs': 2, 'miss': 3, 'master': 4, 'rare': 5, 'NA': -1}
sex_to_int = {'female': 1, 'male': 0, 'NA': -1}
port_to_int = {'s': 0, 'c': 1, 'q': 2, 'NA': -1}

def load_df() -> pd.DataFrame:
    """Return raw Titanic Data

    Returns:
        Titanic data loaded from data/titanic.csv
    """
    return pd.read_csv('data/titanic.csv')

def prep_df(df: pd.DataFrame) -> pd.DataFrame:
    """Returns prepared Titanic data.

    Args:
        df: Dataframe of raw Titanic data

    Returns:
        Prepared Titanic data.
    """
    # Lowercase columns
    df.columns = [col.lower() for col in df.columns]

    # Drop ticket and cabin col
    df.drop(columns=['passengerid', 'ticket', 'cabin'], inplace=True)

    # Create title column
    df = lowercase_column(df, 'name')
    df = extract_title(df, 'name', title_mapping)
    df.drop(columns=['name'], inplace=True)

    # Fill lowercase embarked column
    df = lowercase_column(df, 'embarked')
    df = lowercase_column(df, 'sex')

    # Fill nulls for numeric cols
    for col in ['pclass', 'age', 'sibsp', 'parch', 'fare']:
        df = fill_numeric(df, col, '-1')

    # Fill null values and categorical encoding
    df['title'].fillna('NA', inplace=True)
    df['sex'].fillna('NA', inplace=True)
    df['embarked'].fillna('NA', inplace=True)

    df['title'] = df['title'].map(title_to_int)
    df['sex'] = df['sex'].map(sex_to_int)
    df['embarked'] = df['embarked'].map(port_to_int)

    return df

def split_df(df: pd.DataFrame) -> Tuple[pd.DataFrame, pd.DataFrame]:
    """Splits processed Titanic data into train and test dataframes.

    Args:
        df: Processed Titanic data

    Returns:
        Two dataframes, one for train and one for test.
    """
    train, test = train_test_split(df, test_size=0.2, random_state=1368, stratify=df['survived'])

    return train, test

def get_feats_and_labels(df: pd.DataFrame) -> Tuple[array, array]:
    """Returns a tuple of feature array and label vector

    Args:
        df: Processed Titanic data

    Returns:
        A tuple of feature array and label vector
    """
    # Get labels and features
    X = df.iloc[:, 1:].values
    y = df['survived'].values

    return X, y


from distutils.core import setup
import sys

import weixin

kw = dict(
    name = 'weixinpy',
    version = weixin.__version__,
    description = 'Python client SDK for Micro Message Public Platform API',
    long_description = open('README', 'r').read(),
    author = 'Liang Cha',
    author_email = 'ckmx945@gmail.com',
    url = 'https://github.com/kun945/weixinpy',
    download_url = 'https://github.com/kun945/weixinpy',
    py_modules = ['weixin'],
    classifiers = [
        'Development Status :: 5 - Production/Stable',
        'Environment :: Web Environment',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: Apache Software License',
        'Operating System :: OS Independent',
        'Programming Language :: Python',
        'Topic :: Internet',
        'Topic :: Software Development :: Libraries :: Python Modules',
    ])

setup(**kw)


"""
This module contains various utilities for pretty-printing
structured data.
"""

def indented_list(title=None, indentation_level=0, pairs=[], singles=[], join=True, sep=': '):
    """
    returns the string

    title
      left1: right1
      left2: right2
      s1
      s2

    all nicely indented where pairs contains [(left1, right1),
    (left2, right2)] and singles contains [s1, s2]

    above, ': ' is the sep.

    If title is not present, returns the unindented original list.
    Everything is pre-indented by 2 spaces indentation_level number
    of times.
    """
    indent = indentation_level * "  "
    if title:
        prefix =  (
            indent
            + title
            + "\n"
        ) if join else [indent + title]
        return prefix + indented_list(
                title=None,
                indentation_level=(indentation_level + 1),
                pairs=pairs,
            join=join,
            singles=singles,
            sep=sep
            )
    pairs = list(pairs)
    maxlen = max(len(left) for left, right in pairs) if pairs else 0
    fmt = indent + "{:<" + str(maxlen) + "s}" + sep + "{}"
    items = [fmt.format(*pair) for pair in pairs]
    items.extend([indent + s for s in singles])
    if join:
        return "\n".join(items)
    else:
        return items


#
#
# Created By : Mitchell Van Swol
# Date : 5/8/2018
#

import sys

# find the next iteration in a permutation in place

# following the wikipedia article for the next lexicographic order
# permutation

# find k such that a[k] < a[k+1], and k is the largest
# find largest j > k, such that a[k] < a[j]

class Solution(object):
	def nextPermutation(self, nums):

		if not nums:
			return nums

		len_nums = len(nums)
		k, j = len_nums - 2, len_nums - 1

		while k >= 0 and nums[k] >= nums[k+1]:
			k = k -1
		while j > k and nums[j] <= nums[k]:
			j = j - 1

		nums[k], nums[j] = nums[j], nums[k]
		nums[k+1:] = nums[k+1][:-1]


from re import M
import numpy as np

# 1. 데이터

x1 = np.array([range(100), range(301, 401), range(1, 101)])
x2 = np.array([range(101, 201), range(411, 511), range(100, 200)])

x1 = np.transpose(x1)
x2 = np.transpose(x2)

y1 = np.array(range(1001, 1101))

# print(np.shape(x1), np.shape(x2), np.shape(y1)) # (100, 3) (100, 3) (100,)

from sklearn.model_selection import train_test_split

x1_train, x1_test, x2_train, x2_test = train_test_split(x1, x2,
                        train_size=0.7, shuffle=False)
y1_train, y1_test = train_test_split(y1,
                        train_size=0.7, shuffle=False)

# 2. 모델 구성

from tensorflow.keras.models import Model, load_model
from tensorflow.keras.layers import Dense, Input

# 2-1. 모델1

input1 = Input(shape=(3,))
dense1 = Dense(10, activation='relu', name='dense1')(input1)
dense2 = Dense(7, activation='relu', name='dense2')(dense1)
dense3 = Dense(5, activation='relu', name='dense3')(dense2)
output1 = Dense(4)(dense3)

# 2-2. 모델2

input2 = Input(shape=(3,))
dense11 = Dense(10, activation='relu', name='dense11')(input2)
dense12 = Dense(7, activation='relu', name='dense12')(dense11)
dense13 = Dense(5, activation='relu', name='dense13')(dense12)
dense14 = Dense(5, activation='relu', name='dense14')(dense13)
output2 = Dense(4)(dense14)

from tensorflow.keras.layers import concatenate, Concatenate

merge1 = concatenate([output1, output2])
merge2 = Dense(10)(merge1)
merge3 = Dense(5, activation='relu')(merge2)

last_output = Dense(1)(merge3)

model = Model(inputs=[input1, input2], outputs=last_output)

model.summary()

# 3. 컴파일, 훈련

from keras.callbacks import EarlyStopping, ModelCheckpoint

es = EarlyStopping(monitor='val_loss', patience=20, mode='auto', verbose=1,
        restore_best_weights=True)

mcp = ModelCheckpoint(monitor='val_loss', mode='auto', verbose=1, save_best_only=True,
        filepath='./_save/ModelCheckPoint/keras49_mcp.h5')

model.compile(loss='mse', optimizer='adam', metrics=['mae'])
model.fit([x1_train, x2_train], y1_train, epochs=100, batch_size=8, verbose=1, validation_split=0.2,
        callbacks=[es, mcp])

model.save('./_save/ModelCheckPoint/keras49_model_save.h5')

from sklearn.metrics import r2_score

print("======================기본출력=======================")

# 4. 평가, 예측

result = model.evaluate([x1_test, x2_test], y1_test)
y_predict = model.predict([x1_test, x2_test])

print('model의 loss :', result)

r2 = r2_score(y1_test, y_predict)
print('model의 r2 :', r2)

print("======================1. load_model =======================")

model2 = load_model('./_save/ModelCheckPoint/keras49_model_save.h5')

result = model2.evaluate([x1_test, x2_test], y1_test)
y_predict = model2.predict([x1_test, x2_test])

print('model2의 loss :', result)

r2 = r2_score(y1_test, y_predict)
print('model2의 r2 :', r2)

print("======================2. Model_Check_Point =======================")

model3 = load_model('./_save/ModelCheckPoint/keras49_mcp.h5')

result = model3.evaluate([x1_test, x2_test], y1_test)
y_predict = model3.predict([x1_test, x2_test])

print('model3의 loss :', result)

r2 = r2_score(y1_test, y_predict)
print('model3의 r2 :', r2)

'''

======================기본출력=======================
1/1 [==============================] - 0s 15ms/step - loss: 15173.0469 - mae: 121.8719
model의 loss : [15173.046875, 121.87185668945312]
model의 r2 : -201.53232114706873
======================1. load_model =======================
1/1 [==============================] - 0s 92ms/step - loss: 15173.0469 - mae: 121.8719
model2의 loss : [15173.046875, 121.87185668945312]
model2의 r2 : -201.53232114706873
======================2. Model_Check_Point =======================
1/1 [==============================] - 0s 101ms/step - loss: 11682.0889 - mae: 106.6032
model3의 loss : [11682.0888671875, 106.60320281982422]
model3의 r2 : -154.9344411390443

earlystopping의 restore_best_weights=True = ModelCheckPoint의 save_best_only=True
와 동일

======================기본출력=======================
1/1 [==============================] - 0s 15ms/step - loss: 274.6945 - mae: 13.8220
model의 loss : [274.6944580078125, 13.822030067443848]
model의 r2 : -2.66666701891531
======================1. load_model =======================
1/1 [==============================] - 0s 91ms/step - loss: 274.6945 - mae: 13.8220
model2의 loss : [274.6944580078125, 13.822030067443848]
model2의 r2 : -2.66666701891531
======================2. Model_Check_Point =======================
1/1 [==============================] - 0s 85ms/step - loss: 274.6945 - mae: 13.8220
model3의 loss : [274.6944580078125, 13.822030067443848]
model3의 r2 : -2.66666701891531

'''


from turtle import Turtle, Screen
from paddle import Paddle
from ball import Ball
from scoreboard import Scoreboard
import time

screen = Screen()
screen.bgcolor('Black')
screen.setup(width=800, height=600)
screen.title("Pong")
screen.tracer(0)

l_paddle = Paddle((-350, 0))
r_paddle = Paddle((350, 0))
ball = Ball()
score = Scoreboard()

screen.listen()
screen.onkey(l_paddle.go_up, "w")
screen.onkey(l_paddle.go_down, "s")
screen.onkey(r_paddle.go_up, "Up")
screen.onkey(r_paddle.go_down, "Down")

game_is_on = True
sleep = 0.05
while game_is_on:
    time.sleep(sleep)
    screen.update()
    score.show()
    ball.move()
    if score.l_score == 5:
        score.goto(0, 210)
        score.write("Left player wins!!", align="Center", font=("Helvetica", 30, "normal"))
        game_is_on = False

    if score.r_score == 5:
        score.goto(0, 210)
        score.write("Right player wins!!", align="Center", font=("Helvetica", 30, "normal"))
        game_is_on = False

    # detect collision with the wall
    if abs(ball.ycor()) >= 290:
        ball.bounce_y()

    # detect collision with a paddle
    if ball.distance(r_paddle) < 50 and ball.xcor() > 320 or ball.distance(l_paddle) < 50 and ball.xcor() < -320:
        ball.bounce_x()
        sleep *= 0.9

    # detect out of bounce
    if ball.xcor() > 380:
        score.l_score += 1
        ball.reset_position()

    if ball.xcor() < -380:
        score.r_score += 1
        ball.reset_position()

    ball.debounce()

    # debug
    print(ball.ycor(), ball.xcor(), ball.y_move, ball.metric, sleep)

screen.exitonclick()


#! /usr/bin/env python
from structureDamagePrediction.datahandling import StructuralDamageDataAndMetadataReader, StructuralDamageDataset
from datetime import datetime
from structureDamagePrediction.utils import StartEndLogger
import numpy as np
import structureDamagePrediction.models as models
from structureDamagePrediction.training import NeuralNetTrainer
from torch.utils.data import DataLoader
import torch, math, random
from sklearn.model_selection import train_test_split
import sklearn.metrics as metrics
import scipy.stats as stats
import sys
import argparse

def get_accuracy_w_stderr(real_list, predicted_list):
    # Accuracy w/ statistical significance
    accuracy = 1.0 * sum([real_list[iCnt] == predicted_list[iCnt] for iCnt in range(len(real_list))]) / len(real_list)

    def acc(realAndPredTupleList):
        if realAndPredTupleList[0] == realAndPredTupleList[1]:
            return 1.0
        else:
            return 0.0

    # Mean and std error
    perFoldAcc = list(map(acc, zip(real_list,predicted_list)))
    avgAcc = np.average(perFoldAcc)
    stdErrAcc = np.std(perFoldAcc)/ np.sqrt(len(real_list))

    return avgAcc, stdErrAcc

def output_confusion_matrix(real_list, predicted_list, l):
    classes = list(map(str, set(real_list)))

    # Output confusion matrix
    l.log("Confusion matrix:")
    sHeader = "\tPredicted\n"
    sHeader += "\t%s"%("\t".join(classes))
    l.log("%s"%(sHeader), no_date=True)
    conf_matrix = metrics.confusion_matrix(real_list, predicted_list)

    sStr = ""
    for curClassTrue in classes:
        sStr += curClassTrue
        for curClassPred in classes:
            sStr += "\t" + str(conf_matrix[int(curClassTrue),int(curClassPred)])
        sStr += "\n"
    l.log(sStr, no_date=True)

    sFooter = "^True"
    l.log("%s"%(sFooter), no_date=True)

def main():
    # Setup reproducibility
    torch.manual_seed = 100
    random.seed(100)
    np.random.seed(100)

    # Set up reproducibility for data splitting
    def seed_worker(worker_id):
        worker_seed = torch.initial_seed() % 2**32
        np.random.seed(worker_seed)
        random.seed(worker_seed)
    torch_gen = torch.Generator()
    torch_gen.manual_seed(0)

    # Init utils
    l = StartEndLogger()
    # Init argument parser
    parser = argparse.ArgumentParser(description='Structural data analysis and prediction.')

    parser.add_argument("-b", "--baseDir",  help="The base directory of the dataset. (Default: data/)", default="data/")

    LEAVE_ONE_OUT = "leave-one-out"
    STRATIFY = "stratify"
    RANDOM = "random"
    parser.add_argument("-s", "--splittingMethod", help="The splitting method: leave-one-out or stratify or random. (Default: leave-one-out)",
                        choices=[LEAVE_ONE_OUT, STRATIFY, RANDOM],
                        default=LEAVE_ONE_OUT)
    parser.add_argument("-bsz", "--batchSize", type=int, help="The batch size of the training batches (where applicable). (Default: 5)", default=5)

    CLASSIFICATION = "classification"
    REGRESSION = "regression"
    parser.add_argument("-p", "--predictionType", help="Type of prediction: classification or regression. (Default: classification)",
                        choices=[CLASSIFICATION, REGRESSION], default=CLASSIFICATION)

    parser.add_argument("-e", "--epochs", help="Epochs for neural net training. (Default: 500)",
                        type=int, default=1000)

    SEQUENCE = 'sequence'
    FOURIER = 'fourier'
    parser.add_argument("-r", "--representation", help="Type of representation: sequence or fourier. (Default: sequence)",
                    choices=[SEQUENCE, FOURIER], default=FOURIER)

    parser.add_argument("-fn", "--fourierDimensions", type=int, help="Fourier dimensions to keep. (Default: 100)", default=100)

    def validate_int_none(value):
        if value.lower() == 'none':
            return None
        else:
            try:
                return(int(value))
            except ValueError:
                raise argparse.ArgumentTypeError("Invalid value. It must be either an integer or None.")

    LSTM = 'lstm'
    LINEAR = 'linear'
    MLP = 'mlp'
    KNN = 'knn'
    DUMMY = 'dummy'
    DUMMY_MAJORITY = 'dummy_majority'
    DECISION_TREE = 'decision_tree'
    BASELINE_MEAN = 'baseline_mean'
    parser.add_argument("-cl", "--classifier", choices=[LSTM,MLP,KNN,DUMMY, DUMMY_MAJORITY, DECISION_TREE],
                        help="Selected classifier. (Default: KNN)", default=KNN)
    # TODO: Add arguments for metadata field access as label
    parser.add_argument("-t", "--tupleIndexMetadata", help="Type the index of the tuple in the metadata. Either 1 for the damage percentage or 2 for the layers. (Default=1)",
                        type=int, choices=[1, 2], default=1)
    parser.add_argument("-ro", "--rowInMetadata", help="Type the row in the metadata. Type None if you want the damage percentage",
                         type=validate_int_none, choices=[None, 0, 1, 2, 3, 4], default=None)
    parser.add_argument("-co", "--colInMetadata", help="Type the column in the metadata. Type None if you want the damage percentage.",
                        type=validate_int_none, choices=[None, 0, 1, 2, 3], default=None)
    # TODO: Add arguments for patience

    parser.add_argument("-re", "--regressor", choices=[LSTM,MLP,LINEAR,BASELINE_MEAN],
                        help="Selected regressor. (Default: %s)"%(LINEAR), default=LINEAR)
    # Sequence breaking
    parser.add_argument("-bseq", "--breakSequence", action='store_true',
                        help="Break sequence into subsequences")
    parser.add_argument("-ss", "--subseqSize", type=int,
                        help="Size of subseqeuences that the sequence will be broken down into. ", default=10)

    # LSTM params
    parser.add_argument("-ll", "--lstmLayers", type=int,
                        help="Number of LSTM layers stacked. (Default: 1)", default=1)

    # Read arguments
    args = parser.parse_args(sys.argv[1:])
    base_dir = args.baseDir
    splitting = args.splittingMethod
    classification = args.predictionType == CLASSIFICATION
    # Assign classifier only if we chose classification
    # and rergressor only if we chose regression
    if classification:
        classifier = args.classifier
        args.regressor = None
        regressor = None
    else:
        classifier = None
        args.classifier = None
        regressor = args.regressor

    n_epochs = args.epochs
    fourier_dims = args.fourierDimensions
    representation = args.representation
    tup_in_met=args.tupleIndexMetadata
    row_in_met=args.rowInMetadata
    col_in_met=args.colInMetadata
    batch_size = args.batchSize

    # Select feature vector (sequence) transform function
    if representation == FOURIER:
        # Init transformation function
        def multidim_fft_transform(seq, dimensions=3, fourier_dimensions=fourier_dims):
            # Init concat
            ffts = []
            # For each dimension of the sequence
            for iDim in range(dimensions):
                # Get the data
                cur_dim_seq = seq[:, iDim]
                # Extract fourier
                spectrum = torch.fft.fft(cur_dim_seq, n=fourier_dimensions)
                # Store for concatenation
                ffts.append(spectrum.real)

            # Concatenate and return
            res = torch.cat(ffts)
            return res
        sequence_transform = multidim_fft_transform
        break_sequence = False
        subseq_size = None
    else:
        sequence_transform = None
        # In sequence representation examine if breaking down has been asked (for sequential models)
        break_sequence = args.breakSequence
        subseq_size = args.subseqSize

    l.log("Programme arguments:\n%s"%(str(args)))

    # Init reader
    reader = StructuralDamageDataAndMetadataReader(base_dir=base_dir)
    # Read data and metadata
    data, meta_data = reader.read_data_and_metadata()

    # Transformation function for classification
    transform_idx_list = [] # Init values list
    def transform_func(x):
        if tup_in_met not in [1,2]:
            raise argparse.ArgumentTypeError("Invalid value for tup_in_met. Type 1 or 2 for the tuple index.")

        # Search in existing list
        try:
            idx = transform_idx_list.index(x)
        except ValueError: # If not in list
            idx = len(transform_idx_list) # Make new entry and assign number
            l.log("Adding new class.. %d."%(idx))
            transform_idx_list.append(x)
        return idx

    # Regression (no change)
    if not classification:
        transform_func = None

    # Meta-data format
    # case_id, dmg_perc, dmg_tensor, dmg_loc_x, dmg_loc_y
    dataset = StructuralDamageDataset(data, meta_data,
                                      tgt_tuple_index_in_metadata=tup_in_met,  tgt_row_in_metadata=row_in_met, tgt_col_in_metadata=col_in_met, # What to use: dmg percentage
                                      label_transform_func=transform_func, feature_vector_transform_func=sequence_transform)

    # Update booleans
    leave_one_out = splitting == LEAVE_ONE_OUT
    stratify = splitting == STRATIFY

    if leave_one_out:
        number_of_runs = len(dataset)
    else:
        number_of_runs = 3

    predicted_list = []
    real_list = []

    for iRun in range(number_of_runs):
        l.log("+++++ Starting run #%d"%(iRun))

        if leave_one_out:
            test_perc = 1.0 / len(dataset)
        else:
            test_perc = 0.20

        if stratify:
            _, test_instance_idx = train_test_split(np.arange(len(dataset)),
                                                        test_size=test_perc,
                                                        random_state=5, # Reproducibility
                                                        shuffle=True,
                                                        stratify=list(dataset.labels())
                                                        )
        else:
            # Choose as test instance index the current run number
            if leave_one_out:
                test_instance_idx = [iRun]
            else:
                # Choose test instance indexes
                test_instance_idx=np.random.choice(list(range(0, len(dataset))),  size = math.ceil(test_perc * len(dataset)), replace=False)
                l.log("Selected instances: %s"%(str(test_instance_idx)))

        # Create train and test data
        train_data = []
        test_data = []
        for idx,entry in enumerate(dataset):
            if idx in test_instance_idx:
                test_data.append(entry)
            else:
                train_data.append(entry)

        l.log("Train / test sizes: %4d /%4d"%(len(train_data), len(test_data)))

        # Use batch size and create batches. (Note: batch size is meaningful only on the training part)
        train_dataloader = DataLoader(train_data, batch_size=batch_size, shuffle=True, worker_init_fn=seed_worker, generator=torch_gen)
        test_dataloader = DataLoader(test_data, batch_size=1, shuffle=False)

        # Train model
        device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
        l.log("Device for learning: %s"%(device.type))

        if classification:
            modelsLossesAndSupportedRepr={
                # NN
                LSTM: (models.LSTMClassificationModel(device=device, num_classes=3),torch.nn.CrossEntropyLoss(), [SEQUENCE]),
                MLP: (models.MLPClassifier(device=device,num_classes=3), torch.nn.CrossEntropyLoss(),[FOURIER]),
                # Non-NN
                KNN: (models.KNNModel(3, 3 * fourier_dims), None, [FOURIER]),
                DECISION_TREE: (models.DecisionTreeModel(3 * fourier_dims), None, [FOURIER]),
                DUMMY: (models.DummyModel(), None, [FOURIER]),
                DUMMY_MAJORITY: (models.DummyModel(strategy='most_frequent'), None, [FOURIER]),
            }

            # Classification
            #################
            # Neural netowrk models
            model, loss_fn, compat_repr = modelsLossesAndSupportedRepr[classifier]
            if representation not in compat_repr:
                raise RuntimeError("Model %s only supports representations: %s."%(classifier,str(compat_repr)))
        else:
            # Regression
            #############
            modelsLossesAndSupportedRepr={
                # NN
                LSTM: (models.LSTMRegressionModel(device=device, input_size=3, break_seq=break_sequence, subseq_max_size=subseq_size,
                                                  num_layers=args.lstmLayers),
                       torch.nn.L1Loss(), [SEQUENCE]),
                LINEAR: (models.LinearRegressor(input_size = 3 * fourier_dims), torch.nn.L1Loss(), [FOURIER]),
                MLP: (models.MLPRegressor(device=device,input_size = 3 * fourier_dims,num_classes=1), torch.nn.L1Loss(), [FOURIER]),
                BASELINE_MEAN: (models.BaselineMeanRegressor(), None, [FOURIER, SEQUENCE])
            }

            model, loss_fn, compat_repr = modelsLossesAndSupportedRepr[regressor]
            if representation not in compat_repr:
                raise RuntimeError("Model %s only supports representations: %s."%(classifier,str(compat_repr)))

        if not isinstance(model, models.SKLearnModel):
            trainer = NeuralNetTrainer(model,
                            optimizer=torch.optim.Adam(params=model.parameters(),
                                                                betas=(0.9, 0.999), eps=10e-7, lr=1e-4) ,
                            # optimizer=torch.optim.SGD(model.parameters(),lr=0.1, momentum=0.1),
                            n_epochs=n_epochs, device=device, loss_fn=loss_fn)
            trainer.train(train_dataloader,min_abs_loss_change=0.0001, patience_epochs=200, sufficient_loss=0.001, output_every=100)
            final_model = trainer.get_model()
        else:
            all_X = []
            all_y = []
            # Gather batches
            for X_batch, y_batch in train_dataloader:
                all_X.append(X_batch)
                all_y.append(y_batch)

            all_X = torch.cat(all_X)
            all_y = torch.cat(all_y)
            model.fit(all_X, all_y)
            final_model = model

        l.start("Validation...")
        if not isinstance(model, models.SKLearnModel):
            final_model.eval()
        with torch.no_grad():
            for X_test, y_test in test_dataloader:
                X_test = X_test.to(device)
                y_test = y_test.to(device)
                real_list.append(y_test.item())

                y_pred = final_model(X_test)
                if not isinstance(model, models.SKLearnModel):
                    test_loss = trainer.loss_fn(y_pred.cpu(), y_test.cpu()).cpu()
                else:
                    test_loss = torch.mean(torch.abs(y_pred.cpu() - y_test.cpu()), dtype=torch.float)

                if classification:
                    if not isinstance(model, models.SKLearnModel):
                        ypred_final = y_pred.max(1).indices
                    else:
                        ypred_final = y_pred.cpu()

                    predicted_list.append(ypred_final.cpu().item())
                    prc_loss = 0.0
                else:
                    ypred_final = y_pred.cpu().item()
                    predicted_list.append(ypred_final)
                    try:
                        prc_loss = 100 * test_loss.item() / (y_test.cpu().item() + 10e-10) # Ascertain no division by zero
                    except ZeroDivisionError:
                        prc_loss = float('nan')

                l.log("True: %8.6f -- Predicted: %8.6f (Loss: %8.6f; Percantile: %5.2f%%)"%(y_test.cpu().item(), ypred_final, test_loss ,prc_loss))

        l.end()

    l.log("Outputting overall results list:\nReal,Predicted")
    if classification:
        l.log("\n".join(map(lambda x: "%d,%d"%(x[0],x[1]),list(zip(real_list, predicted_list)))), no_date=True)
    else:
        l.log("\n".join(map(lambda x: "%6.4f,%6.4f"%(x[0],x[1]),list(zip(real_list, predicted_list)))), no_date=True)

    if classification:
        # Output measures
        f1_macro = metrics.f1_score(real_list, predicted_list, average="macro")
        avgAcc, stdErrAcc = get_accuracy_w_stderr(real_list, predicted_list)
        l.log("Avg accuracy  %6.4f+/- stderr %6.4f"%(avgAcc, stdErrAcc))
        l.log("F1 macro  %6.4f"%(f1_macro))

        # Confusion matrix
        output_confusion_matrix(real_list, predicted_list, l)

    else:
        mae = metrics.mean_absolute_error(real_list, predicted_list)
        corr, p = stats.spearmanr(real_list, predicted_list)
        l.log("MAE: %6.4f; Correlation: %6.4f (p-val: %6.4f)"%(mae, corr, p))

    l.log("Programme arguments:\n%s"%(str(args)))

if __name__ == "__main__":
    main()


from django.urls import path
from . import views

urlpatterns = [
	path('', views.home, name="home"),
	# dynamic path / print the room name and username in url
	path('<str:room>/', views.room, name="room"),
	# checking the chat room exists or not if not chat room create and enter the chat room
	# if chat room exist you directly chat with your partner
	path('checkview', views.checkview, name="checkview"),
	# sending for data
	path('send', views.send, name="send"),
	# getting the existing message
	path('getMessages/<str:room>/', views.getMessages,name="getMessages"),
]


import unittest,time,os
from appium import webdriver
from time import sleep

class Android_Kasir_Pintar(unittest.TestCase):
	"class to run test against Kasir Pintar app"
	def setUp(self):
		"Setup for the test"
		desired_caps = {}
		desired_caps['platformName'] = 'Android'
		desired_caps['platformVersion'] = '8.0.0'
		#desired_caps['automationName'] = 'uiautomator2'
		desired_caps['deviceName'] = 'a4f6cbcc'
		#youtube
		#desired_caps['appPackage'] = 'com.google.android.youtube'
		#desired_caps['appActivity'] = 'com.google.android.youtube.HomeActivity'

		desired_caps['appPackage'] = 'org.owline.kasirpintar'
		desired_caps['appActivity'] = 'org.owline.kasirpintar.SplashScreen'
		#desired_caps['appWaitActivity'] = 'org.owline.kasirpintar/org.owline.kasirpintar.SplashScreen'
		self.driver = webdriver.Remote('http://localhost:4723/wd/hub',desired_caps)

	def tearDown(self):
		"Tear down the test"
		self.driver.quit()

	def pilih_bahasa(self):
		#pilih bahasa indonesia
		self.driver.implicitly_wait(30)
		#time.sleep(5)
		bahasa_spinner = self.driver.find_element_by_id('org.owline.kasirpintar:id/select_language')
		bahasa_spinner.click()
		bahasa_indonesia = self.driver.find_element_by_android_uiautomator('new UiSelector().text("Indonesia")')
		bahasa_indonesia.click()
		next_button = self.driver.find_element_by_id('org.owline.kasirpintar:id/fab')
		next_button.click()

	def login(self):
		#login username password
		self.driver.implicitly_wait(30)
		#time.sleep(5)
		email_text = self.driver.find_element_by_id('org.owline.kasirpintar:id/editEmail')
		email_text.send_keys('buangbuangan.1@gmail.com')
		password_text = self.driver.find_element_by_id('org.owline.kasirpintar:id/editPassword')
		password_text.send_keys('pass1234')
		login_button = self.driver.find_element_by_id('org.owline.kasirpintar:id/buttLogin')
		login_button.click()

	def isibiodata(self):
		self.driver.implicitly_wait(30)
		time.sleep(5)

	def test_kasir_pintar(self):
		#Testing kasir pintar app
		self.pilih_bahasa()
		self.login()
		self.isibiodata()

if __name__ == '__main__':
		suite = unittest.TestLoader().loadTestsFromTestCase(Android_Kasir_Pintar)
		unittest.TextTestRunner(verbosity=2).run(suite)


from typing import List
import pygame
from settings import *
from player import Player

class UpgradeMenu:
    def __init__(self, player: Player):

        # general setup
        self.display_surface = pygame.display.get_surface()
        self.player = player
        self.attribute_number = len(player.stats)
        self.attribute_names = list(player.stats.keys())
        self.font = pygame.font.Font(UI_FONT, UI_FONT_SIZE)
        self.max_values = list(player.max_stats.values())

        # selection system
        self.selection_index = 0
        self.selection_time = None
        self.can_select = True

        # item dimensions
        self.width, self.height = self.display_surface.get_size()
        self.width = self.width // 6
        self.height = self.height * 0.8
        self.create_items()

    def input(self):
        keys = pygame.key.get_pressed()

        if self.can_select:
            if keys[pygame.K_RIGHT] and self.selection_index < self.attribute_number - 1:
                self.selection_index += 1
                self.can_select = False
                self.selection_time = pygame.time.get_ticks()
            elif keys[pygame.K_LEFT] and self.selection_index > 0 and self.attribute_number >= 1:
                self.selection_index -= 1
                self.can_select = False
                self.selection_time = pygame.time.get_ticks()

            if keys[pygame.K_SPACE]:
                self.can_select = False
                self.selection_time = pygame.time.get_ticks()
                # print(self.selection_index)
                self.item_list[self.selection_index].trigger(self.player)

    def selection_cooldown(self):
        if not self.can_select:
            current_time = pygame.time.get_ticks()
            if current_time - self.selection_time >= 300:
                self.can_select = True

    def create_items(self):
        self.item_list: List[Item] = []
        for item in range(self.attribute_number):
            index = item
            # horizontal position
            full_width = self.display_surface.get_size()[0]
            increment = full_width // self.attribute_number
            left = (item * increment) + (increment - self.width) // 2

            # vertical posistion
            top = self.display_surface.get_size()[1] * 0.1

            # create object
            item = Item(left, top, self.width, self.height, index, self.font)
            self.item_list.append(item)

    def display(self):
        # self.display_surface.fill('black')
        self.input()
        self.selection_cooldown()

        for index, item in enumerate(self.item_list):

            # get attributes
            name = self.attribute_names[index]
            value = self.player.get_value_by_index(index)
            max_value = self.max_values[index]
            cost = self.player.get_cost_by_index(index)
            item.display(self.display_surface, self.selection_index,
                         name, value, max_value, cost)

class Item:
    def __init__(self, left, top, width, height, index, font: pygame.font.Font):
        self.rect = pygame.Rect(left, top, width, height)
        self.index = index
        self.font = font

    def display_names(self, surface: pygame.Surface, name, cost, is_selected):
        color = TEXT_COLOR_SELECTED if is_selected else TEXT_COLOR

        # title
        title_surface = self.font.render(name, False, color)
        title_rect = title_surface.get_rect(
            midtop=self.rect.midtop + pygame.math.Vector2(0, 20))

        # cost
        cost_surface = self.font.render(f'{int(cost)}', False, color)
        cost_rect = cost_surface.get_rect(
            midbottom=self.rect.midbottom - pygame.math.Vector2(0, 20))

        # draw
        surface.blit(title_surface, title_rect)
        surface.blit(cost_surface, cost_rect)

    def display_bar(self, surface: pygame.Surface, value, max_value, is_selected):

        # drawing setup
        top = self.rect.midtop + pygame.math.Vector2(0, 60)
        bottom = self.rect.midbottom - pygame.math.Vector2(0, 60)
        color = BAR_COLOR_SELECTED if is_selected else BAR_COLOR

        # bar setup
        full_height = bottom[1] - top[1]
        relative_number = (value / max_value) * full_height
        value_rect = pygame.Rect(
            top[0] - 15, bottom[1] - relative_number, 30, 10)

        # draw elements
        pygame.draw.line(surface, color, top, bottom, 5)
        pygame.draw.rect(surface, color, value_rect)

    def trigger(self, player: Player):
        upgrade_attributte = list(player.stats.keys())[self.index]

        if player.exp >= player.upgrade_cost[upgrade_attributte] and player.stats[upgrade_attributte] < player.max_stats[upgrade_attributte]:
            player.exp -= player.upgrade_cost[upgrade_attributte]
            player.stats[upgrade_attributte] *= 1.2
            player.upgrade_cost[upgrade_attributte] *= 1.4

        if player.stats[upgrade_attributte] > player.max_stats[upgrade_attributte]:
            player.stats[upgrade_attributte] = player.max_stats[upgrade_attributte]

    def display(self, surface: pygame.Surface, selection_num, name, value, max_value, cost):
        is_selected = self.index == selection_num
        if is_selected:
            pygame.draw.rect(surface, UPGRADE_BG_COLOR_SELECTED, self.rect)
            pygame.draw.rect(surface, UI_BORDER_COLOR, self.rect, 4)
        else:
            pygame.draw.rect(surface, UI_BG_COLOR, self.rect)
            pygame.draw.rect(surface, UI_BORDER_COLOR, self.rect, 4)
        self.display_names(surface, name, cost, is_selected)
        self.display_bar(surface, value, max_value, is_selected)

if __name__ == '__main__':
    from main import run_game
    run_game()