# -*- coding: utf-8 -*-

"""
Filesystem Operations
"""

import os
import os.path as osp
import pathlib
import re
import shutil
from typing import List

from mathics.builtin.files_io.files import MathicsOpen
from mathics.core.atoms import Integer, String
from mathics.core.attributes import A_LISTABLE, A_LOCKED, A_PROTECTED
from mathics.core.builtin import Builtin, MessageException, Predefined
from mathics.core.convert.expression import to_expression, to_mathics_list
from mathics.core.convert.python import from_python
from mathics.core.convert.regex import to_regex
from mathics.core.evaluation import Evaluation
from mathics.core.expression import Expression
from mathics.core.streams import create_temporary_file, path_search, urlsave_tmp
from mathics.core.symbols import (
    Symbol,
    SymbolFalse,
    SymbolNull,
    SymbolTrue,
    valid_context_name,
)
from mathics.core.systemsymbols import (
    SymbolFailed,
    SymbolGet,
    SymbolMemberQ,
    SymbolNeeds,
    SymbolPackages,
)
from mathics.eval.directories import DIRECTORY_STACK

SymbolAbsoluteTime = Symbol("AbsoluteTime")

class AbsoluteFileName(Builtin):
    """
    <url>:WMA link:
    https://reference.wolfram.com/language/ref/AbsoluteFileName.html</url>

'AbsoluteFileName["$name$"]'

returns the absolute version of the given filename.

    >> AbsoluteFileName["ExampleData/sunflowers.jpg"]
     = ...

    #> AbsoluteFileName["Some/NonExistant/Path.ext"]
     : File not found during AbsoluteFileName[Some/NonExistant/Path.ext].
     = $Failed
    """

    messages = {
        "fstr": ("File specification x is not a string of one or more characters."),
        "nffil": "File not found during `1`.",
    }
    summary_text = "absolute path"

    def eval(self, name, evaluation):
        "AbsoluteFileName[name_]"

        py_name = name.to_python()

        if not (isinstance(py_name, str) and py_name[0] == py_name[-1] == '"'):
            evaluation.message("AbsoluteFileName", "fstr", name)
            return
        py_name = py_name[1:-1]

        result, _ = path_search(py_name)

        if result is None:
            evaluation.message(
                "AbsoluteFileName", "nffil", to_expression("AbsoluteFileName", name)
            )
            return SymbolFailed

        return String(osp.abspath(result))

class CopyDirectory(Builtin):
    """
    <url>:WMA link:
    https://reference.wolfram.com/language/ref/CopyDirectory.html</url>

'CopyDirectory["$dir1$", "$dir2$"]'

copies directory $dir1$ to $dir2$.

    """

    messages = {
        "fstr": (
            "File specification `1` is not a string of " "one or more characters."
        ),
        "filex": "Cannot overwrite existing file `1`.",
        "nodir": "Directory `1` not found.",
    }
    summary_text = "copy a directory into a new path"

    def eval(self, dirs, evaluation):
        "CopyDirectory[dirs__]"

        seq = dirs.get_sequence()
        if len(seq) != 2:
            evaluation.message("CopyDirectory", "argr", "CopyDirectory", 2)
            return
        (dir1, dir2) = (s.to_python() for s in seq)

        if not (isinstance(dir1, str) and dir1[0] == dir1[-1] == '"'):
            evaluation.message("CopyDirectory", "fstr", seq[0])
            return
        dir1 = dir1[1:-1]

        if not (isinstance(dir2, str) and dir2[0] == dir2[-1] == '"'):
            evaluation.message("CopyDirectory", "fstr", seq[1])
            return
        dir2 = dir2[1:-1]

        if not osp.isdir(dir1):
            evaluation.message("CopyDirectory", "nodir", seq[0])
            return SymbolFailed
        if osp.isdir(dir2):
            evaluation.message("CopyDirectory", "filex", seq[1])
            return SymbolFailed

        shutil.copytree(dir1, dir2)

        return String(osp.abspath(dir2))

class CopyFile(Builtin):
    """
    <url>:WMA link:
    https://reference.wolfram.com/language/ref/CopyFile.html</url>

'CopyFile["$file1$", "$file2$"]'

copies $file1$ to $file2$.

    X> CopyFile["ExampleData/sunflowers.jpg", "MathicsSunflowers.jpg"]
     = MathicsSunflowers.jpg
    X> DeleteFile["MathicsSunflowers.jpg"]
    """

    messages = {
        "filex": "Cannot overwrite existing file `1`.",
        "fstr": (
            "File specification `1` is not a string of " "one or more characters."
        ),
        "nffil": "File not found during `1`.",
    }
    summary_text = "copy a file into a new path"

    def eval(self, source, dest, evaluation):
        "CopyFile[source_, dest_]"

        py_source = source.to_python()
        py_dest = dest.to_python()

        # Check filenames
        if not (isinstance(py_source, str) and py_source[0] == py_source[-1] == '"'):
            evaluation.message("CopyFile", "fstr", source)
            return
        if not (isinstance(py_dest, str) and py_dest[0] == py_dest[-1] == '"'):
            evaluation.message("CopyFile", "fstr", dest)
            return

        py_source = py_source[1:-1]
        py_dest = py_dest[1:-1]

        py_source, _ = path_search(py_source)

        if py_source is None:
            evaluation.message("CopyFile", "filex", source)
            return SymbolFailed

        if osp.exists(py_dest):
            evaluation.message("CopyFile", "filex", dest)
            return SymbolFailed

        try:
            shutil.copy(py_source, py_dest)
        except IOError:
            evaluation.message(
                "CopyFile", "nffil", to_expression("CopyFile", source, dest)
            )
            return SymbolFailed

        return dest

class CreateFile(Builtin):
    """
    <url>:WMA link:
    https://reference.wolfram.com/language/ref/CreateFile.html</url>

'CreateFile["filename"]'

Creates a file named "filename" temporary file, but do not open it.

'CreateFile[]'

Creates a temporary file, but do not open it.

    """

    attributes = A_LISTABLE | A_PROTECTED
    options = {
        "CreateIntermediateDirectories": "True",
        "OverwriteTarget": "True",
    }
    rules = {
        "CreateFile[]": "CreateTemporary[]",
    }
    summary_text = "create a file"

    def eval(self, filename, evaluation: Evaluation, **options):
        "CreateFile[filename_String, OptionsPattern[CreateFile]]"
        try:
            # TODO: Implement options
            if not osp.isfile(filename.value):
                f = open(filename.value, "w")
                res = f.name
                f.close()
                return String(res)
            else:
                return filename
        except Exception:
            return SymbolFailed

class CreateTemporary(Builtin):
    """
    <url>:WMA link:
    https://reference.wolfram.com/language/ref/CreateTemporary.html</url>

'CreateTemporary[]'

Creates a temporary file, but do not open it.

    """

    summary_text = "create a temporary file"

    def eval(self, evaluation: Evaluation):
        "CreateTemporary[]"
        try:
            res = create_temporary_file()
        except Exception:
            return SymbolFailed
        return String(res)

class DeleteFile(Builtin):
    """
    <url>:WMA link:
    https://reference.wolfram.com/language/ref/DeleteFile.html</url>

'Delete["$file$"]'

deletes $file$.

'Delete[{"$file1$", "$file2$", ...}]'

deletes a list of files.

    >> CopyFile["ExampleData/sunflowers.jpg", "MathicsSunflowers.jpg"];
    >> DeleteFile["MathicsSunflowers.jpg"]

    >> CopyFile["ExampleData/sunflowers.jpg", "MathicsSunflowers1.jpg"];
    >> CopyFile["ExampleData/sunflowers.jpg", "MathicsSunflowers2.jpg"];
    >> DeleteFile[{"MathicsSunflowers1.jpg", "MathicsSunflowers2.jpg"}]
    """

    messages = {
        "filex": "Cannot overwrite existing file `1`.",
        "strs": (
            "String or non-empty list of strings expected at " "position `1` in `2`."
        ),
        "nffil": "File not found during `1`.",
    }
    summary_text = "delete a file"

    def eval(self, filename, evaluation):
        "DeleteFile[filename_]"

        py_path = filename.to_python()
        if not isinstance(py_path, list):
            py_path = [py_path]

        py_paths = []
        for path in py_path:
            # Check filenames
            if not (isinstance(path, str) and path[0] == path[-1] == '"'):
                evaluation.message(
                    "DeleteFile",
                    "strs",
                    filename,
                    to_expression("DeleteFile", filename),
                )
                return

            path = path[1:-1]
            path, _ = path_search(path)

            if path is None:
                evaluation.message(
                    "DeleteFile", "nffil", to_expression("DeleteFile", filename)
                )
                return SymbolFailed
            py_paths.append(path)

        for path in py_paths:
            try:
                os.remove(path)
            except OSError:
                return SymbolFailed

        return SymbolNull

class Directory(Builtin):
    """
    <url>:WMA link:
    https://reference.wolfram.com/language/ref/Directory.html</url>

'Directory[]'

returns the current working directory.

    >> Directory[]
    = ...
    """

    summary_text = "current working directory"

    def eval(self, evaluation: Evaluation):
        "Directory[]"
        result = os.getcwd()
        return String(result)

class DirectoryName(Builtin):
    """
    <url>:WMA link:https://reference.wolfram.com/language/ref/DirectoryName.html</url>

'DirectoryName["$name$"]'

extracts the directory name from a filename.

    >> DirectoryName["a/b/c"]
     = a/b

    >> DirectoryName["a/b/c", 2]
     = a

    #> DirectoryName["a/b/c", 3] // InputForm
     = ""
    #> DirectoryName[""] // InputForm
     = ""

    #> DirectoryName["a/b/c", x]
     : Positive machine-sized integer expected at position 2 in DirectoryName[a/b/c, x].
     = DirectoryName[a/b/c, x]

    #> DirectoryName["a/b/c", -1]
     : Positive machine-sized integer expected at position 2 in DirectoryName[a/b/c, -1].
     = DirectoryName[a/b/c, -1]

    #> DirectoryName[x]
     : String expected at position 1 in DirectoryName[x].
     = DirectoryName[x]
    """

    messages = {
        "string": "String expected at position 1 in `1`.",
        "intpm": ("Positive machine-sized integer expected at " "position 2 in `1`."),
    }

    options = {
        "OperatingSystem": "$OperatingSystem",
    }
    summary_text = "directory part of a filename"

    def eval_with_n(self, name, n, evaluation: Evaluation, options: dict):
        "DirectoryName[name_, n_, OptionsPattern[DirectoryName]]"

        if n is None:
            expr = to_expression("DirectoryName", name)
            py_n = 1
        else:
            expr = to_expression("DirectoryName", name, n)
            py_n = n.to_python()

        if not (isinstance(py_n, int) and py_n > 0):
            evaluation.message("DirectoryName", "intpm", expr)
            return

        py_name = name.to_python()
        if not (isinstance(py_name, str) and py_name[0] == py_name[-1] == '"'):
            evaluation.message("DirectoryName", "string", expr)
            return
        py_name = py_name[1:-1]

        result = py_name
        for i in range(py_n):
            (result, tmp) = osp.split(result)

        return String(result)

    def eval(self, name, evaluation: Evaluation, options: dict):
        "DirectoryName[name_, OptionsPattern[DirectoryName]]"
        return self.eval_with_n(name, None, evaluation, options)

class DirectoryStack(Builtin):
    """
    <url>:WMA link:https://reference.wolfram.com/language/ref/DirectoryStack.html</url>

'DirectoryStack[]'

returns the directory stack.

    >> DirectoryStack[]
    = ...
    """

    summary_text = "list the sequence of current directories in use"

    def eval(self, evaluation):
        "DirectoryStack[]"
        global DIRECTORY_STACK
        return from_python(DIRECTORY_STACK)

class ExpandFileName(Builtin):
    """
    <url>:WMA link:https://reference.wolfram.com/language/ref/ExpandFileName.html</url>

'ExpandFileName["$name$"]'

expands $name$ to an absolute filename for your system.

    >> ExpandFileName["ExampleData/sunflowers.jpg"]
     = ...
    """

    messages = {
        "string": "String expected at position 1 in `1`.",
    }
    summary_text = "absolute path"

    def eval(self, name, evaluation):
        "ExpandFileName[name_]"

        py_name = name.to_python()

        if not (isinstance(py_name, str) and py_name[0] == py_name[-1] == '"'):
            evaluation.message(
                "ExpandFileName", "string", to_expression("ExpandFileName", name)
            )
            return
        py_name = py_name[1:-1]

        return String(osp.abspath(py_name))

class File(Builtin):
    """
    <url>
    :WMA link:
    https://reference.wolfram.com/language/ref/File.html</url>

'File["$file$"]'

is a symbolic representation of an element in the local file system.

    """

    summary_text = "element of the local filesystem"

class FileBaseName(Builtin):
    """
    <url>
    :WMA link:
    https://reference.wolfram.com/language/ref/FileBaseName.html</url>

'FileBaseName["$file$"]'

gives the base name for the specified file name.

    >> FileBaseName["file.txt"]
     = file

    >> FileBaseName["file.tar.gz"]
     = file.tar

    #> FileBaseName["file."]
     = file

    #> FileBaseName["file"]
     = file
    """

    options = {
        "OperatingSystem": "$OperatingSystem",
    }
    summary_text = "base name of the file"

    def eval(self, filename, evaluation: Evaluation, options: dict):
        "FileBaseName[filename_String, OptionsPattern[FileBaseName]]"
        path = filename.to_python()[1:-1]

        filename_base, filename_ext = osp.splitext(path)
        return String(filename_base)

class FileByteCount(Builtin):
    """
    <url>:WMA link:https://reference.wolfram.com/language/ref/FileByteCount.html</url>

'FileByteCount[$file$]'

returns the number of bytes in $file$.

    >> FileByteCount["ExampleData/sunflowers.jpg"]
     = 142286
    """

    messages = {
        "fstr": "File specification `1` is not a string of one or more characters.",
    }
    summary_text = "length of the file"

    def eval(self, filename, evaluation):
        "FileByteCount[filename_]"
        py_filename = filename.to_python()
        if not (
            isinstance(py_filename, str) and py_filename[0] == py_filename[-1] == '"'
        ):
            evaluation.message("FileByteCount", "fstr", filename)
            return
        py_filename = py_filename[1:-1]

        try:
            with MathicsOpen(py_filename, "rb") as f:
                count = 0
                tmp = f.read(1)
                while tmp != b"":
                    count += 1
                    tmp = f.read(1)

        except IOError:
            evaluation.message("General", "noopen", filename)
            return
        except MessageException as e:
            e.message(evaluation)
            return

        return Integer(count)

class FileExistsQ(Builtin):
    """
    <url>:WMA link:https://reference.wolfram.com/language/ref/FileExistsQ.html</url>

'FileExistsQ["$file$"]'

returns 'True' if $file$ exists and 'False' otherwise.

    >> FileExistsQ["ExampleData/sunflowers.jpg"]
     = True
    >> FileExistsQ["ExampleData/sunflowers.png"]
     = False
    """

    messages = {
        "fstr": (
            "File specification `1` is not a string of " "one or more characters."
        ),
    }
    summary_text = "test whether a file exists"

    def eval(self, filename, evaluation):
        "FileExistsQ[filename_]"
        path = filename.to_python()
        if not (isinstance(path, str) and path[0] == path[-1] == '"'):
            evaluation.message("FileExistsQ", "fstr", filename)
            return
        path = path[1:-1]

        path, is_temporary_file = path_search(path)

        if path is None:
            return SymbolFalse
        return SymbolTrue

class FileExtension(Builtin):
    """
    <url>:WMA link:
    https://reference.wolfram.com/language/ref/FileExtension.html</url>

'FileExtension["$file$"]'

gives the extension for the specified file name.

    >> FileExtension["file.txt"]
     = txt

    >> FileExtension["file.tar.gz"]
     = gz

    #> FileExtension["file."]
     = #<--#
    #> FileExtension["file"]
     = #<--#
    """

    options = {
        "OperatingSystem": "$OperatingSystem",
    }
    summary_text = "file extension"

    def eval(self, filename, evaluation: Evaluation, options: dict):
        "FileExtension[filename_String, OptionsPattern[FileExtension]]"
        path = filename.to_python()[1:-1]
        filename_base, filename_ext = osp.splitext(path)
        filename_ext = filename_ext.lstrip(".")
        return String(filename_ext)

class FileInformation(Builtin):
    """
    <url>:WMA link:https://reference.wolfram.com/language/ref/FileInformation.html</url>

'FileInformation["$file$"]'

returns information about $file$.

    This function is totally undocumented in MMA!

    >> FileInformation["ExampleData/sunflowers.jpg"]
     = {File -> ..., FileType -> File, ByteCount -> 142286, Date -> ...}

    #> FileInformation["ExampleData/missing_file.jpg"]
     = {}
    """

    rules = {
        "FileInformation[name_String]": "If[FileExistsQ[name], {File -> ExpandFileName[name], FileType -> FileType[name], ByteCount -> FileByteCount[name], Date -> AbsoluteTime[FileDate[name]]}, {}]",
    }
    summary_text = "information about a file"

class FindFile(Builtin):
    """
    <url>:WMA link:https://reference.wolfram.com/language/ref/FileFind.html</url>

'FindFile[$name$]'

searches '$Path' for the given filename.

    >> FindFile["ExampleData/sunflowers.jpg"]
     = ...

    >> FindFile["VectorAnalysis`"]
     = ...

    >> FindFile["VectorAnalysis`VectorAnalysis`"]
     = ...

    #> FindFile["SomeTypoPackage`"]
     = $Failed
    """

    messages = {
        "string": "String expected at position 1 in `1`.",
    }
    summary_text = (
        "search the path of of a file in the current directory and its subdirectories"
    )

    def eval(self, name, evaluation):
        "FindFile[name_]"

        py_name = name.to_python()

        if not (isinstance(py_name, str) and py_name[0] == py_name[-1] == '"'):
            evaluation.message("FindFile", "string", to_expression("FindFile", name))
            return
        py_name = py_name[1:-1]

        result, is_temporary_file = path_search(py_name)

        if result is None:
            return SymbolFailed

        return String(osp.abspath(result))

class FileNames(Builtin):
    r"""
    <url>:WMA link:https://reference.wolfram.com/language/ref/FileNames.html</url>

'FileNames[]'

Returns a list with the filenames in the current working folder.

'FileNames[$form$]'

Returns a list with the filenames in the current working folder that \
          matches with $form$.

'FileNames[{$form_1$, $form_2$, ...}]'

Returns a list with the filenames in the current working folder that \
          matches with one of $form_1$, $form_2$, ....

'FileNames[{$form_1$, $form_2$, ...},{$dir_1$, $dir_2$, ...}]'

Looks into the directories $dir_1$, $dir_2$, ....

'FileNames[{$form_1$, $form_2$, ...},{$dir_1$, $dir_2$, ...}]'

Looks into the directories $dir_1$, $dir_2$, ....

'FileNames[{$forms$, $dirs$, $n$]'

Look for files up to the level $n$.

    >> SetDirectory[$InstallationDirectory <> "/autoload"];
    >> FileNames["*.m", "formats"]//Length
     = ...
    >> FileNames["*.m", "formats", 3]//Length
     = ...
    >> FileNames["*.m", "formats", Infinity]//Length
     = ...
    """

    # >> FileNames[]//Length
    #  = 2
    fmtmaps = {Symbol("System`All"): "*"}
    messages = {
        "nofmtstr": "`1` is not a format or a list of formats.",
        "nodirstr": "`1` is not a directory name  or a list of directory names.",
        "badn": "`1` is not an integer number.",
    }
    options = {
        "IgnoreCase": "Automatic",
    }
    summary_text = "list file names in the current directory"

    def eval(self, evaluation, **options):
        """FileNames[OptionsPattern[FileNames]]"""
        return self.eval_with_forms_dirs_and_level(
            String("*"), String(os.getcwd()), None, evaluation, **options
        )

    def eval_with_forms(self, forms, evaluation, **options):
        """FileNames[forms_, OptionsPattern[FileNames]]"""
        return self.eval_with_forms_dirs_and_level(
            forms, String(os.getcwd()), None, evaluation, **options
        )

    def eval_with_forms_and_dirs(self, forms, dirs, evaluation, **options):
        """FileNames[forms_, dirs_, OptionsPattern[FileNames]]"""
        return self.eval_with_forms_dirs_and_level(
            forms, dirs, None, evaluation, **options
        )

    def eval_with_forms_dirs_and_level(self, forms, dirs, n, evaluation, **options):
        """FileNames[forms_, dirs_, n_, OptionsPattern[FileNames]]"""
        filenames = set()
        # Build a list of forms.
        if forms.get_head_name() == "System`List":
            form_list = []
            for p in forms._elements:
                if self.fmtmaps.get(p, None):
                    form_list.append(self.fmtmaps[p])
                else:
                    form_list.append(p)
        else:
            form_list = [
                self.fmtmaps[forms] if self.fmtmaps.get(forms, None) else forms
            ]
        # Build a list of directories.
        if isinstance(dirs, String):
            py_dirs = [dirs.value]
        elif dirs.get_head_name() == "System`List":
            py_dirs = []
            for p in dirs._elements:
                if isinstance(p, String):
                    py_dirs.append(p.value)
                else:
                    evaluation.message("FileNames", "nodirstr", dirs)
                    return
        else:
            evaluation.message("FileNames", "nodirstr", dirs)
            return

        if n is not None:
            if isinstance(n, Integer):
                level = n.value
            # We can't test against SymbolDirectedInfinity,
            # because Infinity a compound expression.
            elif n.get_head_name() == "System`DirectedInfinity":
                level = None
            else:
                evaluation.message("FileNames", "badn", n)
                return
        else:
            level = 1

        # list the files

        def re_compile_form_list(form_list: list, re_flags: int) -> List[re.Pattern]:
            """
            re.compile each Expression in ``form_list``. Compile using
            re_flags which is either re.NO_FLAGS or re.IGNORECASE.
            Return a list of the compiled patterns when the string in
            form_list that are valid string expressions.

            Invalid string expressions are removed removed from the list.
            """
            patterns = []
            for p in form_list:
                opt_pat_str = to_regex(
                    p, abbreviated_patterns=True, show_message=evaluation.message
                )

                if opt_pat_str is None:
                    continue
                pat_str = f"^{opt_pat_str}$"
                patterns.append(re.compile(pat_str, re_flags))
            return patterns

        re_flags = (
            re.IGNORECASE if options.get("System`IgnoreCase", None) is SymbolTrue else 0
        )
        patterns = re_compile_form_list(form_list, re_flags)

        for py_dir in py_dirs:
            if not osp.isdir(py_dir):
                continue
            if level == 1:
                for fn in os.listdir(py_dir):
                    fullname = osp.join(py_dir, fn)
                    for pattern in patterns:
                        if pattern.match(fn):
                            filenames.add(fullname)
                            break
            else:
                pathlen = len(py_dir)
                for root, child_dirs, child_files in os.walk(py_dir):
                    # FIXME: This is an ugly and inefficient way
                    # to avoid looking deeper than the level n, but I do not realize
                    # how to do this better without a lot of code...
                    if level is not None and len(root[pathlen:].split(osp.sep)) > level:
                        continue
                    for fn in child_files + child_dirs:
                        for pattern in patterns:
                            if pattern.match(fn):
                                filenames.add(osp.join(root, fn))
                                break

        return to_mathics_list(*sorted(filenames), elements_conversion_fn=String)

class FileNameTake(Builtin):
    """
    <url>:WMA link:https://reference.wolfram.com/language/ref/FileNameTake.html</url>

'FileNameTake["$file$"]'

returns the last path element in the file name $name$.

'FileNameTake["$file$", $n$]'

returns the first $n$ path elements in the file name $name$.

'FileNameTake["$file$", $-n$]'

returns the last $n$ path elements in the file name $name$.

    """

    # mmatera: please put in a pytest
    # >> FileNameTake["/tmp/file.txt"]
    #  = file.txt
    # >> FileNameTake["tmp/file.txt", 1]
    #  = tmp
    # >> FileNameTake["tmp/file.txt", -1]
    #  = file.txt

    options = {
        "OperatingSystem": "$OperatingSystem",
    }
    summary_text = "take a part of the filename"

    def eval(self, filename, evaluation: Evaluation, options: dict):
        "FileNameTake[filename_String, OptionsPattern[FileBaseName]]"
        path = pathlib.Path(filename.to_python()[1:-1])
        return String(path.name)

    def eval_n(self, filename, n, evaluation: Evaluation, options: dict):
        "FileNameTake[filename_String, n_Integer, OptionsPattern[FileBaseName]]"
        n_int = n.get_int_value()
        parts = pathlib.Path(filename.to_python()[1:-1]).parts
        if n_int >= 0:
            subparts = parts[:n_int]
        else:
            subparts = parts[n_int:]
        return String(str(pathlib.PurePath(*subparts)))

class Needs(Builtin):
    """
    <url>:WMA link:https://reference.wolfram.com/language/ref/Needs.html</url>

'Needs["context`"]'

loads the specified context if not already in '$Packages'.

    >> Needs["VectorAnalysis`"]
    #> Needs["VectorAnalysis`"]

    #> Needs["SomeFakePackageOrTypo`"]
     : Cannot open SomeFakePackageOrTypo`.
     : Context SomeFakePackageOrTypo` was not created when Needs was evaluated.
     = $Failed

    #> Needs["VectorAnalysis"]
     : Invalid context specified at position 1 in Needs[VectorAnalysis]. A context must consist of valid symbol names separated by and ending with `.
     = Needs[VectorAnalysis]

    ## --- VectorAnalysis ---

    #> Needs["VectorAnalysis`"]

    #> DotProduct[{1,2,3}, {4,5,6}]
     = 32
    #> DotProduct[{-1.4, 0.6, 0.2}, {0.1, 0.6, 1.7}]
     = 0.56

    #> CrossProduct[{1,2,3}, {4,5,6}]
     = {-3, 6, -3}
    #> CrossProduct[{-1.4, 0.6, 0.2}, {0.1, 0.6, 1.7}]
     = {0.9, 2.4, -0.9}

    #> ScalarTripleProduct[{-2,3,1},{0,4,0},{-1,3,3}]
     = -20
    #> ScalarTripleProduct[{-1.4,0.6,0.2}, {0.1,0.6,1.7}, {0.7,-1.5,-0.2}]
     = -2.79

    #> CoordinatesToCartesian[{2, Pi, 3}, Spherical]
     = {0, 0, -2}
    #> CoordinatesFromCartesian[%, Spherical]
     = {2, Pi, 0}
    #> CoordinatesToCartesian[{2, Pi, 3}, Cylindrical]
     = {-2, 0, 3}
    #> CoordinatesFromCartesian[%, Cylindrical]
     = {2, Pi, 3}
    ## Needs Sin/Cos exact value (PR #100) for these tests to pass
    ## #> CoordinatesToCartesian[{2, Pi / 4, Pi / 3}, Spherical]
    ##  = {Sqrt[2] / 2, Sqrt[6] / 2, Sqrt[2]}
    ## #> CoordinatesFromCartesian[%, Spherical]
    ##  = {2, Pi / 4, Pi / 3}
    ## #> CoordinatesToCartesian[{2, Pi / 4, -1}, Cylindrical]
    ##  = {Sqrt[2], Sqrt[2], -1}
    ## #> CoordinatesFromCartesian[%, Cylindrical]
    ##  = {2, Pi / 4, -1}
    #> CoordinatesToCartesian[{0.27, 0.51, 0.92}, Cylindrical]
     = {0.235641, 0.131808, 0.92}
    #> CoordinatesToCartesian[{0.27, 0.51, 0.92}, Spherical]
     = {0.0798519, 0.104867, 0.235641}

    #> Coordinates[]
     = {Xx, Yy, Zz}
    #> Coordinates[Spherical]
     = {Rr, Ttheta, Pphi}
    #> SetCoordinates[Cylindrical]
     = Cylindrical[Rr, Ttheta, Zz]
    #> Coordinates[]
     = {Rr, Ttheta, Zz}
    #> CoordinateSystem
     = Cylindrical
    #> Parameters[]
     = {}
    #> CoordinateRanges[]
    ## = {0 <= Rr < Infinity, -Pi < Ttheta <= Pi, -Infinity < Zz < Infinity}
     = {0 <= Rr && Rr < Infinity, -Pi < Ttheta && Ttheta <= Pi, -Infinity < Zz < Infinity}
    #> CoordinateRanges[Cartesian]
     = {-Infinity < Xx < Infinity, -Infinity < Yy < Infinity, -Infinity < Zz < Infinity}
    #> ScaleFactors[Cartesian]
     = {1, 1, 1}
    #> ScaleFactors[Spherical]
     = {1, Rr, Rr Sin[Ttheta]}
    #> ScaleFactors[Cylindrical]
     = {1, Rr, 1}
    #> ScaleFactors[{2, 1, 3}, Cylindrical]
     = {1, 2, 1}
    #> JacobianDeterminant[Cartesian]
     = 1
    #> JacobianDeterminant[Spherical]
     = Rr ^ 2 Sin[Ttheta]
    #> JacobianDeterminant[Cylindrical]
     = Rr
    #> JacobianDeterminant[{2, 1, 3}, Cylindrical]
     = 2
    #> JacobianMatrix[Cartesian]
     = {{1, 0, 0}, {0, 1, 0}, {0, 0, 1}}
    #> JacobianMatrix[Spherical]
     = {{Cos[Pphi] Sin[Ttheta], Rr Cos[Pphi] Cos[Ttheta], -Rr Sin[Pphi] Sin[Ttheta]}, {Sin[Pphi] Sin[Ttheta], Rr Cos[Ttheta] Sin[Pphi], Rr Cos[Pphi] Sin[Ttheta]}, {Cos[Ttheta], -Rr Sin[Ttheta], 0}}
    #> JacobianMatrix[Cylindrical]
     = {{Cos[Ttheta], -Rr Sin[Ttheta], 0}, {Sin[Ttheta], Rr Cos[Ttheta], 0}, {0, 0, 1}}
    """

    messages = {
        "ctx": (
            "Invalid context specified at position `2` in `1`. "
            "A context must consist of valid symbol names separated by "
            "and ending with `3`."
        ),
        "nocont": "Context `1` was not created when Needs was evaluated.",
    }
    summary_text = "load a package if it is not already loaded"

    def eval(self, context, evaluation):
        "Needs[context_String]"
        contextstr = context.get_string_value()
        if contextstr == "":
            return SymbolNull
        if contextstr[0] == "`":
            curr_ctxt = evaluation.definitions.get_current_context()
            contextstr = curr_ctxt + contextstr[1:]
            context = String(contextstr)
        if not valid_context_name(contextstr):
            evaluation.message("Needs", "ctx", Expression(SymbolNeeds, context), 1, "`")
            return
        test_loaded = Expression(SymbolMemberQ, SymbolPackages, context)
        test_loaded = test_loaded.evaluate(evaluation)
        if test_loaded is SymbolTrue:
            # Already loaded
            return SymbolNull
        result = Expression(SymbolGet, context).evaluate(evaluation)

        if result is SymbolFailed:
            evaluation.message("Needs", "nocont", context)
            return SymbolFailed

        return SymbolNull

class OperatingSystem(Predefined):
    """
    <url>:WMA link:
    https://reference.wolfram.com/language/ref/OperatingSystem.html</url>

'$OperatingSystem'

gives the type of operating system running Mathics.

    >> $OperatingSystem
     = ...
    """

    attributes = A_LOCKED | A_PROTECTED
    name = "$OperatingSystem"
    summary_text = "type of operating system"

    def evaluate(self, evaluation):
        if os.name == "posix":
            return String("Unix")
        elif os.name == "nt":
            return String("Windows")
        elif os.name == "os2":
            return String("MacOSX")
        else:
            return String("Unknown")

class PathnameSeparator(Predefined):
    """
    <url>
    :WMA link:
    https://reference.wolfram.com/language/ref/$PathnameSeparator.html</url>

'$PathnameSeparator'

returns a string for the separator in paths.

    >> $PathnameSeparator
     = ...
    """

    name = "$PathnameSeparator"
    summary_text = "system character path separator"

    def evaluate(self, evaluation):
        return String(os.sep)

class RenameFile(Builtin):
    """
    <url>:WMA link:
    https://reference.wolfram.com/language/ref/RenameFile.html</url>

'RenameFile["$file1$", "$file2$"]'

renames $file1$ to $file2$.

    >> CopyFile["ExampleData/sunflowers.jpg", "MathicsSunflowers.jpg"]
     = MathicsSunflowers.jpg
    >> RenameFile["MathicsSunflowers.jpg", "MathicsSunnyFlowers.jpg"]
     = MathicsSunnyFlowers.jpg
    >> DeleteFile["MathicsSunnyFlowers.jpg"]
    """

    messages = {
        "filex": "Cannot overwrite existing file `1`.",
        "fstr": (
            "File specification `1` is not a string of " "one or more characters."
        ),
        "nffil": "File not found during `1`.",
    }
    summary_text = "change the name of a file"

    def eval(self, source, dest, evaluation):
        "RenameFile[source_, dest_]"

        py_source = source.to_python()
        py_dest = dest.to_python()

        # Check filenames
        if not (isinstance(py_source, str) and py_source[0] == py_source[-1] == '"'):
            evaluation.message("RenameFile", "fstr", source)
            return
        if not (isinstance(py_dest, str) and py_dest[0] == py_dest[-1] == '"'):
            evaluation.message("RenameFile", "fstr", dest)
            return

        py_source = py_source[1:-1]
        py_dest = py_dest[1:-1]

        py_source, is_temporary_file = path_search(py_source)

        if py_source is None:
            evaluation.message("RenameFile", "filex", source)
            return SymbolFailed

        if osp.exists(py_dest):
            evaluation.message("RenameFile", "filex", dest)
            return SymbolFailed

        try:
            shutil.move(py_source, py_dest)
        except IOError:
            evaluation.message("RenameFile", "nffil", dest)
            return SymbolFailed

        return dest

class ResetDirectory(Builtin):
    """
    <url>:WMA link:
    https://reference.wolfram.com/language/ref/ResetDirectory.html</url>

'ResetDirectory[]'

pops a directory from the directory stack and returns it.

    >> ResetDirectory[]
    = ...
    """

    messages = {
        "dtop": "Directory stack is empty.",
    }
    summary_text = "return to the directory before the last SetDirectory call"

    def eval(self, evaluation):
        "ResetDirectory[]"
        try:
            tmp = DIRECTORY_STACK.pop()
        except IndexError:
            tmp = os.getcwd()
            evaluation.message("ResetDirectory", "dtop")
        else:
            os.chdir(tmp)
        return String(tmp)

class SetDirectory(Builtin):
    """
    <url>:WMA link:
    https://reference.wolfram.com/language/ref/SetDirectory.html</url>

'SetDirectory[$dir$]'

sets the current working directory to $dir$.

    S> SetDirectory[]
    = ...

    #> SetDirectory["MathicsNonExample"]
     : Cannot set current directory to MathicsNonExample.
     = $Failed
    """

    messages = {
        "fstr": (
            "File specification `1` is not a string of " "one or more characters."
        ),
        "cdir": "Cannot set current directory to `1`.",
    }
    rules = {
        "SetDirectory[]": "SetDirectory[$HomeDirectory]",
    }
    summary_text = "set the working directory"

    def eval(self, path, evaluation):
        "SetDirectory[path_]"

        if not isinstance(path, String):
            evaluation.message("SetDirectory", "fstr", path)
            return

        py_path = path.__str__()[1:-1]

        if py_path is None or not osp.isdir(py_path):
            evaluation.message("SetDirectory", "cdir", path)
            return SymbolFailed

        try:
            os.chdir(py_path)
        except Exception:
            return SymbolFailed

        DIRECTORY_STACK.append(os.getcwd())
        return String(os.getcwd())

class ToFileName(Builtin):
    """
    <url>:WMA link:
    https://reference.wolfram.com/language/ref/ToFileName.html</url>

'ToFileName[{"$dir_1$", "$dir_2$", ...}]'

joins the $dir_i$ together into one path.

    'ToFileName' has been superseded by 'FileNameJoin'.

    >> ToFileName[{"dir1", "dir2"}, "file"]
     = dir1...dir2...file

    >> ToFileName["dir1", "file"]
     = dir1...file

    >> ToFileName[{"dir1", "dir2", "dir3"}]
     = dir1...dir2...dir3
    """

    rules = {
        "ToFileName[dir_String, name_String]": "FileNameJoin[{dir, name}]",
        "ToFileName[dirs_List, name_String]": "FileNameJoin[Append[dirs, name]]",
        "ToFileName[dirs_List]": "FileNameJoin[dirs]",
    }
    summary_text = "build a path from a list of directory names and a filename"

class URLSave(Builtin):
    """
    <url>:WMA link:
    https://reference.wolfram.com/language/ref/URLSave.html</url>

'URLSave["url"]'

Save "url" in a temporary file.

'URLSave["url", $filename$]'

Save "url" in $filename$.

    """

    messages = {
        "invfile": "`1` is not a valid Filename",
        "invhttp": "`1` is not a valid URL",
    }
    summary_text = "save the content of an URL"

    def eval_1(self, url, evaluation, **options):
        "URLSave[url_String, OptionsPattern[URLSave]]"
        return self.eval_2(url, None, evaluation, **options)

    def eval_2(self, url, filename, evaluation, **options):
        "URLSave[url_String, filename_, OptionsPattern[URLSave]]"
        url = url.value
        if filename is None:
            result = urlsave_tmp(url, None, **options)
        elif isinstance(filename, String):
            filename = filename.value
            result = urlsave_tmp(url, filename, **options)
        else:
            evaluation.message("URLSave", "invfile", filename)
            return SymbolFailed
        if result is None:
            return SymbolFailed
        return String(result)


import unittest

from .solution import part_1

class Test(unittest.TestCase):
    def test_part_1(self):
        result = part_1(
            [
                "R75,D30,R83,U83,L12,D49,R71,U7,L72".split(sep=","),
                "U62,R66,U55,R34,D71,R55,D58,R83".split(sep=","),
            ]
        )
        assert result == 159, result
        result = part_1(
            [
                "R98,U47,R26,D63,R33,U87,L62,D20,R33,U53,R51".split(sep=","),
                "U98,R91,D20,R16,D67,R40,U7,R15,U6,R7".split(sep=","),
            ]
        )
        assert result == 135, result

if __name__ == "__main__":
    unittest.main()


from django.shortcuts import get_object_or_404, render_to_response,render
from blog.models import Entry, Link, Category,fakeusers
from django.template import RequestContext
from datetime import datetime, timedelta
from django.contrib.comments.models import Comment
from django.db.models import F
from django.contrib.auth.models import User
# Create your views here.

def entries_index(request):
	marque=Entry.objects.all().order_by('-pub_date')[:3]
	newest=Entry.objects.filter(pub_date=datetime.today())[:4]
	new_stories=Entry.objects.filter(pub_date=datetime.today())
	new_stories=new_stories.count()
	featured=Entry.objects.filter(featured=True).order_by('-pub_date')[:4]
	item_big=Entry.objects.filter(tags='Explicit').order_by('-pub_date')[:1]
	item_small=Entry.objects.all().order_by('-pub_date')[:4]
	this_week_featured=Entry.objects.filter(featured=True).order_by('-pub_date')[:4]
	featured_last_week = Entry.objects.filter(pub_date__lt=F('pub_date') - timedelta(days=7))
	last_month= datetime.today() - timedelta(days=30)
	featured_last_month = Entry.objects.filter(pub_date__lt=F('pub_date') - timedelta(days=30))
	all_stories=Entry.objects.all().order_by('-pub_date')[:5]
	sponserd=Entry.objects.filter(tags='sponsored').order_by('-pub_date')[:5]
	campus=Entry.objects.filter(tags='campus').filter(featured=True).order_by('-pub_date')[:1]
	politics=Entry.objects.filter(tags='politics').filter(featured=True).order_by('-pub_date')[:1]
	f_campus=Entry.objects.filter(tags='campus').order_by('-pub_date')[:5]
	f_politics=Entry.objects.filter(tags='politics').order_by('-pub_date')[:5]
	popular=Entry.objects.filter(tags='popular').order_by('-pub_date')[:5]
	recent=Entry.objects.all().order_by('-pub_date')[:5]
	comments=Comment.objects.all().order_by('-submit_date')[:5]
	trending=Entry.objects.all().order_by('-pub_date')[:5]
	most_recent=Entry.objects.all().order_by('-pub_date')[:1]
	#print most_recent
	other_recent=Entry.objects.all().order_by('-pub_date')[:3]
	news=Entry.objects.filter(tags='news').order_by('-pub_date')[:4]
	count_more_stories=Entry.objects.filter(tags='news')
	count_more_stories=count_more_stories.count()
	count_more_stories=	count_more_stories-4
	count_today_unread=newest.count()
	count_today_unread=count_today_unread-4
	cats=Category.objects.all()
	return render_to_response('index.html',
							  {'entries': Entry.objects.all(),
							   'marque':marque,
							   'new_stories':new_stories,
							   'featured':featured,
							   'item_big':item_big,
							   'item_small':item_small,
							   'this_week_featured':this_week_featured,
							   'featured_last_week':featured_last_week,
							   'featured_last_month':featured_last_month,
							   'all_stories':all_stories,
							   'sponserd':sponserd,
							   'campus':campus,
							   'politics':politics,
							   'f_campus':f_campus,
							   'f_politics':f_politics,
							   'popular':popular,
							   'recent':recent,
							   'comments':comments,
							   'trending':trending,
							   'most_recent':most_recent,
							   'other_recent':other_recent,
							   'news':news,
							   'count_more_stories':count_more_stories,
							   'newest':newest,
							   'count_today_unread':count_today_unread,
							   'cats':cats

							   })

def view_more(request, slug):
	#count=Entry.objects.get(slug=slug)
	#print count
	marque = Entry.objects.all().order_by('-pub_date')[:3]
	trending = Entry.objects.all().order_by('-pub_date')[:5]
	recent = Entry.objects.all().order_by('-pub_date')[:5]
	comments = Comment.objects.all().order_by('-submit_date')[:5]
	cats = Category.objects.all()
	# user = User.objects.get(username=request.user.username)
	# bio=fakeusers.objects.filter(user=user)
	o=Entry.objects.get(slug=slug)
	author_id= o.author_id
	bio=User.objects.get(id=author_id)
	id= bio.id
	bio=fakeusers.objects.filter(user_id=id)
	return render_to_response('entry_detail.html',{
	'object':get_object_or_404(Entry, slug=slug),
		'marque':marque,
		'bio':bio,
		'trending':trending,
		'recent':recent,
		'comments':comments,
		'cats':cats
	},RequestContext(request))

def search(request):
	query=request.GET.get('q', '')
	results=[]
	marque = Entry.objects.all().order_by('-pub_date')[:3]
	recent = Entry.objects.all().order_by('-pub_date')[:5]
	comments = Comment.objects.all().order_by('-submit_date')[:5]
	trending = Entry.objects.all().order_by('-pub_date')[:5]
	if query:
		results=Entry.objects.filter(title__contains=query)
		count=results.count()
	return render_to_response('search.html', {'query':query, 'results':results,
											  'marque':marque, 'count':count,
											  'recent':recent,'comments':comments,
											  'trending':trending})
def category_list(request):
	return render_to_response('category_list.html',
                                  { 'object_list': Category.objects.all() })

def category_detail(request, slug):
	return render_to_response('entry_detail.html', {
		'object': get_object_or_404(Entry, category=slug)
	}, RequestContext(request))


def activation(w_sum):
    """
    Activation function: Transforms the input to 1 or 0.
    """
    if w_sum >= 0.5:
        return 1
    else:
        return 0

def perceptron(x1, x2, y_hat, y):
    n = len(y)
    weights = [0.1, 0.1]
    learning_rate = 0.1
    state = 1

    print("Initial weights:", weights)
    print("Training the perceptron...")

    while state == 1:
        for i in range(n):
            w_sum = x1[i]*weights[0] + x2[i]*weights[1]
            y_hat[i] = activation(w_sum)

            if y_hat[i] != y[i]:
                weights[0] = weights[0] + learning_rate*(y[i] - y_hat[i])
                weights[1] = weights[1] + learning_rate*(y[i] - y_hat[i])

        if y_hat == y:
            state = 0

    print("Training is complete.")
    print("Actual values:", y)
    print("Predicted values:", y_hat)
    print("Final weights:", weights)

    return None

if __name__ == "__main__":
    y = [0, 1, 1, 1]
    y_hat = [-1, -1, -1, -1]
    x1 = [0, 0, 1, 1]
    x2 = [0, 1, 0, 1]
    print("The input data (y, x1, x2):", y, x1, x2)
    print()

    perceptron(x1, x2, y_hat, y)


from iou_db import DB

class Document(object):
    ''' I Owe You Document
    '''

    dc = {'Debit':'D', 'Credit':'C'}

    def __init__(self, db, number=None, lender=None, borrower=None, amount=None, **kwargs):
        self.__db = db
        self.__number = number
        self.lender = lender
        self.borrower = borrower
        self.amount = amount

    def save(self):
        ''' Save IOU Document to database
        '''
        if self.__number==None:
            self.__number=Document.__create(self.__db, **self.__dict__)
        else:
            self.__number=Document.__update(self.__db, **self.__dict__)

    @staticmethod
    def read(db, number=None, lender=None, borrower=None, **kwargs):
        ''' Return iou records
        '''
        return [ Document(db, **record)
                 for record in Document.__read(db, number, lender, borrower)]

    @staticmethod
    def __create(db, lender, borrower, amount=0, **kwargs):
        ''' Create IOU Document in database
        '''
        query = '''
            INSERT INTO documents(lender, borrower, amount)
                           values(     ?,        ?,      ?)
        '''
        cursor = db.conn.cursor()
        cursor.execute(query, (lender, borrower, amount) )
        return cursor.lastrowid

    @staticmethod
    def __read(db, number=None, lender=None, borrower=None, **kwargs):
        ''' Read IOU Document From database
        '''
        params={}
        if number:   params['number']=str(number)
        if lender:   params['lender']=lender
        if borrower: params['borrower']=borrower

        where = ''
        if params != {}:
            filter = ' and '.join( ['{} = ?'.format(k) for k in params ] )
            where = 'WHERE {}'.format(filter)

        query = '''
            SELECT number, lender, borrower, amount FROM documents {}
        '''.format(where)

        result = db.conn.execute(query, list(params.values()) )

        records = [{
                'number': record[0],
                'lender': record[1],
                'borrower': record[2],
                'amount': record[3]
        } for record in result.fetchall() ]

        return records

    @staticmethod
    def __update(db, number, lender=None, borrower=None, amount=0, **kwargs):
        ''' Update IOU Document in database
        '''
        query = '''
            UPDATE documents
                SET lender   = ?,
                    borrower = ?,
                    amount   = ?
                WHERE number = ?
        '''
        db.conn.execute(query, (lender, borrower, str(amount), str(number)))

    @property
    def __dict__(self):
        return {
            'number': self.__number,
            'lender': self.lender,
            'borrower': self.borrower,
            'amount': self.amount
        }


# -*- coding: utf-8 -*-
# @File    : OpenTheLock.py
# @Date    : 2022-06-20
# @Author  : tc
"""
752. 打开转盘锁
你有一个带有四个圆形拨轮的转盘锁。每个拨轮都有10个数字： '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' 。每个拨轮可以自由旋转：例如把 '9' 变为 '0'，'0' 变为 '9' 。每次旋转都只能旋转一个拨轮的一位数字。
锁的初始数字为 '0000' ，一个代表四个拨轮的数字的字符串。
列表 deadends 包含了一组死亡数字，一旦拨轮的数字和列表里的任何一个元素相同，这个锁将会被永久锁定，无法再被旋转。
字符串 target 代表可以解锁的数字，你需要给出解锁需要的最小旋转次数，如果无论如何不能解锁，返回 -1 。

示例 1:
输入：deadends = ["0201","0101","0102","1212","2002"], target = "0202"
输出：6
解释：
可能的移动序列为 "0000" -> "1000" -> "1100" -> "1200" -> "1201" -> "1202" -> "0202"。
注意 "0000" -> "0001" -> "0002" -> "0102" -> "0202" 这样的序列是不能解锁的，
因为当拨动到 "0102" 时这个锁就会被锁定。

示例 2:
输入: deadends = ["8888"], target = "0009"
输出：1
解释：把最后一位反向旋转一次即可 "0000" -> "0009"。

示例 3:
输入: deadends = ["8887","8889","8878","8898","8788","8988","7888","9888"], target = "8888"
输出：-1
解释：无法旋转到目标数字且不被锁定。
"""
from typing import List,Generator
from collections import deque

class Solution:
    def openLock(self, deadends: List[str], target: str) -> int:
        if target == "0000":
            return 0

        dead = set(deadends)
        if "0000" in dead:
            return -1

        def num_prev(x: str) -> str:
            return "9" if x == "0" else str(int(x) - 1)

        def num_succ(x: str) -> str:
            return "0" if x == "9" else str(int(x) + 1)

        # 枚举 status 通过一次旋转得到的数字
        def get(status: str) -> Generator[str, None, None]:
            s = list(status)
            for i in range(4):
                num = s[i]
                s[i] = num_prev(num)
                yield "".join(s)
                s[i] = num_succ(num)
                yield "".join(s)
                s[i] = num

        q = deque([("0000", 0)])
        seen = {"0000"}
        while q:
            status, step = q.popleft()
            for next_status in get(status):
                print(next_status)
                if next_status not in seen and next_status not in dead:
                    if next_status == target:
                        return step + 1
                    q.append((next_status, step + 1))
                    seen.add(next_status)

        return -1


import math
import numpy as np
from datascience import *
from numbers import Number
from enum import Enum

Modes = Enum('Modes', 'CHECK TEST')
CHECK = Modes.CHECK
TEST = Modes.TEST

def result(passes, msg, mode):
    if mode==TEST:
        assert passes, msg
    elif mode==CHECK:
        print(msg)
    else:
        assert "Illegal mode"

def passes(msg, mode):
    result(True, msg, mode)

def fails(msg, mode):
    result(False, msg, mode)

def check_bool(correct, mode):
    if correct:
        passes('Correct.', mode)
    else:
        fails('Incorrect.', mode)

def check_multiple_choice_in_bounds(ans, outof, mode):
    if not (isinstance(ans, int) and 1 <= ans <= outof):
        fails('Incorrect.  Answer must be an integer between 1 and {}.'.format(str(outof)), mode)
    else:
        passes('Ok.', mode)

def is_table(t):
    return type(t) == tables.Table

def eq_table(t1, t2):
    if not(is_table(t1) and is_table(t2)):
        return False
    if not len(t1.keys()) == len(t2.keys()):
        return False
    for k in t1.keys():
        if not k in t2.keys():
            return False
        if not np.array_equal(t1[k], t2[k]):
            return False
    return True

def is_number(x):
    return isinstance(x, Number)

def is_np_array(x):
    return type(x) == np.ndarray

def is_string_type(x):
    return x in (str, np.str_)

def is_close(a,b):
    return np.isclose(a, b, rtol=1e-09)

def is_iterable(obj):
    try:
        _ = iter(obj)
        return True
    except TypeError:
        return False

def fails_generic(mode):
    if mode == CHECK:
        fails("Incorrect. Something is wrong with your answer, but it's not a mistake we were expecting.  Check with a TA or neighbor to see what might be wrong.", mode)
    elif mode == TEST:
        fails("Incorrect.", mode)
    else:
        assert "Illegal mode"

def correct(mode):
    passes('Correct.', mode)

def ok(mode):
    passes('Ok.', mode)

def check_bool_ask_if_err(b, mode):
    if b:
        correct(mode)
    else:
        fails_generic(mode)

def check_fruitful_function(fn, arg, mode):
    if not callable(fn):
        fails("Incorrect. Make sure you've used the right syntax to define the function.", mode)
        return False
    elif fn(arg) == None:
        fails("Incorrect. Make sure you used the return keyword in your function.", mode)
        return False
    else:
        return True

def check_table_labels(table, labels, mode):
    if not is_table(table):
        fails('Incorrect. Your answer should be a table.', mode)
        return False
    elif table.labels != labels:
        fails('Incorrect. Double check your column labels and order.', mode)
        return False
    else:
        return True

def check_select_all_that_apply(lst, max_val, mode):
    if not (is_iterable(lst) and all(is_number(x) and x in range(1, max_val+1) for x in lst)):
        fails('Your answer is not in the form of a list of numbers between 1 and {}. Try again.'.format(str(max_val)), mode)
    else:
        ok(mode)

def normalize_bool(b):
    return True if b else False

def is_probability(x):
    return is_number(x) and 0 <= x <= 1

##################################################

def check1_4(mean_based_estimator, mode=CHECK):
    if not callable(mean_based_estimator):
        fails("Incorrect. Make sure you've used the right syntax to define the function.", mode)
    elif mean_based_estimator(np.array([1, 2, 3])) is None:
        fails("Incorrect, it looks like you forgot to return something.", mode)
    elif int(np.round(mean_based_estimator(np.array([1, 2, 3])))) != 4:
        fails('''It looks like your function doesn't compute the
        right estimate.  For consistency in the rest of the
        lab, it's best if you use the twice-the-mean estimate,
        even if you prefer some other estimate.''', mode)
    else:
        ok(mode)

def check1_5(max_estimate, mode=CHECK):
    if not is_number(max_estimate):
        fails("Incorrect. max_estimate should be a number.", mode)
    elif max_estimate != 135:
        fails("Incorrect. Make sure you return the maximum number in the sample.", mode)
    else:
        ok(mode)

def check2_1(one_resample, mode=CHECK):
    np.random.seed(123)
    if not is_table(one_resample):
        fails("Incorrect. Make sure your function returns a table.", mode)
    elif one_resample.num_rows != 17:
        fails("Incorrect. Make sure you sample `num_observations` rows of the data.", mode)
    elif one_resample['serial number'][5] != 42:
        fails("Incorrect. Make sure you are taking a random sample (and don't change our seed).", mode)
    else:
        ok(mode)

def check2_3(true_statements, mode=CHECK):
    if not is_iterable(true_statements):
        fails("Incorrect. Please make sure `true_statements` is a list.", mode)
    elif len(true_statements) != 2:
        fails("Incorrect. Check with a neighbor or TA to verify your answer.", mode)
    elif not is_number(true_statements[0]):
        fails("Incorrect. Please give a list of integers corresponding to the numbers of the true statements.", mode)
    elif not (1 in true_statements and 4 in true_statements):
        fails("Incorrect. Check with a neighbor or TA to verify your answer.", mode)
    else:
        ok(mode)

def check4_1(chebyshev_upper_limit, mode=CHECK):
    if not is_number(chebyshev_upper_limit):
        fails("Incorrect. Make sure `chebyshev_upper_limit` is a number.", mode)
    elif not is_close(chebyshev_upper_limit, 0.25):
        fails("Incorrect. Try again or ask a TA for help.", mode)
    else:
        ok(mode)

def check4_2(simulations, prob_winning, mode=CHECK):
    if not is_table(simulations):
        fails("Incorrect. `simulations` should be a table.", mode)
    elif simulations.num_rows != 50:
        fails("Incorrect. Make sure you simulate 50 tosses.", mode)
    elif not is_probability(prob_winning):
        fails("Incorrect. Make sure `prob_winning` is a probability.", mode)
    elif prob_winning > 0.1:
        fails("Incorrect. Your probability seems too high.", mode)
    else:
        ok(mode)


import numpy as np

def count_inversion(a, num_inv):
    if len(a) == 2:
        if a[0] > a[1]:
            num_inv += 1
            return a[::-1], num_inv
        else:
            return a, num_inv
    elif len(a) == 1:
        return a, num_inv

    mid_idx = int(len(a) / 2)
    l_a, r_a = a[: mid_idx], a[mid_idx:]

    # get sorted left and right half of the array
    l_a, l_inv = count_inversion(l_a, num_inv)
    r_a, r_inv = count_inversion(r_a, num_inv)

    num_inv += (l_inv + r_inv)

    # merge and count
    final_a = []
    l_i, r_i = 0, 0
    while l_i < len(l_a) or r_i < len(r_a):
        if l_i == len(l_a) and r_a[r_i:]:
            final_a.extend(r_a[r_i:])
            break
        if r_i == len(r_a) and l_a[l_i:]:
            # num_inv += len(l_a[l_i + 1:]) * r_i
            final_a.extend(l_a[l_i:])
            break
        next_l = -np.inf if l_i == len(l_a) else l_a[l_i]
        next_r = np.inf if r_i == len(r_a) else r_a[r_i]

        if next_l > next_r:
            final_a.append(next_r)
            num_inv += (len(l_a[l_i:]))
            r_i += 1
        else:
            # next_r >= next_l
            final_a.append(next_l)
            l_i += 1

    return final_a, num_inv

def mergeSort(arr, n):
    # A temp_arr is created to store
    # sorted array in merge function
    temp_arr = [0] * n
    return _mergeSort(arr, temp_arr, 0, n - 1)

# This Function will use MergeSort to count inversions

def _mergeSort(arr, temp_arr, left, right):
    # A variable inv_count is used to store
    # inversion counts in each recursive call

    inv_count = 0

    # We will make a recursive call if and only if
    # we have more than one elements

    if left < right:
        # mid is calculated to divide the array into two subarrays
        # Floor division is must in case of python

        mid = (left + right) // 2

        # It will calculate inversion
        # counts in the left subarray

        inv_count += _mergeSort(arr, temp_arr,
                                left, mid)

        # It will calculate inversion
        # counts in right subarray

        inv_count += _mergeSort(arr, temp_arr,
                                mid + 1, right)

        # It will merge two subarrays in
        # a sorted subarray

        inv_count += merge(arr, temp_arr, left, mid, right)
    return inv_count

# This function will merge two subarrays
# in a single sorted subarray
def merge(arr, temp_arr, left, mid, right):
    i = left  # Starting index of left subarray
    j = mid + 1  # Starting index of right subarray
    k = left  # Starting index of to be sorted subarray
    inv_count = 0

    # Conditions are checked to make sure that
    # i and j don't exceed their
    # subarray limits.

    while i <= mid and j <= right:

        # There will be no inversion if arr[i] <= arr[j]

        if arr[i] <= arr[j]:
            temp_arr[k] = arr[i]
            k += 1
            i += 1
        else:
            # Inversion will occur.
            temp_arr[k] = arr[j]
            inv_count += (mid - i + 1)
            k += 1
            j += 1

    # Copy the remaining elements of left
    # subarray into temporary array
    while i <= mid:
        temp_arr[k] = arr[i]
        k += 1
        i += 1

    # Copy the remaining elements of right
    # subarray into temporary array
    while j <= right:
        temp_arr[k] = arr[j]
        k += 1
        j += 1

    # Copy the sorted subarray into Original array
    for loop_var in range(left, right + 1):
        arr[loop_var] = temp_arr[loop_var]

    return inv_count

if __name__ == '__main__':
    with open('data/prob2_data.txt', 'r') as f:

        s = f.readlines()
    s = [int(_s.split()[0]) for _s in s]

    # s = [1, 20, 6, 4, 5]

    _, x = count_inversion(s, 0)
    print(x)
    x = mergeSort(s, len(s))
    print(x)


class Solution:
    """
    @param height: A list of integer
    @return: The area of largest rectangle in the histogram
    """
    def largestRectangleArea(self, height):

        len_histogram = len(height)

        ans = 0
        height_list = sorter(height, reverse=True)

        for now_height in height_list:
            max_area = 0
            now_area = 0
            for i in range(len_histogram):
                if height[i] >= now_height:
                    now_area += height[i] * now_height
                else:
                    max_area = max(max_area, now_area)
            ans = max(max_area, ans)

        return ans


import pandas
import math
__author__ = 'Zhenxin Lei'
import pandas.io.data as pdata
import com.datautil.SymbolList as slist
import pandas.io.excel as pexcel
import numpy as np

# Get High Low average price data of list of stocks
# return time, average price matrix
def get_avg_price_matrix(startDate,endDate):
    #symbolList=list(slist.get_usa_yahoo_stock_tickers().keys())
    symbolList=['RGDX', 'APC', 'FIGY', 'TIF', 'APB']
    d=pandas.DataFrame(columns=symbolList)
    for i in range(len(symbolList)):
        data=pdata.get_data_yahoo(symbolList[i],startDate,endDate)
        print(data.values)
        avg=(data.High+data.Low)/2
        #add avg serise to column
        d[symbolList[i]]=avg
        #print("+++++d.items+++++++++++++")
        #print(d.items)

    # print("+++++d.items+++++++++++++")
    # print(d.items)
    # #d.to_excel('../../com/resource/AvgHighLow.xlsx')
    #
    # print("d.value")
    # print(d.values)
    print("+++++d.keys+++++++++++++")
    print(d.keys())
    # print("+++++d.items+++++++++++++")
    # print(d.items)
    # print("+++++d.axes+++++++++++++")
    # print(d.axes)

    return d

def get_return(priceDataFrame):
    startDate='9/1/2014'
    endDate='11/7/2014'
    priceDataFrame=get_avg_price_matrix(startDate,endDate)
    d=priceDataFrame
    print(priceDataFrame.items)
    symbolList=['RGDX', 'APC', 'FIGY', 'TIF', 'APB']
    d=pandas.DataFrame(columns=symbolList)

    pre=priceDataFrame.values[0].copy()
    for i in range(1,len(priceDataFrame.values)):
        cur=priceDataFrame.values[i]
        temp=cur
        cur=np.log(cur/pre)
        pre=temp.copy()
        priceDataFrame.values[i]=cur
        b=priceDataFrame.values[i]
        #d.values[i]= priceDataFrame.values[i]/priceDataFrame.values[i-1]

        print('a====================')
        print(len(priceDataFrame.values))

    priceDataFrame.values[0]=np.zeros(len(priceDataFrame.keys()))
    priceDataFrame=priceDataFrame.values[1:]
    return priceDataFrame

startDate='9/1/2014'
endDate='11/7/2014'
d= get_avg_price_matrix(startDate,endDate)
print (get_return(d))

print('===============')
print ('data.row')
#print(data.values[0][0]) #get first column in first row in the dataframe


while True:
    try:
        n, m = input().split(" ")
        soma = 0

        for i in m:
            soma += int(i)
        print(soma, end=' ')

        if soma % 3 == 0:
            print("sim")
        else:
            print("nao")
    except EOFError:
        break

Exercícios/1987 - Divisibilidade por 3.py


from ajaxtoolkit.http import JsonResponse

from django.contrib import messages

class AjaxMiddleware(object):
    def process_template_response(self, request, response):
        if request.is_ajax() and isinstance(response, JsonResponse):
            django_messages = []

            for message in messages.get_messages(request):
                django_messages.append({
                    "level": message.level,
                    "message": unicode(message.message),
                    "extra_tags": message.tags,
                    })
            response.dict_content['django_messages'] = django_messages
        return response


import sys
import time

import array
import smbus
import serial
import numpy as np

import logging
from ctypes import *

logger = logging.getLogger()
# logger.setLevel(logging.INFO)   # Display all print information
logger.setLevel(logging.FATAL)   # If you don’t want to display too many prints, only print errors, please use this option
ph = logging.StreamHandler()
formatter = logging.Formatter("%(asctime)s - [%(filename)s %(funcName)s]:%(lineno)d - %(levelname)s: %(message)s")
ph.setFormatter(formatter)
logger.addHandler(ph)

## i2c address
DF2301Q_I2C_ADDR                  = 0x64

## Address of the register for requesting command word ID
DF2301Q_I2C_REG_CMDID             = 0x02
## Address of the register for playing audio by command word ID
DF2301Q_I2C_REG_PLAY_CMDID        = 0x03
## Register for setting mute mode
DF2301Q_I2C_REG_SET_MUTE          = 0x04
## Register for setting volume
DF2301Q_I2C_REG_SET_VOLUME        = 0x05
## Address of the register for wake-up time
DF2301Q_I2C_REG_WAKE_TIME         = 0x06

# tail
DF2301Q_I2C_MSG_TAIL              = 0x5A

## UART baud rate
DF2301Q_UART_BAUDRATE             = 9600
## Maximum data length of serial data frame
DF2301Q_UART_MSG_DATA_MAX_SIZE    = 8

# header
DF2301Q_UART_MSG_HEAD_LOW         = 0xF4
DF2301Q_UART_MSG_HEAD_HIGH        = 0xF5
DF2301Q_UART_MSG_HEAD             = 0xF5F4
# tail
DF2301Q_UART_MSG_TAIL             = 0xFB
# msg_type
DF2301Q_UART_MSG_TYPE_CMD_UP      = 0xA0
DF2301Q_UART_MSG_TYPE_CMD_DOWN    = 0xA1
DF2301Q_UART_MSG_TYPE_ACK         = 0xA2
DF2301Q_UART_MSG_TYPE_NOTIFY      = 0xA3
# msg_cmd
## Report voice recognition results
DF2301Q_UART_MSG_CMD_ASR_RESULT        = 0x91
## Play local broadcast audio
DF2301Q_UART_MSG_CMD_PLAY_VOICE        = 0x92
## Read the serial number of FLASH
DF2301Q_UART_MSG_CMD_GET_FLASHUID      = 0x93
## Read version number
DF2301Q_UART_MSG_CMD_GET_VERSION       = 0x94
## Reset the voice module
DF2301Q_UART_MSG_CMD_RESET_MODULE      = 0x95
## Settings
DF2301Q_UART_MSG_CMD_SET_CONFIG        = 0x96
## Enter update mode
DF2301Q_UART_MSG_CMD_ENTER_OTA_MODE    = 0x97
## Event notification
DF2301Q_UART_MSG_CMD_NOTIFY_STATUS     = 0x9A
DF2301Q_UART_MSG_CMD_ACK_COMMON        = 0xAA
# if user want add please add form DF2301Q_UART_MSG_CMD_USER_START
DF2301Q_UART_MSG_CMD_USER_START        = 0xB0
# msg_data  msg_cmd:DF2301Q_UART_MSG_CMD_PLAY_VOICE
DF2301Q_UART_MSG_DATA_PLAY_START            = 0x80
DF2301Q_UART_MSG_DATA_PLAY_PAUSE            = 0x81
DF2301Q_UART_MSG_DATA_PLAY_RESUME           = 0x82
DF2301Q_UART_MSG_DATA_PLAY_STOP             = 0x83
DF2301Q_UART_MSG_DATA_PLAY_BY_VOICEID       = 0x90
DF2301Q_UART_MSG_DATA_PLAY_BY_SEMANTIC_ID   = 0x91
DF2301Q_UART_MSG_DATA_PLAY_BY_CMD_ID        = 0x92
# msg_data  msg_cmd:DF2301Q_UART_MSG_CMD_GET_VERSION
## Serial protocol version number
DF2301Q_UART_MSG_DATA_VER_PROTOCOL          = 0x80
## SDK version number
DF2301Q_UART_MSG_DATA_VER_SDK               = 0x81
## ASR component version number
DF2301Q_UART_MSG_DATA_VER_ASR               = 0x82
## Audio pre-processing algorithm version number
DF2301Q_UART_MSG_DATA_VER_PREPROCESS        = 0x83
## Player version number
DF2301Q_UART_MSG_DATA_VER_PLAYER            = 0x84
## App version number
DF2301Q_UART_MSG_DATA_VER_APP               = 0x8A
# msg_data  msg_cmd:DF2301Q_UART_MSG_CMD_NOTIFY_STATUS
DF2301Q_UART_MSG_DATA_NOTIFY_POWERON        = 0xB0
DF2301Q_UART_MSG_DATA_NOTIFY_WAKEUPENTER    = 0xB1
DF2301Q_UART_MSG_DATA_NOTIFY_WAKEUPEXIT     = 0xB2
DF2301Q_UART_MSG_DATA_NOTIFY_PLAYSTART      = 0xB3
DF2301Q_UART_MSG_DATA_NOTIFY_PLAYEND        = 0xB4
# msg_data msg_cmd:DF2301Q_UART_MSG_CMD_SET_CONFIG
DF2301Q_UART_MSG_CMD_SET_VOLUME             = 0x80
DF2301Q_UART_MSG_CMD_SET_ENTERWAKEUP        = 0x81
DF2301Q_UART_MSG_CMD_SET_PRT_MID_RST        = 0x82
DF2301Q_UART_MSG_CMD_SET_MUTE               = 0x83
DF2301Q_UART_MSG_CMD_SET_WAKE_TIME          = 0x84
DF2301Q_UART_MSG_CMD_SET_NEEDACK            = 0x90
DF2301Q_UART_MSG_CMD_SET_NEEDSTRING         = 0x91
# ACK error code
DF2301Q_UART_MSG_ACK_ERR_NONE               = 0x00
DF2301Q_UART_MSG_ACK_ERR_CHECKSUM           = 0xff
DF2301Q_UART_MSG_ACK_ERR_NOSUPPORT          = 0xfe

class DFRobot_DF2301Q(object):
  '''!
    @brief Define DFRobot_DF2301Q basic class
  '''

  def __init__(self):
    '''!
      @brief Module init
    '''
    pass

class DFRobot_DF2301Q_I2C(DFRobot_DF2301Q):
  '''!
    @brief Define DFRobot_DF2301Q_I2C basic class
  '''

  def __init__(self, i2c_addr=DF2301Q_I2C_ADDR, bus=1):
    '''!
      @brief Module I2C communication init
      @param i2c_addr - I2C communication address
      @param bus - I2C bus
    '''
    self._addr = i2c_addr
    self._i2c = smbus.SMBus(bus)
    super(DFRobot_DF2301Q_I2C, self).__init__()

  def get_CMDID(self):
    '''!
      @brief Get the ID corresponding to the command word
      @return Return the obtained command word ID, returning 0 means no valid ID is obtained
    '''
    time.sleep(0.05)   # Prevent the access rate from interfering with other functions of the voice module
    return self._read_reg(DF2301Q_I2C_REG_CMDID)

  def play_by_CMDID(self, CMDID):
    '''!
      @brief Play the corresponding reply audio according to the command word ID
      @param CMDID - Command word ID
      @note Can enter wake-up state through ID-1 in I2C mode
    '''
    self._write_reg(DF2301Q_I2C_REG_PLAY_CMDID, CMDID)
    time.sleep(1)

  def get_wake_time(self):
    '''!
      @brief Get the wake-up duration
      @return The current set wake-up period
    '''
    return self._read_reg(DF2301Q_I2C_REG_WAKE_TIME)

  def set_wake_time(self, wake_time):
    '''!
      @brief Set wake-up duration
      @param wakeTime - Wake-up duration(0-255)
    '''
    wake_time = wake_time & 0xFF
    self._write_reg(DF2301Q_I2C_REG_WAKE_TIME, wake_time)

  def set_volume(self, vol):
    '''!
      @brief Set voice volume
      @param vol - Volume value(1~7)
    '''
    # if (vol < 0):
    #   vol = 0
    # elif (vol > 20):
    #   vol = 20
    self._write_reg(DF2301Q_I2C_REG_SET_VOLUME, vol)

  def set_mute_mode(self, mode):
    '''!
      @brief Set mute mode
      @param mode - Mute mode; set value 1: mute, 0: unmute
    '''
    if (0 != mode):
      mode = 1
    self._write_reg(DF2301Q_I2C_REG_SET_MUTE, mode)

  def _write_reg(self, reg, data):
    '''!
      @brief writes data to a register
      @param reg - register address
      @param data - written data
    '''
    if isinstance(data, int):
      data = [data]
      #logger.info(data)
    self._i2c.write_i2c_block_data(self._addr, reg, data)

  def _read_reg(self, reg):
    '''!
      @brief read the data from the register
      @param reg - register address
      @return read data
    '''
    data = self._i2c.read_i2c_block_data(self._addr, reg, 1)
    return data[0]

class DFRobot_DF2301Q_UART(DFRobot_DF2301Q):
  '''!
    @brief Define DFRobot_DF2301Q_UART basic class
  '''

  REV_STATE_HEAD0   = 0x00
  REV_STATE_HEAD1   = 0x01
  REV_STATE_LENGTH0 = 0x02
  REV_STATE_LENGTH1 = 0x03
  REV_STATE_TYPE    = 0x04
  REV_STATE_CMD     = 0x05
  REV_STATE_SEQ     = 0x06
  REV_STATE_DATA    = 0x07
  REV_STATE_CKSUM0  = 0x08
  REV_STATE_CKSUM1  = 0x09
  REV_STATE_TAIL    = 0x0a

  class uart_msg():
    '''!
      @brief Class for serial data frame struct
    '''
    def __init__(self):
      '''!
        @brief sensor_status structure init
      '''
      self.header = 0
      self.data_length = 0
      self.msg_type = 0
      self.msg_cmd = 0
      self.msg_seq = 0
      self.msg_data = [0] * 8

  def __init__(self):
    '''!
      @brief Module UART communication init
    '''
    self.uart_cmd_ID = 0
    self._send_sequence = 0
    self._ser = serial.Serial("/dev/ttyAMA0", baudrate=DF2301Q_UART_BAUDRATE, bytesize=8, parity='N', stopbits=1, timeout=0.5)
    if self._ser.isOpen == False:
      self._ser.open()
    super(DFRobot_DF2301Q_UART, self).__init__()

  def get_CMDID(self):
    '''!
      @brief Get the ID corresponding to the command word
      @return Return the obtained command word ID, returning 0 means no valid ID is obtained
    '''
    self._recv_packet()
    temp = self.uart_cmd_ID
    self.uart_cmd_ID = 0
    return temp

  def play_by_CMDID(self, play_id):
    '''!
      @brief Play the corresponding reply audio according to the command word ID
      @param CMDID - Command word ID
    '''
    msg = self.uart_msg()
    msg.header = DF2301Q_UART_MSG_HEAD
    msg.data_length = 6
    msg.msg_type = DF2301Q_UART_MSG_TYPE_CMD_DOWN
    msg.msg_cmd = DF2301Q_UART_MSG_CMD_PLAY_VOICE
    msg.msg_seq = self._send_sequence
    self._send_sequence += 1
    msg.msg_data[0] = DF2301Q_UART_MSG_DATA_PLAY_START
    msg.msg_data[1] = DF2301Q_UART_MSG_DATA_PLAY_BY_CMD_ID
    msg.msg_data[2] = play_id

    self._send_packet(msg)
    time.sleep(1)

  def reset_module(self):
    '''!
      @brief Reset the module
    '''
    msg = self.uart_msg()
    msg.header = DF2301Q_UART_MSG_HEAD
    msg.data_length = 5
    msg.msg_type = DF2301Q_UART_MSG_TYPE_CMD_DOWN
    msg.msg_cmd = DF2301Q_UART_MSG_CMD_RESET_MODULE
    msg.msg_seq = self._send_sequence
    self._send_sequence += 1
    msg.msg_data[0] = 'r'
    msg.msg_data[1] = 'e'
    msg.msg_data[2] = 's'
    msg.msg_data[3] = 'e'
    msg.msg_data[4] = 't'

    self._send_packet(msg)
    time.sleep(3)

  def setting_CMD(self, set_type, set_value):
    '''!
      @brief Set commands of the module
      @param set_type - Set type
      @n       DF2301Q_UART_MSG_CMD_SET_VOLUME : Set volume, the set value range 1-7
      @n       DF2301Q_UART_MSG_CMD_SET_ENTERWAKEUP : Enter wake-up state; set value 0
      @n       DF2301Q_UART_MSG_CMD_SET_MUTE : Mute mode; set value 1: mute, 0: unmute
      @n       DF2301Q_UART_MSG_CMD_SET_WAKE_TIME : Wake-up duration; the set value range 0-255s
      @param set_value - Set value, refer to the set type above for the range
    '''
    msg = self.uart_msg()
    msg.header = DF2301Q_UART_MSG_HEAD
    msg.data_length = 5
    msg.msg_type = DF2301Q_UART_MSG_TYPE_CMD_DOWN
    msg.msg_cmd = DF2301Q_UART_MSG_CMD_SET_CONFIG
    msg.msg_seq = self._send_sequence
    self._send_sequence += 1
    msg.msg_data[0] = set_type
    msg.msg_data[1] = set_value

    self._send_packet(msg)

  def _send_packet(self, msg):
    '''
      @brief Write data through UART
      @param msg - Data packet to be sent
    '''
    chk_sum = 0x0000
    data = []
    data.append(msg.header & 0xFF)
    data.append((msg.header >> 8) & 0xFF)
    data.append(msg.data_length & 0xFF)
    data.append((msg.data_length >> 8) & 0xFF)
    data.append(msg.msg_type & 0xFF)
    chk_sum += msg.msg_type
    data.append(msg.msg_cmd & 0xFF)
    chk_sum += msg.msg_cmd
    data.append(msg.msg_seq & 0xFF)
    chk_sum += msg.msg_seq
    for i in range(0, msg.data_length):
      data.append(msg.msg_data[i] & 0xFF)
      chk_sum += msg.msg_data[i]
    data.append(chk_sum & 0xFF)
    data.append((chk_sum >> 8) & 0xFF)
    data.append(DF2301Q_UART_MSG_TAIL & 0xFF)
    logger.info(data)
    self._ser.write(data)
    time.sleep(0.1)

  def _recv_packet(self):
    '''
      @brief Read data through UART
      @param msg - Buffer for receiving data packet
    '''
    msg = self.uart_msg()
    rev_state = self.REV_STATE_HEAD0
    receive_char = 0
    chk_sum = 0
    data_rev_count = 0
    while self._ser.in_waiting:
      receive_char = ord(self._ser.read(1))
      if(self.REV_STATE_HEAD0 == rev_state):
        if(DF2301Q_UART_MSG_HEAD_LOW == receive_char):
          rev_state = self.REV_STATE_HEAD1
      elif(self.REV_STATE_HEAD1 == rev_state):
        if(DF2301Q_UART_MSG_HEAD_HIGH == receive_char):
          rev_state = self.REV_STATE_LENGTH0
          msg.header = DF2301Q_UART_MSG_HEAD
        else:
          rev_state = self.REV_STATE_HEAD0
      elif(self.REV_STATE_LENGTH0 == rev_state):
        msg.data_length = receive_char
        rev_state = self.REV_STATE_LENGTH1
      elif(self.REV_STATE_LENGTH1 == rev_state):
        msg.data_length += receive_char << 8
        rev_state = self.REV_STATE_TYPE
      elif(self.REV_STATE_TYPE == rev_state):
        msg.msg_type = receive_char
        rev_state = self.REV_STATE_CMD
      elif(self.REV_STATE_CMD == rev_state):
        msg.msg_cmd = receive_char
        rev_state = self.REV_STATE_SEQ
      elif(self.REV_STATE_SEQ == rev_state):
        msg.msg_seq = receive_char
        rev_state = rev_state
        if(msg.data_length > 0):
          rev_state = self.REV_STATE_DATA
          data_rev_count = 0
        else:
          rev_state = self.REV_STATE_CKSUM0
      elif(self.REV_STATE_DATA == rev_state):
        msg.msg_data[data_rev_count] = receive_char
        data_rev_count += 1
        if(msg.data_length == data_rev_count):
          rev_state = self.REV_STATE_CKSUM0
      elif(self.REV_STATE_CKSUM0 == rev_state):
        chk_sum = receive_char
        rev_state = self.REV_STATE_CKSUM1
      elif(self.REV_STATE_CKSUM1 == rev_state):
        chk_sum += receive_char << 8

        rev_state = self.REV_STATE_TAIL
      elif(self.REV_STATE_TAIL == rev_state):
        if(DF2301Q_UART_MSG_TAIL == receive_char):
          if(DF2301Q_UART_MSG_TYPE_CMD_UP == msg.msg_type):
            self.uart_cmd_ID = msg.msg_data[0]
        else:
          data_rev_count = 0
        rev_state = self.REV_STATE_HEAD0
      else:
        rev_state = self.REV_STATE_HEAD0

    return data_rev_count


import contextlib
import six

from shuup.apps.provides import get_provide_objects
from shuup.utils.importing import cached_load, load

_registry = []

def register(module_class):
    if isinstance(module_class, six.string_types):
        module_class = load(module_class, "Admin Module")
    _registry.append(module_class())

def discover():
    for obj in get_provide_objects("admin_module"):
        register(obj)

def get_admin_modules():
    """
    :rtype: list[shuup.admin.base.AdminModule]
    """
    if not _registry:
        discover()
    return iter(_registry)

def get_modules():
    """
    :rtype: list[shuup.admin.base.AdminModule]
    """
    get_modules_spec = cached_load("SHUUP_GET_ADMIN_MODULES_SPEC")
    return get_modules_spec()

def get_module_urls():
    for module in get_modules():  # pragma: no branch
        for url in module.get_urls():  # pragma: no branch
            yield url

@contextlib.contextmanager
def replace_modules(new_module_classes):
    """
    Context manager to temporarily replace all modules with something else.

    Test utility, mostly.

    >>> def some_test():
    ...     with replace_modules(["foo.bar:QuuxModule"]):
    ...         pass # do stuff

    :param new_module_classes: Iterable of module classes, like you'd pass to `register`
    """
    old_registry = _registry[:]
    _registry[:] = []
    for cls in new_module_classes:
        register(cls)
    try:
        yield
    finally:
        _registry[:] = old_registry


import os

from setuptools import setup, find_packages

from distutils.core import Extension

cmandelbrot = Extension('cmandelbrot', sources = ['mandelbrot/cmandelbrot.c'])
cymandelbrot = Extension('cymandelbrot', ['mandelbrot/cymandelbrot.c'])

cysoe = Extension('cysoe', sources = ['sieve_of_eratosthenes/cysoe.c'])
cycsoe = Extension('cycsoe', sources = ['sieve_of_eratosthenes/cycsoe.c'])

csoe = Extension('csoe', sources = ['sieve_of_eratosthenes/csoe.c'])

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

setup(name='pyperf',
      version='0.1',
      author='',
      author_email='',
      url='',
      packages=find_packages(),
      test_suite="tests",
      ext_modules = [cymandelbrot, cmandelbrot, cysoe, csoe, cycsoe],
)


import io

class Codec:
    """
    Implements encode/decode primitives
    """

    @staticmethod
    def read_boolean(reader: io.BytesIO):
        b = reader.read(1)
        return b == 1

    @staticmethod
    def read_uint(reader: io.BytesIO):
        """
        The ending "big" doesn't play any role here,
        since we're dealing with data per one byte
        """
        x = 0  # the result
        s = 0  # the shift (our result is big-ending)
        i = 0  # n of byte (max 9 for uint64)
        while True:
            b = reader.read(1)
            if len(b) == 0:
                raise IndexError('bytes out of range')
            num = int.from_bytes(b, "big", signed=False)
            # print(i, x)

            if num < 0x80:
                if i > 9 | i == 9 & num > 1:
                    raise OverflowError()
                return int(x | num << s)
            x |= (num & 0x7f) << s
            s += 7
            i += 1

    @staticmethod
    def read_size(reader: io.BytesIO):
        size = 0
        for i in range(3):
            b = reader.read(1)
            num = int.from_bytes(b, "big", signed=False)
            size += num << (8*i)
        return size

    @staticmethod
    def read_int(reader: io.BytesIO) -> int:
        """
        ux, err := ReadUint(reader)
        x := int64(ux >> 1)
        if err != nil {
            return x, err
        }
        if ux&1 != 0 {
            x = ^x
        }
        return x, err
        """
        ux = Codec.read_uint(reader)
        x = int(ux >> 1)

        if ux & 1 != 0:
            x = - x - 1
        return x

    @staticmethod
    def read_string(reader: io.BytesIO) -> str:
        length = Codec.read_uint(reader)
        try:
            s = reader.read(length)
        except Exception as e:
            print(f'Error while reading string of length {length}')
            raise Exception(e)
        try:
            return s.decode("utf-8", errors="replace").replace("\x00", "\uFFFD")
        except UnicodeDecodeError:
            return None


#  File: DNA.py

#  Description:

#  Student Name: Sashi Ayyalasomayajula

#  Student UT EID: sa55465

#  Partner Name:

#  Partner UT EID:

#  Course Name: CS 313E

#  Unique Number:

#  Date Created:

#  Date Last Modified:

import sys

def longest_subsequence (s1, s2):

    subsequence_array = []
    str_seq = ""

    for i in range(len(s1)):
        for j in range(len(s2)):
            c1 = i
            c2 = j
            while c1 < len(s1) and c2 < len(s2) and s1[c1] == s2[c2]:
                str_seq += s1[c1]
                c1 += 1
                c2 += 1
            if str_seq:
                subsequence_array.append(str_seq)
            str_seq = ""

    # find a way to get all maxes + sort
    return max(subsequence_array)

longest_subsequence("GAAGGTCGAA", "CCTCGGGA")

# def main():

# 	#read the number of pairs

# 	num_pairs = sys.stdin.readline()
# 	num_pairs = num_pairs.strip()
# 	num_pairs = int (num_pairs)

# 	print(num_pairs)

# if __name__ == "__main__":
#   main()


"""
You are given an array a consisting of n positive integers.

You are allowed to perform this operation any number of times (possibly, zero):

choose an index i (2≤i≤n), and change ai to ai−ai−1.
Is it possible to make ai=0 for all 2≤i≤n?

Input
The input consists of multiple test cases. The first line contains a single integer t (1≤t≤100)  — the number of test cases. The description of the test cases follows.

The first line contains one integer n (2≤n≤100) — the length of array a.

The second line contains n integers a1,a2,…,an (1≤ai≤109).

Output
For each test case, print "YES" (without quotes), if it is possible to change ai to 0 for all 2≤i≤n, and "NO" (without quotes) otherwise.

You can print letters in any case (upper or lower).
"""

t =  int(input())

for case in range(t):
    n = int(input())
    numbers = list(map(int, input().split()))

    base_number = numbers[0]
    answer = "YES"
    for i in range(1, n):
        if numbers[i]%base_number != 0:
            answer = "NO"
            break
    print(answer)


from data_preparation import load_conv_weight, load_conv_param, load_data_from_file
from layer_operations import my_conv2d, my_fc, my_bn, compute_relu_layer, my_avg_pool, my_max_pool

def compute_conv_layer(in_data, layer_name):
  print("-- compute " + layer_name)
  weight = load_conv_weight(layer_name)
  param = load_conv_param(layer_name)
  # ci, co, kernel, stride, pad
  hi = in_data.shape[0]
  wi = in_data.shape[1]
  ci = param[0]
  co = param[1]
  kernel = param[2]
  stride = param[3]
  pad = param[4]
  res = my_conv2d(in_data, weight, hi, wi, ci, co, kernel, stride, pad)
  print(res.shape)
  return res

def compute_fc_layer(in_data, layer_name):
  print("-- compute " + layer_name)
  weight_file_name = "../model/resnet50_weight/resnet50_" + layer_name + "_weight.txt"
  bias_file_name = "../model/resnet50_weight/resnet50_" + layer_name + "_bias.txt"
  weight = load_data_from_file(weight_file_name)
  bias = load_data_from_file(bias_file_name)
  res = my_fc(in_data, weight, bias)
  print(res.shape)
  return res

def compute_bn_layer(in_data, layer_name):
  print("-- compute " + layer_name)
  weight = load_conv_weight(layer_name)
  weight_file_name = "../model/resnet50_weight/resnet50_" + layer_name + "_weight.txt"
  bias_file_name = "../model/resnet50_weight/resnet50_" + layer_name + "_bias.txt"
  mean_file_name = "../model/resnet50_weight/resnet50_" + layer_name + "_running_mean.txt"
  var_file_name = "../model/resnet50_weight/resnet50_" + layer_name + "_running_var.txt"
  weight = load_data_from_file(weight_file_name)
  bias = load_data_from_file(bias_file_name)
  mean = load_data_from_file(mean_file_name)
  var = load_data_from_file(var_file_name)
  res = my_bn(in_data, mean, var, weight, bias)
  print(res.shape)
  return res

def compute_maxpool_layer(in_data):
  print("-- compute maxpool")
  res = my_max_pool(in_data)
  print(res.shape)
  return res

def compute_avgpool_layer(in_data):
  print("-- compute avgpool")
  res = my_avg_pool(in_data)
  print(res.shape)
  return res

def compute_bottleneck(in_data, bottleneck_layer_name, down_sample = False):
  print("compute " + bottleneck_layer_name)
  out = compute_conv_layer(in_data, bottleneck_layer_name + "_conv1")
  out = compute_bn_layer(out, bottleneck_layer_name + "_bn1")
  out = compute_relu_layer(out)
  out = compute_conv_layer(out, bottleneck_layer_name + "_conv2")
  out = compute_bn_layer(out, bottleneck_layer_name + "_bn2")
  out = compute_relu_layer(out)
  out = compute_conv_layer(out, bottleneck_layer_name + "_conv3")
  bn_out = compute_bn_layer(out, bottleneck_layer_name + "_bn3")

  if down_sample == True:
    conv_out= compute_conv_layer(in_data, bottleneck_layer_name + "_downsample_conv2d")
    short_cut_out = compute_bn_layer(conv_out, bottleneck_layer_name + "_downsample_batchnorm")
    bn_out = bn_out + short_cut_out
  else:
    bn_out = bn_out + in_data
  return compute_relu_layer(bn_out)


from django import forms
from .models import SystemPilates, Contact
from django.core.exceptions import ValidationError

class SystemPilatesForm(forms.ModelForm):
	delta_day = forms.IntegerField(label='Dias que podrá ver el usuario a escoger', required=True, min_value=0, max_value=31)
	cant_max = forms.IntegerField(label='Cantidad máxima por clase', required=True, min_value=0, max_value=10)

	class Meta:
		model= SystemPilates
		fields= (
					"delta_day",
					"cant_max",
					"reglas",

				)
	def __init__(self, *args, **kwargs):
	    super().__init__(*args, **kwargs)
	    self.fields['reglas'].widget.attrs.update({'label':'Reglas','rows': '20', 'cols':"120"})

class SystemContactForm(forms.ModelForm):
	class Meta:
		model= Contact
		fields= (
					"email",
					"phone_number",
					"direction",

				)
	def __init__(self, *args, **kwargs):
	    super().__init__(*args, **kwargs)
	    self.fields['direction'].widget.attrs.update({'rows': '10', 'cols':"60"})


from flask import Flask, jsonify, request

app = Flask(__name__)

@app.route('/api', methods=['GET'])
def api():
    data = {
        'message': 'Hello, this is a simple API!'
    }
    return jsonify(data)

@app.route('/api/params', methods=['GET'])
def params():
    param1 = request.args.get('param1')
    param2 = request.args.get('param2')

    if param1 and param2:
        result = f'Received parameters: param1={param1}, param2={param2}'
    else:
        result = 'Missing parameters'

    data = {
        'message': result
    }
    return jsonify(data)

@app.route('/api', methods=['POST'])
def postapi():
    data = request.get_json()  # Get JSON data from the POST request
    if data is not None:
        # Process the received JSON data (you can perform any operation here)
        response = {
            'message': 'POST request successful',
            'data_received': data
        }
        return jsonify(response), 200  # Return a JSON response with a success status code
    else:
        return jsonify({'error': 'Invalid JSON'}), 400  # Return an error response for invalid JSON data

if __name__ == '__main__':
    app.run(debug=True)


import json
import logging
import os
import re
import sys
import shutil
import string
import time
import urllib

class ScriptWriter(object):
    """
        Script writer class
    """
    # Directory containing the templates
    _script_name = "reduce_%s.py"
    # Name of the template file
    _template_name = "reduce_%s.py.template"
    # Name of the default reduction script
    _default_script_name = "reduce_%s_default.py"
    # Path of the autoreduction directory
    _autoreduction_dir = "/SNS/%s/shared/autoreduce"
    # Log file
    _log_file = "reduction_parameters.txt"

    def __init__(self, instrument):
        """
            Initialize and find the appropriate template file
            @param str instrument: instrument name
        """
        # Instrument name
        self.instrument = instrument
        # Reduction script name
        self.script_name = self._script_name % instrument.upper()
        # Name of the reduction template file
        self.template_name = self._template_name % instrument.upper()
        # Default reduction script name
        self.default_script_name = self._default_script_name % instrument.upper()
        # Content of the template
        self._template_content = None
        # Shared autoredudction directory
        self.autoreduction_dir = self._autoreduction_dir % instrument.upper()

    @property
    def _template_path(self):
        r"""Absolute path to reduction script"""
        return os.path.join(self.autoreduction_dir, self.template_name)

    @property
    def log_file(self):
        r"""Absolute path to the log file"""
        return os.path.join(self.autoreduction_dir, self._log_file)

    def get_arguments(self):
        """
            Return a list of template arguments
        """
        if self._template_content is None:
            self._template_content = open(self._template_path).read()

        tag_list = re.findall(r"\$(\w+)", self._template_content)
        tag_list.extend(re.findall(r"\${(\w+)}", self._template_content))
        return set(tag_list)

    def check_arguments(self, **template_args):
        """
            Check that all arguments provided in the input dictionary
            are sufficient to fill the template. Otherwise raise an exception.

            @param template_args: dictionary of arguments to fill the template
        """
        missing_args = []
        for item in self.get_arguments():
            if item not in template_args:
                missing_args.append(item)
        if len(missing_args) > 0:
            raise KeyError("Template arguments missing: %s" % str(missing_args))

    def write_script(self, **template_args):
        r"""Write the script using a template
        @param dict template_args: dictionary of arguments to fill the template
        @raises KeyError: if missing template arguments
        """
        self.check_arguments(**template_args)
        # If we use a template, make sure we load it first
        if self._template_content is None:
            self._template_content = open(self._template_path).read()
        # Replace the dictionary entries
        template = string.Template(self._template_content)
        script = template.substitute(**template_args)
        # Write the script
        if os.path.isdir(self.autoreduction_dir):
            script_file = open(os.path.join(self.autoreduction_dir, self.script_name), 'w')
            script_file.write(script)
            script_file.close()
        else:
            raise RuntimeError("Script directory does not exist: %s" % self.autoreduction_dir)

    def log_entry(self, **template_args):
        r"""Log the template parameters in the reduction directory.
        @details The log file is tab delimited.
        @param dic template_args: arguments to fill the template
        """
        try:
            template_keys = sorted(template_args.keys())
            template_values = [string.replace(str(template_args[k]), '\n', '; ') for k in template_keys]
            template_keys.insert(0, "Time")
            template_values.insert(0, "%s" % time.ctime())
            log_entry = ""
            # If the file doesn't exist, create it with a header line
            if not os.path.isfile(self.log_file):
                log_entry = '\t '.join(template_keys)
                log_entry += '\n'
            log_entry += '\t '.join(template_values)
            log_entry += '\n'
            log_file = open(self.log_file, 'a')
            log_file.write(log_entry)
            log_file.close()
        except Exception:
            logging.error("ScriptWriter: Could not write log entry for %s: %s" % (self.script_name, sys.exc_value))

    def process_request(self, request_data, configuration, send_function):
        r"""Process a request to write a new reduction script from an existing template
        @param dict request_data: request dictionary with template arguments
        @param configuration: Configuration object
        @param send_function: function to call to send an AMQ message
        """
        if 'instrument' not in request_data:
            logging.error("Script writer request: missing instrument")
            return
        # Determine the ActiveMQ topic to use for reporting
        amq_template = string.Template(configuration.service_status)
        amq_topic = amq_template.substitute(instrument=request_data['instrument'])
        amq_data = {'src_id': 'postprocessing'}
        try:
            # Verify that the dictionary of template arguments is complete
            if "template_data" in request_data:
                template_data = {}
                for key, value in request_data["template_data"].items():
                    if isinstance(value, basestring):
                        # replace '+' sign with a blank space ('+' -> ' ')
                        # replace %xx escapes by their single-character equivalent
                        template_data[key] = urllib.unquote_plus(value)
                    else:
                        template_data[key] = value

                # Check for a request to use the default script
                if 'use_default' in request_data and request_data['use_default'] is True:
                    # Copy the default script to the production script
                    default_script_path = os.path.join(self.autoreduction_dir, self.default_script_name)
                    if not os.path.isfile(default_script_path):
                        raise RuntimeError("ScriptWriter: Could not find script %s" % self.default_script_name)
                    shutil.copy(default_script_path,
                                os.path.join(self.autoreduction_dir, self.script_name))
                    amq_data['status'] = "Installed default %s script" % request_data['instrument']
                else:
                    # Verify that the template file exists
                    if not os.path.isfile(self._template_path):
                        raise RuntimeError("ScriptWriter: Could not find template %s" % self.template_name)

                    self.check_arguments(**template_data)
                    self.write_script(**template_data)
                    amq_data['status'] = "Created %s reduction script" % request_data['instrument']
                self.log_entry(**template_data)
            else:
                logging.error("Script writer: missing template data")
                amq_data['status'] = "Missing %s reduction template" % request_data['instrument']
        except RuntimeError:
            logging.error("Script writer: %s" % sys.exc_value)
            amq_data['status'] = "Error creating %s reduction script: %s" % (request_data['instrument'],
                                                                             sys.exc_value)
        send_function(amq_topic, json.dumps(amq_data))


"""
https://leetcode.com/problems/product-of-array-except-self/

Input:  [1,2,3,4]
Output: [24,12,8,6]
"""

nums = [2, 3, 4, 5]

# self, not O(n)
output = []
one = 1
for i in range(0, len(nums)):
    for j, vt in enumerate(nums):
        if i == j:
            continue
        one = one * vt
    output.append(one)
    one = 1
print(output)

# # solution book
out = []
p = 1

for i in range(0, len(nums)):  # 0 ~ 4
    out.append(p)
    p = p * nums[i]
p = 1

for i in range(len(nums) - 1, 0 - 1, -1):  # 3 ~ -1
    out[i] = out[i] * p
    p = p * nums[i]
print(out)


import sys
si = sys.stdin.readline
n = int(si())
stack = []
result = []

# 스택 구현
def call_stack(order):
  if order[0] == 'push':
    stack.append(order[1])
  elif order[0] == 'pop':
    if stack:
      result.append(stack[-1])
      del stack[-1]
    else:
      result.append(-1)
  elif order[0] == 'size':
    result.append(len(stack))
  elif order[0] == 'empty':
    if stack:
      result.append(0)
    else:
      result.append(1)
  elif order[0] == 'top':
    if stack:
      result.append(stack[-1])
    else:
      result.append(-1)
  else:
    print('알맞은 연산자가 아닙니다.')

# 입력 받는 인자가 optional 하게 있기 때문에 배열을 통해서 입력받도록 함
for _ in range(n):
  order = list(si().split())
  call_stack(order)

# 정답 출력
for x in result:
  print(x)

#https://www.acmicpc.net/problem/10828

WEEK2/min/알고리즘_기초_1/200_자료구조1/10828_스택.py


import os
import requests
from requests.exceptions import ConnectionError
import getpass
from time import sleep
import keyboard as kb
import ctypes
import sys
from pystyle import Write, Colorate, Colors
import random
from urllib.parse import urlparse

banner = '''

    ___     / __      ___      ___      ___
  //   ) ) //   ) ) //   ) ) //   ) ) //   ) )
 //       //   / / //   / / //       //   / /
((____   //   / / ((___/ / ((____   ((___/ /

Supports : exe, zip
Version : v1.0.0
'''
def is_admin():
    try:
        return ctypes.windll.shell32.IsUserAnAdmin()
    except:
        return False
if is_admin():
    print(Colorate.Color(Colors.red, banner, True))
    print('')
    username = getpass.getuser()

    def install_choco():
        filesize = os.path.getsize("choco.t")
        if filesize == 0:
            print("0 applications need to be installed: " + str(filesize))
        else:
            Write.Print(f"Make Sure You Installed Chocolatey...", Colors.blue_to_green, interval=0.05)
            with open(f'choco.t', 'r') as a:
                lines = a.readlines()
                for line in lines:
                    app = line
                    os.system(f'choco install {app} -y --force')
                    print('')
    install_choco()

    def install_exe():
        filesize = os.path.getsize("exe.t")
        if filesize == 0:
             print("0 executables need to be installed: " + str(filesize))
        else:
            Write.Print(f"Installing Your executables!", Colors.blue_to_green, interval=0.05)
            print('')
            with open(f'exe.t', 'r') as b:
                lines = b.readlines()
                for line in lines:
                    url = line
                    r = requests.get(url, allow_redirects=True)
                    t = urlparse(url).netloc
                    print ('.'.join(t.split('.')[-2:]))
                    open(f'{t}.exe', 'wb').write(r.content)
                    print('')
    install_exe()

    def install_zip():
        filesize = os.path.getsize("zip.t")
        if filesize == 0:
            Write.Print("0 zip files need to be installed: " + str(filesize),  Colors.blue_to_green, interval=0.05)
        else:
            Write.Print(f"Installing Your zip files!", Colors.blue_to_green, interval=0.05)
            print('')
            with open(f'zip.t', 'r') as c:
                lines = c.readlines()
                for line in lines:
                    url = line
                    r = requests.get(url, allow_redirects=True)
                    t = urlparse(url).netloc
                    print ('.'.join(t.split('.')[-2:]))
                    open(f'{t}.zip', 'wb').write(r.content)
                    print(f'Successfully installed {t}.zip')
                    print('')
    install_zip()

else:
    ctypes.windll.shell32.ShellExecuteW(None, "runas", sys.executable, " ".join(sys.argv), None, 1)