"""A growing set of tests designed to ensure when isort implements a feature described in a ticket
it fully works as defined in the associated ticket.
"""
from functools import partial
from io import StringIO

import pytest

import isort
from isort import Config, exceptions

def test_semicolon_ignored_for_dynamic_lines_after_import_issue_1178():
    """Test to ensure even if a semicolon is in the decorator in the line following an import
    the correct line spacing determination will be made.
    See: https://github.com/pycqa/isort/issues/1178.
    """
    assert isort.check_code(
        """
import pytest

@pytest.mark.skip(';')
def test_thing(): pass
""",
        show_diff=True,
    )

def test_isort_automatically_removes_duplicate_aliases_issue_1193():
    """Test to ensure isort can automatically remove duplicate aliases.
    See: https://github.com/pycqa/isort/issues/1281
    """
    assert isort.check_code("from urllib import parse as parse\n", show_diff=True)
    assert (
        isort.code("from urllib import parse as parse", remove_redundant_aliases=True)
        == "from urllib import parse\n"
    )
    assert isort.check_code("import os as os\n", show_diff=True)
    assert isort.code("import os as os", remove_redundant_aliases=True) == "import os\n"

def test_isort_enables_floating_imports_to_top_of_module_issue_1228():
    """Test to ensure isort will allow floating all non-indented imports to the top of a file.
    See: https://github.com/pycqa/isort/issues/1228.
    """
    assert (
        isort.code(
            """
import os

def my_function_1():
    pass

import sys

def my_function_2():
    pass
""",
            float_to_top=True,
        )
        == """
import os
import sys

def my_function_1():
    pass

def my_function_2():
    pass
"""
    )

    assert (
        isort.code(
            """
import os

def my_function_1():
    pass

# isort: split
import sys

def my_function_2():
    pass
""",
            float_to_top=True,
        )
        == """
import os

def my_function_1():
    pass

# isort: split
import sys

def my_function_2():
    pass
"""
    )

    assert (
        isort.code(
            """
import os

def my_function_1():
    pass

# isort: off
import b
import a
def y():
    pass

# isort: on
import b

def my_function_2():
    pass

import a
""",
            float_to_top=True,
        )
        == """
import os

def my_function_1():
    pass

# isort: off
import b
import a
def y():
    pass

# isort: on
import a
import b

def my_function_2():
    pass
"""
    )

def test_isort_provides_official_api_for_diff_output_issue_1335():
    """Test to ensure isort API for diff capturing allows capturing diff without sys.stdout.
    See: https://github.com/pycqa/isort/issues/1335.
    """
    diff_output = StringIO()
    isort.code("import b\nimport a\n", show_diff=diff_output)
    diff_output.seek(0)
    assert "+import a" in diff_output.read()

def test_isort_warns_when_known_sections_dont_match_issue_1331():
    """Test to ensure that isort warns if there is a mismatch between sections and known_sections.
    See: https://github.com/pycqa/isort/issues/1331.
    """
    assert (
        isort.place_module(
            "bot_core",
            config=Config(
                known_robotlocomotion_upstream=["bot_core"],
                sections=["ROBOTLOCOMOTION_UPSTREAM", "THIRDPARTY"],
            ),
        )
        == "ROBOTLOCOMOTION_UPSTREAM"
    )
    with pytest.warns(UserWarning):
        assert (
            isort.place_module(
                "bot_core",
                config=Config(
                    known_robotlocomotion_upstream=["bot_core"],
                    sections=["ROBOTLOOMOTION_UPSTREAM", "THIRDPARTY"],
                ),
            )
            == "THIRDPARTY"
        )
    with pytest.warns(UserWarning):
        assert (
            isort.place_module(
                "bot_core", config=Config(known_robotlocomotion_upstream=["bot_core"])
            )
            == "THIRDPARTY"
        )

def test_isort_supports_append_only_imports_issue_727():
    """Test to ensure isort provides a way to only add imports as an append.
    See: https://github.com/pycqa/isort/issues/727.
    """
    assert isort.code("", add_imports=["from __future__ import absolute_imports"]) == ""
    assert (
        isort.code("import os", add_imports=["from __future__ import absolute_imports"])
        == """from __future__ import absolute_imports

import os
"""
    )

    # issue 1838: don't append in middle of class
    assert isort.check_code(
        '''class C:
    """a

    """
    # comment
''',
        append_only=True,
        add_imports=["from __future__ import annotations"],
        show_diff=True,
    )

def test_isort_supports_shared_profiles_issue_970():
    """Test to ensure isort provides a way to use shared profiles.
    See: https://github.com/pycqa/isort/issues/970.
    """
    assert isort.code("import a", profile="example") == "import a\n"  # shared profile
    assert isort.code("import a", profile="black") == "import a\n"  # bundled profile
    with pytest.raises(exceptions.ProfileDoesNotExist):
        assert isort.code("import a", profile="madeupfake") == "import a\n"  # non-existent profile

def test_treating_comments_as_code_issue_1357():
    """Test to ensure isort provides a way to treat comments as code.
    See: https://github.com/pycqa/isort/issues/1357
    """
    assert (
        isort.code(
            """# %%
import numpy as np
np.array([1,2,3])

# %%
import pandas as pd
pd.Series([1,2,3])

# %%
# This is a comment on the second import
import pandas as pd
pd.Series([4,5,6])""",
            treat_comments_as_code=["# comment1", "# %%"],
        )
        == """# %%
import numpy as np

np.array([1,2,3])

# %%
import pandas as pd

pd.Series([1,2,3])

# %%
# This is a comment on the second import
import pandas as pd

pd.Series([4,5,6])
"""
    )
    assert (
        isort.code(
            """# %%
import numpy as np
np.array([1,2,3])

# %%
import pandas as pd
pd.Series([1,2,3])

# %%
# This is a comment on the second import
import pandas as pd
pd.Series([4,5,6])""",
            treat_comments_as_code=["# comment1", "# %%"],
            float_to_top=True,
        )
        == """# %%
import numpy as np
# This is a comment on the second import
import pandas as pd

np.array([1,2,3])

# %%
pd.Series([1,2,3])

# %%
pd.Series([4,5,6])
"""
    )
    assert (
        isort.code(
            """# %%
import numpy as np
np.array([1,2,3])

# %%
import pandas as pd
pd.Series([1,2,3])

# %%
# This is a comment on the second import
import pandas as pd
pd.Series([4,5,6])""",
            treat_all_comments_as_code=True,
        )
        == """# %%
import numpy as np

np.array([1,2,3])

# %%
import pandas as pd

pd.Series([1,2,3])

# %%
# This is a comment on the second import
import pandas as pd

pd.Series([4,5,6])
"""
    )
    assert (
        isort.code(
            """import b

# these are special imports that have to do with installing X plugin
import c
import a
""",
            treat_all_comments_as_code=True,
        )
        == """import b

# these are special imports that have to do with installing X plugin
import a
import c
"""
    )

def test_isort_allows_setting_import_types_issue_1181():
    """Test to ensure isort provides a way to set the type of imports.
    See: https://github.com/pycqa/isort/issues/1181
    """
    assert isort.code("from x import AA, Big, variable") == "from x import AA, Big, variable\n"
    assert (
        isort.code("from x import AA, Big, variable", constants=["variable"])
        == "from x import AA, variable, Big\n"
    )
    assert (
        isort.code("from x import AA, Big, variable", variables=["AA"])
        == "from x import Big, AA, variable\n"
    )
    assert (
        isort.code(
            "from x import AA, Big, variable",
            constants=["Big"],
            variables=["AA"],
            classes=["variable"],
        )
        == "from x import Big, variable, AA\n"
    )

def test_isort_enables_deduping_section_headers_issue_953():
    """isort should provide a way to only have identical import headings show up once.
    See: https://github.com/pycqa/isort/issues/953
    """
    isort_code = partial(
        isort.code,
        config=Config(
            import_heading_firstparty="Local imports.",
            import_heading_localfolder="Local imports.",
            dedup_headings=True,
            known_first_party=["isort"],
        ),
    )

    assert (
        isort_code("from . import something")
        == """# Local imports.
from . import something
"""
    )
    assert (
        isort_code(
            """from isort import y

from . import something"""
        )
        == """# Local imports.
from isort import y

from . import something
"""
    )
    assert isort_code("import os") == "import os\n"

def test_isort_doesnt_remove_as_imports_when_combine_star_issue_1380():
    """Test to ensure isort will not remove as imports along side other imports
    when requested to combine star imports together.
    See: https://github.com/PyCQA/isort/issues/1380
    """
    test_input = """
from a import a
from a import *
from a import b
from a import b as y
from a import c
"""
    assert (
        isort.code(
            test_input,
            combine_star=True,
        )
        == isort.code(test_input, combine_star=True, force_single_line=True)
        == isort.code(
            test_input,
            combine_star=True,
            force_single_line=True,
            combine_as_imports=True,
        )
        == """
from a import *
from a import b as y
"""
    )

def test_isort_support_custom_groups_above_stdlib_that_contain_stdlib_modules_issue_1407():
    """Test to ensure it is possible to declare custom groups above standard library that include
    modules from the standard library.
    See: https://github.com/PyCQA/isort/issues/1407
    """
    assert isort.check_code(
        """
from __future__ import annotations
from typing import *

from pathlib import Path
""",
        known_typing=["typing"],
        sections=["FUTURE", "TYPING", "STDLIB", "THIRDPARTY", "FIRSTPARTY", "LOCALFOLDER"],
        no_lines_before=["TYPING"],
        show_diff=True,
    )

def test_isort_intelligently_places_noqa_comments_issue_1456():
    assert isort.check_code(
        """
from my.horribly.long.import.line.that.just.keeps.on.going.and.going.and.going import (  # noqa
    my_symbol,
)
""",
        force_single_line=True,
        show_diff=True,
        multi_line_output=3,
        include_trailing_comma=True,
        force_grid_wrap=0,
        use_parentheses=True,
        line_length=79,
    )

    assert isort.check_code(
        """
from my.horribly.long.import.line.that.just.keeps.on.going.and.going.and.going import (
    my_symbol,
)
""",
        force_single_line=True,
        show_diff=True,
        multi_line_output=3,
        include_trailing_comma=True,
        force_grid_wrap=0,
        use_parentheses=True,
        line_length=79,
    )

    assert isort.check_code(
        """
from my.horribly.long.import.line.that.just.keeps.on.going.and.going.and.going import (  # noqa
    my_symbol
)
""",
        force_single_line=True,
        use_parentheses=True,
        multi_line_output=3,
        line_length=79,
        show_diff=True,
    )

    assert isort.check_code(
        """
from my.horribly.long.import.line.that.just.keeps.on.going.and.going.and.going import (
    my_symbol
)
""",
        force_single_line=True,
        use_parentheses=True,
        multi_line_output=3,
        line_length=79,
        show_diff=True,
    )

    # see: https://github.com/PyCQA/isort/issues/1415
    assert isort.check_code(
        "from dials.test.algorithms.spot_prediction."
        "test_scan_static_reflection_predictor import (  # noqa: F401\n"
        "    data as static_test,\n)\n",
        profile="black",
        show_diff=True,
    )

def test_isort_respects_quiet_from_sort_file_api_see_1461(capsys, tmpdir):
    """Test to ensure isort respects the quiet API parameter when passed in via the API.
    See: https://github.com/PyCQA/isort/issues/1461.
    """
    settings_file = tmpdir.join(".isort.cfg")
    custom_settings_file = tmpdir.join(".custom.isort.cfg")
    tmp_file = tmpdir.join("file.py")
    tmp_file.write("import b\nimport a\n")
    isort.file(tmp_file)

    out, error = capsys.readouterr()
    assert not error
    assert "Fixing" in out

    # When passed in directly as a setting override
    tmp_file.write("import b\nimport a\n")
    isort.file(tmp_file, quiet=True)
    out, error = capsys.readouterr()
    assert not error
    assert not out

    # Present in an automatically loaded configuration file
    settings_file.write(
        """
[isort]
quiet = true
"""
    )
    tmp_file.write("import b\nimport a\n")
    isort.file(tmp_file)
    out, error = capsys.readouterr()
    assert not error
    assert not out

    # In a custom configuration file
    settings_file.write(
        """
[isort]
quiet = false
"""
    )
    custom_settings_file.write(
        """
[isort]
quiet = true
"""
    )
    tmp_file.write("import b\nimport a\n")
    isort.file(tmp_file, settings_file=str(custom_settings_file))
    out, error = capsys.readouterr()
    assert not error
    assert not out

    # Reused configuration object
    custom_config = Config(settings_file=str(custom_settings_file))
    isort.file(tmp_file, config=custom_config)
    out, error = capsys.readouterr()
    assert not error
    assert not out

def test_isort_should_warn_on_empty_custom_config_issue_1433(tmpdir):
    """Feedback should be provided when a user provides a custom settings file that has no
    discoverable configuration.
    See: https://github.com/PyCQA/isort/issues/1433
    """
    settings_file = tmpdir.join(".custom.cfg")
    settings_file.write(
        """
[settings]
quiet = true
"""
    )
    with pytest.warns(UserWarning):
        assert not Config(settings_file=str(settings_file)).quiet

    settings_file.write(
        """
[isort]
quiet = true
"""
    )
    with pytest.warns(None) as warning:  # type: ignore
        assert Config(settings_file=str(settings_file)).quiet
    assert not warning

def test_float_to_top_should_respect_existing_newlines_between_imports_issue_1502():
    """When a file has an existing top of file import block before code but after comments
    isort's float to top feature should respect the existing spacing between the top file comment
    and the import statements.
    See: https://github.com/PyCQA/isort/issues/1502
    """
    assert isort.check_code(
        """#!/bin/bash
'''My comment'''

import a

x = 1
""",
        float_to_top=True,
        show_diff=True,
    )
    assert isort.check_code(
        """#!/bin/bash
'''My comment'''

import a

x = 1
""",
        float_to_top=True,
        show_diff=True,
    )
    assert (
        isort.code(
            """#!/bin/bash
'''My comment'''

import a

x = 1
""",
            float_to_top=True,
            add_imports=["import b"],
        )
        == """#!/bin/bash
'''My comment'''

import a
import b

x = 1
"""
    )

    assert (
        isort.code(
            """#!/bin/bash
'''My comment'''

def my_function():
    pass

import a
""",
            float_to_top=True,
        )
        == """#!/bin/bash
'''My comment'''
import a

def my_function():
    pass
"""
    )

    assert (
        isort.code(
            """#!/bin/bash
'''My comment'''

def my_function():
    pass
""",
            add_imports=["import os"],
            float_to_top=True,
        )
        == """#!/bin/bash
'''My comment'''
import os

def my_function():
    pass
"""
    )

def test_api_to_allow_custom_diff_and_output_stream_1583(capsys, tmpdir):
    """isort should provide a way from the Python API to process an existing
    file and output to a stream the new version of that file, as well as a diff
    to a different stream.
    See: https://github.com/PyCQA/isort/issues/1583
    """
    tmp_file = tmpdir.join("file.py")
    tmp_file.write("import b\nimport a\n")

    isort_diff = StringIO()
    isort_output = StringIO()

    isort.file(tmp_file, show_diff=isort_diff, output=isort_output)

    _, error = capsys.readouterr()
    assert not error

    isort_diff.seek(0)
    isort_diff_content = isort_diff.read()
    assert "+import a" in isort_diff_content
    assert " import b" in isort_diff_content
    assert "-import a" in isort_diff_content

    isort_output.seek(0)
    assert isort_output.read().splitlines() == ["import a", "import b"]

    # should still work with no diff produced
    tmp_file2 = tmpdir.join("file2.py")
    tmp_file2.write("import a\nimport b\n")

    isort_diff2 = StringIO()
    isort_output2 = StringIO()

    isort.file(tmp_file2, show_diff=isort_diff2, output=isort_output2)

    _, error = capsys.readouterr()
    assert not error

    isort_diff2.seek(0)
    assert not isort_diff2.read()

def test_autofix_mixed_indent_imports_1575():
    """isort should automatically fix import statements that are sent in
    with incorrect mixed indentation.
    See: https://github.com/PyCQA/isort/issues/1575
    """
    assert (
        isort.code(
            """
import os
  import os
  """
        )
        == """
import os
"""
    )
    assert (
        isort.code(
            """
def one():
    import os
import os
    """
        )
        == """
def one():
    import os

import os
"""
    )
    assert (
        isort.code(
            """
import os
    import os
        import os
    import os
import os
"""
        )
        == """
import os
"""
    )

def test_indented_import_headings_issue_1604():
    """Test to ensure it is possible to toggle import headings on indented import sections
    See: https://github.com/PyCQA/isort/issues/1604
    """
    assert (
        isort.code(
            """
import numpy as np

def function():
    import numpy as np
""",
            import_heading_thirdparty="External imports",
        )
        == """
# External imports
import numpy as np

def function():
    # External imports
    import numpy as np
"""
    )
    assert (
        isort.code(
            """
import numpy as np

def function():
    import numpy as np
""",
            import_heading_thirdparty="External imports",
            indented_import_headings=False,
        )
        == """
# External imports
import numpy as np

def function():
    import numpy as np
"""
    )

def test_isort_auto_detects_and_ignores_invalid_from_imports_issue_1688():
    """isort should automatically detect and ignore incorrectly written from import statements
    see: https://github.com/PyCQA/isort/issues/1688
    """
    assert (
        isort.code(
            """
from package1 import alright
from package2 imprt and_its_gone
from package3 import also_ok
"""
        )
        == """
from package1 import alright

from package2 imprt and_its_gone
from package3 import also_ok
"""
    )

def test_isort_allows_reversing_sort_order_issue_1645():
    """isort allows reversing the sort order for those who prefer Z or longer imports first.
    see: https://github.com/PyCQA/isort/issues/1688
    """
    assert (
        isort.code(
            """
from xxx import (
    g,
    hi,
    def,
    abcd,
)
""",
            profile="black",
            reverse_sort=True,
            length_sort=True,
            line_length=20,
        )
        == """
from xxx import (
    abcd,
    def,
    hi,
    g,
)
"""
    )

def test_isort_can_push_star_imports_above_others_issue_1504():
    """isort should provide a way to push star imports above other imports to avoid explicit
    imports from being overwritten.
    see: https://github.com/PyCQA/isort/issues/1504
    """
    assert (
        (
            isort.code(
                """
from ._bar import Any, All, Not
from ._foo import a, *
""",
                star_first=True,
            )
        )
        == """
from ._foo import *
from ._foo import a
from ._bar import All, Any, Not
"""
    )

def test_isort_can_combine_reverse_sort_with_force_sort_within_sections_issue_1726():
    """isort should support reversing import order even with force sort within sections turned on.
    See: https://github.com/PyCQA/isort/issues/1726
    """
    assert (
        isort.code(
            """
import blaaa
from bl4aaaaaaaaaaaaaaaa import r
import blaaaaaaaaaaaa
import bla
import blaaaaaaa
from bl1aaaaaaaaaaaaaa import this_is_1
from bl2aaaaaaa import THIIIIIIIIIIIISS_is_2
from bl3aaaaaa import less
""",
            length_sort=True,
            reverse_sort=True,
            force_sort_within_sections=True,
        )
        == """
from bl2aaaaaaa import THIIIIIIIIIIIISS_is_2
from bl1aaaaaaaaaaaaaa import this_is_1
from bl4aaaaaaaaaaaaaaaa import r
from bl3aaaaaa import less
import blaaaaaaaaaaaa
import blaaaaaaa
import blaaa
import bla
"""
    )

def test_isort_can_turn_off_import_adds_with_action_comment_issue_1737():
    assert (
        isort.code(
            """
import os
""",
            add_imports=[
                "from __future__ import absolute_imports",
                "from __future__ import annotations",
            ],
        )
        == """
from __future__ import absolute_imports, annotations

import os
"""
    )

    assert isort.check_code(
        """
# isort: dont-add-imports
import os
""",
        show_diff=True,
        add_imports=[
            "from __future__ import absolute_imports",
            "from __future__ import annotations",
        ],
    )

    assert (
        isort.code(
            """
# isort: dont-add-import: from __future__ import annotations
import os
""",
            add_imports=[
                "from __future__ import absolute_imports",
                "from __future__ import annotations",
            ],
        )
        == """
# isort: dont-add-import: from __future__ import annotations
from __future__ import absolute_imports

import os
"""
    )

def test_sort_configurable_sort_issue_1732() -> None:
    """Test support for pluggable isort sort functions."""
    test_input = (
        "from bob2.apples2 import aardvark as aardvark2\n"
        "from bob.apples import aardvark \n"
        "import module9\n"
        "import module10\n"
        "import module200\n"
    )
    assert isort.code(test_input, sort_order="native") == (
        "import module10\n"
        "import module200\n"
        "import module9\n"
        "from bob.apples import aardvark\n"
        "from bob2.apples2 import aardvark as aardvark2\n"
    )
    assert (
        isort.code(test_input, sort_order="natural")
        == isort.code(test_input)
        == (
            "import module9\n"
            "import module10\n"
            "import module200\n"
            "from bob2.apples2 import aardvark as aardvark2\n"
            "from bob.apples import aardvark\n"
        )
    )
    assert (
        isort.code(test_input, sort_order="natural_plus")
        == isort.code(test_input)
        == (
            "import module9\n"
            "import module10\n"
            "import module200\n"
            "from bob2.apples2 import aardvark as aardvark2\n"
            "from bob.apples import aardvark\n"
        )
    )
    with pytest.raises(exceptions.SortingFunctionDoesNotExist):
        isort.code(test_input, sort_order="round")

def test_cython_pure_python_imports_2062():
    """Test to ensure an import form a cython.cimports remains import, not cimport.
    See: https://github.com/pycqa/isort/issues/2062.
    """
    assert isort.check_code(
        """
import cython
from cython.cimports.libc import math

def use_libc_math():
    return math.ceil(5.5)
""",
        show_diff=True,
    )


#menggunakan library numpy sebagai operasi matrix
import numpy as nump

#fungsi iTerminal digunakan untuk input matrix dari Terminal
def iTerminal():
    print('================================')
    n=int(input("Masukkan ukuran Matriks : "))
    a=nump.zeros((n,n),float)
    b=nump.zeros(n,float)
    print("================================")
    print("Masukkan Matriks A : ")
    for i in range (n):
        for j in range(n):
            a[i][j]=float(input("[Baris %d][Kolom %d] = " %(i+1,j+1)))
    print("Matriks A")
    print (a)
    print("================================")
    print("Masukkan Matriks B : ")
    for i in range (n):
        b[i]=float(input("b[%d] = " %(i+1)))

    return a,b

#Fungsi iFile digunakan untuk menginput matrix dari file
#Edit file iMatrixA.txt dan iMatrixB.txt jika ingin mengganti isi matrix
def iFile():
    a = nump.loadtxt("bin\iMatrixA.txt", dtype='f', delimiter=' ')
    #dtype untuk menafsirkan blok memori berukuran tetap dalam array, f sebagai floating point
    #delimiter sebagai pemisah sesuai yang diberikan
    b = nump.loadtxt("bin\iMatrixB.txt", dtype='f', delimiter=' ')
    return a,b

#Fungsi SPL Gauss
def gauss():
    a,b=menuInput()
    n=len(b) #menentukan panjang input var b
    A=nump.column_stack((a,b))
    x=nump.zeros(n,float)

    #Eliminasi Pivoting
    for i in range(0, n):
       # Mencari kolom dengan nilai Maximal
       maxE = abs(A[i][i])
       maxBar = i
       for k in range(i+1, n):
           # mengecek perbaris dan baris pertama tidak boleh 0
           if abs(A[k][i]) < maxE or maxE == 0:
               maxE = abs(A[k][i])
               maxBar = k
       # menukar baris terakhir dengan baris bernilai 0 dilakukan kolom per kolom
       for k in range(i, n+1):
           tmp = A[maxBar][k]
           A[maxBar][k] = A[i][k]
           A[i][k] = tmp
       # membuat semua baris dibawah 1 utama menjadi nilai 0
       for k in range(i+1, n):
           c = -A[k][i]/A[i][i]
           for j in range(i, n+1):
               if i == j:
                   A[k][j] = 0
               else:
                   A[k][j] = A[k][j] + c * A[i][j]

    #Melakukan subtitusi mundur

    for i in range(n-1, -1, -1):
        if A[i][i] == 0:
            return [0 for i in range(n)]
        else:
            x[i] = A[i][n]/A[i][i]
            for k in range(i-1, -1, -1):
                A[k][n] = A[k][n] - A[k][i]*x[i]
    a,b=nump.hsplit(A,[n])
    return a,x

#Fungsi gauss-Jordan
def gaussJordan():
    a,b=menuInput()
    n=len(b)

    for i in range(n):
        #Pivoting
        if nump.fabs(a[i,i]) == 0:
            for j in range(i+1,n):
                if nump.fabs(a[j,i]) > nump.fabs(a[i,i]):
                    for k in range(i,n):
                        a[i,k],a[j,k] = a[j,k],a[i,k]
                    b[i],b[j] = b[j],b[i]
                    break

        pivot = a[i,i]
        for j in range(i,n):
            a[i,j] /= pivot
        b[i] /= pivot

        #Substitusi
        for j in range(n):
            if j == i or a[j,i] == 0: continue
            factor = a[j,i]
            for k in range(i,n):
                a[j,k] -= factor * a[i,k]
            b[j] -= factor*b[i]
    return a,b

#Fungsi ini untuk mengecek apakah tidak ada solusi atau memiliki banyak solusi
def Hasil(A,B):
    i=len(B)-1

    #jika tidak ada solusi/ memiliki banyak solusi maka program menampilakan pesan
    #hasil yang bukan solusi tunggal/unik
    if nump.all(nump.isinf(B)):
        print('Hasil Eliminasi :\nTidak ada Solusi')
        #Menyimpan output kedalam file
        with open('bin\output.txt', 'a') as out:
            print('Hasil Eliminasi :\nTidak ada Solusi',file=out) #pesan yang ditampilkan
            print('================================================',file=out)
        return

    elif nump.all(nump.isnan(B)):
        print('Hasil Eliminasi :\nMemiliki Banyak solusi') #pesan yang ditampilkan
        #Menyimpan output kedalam file
        with open('bin\output.txt', 'a') as out:
            print('Hasil Eliminasi :\nMemiliki Solusi Banyak',file=out)
            print('================================================',file=out)
        return

    #Syntax dibawah berjalan karena matrix memiliki solusi dan tidak memiliki banyak solusi
    print("================================")
    print("Matrix setelah OBE : ")
    print(A)
    print("================================")
    print("Hasil Eliminasi  : ")
    for j in range(len(B)):
        print("X%d = %0.1f" %(j+1,B[j]) , end='\n')
    print("================================")

    #menyimpan hasil ke file output.txt
    with open('bin\output.txt', 'ab') as out:
        nump.savetxt(out,A,fmt='%0.1f',delimiter=' ',header='Matrix Setelah OBE')
        nump.savetxt(out,B,fmt='%0.1f',delimiter='\n',header='Hasil Eliminasi',footer='=========================================================')

#Index Menu merupakan menu awal yang ditampilkan di layar
def Indexmenu():
    print('================================')
    print('          Program')
    print('   Gauss & Gauss Jordan')
    print('================================')
    print('        Pilih Menu Index')
    print('1). SPL Gauss')
    print('2). SPL Gauss Jordan')
    print('999). Hentikan Program')
    switch=int(input('Input Angka : '))
    if switch==999:
        print('Program Dihentikan!')
        exit()
    elif switch==1 :
        a,b = gauss()
    elif switch==2 :
        a,b = gaussJordan()
    else:
        print('Inputan tidak ada dalam List!')
        Indexmenu()
    return a,b

#Pemilihan input menu
def menuInput():
    print('================================')
    print('        Pilih Cara Input')
    print('1). Input dari Terminal')
    print('2). Input dari File')
    print('999). Hentikan Program')
    switch=int(input('Input Angka : '))

    if switch==999:
        print('Program Dihentikan!')
        exit()
    elif(switch==1):
        a,b = iTerminal()
    elif(switch==2):
        a,b = iFile()
    else:
        print('Inputan tidak ada dalam List! ')
        menuInput()
    return a,b

#Program mulai !!
A,X = Indexmenu()
Hasil(A,X)


import unittest
import wx
import os
import sys
from mockito import mock
from nose.tools import assert_equal, assert_true

from robotide.robotapi import Variable
from robotide.controller import DataController
from robotide.controller.robotdata import NewTestCaseFile
from robotide.controller.settingcontrollers import VariableController
from robotide.controller.tablecontrollers import VariableTableController
from robotide.editor import EditorCreator
from robotide.editor.editors import TestCaseFileEditor, WelcomePage
# Workaround for relative import in non-module
# see https://stackoverflow.com/questions/16981921/relative-imports-in-python-3
PACKAGE_PARENT = '..'
SCRIPT_DIR = os.path.dirname(os.path.realpath(os.path.join(os.getcwd(),
                                              os.path.expanduser(__file__))))
sys.path.append(os.path.normpath(os.path.join(SCRIPT_DIR, PACKAGE_PARENT)))
try:
    from fakeplugin import FakePlugin
except ImportError:  # Python 3
    from .fakeplugin import FakePlugin

from resources import PYAPP_REFERENCE

DATADIR = 'fake'
DATAPATH = '%s/path' % DATADIR
TestCaseFileEditor._populate = lambda self: None

class EditorCreatorTest(unittest.TestCase):

    def setUp(self):
        self._registered_editors = {}
        self.creator = EditorCreator(self._register)
        self.creator.register_editors()

    def tearDown(self):
        if os.path.exists(DATADIR):
            os.rmdir(DATADIR)

    def _register(self, iclass, eclass):
        self._registered_editors[iclass] = eclass

    def test_registering_editors_for_model_objects(self):
        assert_equal(len(self._registered_editors), len(self.creator._EDITORS))

    def test_creating_editor_for_datafile_controller(self):
        plugin = self._datafile_plugin()
        editor = self._editor_for(plugin)
        assert_true(isinstance(editor, TestCaseFileEditor))

    def _editor_for(self, plugin):
        return self.creator.editor_for(plugin, wx.Frame(None), None)

    def test_creating_editor_with_variable(self):
        plugin = self._variable_plugin()
        editor = self._editor_for(plugin)
        assert_true(isinstance(editor, TestCaseFileEditor))

    def test_creating_welcome_page_when_no_item(self):
        plugin = self._no_item_selected_plugin()
        editor = self._editor_for(plugin)
        assert_true(isinstance(editor, WelcomePage))

    def test_same_welcome_page_editor_instance_is_returned_if_called_multiple_times(self):
        plugin = self._no_item_selected_plugin()
        editor = self._editor_for(plugin)
        editor2 = self._editor_for(plugin)
        assert_equal(editor, editor2)

    def test_same_testcasefile_editor_instance_is_returned_if_called_multiple_times(self):
        plugin = self._variable_plugin()
        editor = self._editor_for(plugin)
        editor2 = self._editor_for(plugin)
        assert_equal(editor, editor2)

    def test_editor_is_recreated_when_controller_changes(self):
        p1 = self._datafile_plugin()
        p2 = self._datafile_plugin()
        e1 = self._editor_for(p1)
        e2 = self._editor_for(p2)
        assert_true(e1 is not e2)

    def test_editor_is_destroyed_when_new_is_created(self):
        ed = self._datafile_editor()
        ed.destroy = mock()
        self._datafile_editor()
        assert_true(ed.destroy.called)

    def _datafile_editor(self):
        return self.creator.editor_for(self._datafile_plugin(),
                                       wx.Frame(None), None)

    def _datafile_plugin(self):
        return FakePlugin(self._registered_editors,
                          self._datafile_controller())

    def _variable_plugin(self):
        return FakePlugin(self._registered_editors,
                          VariableController(VariableTableController(
                              self._datafile_controller(), None),
                              Variable(None, '','')))

    def _no_item_selected_plugin(self):
        return FakePlugin(self._registered_editors, None)

    def _datafile_controller(self):
        return DataController(NewTestCaseFile(DATAPATH), None)


# 测试VOC2007数据集的读取
import cv2
import numpy as np
import os
import pandas as pd
import torch
import albumentations as A

from PIL import Image, ImageFile
from torch.utils.data import Dataset, DataLoader

ImageFile.LOAD_TRUNCATED_IMAGES = True

class YOLODataset(Dataset):
    def __init__(
        self,
        csv_file,
        img_dir,
        label_dir,
        image_size=416,
        transforms=None,
    ):
        self.annotations = pd.read_csv(csv_file)
        self.img_dir = img_dir
        self.label_dir = label_dir
        self.image_size = image_size
        self.transform = transforms

    def __len__(self):
        return len(self.annotations)

    def __getitem__(self, index):
        label_path = os.path.join(self.label_dir, self.annotations.iloc[index, 1])
        # 改变labels信息排列
        bboxes = np.roll(np.loadtxt(fname=label_path, delimiter=" ", ndmin=2), 4, axis=1).tolist()
        img_path = os.path.join(self.img_dir, self.annotations.iloc[index, 0])
        image = cv2.imread(img_path)

        # 图像格式转换
        if self.transform:
            image = self.transform(image=image)['image']
        bboxes = np.array(bboxes)
        return image, bboxes # [3,416,416] (0/1，x, y, w, h, classes)等

def test():
    transforms = A.Compose(
        [
            # 保持宽高比缩放图片，使最大边等于max_size,即IMAGE_SIZE
            A.LongestMaxSize(max_size=416),
            # padding填充图像
            A.PadIfNeeded(
                min_height=416, min_width=416, border_mode=cv2.BORDER_CONSTANT
            ),
            A.Normalize(mean=[0, 0, 0], std=[1, 1, 1], max_pixel_value=255, ),
            #ToTensorV2(),
        ],
        # bounding box参数检查
        #bbox_params=A.BboxParams(format="pascal_voc", min_visibility=0.4, label_fields=[]),
    )
    dataset = YOLODataset(
        csv_file="./VOC2007/train.csv",
        img_dir="./VOC2007/JPEGImages/",
        label_dir="./VOC2007/Labels/",
        transform=transforms,
    )
    loader = DataLoader(dataset=dataset, batch_size=1, shuffle=False)
    for batch_idx, (x, y) in enumerate(loader):         # iamge 和 三个不同的特征图
        print(y)

if __name__ == '__main__':
    test()


import socket

addr = ('localhost', 8001)

cli = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
cli.connect(addr)
cli.send(bytearray("something",'utf-8'))

reply = cli.recv(4096)

cli.close()
print(reply)


from tqdm import tqdm
import json
import os

lang = 'fortran'

rel_constrcuts = ['do' if lang == 'fortran' else 'for']
rel_clauses = ['private', 'reduction', 'simd', '_']

data_dir = '/home/1010/talkad/Downloads/OMP_Dataset/fortran/source'

counter = {construct:{clause:0 for clause in rel_clauses} for construct in rel_constrcuts}

for file in [os.path.join(data_dir, 'total_uniq.jsonl')]:

    with open(os.path.join(data_dir, file), 'r') as f:
        for line in tqdm(f):
            js = json.loads(line.strip())

            clauses = js['pragma'].split()
            clauses_key = [clause[:clause.find('(')] if '(' in clause else clause for clause in clauses]

            for k,v in counter.items():
                if k in clauses_key:
                    counter[k]['_'] += 1

                for vv in v:
                    if k in clauses_key and vv in clauses_key:
                        counter[k][vv] += 1

    print(counter)

# fortran: {'do': {'private': 422, 'reduction': 51, 'simd': 5, '_': 1062}}
# c: {'for': {'private': 1035, 'reduction': 216, 'simd': 122, '_': 3351}}
# cpp: {'for': {'private': 509, 'reduction': 431, 'simd': 171, '_': 5220}}


import sys
from bzrlib import branch
from bzrlib.lazy_import import lazy_import
lazy_import(globals(), """
import urllib
from bzrlib import builtins, errors, option
""")

LINUX = sys.platform.startswith('linux')
WINDOWS = sys.platform.startswith('win')

def master_to_path(master):
    path = urllib.unquote(master.base.replace('file://', ''))
    if WINDOWS:
        path = path.lstrip('/').replace('/', '\\')
    return path

def pre_commit_hook(local, master, old_revno, old_revid, future_revno,
        future_revid, tree_delta, future_tree):
    """This hook will execute precommit script from root path of the bazaar
    branch. Commit will be canceled if precommit fails."""

    # bzr requires that modules are imported inside the hook
    import os
    import subprocess
    import time
    import urllib

    # initialize time
    time_start = time.time()

    # initializes paths
    current_dir = os.getcwd()
    master_dir = master_to_path(master)
    test_dir = os.path.join(master_dir, 'tests')
    phatch_dir = os.path.join(master_dir, 'phatch')

    if not os.path.exists(phatch_dir):
        # Ignore other projects other than Phatch
        return

    # Ensure to undo the directory change
    def exit(error=None):
        os.chdir(current_dir)
        print('\nRan precommit tests in %.3fs\n' % (time.time() - time_start))
        if error:
            raise errors.BzrError(
                'Unable to commit, because %s test failed.' % error)

    os.chdir(test_dir)

    # Use subprocesses so exceptions can't mess with the state
    print(' ' * 80)

    if LINUX and subprocess.call(['python', 'license_test.py']):
        exit('license')

    if not WINDOWS and subprocess.call(['python', 'doc_test.py']):
        exit('doctest')

    print('-' * 70)

    if subprocess.call(['python', 'pep8_test.py']):
        exit('PEP8')

    exit()

branch.Branch.hooks.install_named_hook('pre_commit', pre_commit_hook,
    'Check pre_commit hook')


# -*- coding: utf-8 -*-
"""
Created on Sun Nov 10 15:10:01 2019

@author: Rajdeep
@author: Mtajic
"""

import pydotplus
import numpy as np

import matplotlib.pyplot as plt

from sklearn import svm, tree, datasets
from sklearn.utils import shuffle
from sklearn.metrics import confusion_matrix, classification_report
from sklearn.externals.six import StringIO
from sklearn.model_selection import cross_validate

from skimage import io
from skimage.filters import gaussian
from skimage.transform import resize

from IPython.display import SVG, display
from graphviz import Source
from ipywidgets import interactive

from IPython.display import Image
from sklearn.tree import export_graphviz

from IPython.display import Image

class DataSet:
    def __init__(self, inputs=None, targets=None):
        self.inputs = [] if inputs is None else inputs
        self.targets = [] if targets is None else targets

if __name__ == '__main__':
    dataset = DataSet()
    print('Loading Training Data...')
    labels = ['01_palm', '02_l', '03_fist', '04_fist_moved', '05_thumb',
              '06_index', '07_ok', '08_palm_moved', '09_c', '10_down', ]

    # TODO: need to shuffle data before partitioning
    # 75% to train
    for i in range(10):
        for label in labels:
            for j in range(1, 151):  # 201):
                label.split()
                image = io.imread('data/leapGestRecog/0' +
                                  str(i) + '/' +
                                  label + '/frame_0' +
                                  str(i) + '_' +
                                  label[0:2] + '_' +
                                  str(j).zfill(4) + '.png')
                # TODO: should we flatten or resize here?
                img_blurred = gaussian(image, sigma=1.65)
                dataset.inputs.append(resize(img_blurred, (60, 160), preserve_range=True).flatten())
                dataset.targets.append(label)

    # shuffle data
    x_train, y_train = shuffle(dataset.inputs, dataset.targets)

    # Model Selection

    print('Model Selection...')
    testScores = {}
    myMaxScore = 0
    bestFunctionPrameters = ""
    clf_cv5 = ""
    for i in [6, 7, 8, 9, 10]:
        for j in ["gini", "entropy"]:
            clf = tree.DecisionTreeClassifier(criterion=j, random_state=100, max_depth=i, max_features=240)

            # perform 5-fold cross validation for each model
            scores = cross_validate(clf, x_train, y_train, scoring='precision_macro', cv=5, return_estimator=True)
            testScores[j + "_" + str(i)] = scores["test_score"]
            myScore = np.max(scores["test_score"], axis=0)
            print(j + "_" + str(i), " Score: ", str(myScore))
            if myScore > myMaxScore:
                clf_cv5 = scores["estimator"][np.argmax(scores["test_score"], axis=0)]
                myMaxScore = myScore
                bestFunctionPrameters = j + "_" + str(i)

    # Training
    print('Training...')
    bst_dt = clf_cv5

    labels = ['01_palm', '02_l', '03_fist', '04_fist_moved', '05_thumb',
              '06_index', '07_ok', '08_palm_moved', '09_c', '10_down', ]
    print('Loading Testing Data...')

    # 25% to test
    test_data = DataSet()
    for i in range(10):
        for label in labels:
            for j in range(151, 201):  # 1, 201):
                label.split()
                image = io.imread('data/leapGestRecog/0' +
                                  str(i) + '/' +
                                  label + '/frame_0' +
                                  str(i) + '_' +
                                  label[0:2] + '_' +
                                  str(j).zfill(4) + '.png')
                img_blurred = gaussian(image, sigma=1.65)
                test_data.inputs.append(resize(img_blurred, (60, 160), preserve_range=True).flatten())
                test_data.targets.append(label)

    print('Testing...')
    predicted = bst_dt.predict(test_data.inputs)
    print("\nClassification Report")

    print(classification_report(test_data.targets, predicted))
    print("\nConfusion Matrix")
    print(confusion_matrix(test_data.targets, predicted))

    # Visualizing the Decision Tree Graph
    print('Visualizing the Decision Tree Graph')

    dot_data = StringIO()
    tree.export_graphviz(bst_dt, out_file=dot_data
                         , feature_names=[f"X{i},{j}" for i in range(60) for j in range(160)]
                         , class_names=['01_palm', '02_l', '03_fist', '04_fist_moved', '05_thumb',
                                        '06_index', '07_ok', '08_palm_moved', '09_c', '10_down', ]
                         , filled=True, rounded=True
                         , special_characters=True)

    graph = pydotplus.graph_from_dot_data(dot_data.getvalue())
    Image(graph.create_png())

    # creating the box plot for model-selection
    s = testScores.values()
    labels = testScores.keys()

    fig = plt.figure(figsize=(8, 6))

    plt.boxplot([x for x in s], 0, '', 1)
    plt.xticks([y + 1 for y in range(len([x for x in s]))], labels, rotation=70)
    plt.xlabel('Models(metric and max depth)')
    plt.ylabel('Accuracy')
    t = plt.title('Box plot of HyperParameters with 5-fold cross validation')
    plt.show()


from pygame import *
import random

init()

screen_width = 1200
screen_height = 800
screen = display.set_mode((screen_width,screen_height))
display.set_caption("ping-pong virus")

bg = image.load("e:/dev/python_workspace/img/bg.jpg")
bg = transform.scale(bg,(1200,800))

ball = image.load("e:/dev/python_workspace/img/lotto/ball7.png")
bx = 580
by =700

inc_x = random.randint(-10,50)
inc_y = random.randint(-10,50)

def changeDirection(x,y,ix,iy):
    if y<=3 or y>=770:
        iy = -iy
    if x<=3 or x>=1170:
        ix = -ix
    return ix, iy

isRunning = True
while isRunning:

    bx -= inc_x
    by -= inc_y

    inc_x, inc_y = changeDirection(bx,by,inc_x,inc_y)

    screen.blit(bg,(0,0))
    screen.blit(ball,(bx,by))

    for e in event.get():
        if e.type == QUIT:
            isRunning = False

    display.update()

quit()


import webapp2
import jinja2
import os
from google.appengine.ext import ndb
from twilio.rest import TwilioRestClient
from time import time
import json
import logging
from common import make_template
from private import account_sid, auth_token

class User(ndb.Model):
    """Model for the user db"""
    fullname = ndb.StringProperty(indexed=True)
    phone_number = ndb.StringProperty(indexed=True)
    phone_worker = ndb.BooleanProperty()
    can_text = ndb.BooleanProperty()
    PAB = ndb.BooleanProperty()

class Call(ndb.Model):
    """model for the calls db"""
    calls = ndb.TextProperty(indexed=False)

JINJA_ENVIRONMENT = jinja2.Environment(
    loader=jinja2.FileSystemLoader(os.path.dirname(__file__)),
    extensions=['jinja2.ext.autoescape'],
    autoescape=True)

class NewCall(webapp2.RequestHandler):
    """This gives a page to make a call to any specified users"""
    def get(self):
        template_values = make_template(self)

        info = ndb.gql("SELECT * FROM User")
        user_list = []
        for i in info:
            to_append = {}
            to_append['fullname'] = i.fullname
            to_append['phone_number'] = i.phone_number
            to_append['can_text'] = "disabled" if (i.can_text==False) else ""
            user_list.append(to_append)
        template_values['user_list'] = user_list

        template = JINJA_ENVIRONMENT.get_template('newcall.jinja')
        self.response.write(template.render(template_values))

class MakeCall(webapp2.RequestHandler):
    """Actually does call and text type stuff.  Yay."""
    def get(self):
        template_values = make_template(self)
        if template_values['admin']:
            client = TwilioRestClient(account_sid, auth_token)

            to_text = self.request.get_all('text')
            if self.request.get('PAB_text')=="on":
                info = ndb.gql("SELECT * FROM User WHERE PAB=True")
                for i in info:
                    if i.can_text and i.fullname not in to_text:
                        to_text.append(i.fullname)
            if self.request.get('ALL_text')=="on":
                info = ndb.gql("SELECT * FROM User WHERE can_text=True")
                for i in info:
                    if i.fullname not in to_text:
                        to_text.append(i.fullname)
            for i in to_text:
                infos = User.query(User.fullname==i).fetch(1, projection=[User.phone_number])
                for info in infos:
                    message_out = client.messages.create(to=info.phone_number, from_='2065576875', body=self.request.get('smstext'))
                    logging.debug(message_out)

            call_id=int(time())
            call = Call(key=ndb.Key(Call, call_id))
            to_call = []
            for i in self.request.get_all('call'):
                info = ndb.gql("SELECT * FROM User WHERE fullname=:1", i)
                for i in info:
                    to_call.append(i.phone_number)
            if self.request.get('PAB_call')=="on":
                info = ndb.gql("SELECT * FROM User WHERE PAB=True")
                for i in info:
                    if i.phone_number not in to_call:
                        to_call.append(i.phone_number)
            if self.request.get('ALL_call')=='on':
                info = ndb.gql("SELECT * FROM User")
                for i in info:
                    if i.phone_number not in to_call:
                        to_call.append(i.phone_number)
            call.calls = str(json.dumps(to_call))
            call_id = call.put()
            call_id = call_id.id()
            call_out = client.calls.create(to=self.request.get('your_phone'),
                                       from_='2065576875',
                                       url='https://teen-link.appspot.com/twiml?to_call=%s' % (str(call_id)),
                                       method='GET')
            logging.debug(call_out)
        template = JINJA_ENVIRONMENT.get_template('makecall.jinja')
        self.response.write(template.render(template_values))

app = webapp2.WSGIApplication([
                               ('/action/newcall', NewCall),
                               ('/action/makecall', MakeCall)],
                              debug=True)


totalequity=0
equitysharecapital=0
reservesandsurplus=0
preferredequity=0
totaldebt=0
shorttermdebt=0
longtermdebt=0

print("CALCULATING DEBT TO EQUITY RATIO:")
print("PROVIDE THE EQUITY VALUES")
equitysharecapital=float(input("ENTER EQUITY SHARE CAPITAL"))
reservesandsurplus=float(input("ENTER RESERVESAND SURPLUS:"))
preferredequity=float(input("ENTER PREFERRED EQUITY:"))
print("PROVIDE THE DEBT VALUES")
shorttermdebt=float(input("ENTER SHORT TERM DEBT:"))
longtermdebt=float(input("ENTER LONG TERM DEBT:"))

totalequity=equitysharecapital+reservesandsurplus+preferredequity
totaldebt=shorttermdebt+longtermdebt
print("DEBT TO EQUITY RATIO:",totaldebt/totalequity)


import json
import psycopg2
import os

def lambda_handler(event, context):
    user = event['request']['userAttributes']
    print('userAttributes')# for debugging
    print(user)# for debugging

    try:
      print('entered-try') # for debugging
      sql = """
         INSERT INTO public.users (
          display_name,
          email,
          handle,
          cognito_user_id
          )
        VALUES(
            %(user_display_name)s,
            %(user_emails)s,
            %(user_handle)s,
            %(user_cognito_id)s
            )
      """
      print('SQL Statement ----')# for debugging
      print(sql)# for debugging
      conn = psycopg2.connect(os.getenv('CONNECTION_URL'))
      cur = conn.cursor()
      params = {
        'user_display_name' : user['name'],
        'user_emails' : user['email'],
        'user_handle' : user['preferred_username'],
        'cognito_user_id' : user['sub']
      }
      cur.execute(sql, params)
      conn.commit()

    except (Exception, psycopg2.DatabaseError) as error:
      print(error)
    finally:
      if conn is not None:
          cur.close()
          conn.close()
          print('Database connection closed.')
    return event


import math
import re
from math import *  # noqa: F401, F403

from sympy import Eq, solve, symbols

from .calculate import Calculate

def Solve(equations_str):
    try:
        equations_str = equations_str.replace(' ', '')
        equations_ori = re.split(r'[,;]+', equations_str)
        equations_str = equations_str.replace('^', '**')
        equations_str = re.sub(r'(\(.*\))([a-zA-Z])', r'\1 * \2',
                               equations_str)
        equations_str = re.sub(r'(\d+)([a-zA-Z])', r'\1 * \2', equations_str)
        equations_str = equations_str.replace('pi', str(math.pi))
        equations = re.split(r'[,;]+', equations_str)
        vars_list = list(set(re.findall(r'[a-zA-Z]+', equations_str)))
        vars = {var: symbols(var) for var in vars_list}

        output = ''
        eqs = []
        for eq in equations:
            if '=' in eq:
                left, right = eq.split('=')
                eqs.append(
                    Eq(
                        eval(left.strip(), {}, vars),
                        eval(right.strip(), {}, vars)))
        solutions = solve(eqs, vars, dict=True)

        vars_values = {var: [] for var in vars_list}
        if isinstance(solutions, list):
            for idx, solution in enumerate(solutions):
                for var, sol in solution.items():
                    output += f'{var}_{idx} = {sol}\n'
                    vars_values[str(var)].append(sol)
        else:
            for var, sol in solutions.items():
                output += f'{var} = {sol}\n'
                vars_values[str(var)].append(sol)
        for eq, eq_o in zip(equations, equations_ori):
            if '=' not in eq:
                for var in vars_list:
                    need_note = True if len(vars_values[var]) > 1 else False
                    for idx, value in enumerate(vars_values[var]):
                        eq_to_calc = eq.replace(var, str(value))
                        calc_result = Calculate(eq_to_calc)
                        if need_note:
                            eq_name = eq_o.replace(var, f'{var}_{idx}')
                        else:
                            eq_name = eq_o
                        if calc_result != 'No results.':
                            output += f'{eq_name} = {calc_result}\n'

        return output.strip()
    except Exception:
        return 'No result.'


import os,sys
import numpy as np
import cv2,time
import re
data_dir = '/home/sjhbxs/code/ICDAR_TASK2_new1/train_data/out'
i = 0
for root, sub_folder, file_list in os.walk(data_dir):
            for file_path in file_list:
                try:
                    Olddir=os.path.join(root,file_path);
                    i = 1
                    if os.path.isdir(Olddir):
                        continue;
                    i = 2
                    filename=os.path.splitext(file_path)[0];
                    i = 3
                    filetype=os.path.splitext(file_path)[1];
                    i = 4
                    new_filename = '111_' + re.sub('[\r\n\t]', '',filename)
                    i = 5
                    Newdir=os.path.join(root, new_filename+filetype);
                    i = 6
                    os.rename(Olddir,Newdir);
                except:
                    print("wrong!!!",i)


# 新建登录测试类,继承 unittest.Testcase
import unittest

from parameterized import parameterized

from base.get_driver import GetDriver
from page.page_login import PageLogin

# from base.base import base_click
from tools.read_txt import read_txt
from base.get_logger import GetLogger

log = GetLogger().get_logger()

def get_data():
    # 逆向,正向
    # return [("13800138003", "123456", "8888", "账号不存在!", False,),
    #         ("13800138006", "123456", "8888", "", True,)]
    # return [("13800138003", "123456", "8888", "账号不存在!", False,)]
    arrs = []
    for data in read_txt("login.txt"):
        # 列表添加元组
        arrs.append(tuple(data.strip().split(",")))
    # 返回列表下标为1之外的所有元素
    return arrs[2:]

class TestLogin(unittest.TestCase):
    driver = None
    login = None

    @classmethod
    def setUpClass(cls):
        try:
            # 实例化并获取driver
            cls.driver = GetDriver().get_driver()
            # 操作都封装在 PageLogin 类中,先实例化
            cls.login = PageLogin(cls.driver)
            # 点击登录链接 (放在这里很重要,无论正向,逆向 先后 都可以走)
            cls.login.page_click_login_link()
        except Exception as e:
            log.error("错误:", e)

    @classmethod
    def tearDownClass(cls):
        # 关闭driver 驱动对象
        GetDriver().quit_driver()

    # 第三个方法,  新建登录测试方法
    @parameterized.expand(get_data())
    def test_login(self, username, pwd, verify_code, expect_result, status):
        try:
            # 调用组合业务方法
            # @parameterized.expand(username,pwd,verify_code)
            self.login.page_login(username, pwd, verify_code)
            # 判断正向:
            # 根据文本文件中的状态字符串判断
            if status == "true":
                #     断言
                # print(self.login.page_if_login_success())
                self.assertTrue(self.login.page_if_login_success())
                #     点击安全退出
                self.login.page_click_logout_link()
                #     点击登录链接
                self.login.page_click_login_link()
            # 判断逆向:
            else:
                #     获取错误信息
                msg = self.login.page_get_error_msg()
                print(msg)
                # 点击弹窗确定按钮
                self.login.page_click_error_alert()
                try:
                    self.assertEqual(msg, expect_result)
                except Exception as e:
                    # 出错的地方,都需要 log.error
                    log.error("错误:", e)
                    self.login.base_get_screen_shot()
        except Exception as e:
            log.error("错误:", e)
            self.login.base_get_screen_shot()

        # 无论正向,逆向 先后 都可以走


import os
import re
import psutil
from time import process_time
import csv

# Start time
startTime = process_time()

#variable for unique list of words that was replace
uniqueWord = []
#variable for no. of times a word replace
wordFrequency = []

def createRequiredWordDictionary(enWord, frWord):
    """function to create french dictionary for only find words """
    dictionary_dict = {}
    if(enWord == frWord.split(",")[0]):
        dictionary_dict[enWord] = frWord.split(",")[1]
    return dictionary_dict

def readFile(file):
    """ read convert english words text file """
    findWordFile = open(file, "r")
    enlines = findWordFile.read()
    listOfLines = enlines.splitlines()
    return listOfLines

def freqency(content,findword):
    """Function used to find frequency of a word in given text"""
    freqList={}
    for key in findword:
        if content.count(key):
            freqList[key]= content.count(key)
            uniqueWord.append(key)
    return freqList

# read  content text
file = open("t8.shakespeare.txt", "r")
content = file.read()
#read find words file
listOfenLines=readFile("find_words.txt")
#read french dictionary file
listOffrLines=readFile("french_dictionary.csv")

findWordDict={}
for sub in list(map(createRequiredWordDictionary, listOfenLines, listOffrLines)):
    for key in sub:
        findWordDict[key]=sub[key]

wordFreq=freqency(content,listOfenLines)

for key,value in wordFreq.items():
    replacetxt=re.sub(key, findWordDict[key], content)
    content=replacetxt
    wordFrequency.append([key,findWordDict[key],value])

# write  new created text file after change english into french words
file_handle = open("t8.shakespeare.translate.txt", "w")
file_handle.write(content)
file_handle.close()

# Stop the time
stopTime = process_time()

print(uniqueWord)

# print(wordFrequency)

timeToProcress=stopTime-startTime

memoryUsed=psutil.Process(os.getpid()).memory_info().rss / 1024 ** 2

# save time to process and memory into performance.txt
file_handle = open("performance.txt", "w")
file_handle.write("Time to process: "+str(timeToProcress)+" seconds\nMemory used: "+str(memoryUsed)+" MB")
file_handle.close()

#Create csv file for store english word with its french word and also frequency count
with open('frequency.csv', 'w', newline='') as file:
    writer = csv.writer(file)
    writer.writerow(["English word", "French word", "Frequency"])
    for element in wordFrequency:
        writer.writerow(element)


from sqlalchemy.exc import IntegrityError
from src.config.database import SessionLocal
from ..config.models import Timezones, ZoneDetails, ErrorLog

def populate_timezones_table(timezones):
    with SessionLocal() as db:
        try:
            db.query(Timezones).delete()
            for tz in timezones:
                timezone = Timezones(
                    countrycode=tz['countrycode'],
                    countryname=tz['countryname'],
                    zonename=tz['zonename'],
                    gmtoffset=tz['gmtoffset']
                )
                db.add(timezone)
            db.commit()
        except IntegrityError as e:
            db.rollback()
            error_message = f"Integrity error occurred while populating timezones table: {str(e)}"
            save_error_log(error_message)

def populate_zone_details_table(detail):
    with SessionLocal() as db:
        # Check if a row with the same zonename, zonestart, and zoneend already exists
        existing_row = db.query(ZoneDetails).filter_by(
            zonename=detail['zonename'],
            zonestart=detail['zonestart'],
            zoneend=detail['zoneend']
        ).first()

        if not existing_row:
            zone_detail = ZoneDetails(
                countrycode=detail['countrycode'],
                countryname=detail['countryname'],
                zonename=detail['zonename'],
                gmtoffset=detail['gmtoffset'],
                dst=detail['dst'],
                zonestart=detail['zonestart'],
                zoneend=detail['zoneend']
            )

            try:
                db.add(zone_detail)
                db.commit()
            except IntegrityError as e:
                db.rollback()
                print(f"IntegrityError occurred: {str(e)}")

def save_error_log(error_message):
    with SessionLocal() as db:
        error_log = ErrorLog(error_message=error_message)
        db.add(error_log)
        db.commit()


"""
Created on Nov 25, 2016
Utility class for image processing
@author: Levan Tsinadze
"""

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

import argparse

from cnn.utils.image_utils import image_converter

IMAGE_SIZE = 299

class document_image_converter(image_converter):
  """Image converter implementation with cropping"""

  def __init__(self, from_parent, to_dir, prefx,
               rotate_image=True,
               rotate_pos=[],
               add_extensions=True,
               image_extensions=['jpg', 'png'],
               change_extensions=['gif'],
               resize_image=True,
               box_image=False,
               box_sizes=[],
               image_size=IMAGE_SIZE):
    super(document_image_converter, self).__init__(from_parent, to_dir, prefx,
                                                   rotate_image=rotate_image,
                                                   rotate_pos=rotate_pos,
                                                   add_extensions=add_extensions,
                                                   image_extensions=image_extensions,
                                                   change_extensions=change_extensions,
                                                   resize_image=resize_image,
                                                   box_image=box_image,
                                                   box_sizes=box_sizes,
                                                   image_size=image_size)

  def crop_image(self, im):
    """Document image croping"""

    [x, y] = im.size
    left = (x - x / 5) / 2
    top = (y - y / 3.5) / 2
    right = x
    bottom = (y + y / 2.6) / 2
    box = [left, top, right, bottom]
    croped_image = im.crop(box)

    return croped_image

  def resize_if_nedded(self, im):
    """Resizes passed image if configured
      Args:
        im - image
      Returns:
        img - resized image
    """

    if self.resize_image:
      if self.box_image:
        [x, y] = im.size
        left = (x - x / 5) / 2
        top = (y - y / 3.5) / 2
        right = x
        bottom = (y + y / 2.6) / 2
        box = [left, top, right, bottom]
        im_to_write = im.crop(box)
      else:
        im_to_write = im
      img = self.resizer.resize_thumbnail(im_to_write)
    else:
      img = im

    return img

def run_image_processing(argument_flags):
  """Runs image processing
    Args:
      argument_flags - Command line arguments
  """

  from_dirs = argument_flags.src_dir
  to_dir = argument_flags.dst_dir
  prefx = argument_flags.file_prefix
  rotate_image = argument_flags.rotate_images
  if argument_flags.rotate_pos:
    rotate_pos = argument_flags.rotate_pos.split('|')
  else:
    rotate_pos = []

  add_extensions = argument_flags.add_extensions

  resize_image = argument_flags.resize_images
  image_size = argument_flags.image_size

  image_extensions = argument_flags.image_extensions.split('-')
  change_extensions = argument_flags.change_ext.split('-')

  if argument_flags.box_images and argument_flags.box_sizes:
    box_image = True
    sizes = argument_flags.box_sizes.split('-')
    box_sizes = [int(sizes[0]), int(sizes[1])]
  else:
    box_image = False
    box_sizes = []

  converter = document_image_converter(from_dirs, to_dir, prefx,
                              rotate_image=rotate_image,
                              rotate_pos=rotate_pos,
                              add_extensions=add_extensions,
                              image_extensions=image_extensions,
                              change_extensions=change_extensions,
                              resize_image=resize_image,
                              box_image=box_image,
                              box_sizes=box_sizes,
                              image_size=image_size)
  converter.migrate_images()

def read_arguments_and_run():
  """Retrieves command line arguments for image processing"""

  arg_parser = argparse.ArgumentParser()
  arg_parser.add_argument('--src_dir',
                          type=str,
                          help='Source directory.')
  arg_parser.add_argument('--dst_dir',
                          type=str,
                          help='Destination directory.')
  arg_parser.add_argument('--file_prefix',
                          type=str,
                          default='trn_',
                          help='Converted file prefix.')
  arg_parser.add_argument('--resize_images',
                          type=bool,
                          default=True,
                          help='Resize images.')
  arg_parser.add_argument('--box_images',
                          dest='box_images',
                          action='store_true',
                          help='Crop images.')
  arg_parser.add_argument('--not_box_images',
                          dest='box_images',
                          action='store_false',
                          help='Do not Crop images.')
  arg_parser.add_argument('--box_sizes',
                          type=str,
                          default='2-2',
                          help='Resize images.')

  arg_parser.add_argument('--image_size',
                          type=int,
                          default=IMAGE_SIZE,
                          help='Images Size.')

  arg_parser.add_argument('--log_errors',
                          type=bool,
                          default=False,
                          help='Log errors.')

  arg_parser.add_argument('--add_extensions',
                          type=bool,
                          default=True,
                          help='Adds extensions to images.')

  arg_parser.add_argument('--image_extensions',
                          type=str,
                          default='jpg-png',
                          help='Image extensions to filter.')

  arg_parser.add_argument('--rotate_images',
                          dest='rotate_images',
                          action='store_true',
                          help='Rotate images flag')

  arg_parser.add_argument('--not_rotate_images',
                          dest='rotate_images',
                          action='store_false',
                          help='Rotate images flag')

  arg_parser.add_argument('--rotate_pos',
                          type=str,
                          default='30|-30|45|-45|180|90|-90|95|-95',
                          help='Rotate images (--rotate_pos 30|-30|45|-45).')

  arg_parser.add_argument('--change_ext',
                          type=str,
                          default='gif-GIF',
                          help='Change extension to JPG flag')
  (argument_flags, _) = arg_parser.parse_known_args()
  run_image_processing(argument_flags)

if __name__ == '__main__':
  """Converts images for training data set"""

  read_arguments_and_run()


import CDAE
import load_data
import metrics

import sys

from sklearn.metrics import precision_recall_fscore_support
import numpy as np

batch_size = int(sys.argv[1])
epochs = int(sys.argv[2])
embedding_size = int(sys.argv[3])

# Load the proejct data
train_movies, train_x, test_movies, test_x = load_data.load_movies()
train_x_movies = np.array(train_movies, dtype=np.int32).reshape(len(train_movies), 1)
test_x_movies = np.array(test_movies, dtype=np.int32).reshape(len(test_movies), 1)

# Create our model
model = CDAE.create(I=train_x.shape[1], U=len(train_movies)+1, K=embedding_size,
                    hidden_activation='relu', output_activation='sigmoid', q=0.50, l=0.01)
model.compile(loss='mean_absolute_error', optimizer='adam')
model.summary()

# Train our Autoencoder
history = model.fit(x=[train_x, train_x_movies], y=train_x,
                    batch_size=batch_size, nb_epoch=epochs, verbose=1,
#                    validation_split=0.2)
                    validation_data=[[test_x, test_x_movies], test_x])

# Save the model
model_name = 'autoencoder_movies_' + str(embedding_size) + '.h5'
model.save(model_name)


def solution(string,markers):
    ORIGINAL_STRING = string
    for m in markers:
        string = string.replace(m,"#")
    mas = string.split("#")
    SAXLANILACAQ = mas[0].strip()
    for hedd in mas:
        if "\n" in hedd:
            muveq = hedd.split("\n")
            for i in range(1,len(muveq)):
                SAXLANILACAQ = SAXLANILACAQ + "\n"+muveq[i].strip()
    return SAXLANILACAQ


"""
Kártyák definíciója
"""
from enum import IntEnum, unique
from functools import total_ordering

@unique
class Szinek(IntEnum):
    """
    Francia kártya színek
    """
    KARO = 0
    PIKK = 1
    KOR = 2
    TREFF = 3
    JOKER = 4

    def __str__(self):
        """
        Stringgé alakítja az értéket.
        :return: Szín Unicode karakterként
        """
        return ['\u2662', '\u2660', '\u2661', '\u2663', '*'][self.value]

# Default konstruktor átdefiniálása
# https://stackoverflow.com/questions/24105268/is-it-possible-to-override-new-in-an-enum-to-parse-strings-to-an-instance
def _szinek_konstruktor(cls, value):
    if not isinstance(value, str):
        # forward call to 'Szinek' superclass (enum.Enum)
        return super(Szinek, cls).__new__(cls, value)
    else:
        # map strings to enum values, default to Unknown
        return {'\u2662': Szinek.KARO,
                '\u2660': Szinek.PIKK,
                '\u2661': Szinek.KOR,
                '\u2663': Szinek.TREFF,
                'D': Szinek.KARO,
                'C': Szinek.PIKK,
                'H': Szinek.KOR,
                'S': Szinek.TREFF,
                '*': Szinek.JOKER}.get(value)

setattr(Szinek, '__new__', _szinek_konstruktor)

@unique
class Ertekek(IntEnum):
    """
    Francia kártya értékek
    """
    C2 = 0  # 2-es lap ....
    C3 = 1
    C4 = 2
    C5 = 3
    C6 = 4
    C7 = 5  # 7-es lap
    C8 = 6
    C9 = 7
    C0 = 8  # 10
    CJ = 9  # Jumi
    CQ = 10  # Dáma
    CK = 11  # Király
    CA = 12  # Ász
    CO = 13  # Joker

    def __str__(self):
        """
        Stringgé alakítja az értéket.
        :return: Érték Unicode karakterként
        """
        return '234567890JQKA*'[self.value]

def _ertekek_konstruktor(cls, value):
    if not isinstance(value, str):
        # forward call to 'Szinek' superclass (enum.Enum)
        return super(Ertekek, cls).__new__(cls, value)
    else:
        # map strings to enum values, default to Unknown
        ertek_dict = {'234567890JQKA*'[k]: Ertekek(k) for k in range(14)}
        ertek_dict['O'] = Ertekek.CO
        return ertek_dict.get(value)

setattr(Ertekek, '__new__', _ertekek_konstruktor)

@total_ordering
class MocsarCard(object):
    """
    Kártya lapokat reprezentáló osztály
    """
    suit: Szinek
    rank: Ertekek  # Ez az effektív érték, Kinevezett Joker esetén Joker pl., Körönként változhat
    displ_rank: Ertekek  # Ez a kártya lap megjelenítendő értéke, nem változik
    ACTION_PASS = 0  # Pass akció

    def __init__(self, krty):
        """
        Egy kártya lapot példányosít
        :param krty: Vagy egy kettő hosszú str ('♣3'), vagy egy két tagú tuple (0,8) Szín, Érték
        """
        # Stringből vagy tuple-ből konstruálunk, ugyanaz!
        self.suit = Szinek(krty[0])
        self.rank = Ertekek(krty[1])
        self.displ_rank = self.rank

    def __str__(self) -> str:
        return self.suit.__str__() + self.displ_rank.__str__()

    def __repr__(self):
        return "Card(Suit:{}, Rank:{}, Displ:{})".format(self.suit, self.rank, self.displ_rank)

    def __eq__(self, other):
        if type(other) is type(self):
            return self.rank == other.rank
        return False

    def __lt__(self, other):
        if type(other) is type(self):
            return self.rank < other.rank
        return NotImplemented

    def map_joker(self, ertek: Ertekek):
        """
        Joker átnevezést végez, Ha törölni akarjuk, akkor Ertekek.CO hívás kell
        :param ertek: ez a kártya lap lesz még Joker
        :type ertek: Ertekek
        """
        if self.displ_rank == ertek:
            # Kell Joker átnevezés, pont ez egy Joker
            self.rank = Ertekek.CO
        else:
            self.rank = self.displ_rank
        return self

    def get_index(self):
        """ Get index of a card.

        Returns:
            string: the combination of suit and rank of a card. Eg: 1S, 2H, AD, BJ, RJ...
        """
        return self.__str__()


__author__ = "Manuel Yves Galliker"
__maintainer__ = "Manuel Yves Galliker"
__license__ = "Apache-2.0"

from PyQt5 import QtCore
from PyQt5.QtWidgets import QVBoxLayout, QWidget, QDialog, QDialogButtonBox

class ConfirmSelectionWindow(QDialog):
    def __init__(self):
        super().__init__()

        buttonBox = QDialogButtonBox(QDialogButtonBox.Cancel | QDialogButtonBox.Ok)

        buttonBox.accepted.connect(self.accept)
        buttonBox.rejected.connect(self.reject)

        layout = QVBoxLayout()

        layout.addWidget(buttonBox)

        # Set dialog layout
        self.setLayout(layout)
        self.setWindowTitle("Confirm selection")
        self.setWindowModality(QtCore.Qt.ApplicationModal)


def permute(nums):
    # Approach uses recursion:
    # Base case is if list is length 1, then return that list
    # Find the ith element in the list
    # Find the remaining elements in the list
    # Call the permute function on the remaining elements list
    if len(nums) == 0:
        return []
    if len(nums) == 1:
        return [nums]
    lst = []
    for i in range(len(nums)):
        k = [nums[i]]
        remaining_lst = nums[:i] + nums[i+1:]
        for j in permute(remaining_lst):
            lst.append(k + j)
    return lst

print(permute(['1','2','3','4','5']))


#!/usr/bin/env python2

import json
import math
import re
import sys

def entropy(seq):
    bins = {}
    total = 0
    for x in seq:
        bins[x] = 1 + bins.get(x,0)
        total += 1

    return 0 - sum((float(p) / total) * math.log(float(p) / total, 2) for p in bins.itervalues())

if __name__ == "__main__":
  bins = {}
  for line in sys.stdin:
    try:
        tweet = json.loads(line)
        e = entropy(tweet['text'])
        if e > 6.6:
            sys.stdout.write(line)

    except KeyError:
        continue
        # text was missing
    except ValueError:
        # json decoding failed ?
        continue


import setuptools
import setuptools.command.install
from setuptools import setup
from torch.utils.cpp_extension import CppExtension, BuildExtension, CUDAExtension
import subprocess
import os
import sys
import torch
import glob

BUILD_PATH = os.path.join(os.getcwd(), 'python', 'cpp_build')
INSTALL_PATH = os.path.join(os.getcwd(), 'python', 'stillleben')

DEBUG = int(os.environ.get('DEBUG', '0')) == 1

def build_stillleben():
    os.makedirs(BUILD_PATH, exist_ok=True)

    env = os.environ.copy()
    env['CLICOLOR_FORCE'] = '1'

    if (not os.path.exists(os.path.join(BUILD_PATH, 'build.ninja'))) or os.environ.get('CMAKE', '0') == '1':
        cmd = [
            'cmake',
            '-DCMAKE_BUILD_TYPE={}'.format('Debug' if DEBUG else 'RelWithDebInfo'),
            '-DCMAKE_INSTALL_PREFIX=' + INSTALL_PATH,
            '-DUSE_RELATIVE_RPATH=ON',
            '-GNinja',
            '../..'
        ]

        # if CUDA_HOME is available, respect it to use non-default CUDA versions
        if 'CUDA_HOME' in env:
            cmd.append('-DCUDA_TOOLKIT_ROOT_DIR={}'.format(env['CUDA_HOME']))

        # are we installing inside anaconda?
        # if so, try to be helpful.
        if 'CONDA_PREFIX' in env:
            cmd.append(f'-DEXTRA_RPATH={env["CONDA_PREFIX"]}/lib')

            if 'CMAKE_PREFIX_PATH' in env:
                env['CMAKE_PREFIX_PATH'] = env['CONDA_PREFIX'] + ':' + env['CMAKE_PREFIX_PATH']
            else:
                env['CMAKE_PREFIX_PATH'] = env['CONDA_PREFIX']

        if subprocess.call(cmd, cwd=BUILD_PATH, env=env) != 0:
            print('Failed to run "{}"'.format(' '.join(cmd)))

    make_cmd = [
        'ninja',
        'install',
    ]

    if subprocess.call(make_cmd, cwd=BUILD_PATH, env=env) != 0:
        raise RuntimeError('Failed to call ninja')

# Build all dependent libraries
class build_deps(setuptools.Command):
    user_options = []

    def initialize_options(self):
        pass

    def finalize_options(self):
        pass

    def run(self):
        # Check if you remembered to check out submodules

        def check_file(f):
            if not os.path.exists(f):
                print("Could not find {}".format(f))
                print("Did you run 'git submodule update --init --recursive'?")
                sys.exit(1)

        check_file(os.path.join(os.getcwd(), 'contrib', 'corrade', 'CMakeLists.txt'))
        check_file(os.path.join(os.getcwd(), 'contrib', 'magnum', 'CMakeLists.txt'))
        check_file(os.path.join(os.getcwd(), 'contrib', 'magnum-plugins', 'CMakeLists.txt'))

        build_stillleben()

class install(setuptools.command.install.install):
    def run(self):
        if not self.skip_build:
            self.run_command('build_deps')

        setuptools.command.install.install.run(self)

def make_relative_rpath(path):
    return '-Wl,-rpath,$ORIGIN/' + path

cmdclass = {
    'build_deps': build_deps,
    'install': install,
}

MAGNUM_SUFFIX = '-d' if DEBUG else ''

setuptools.setup(
    name='stillleben',
    cmdclass=cmdclass,
    packages=['stillleben'],
    package_dir={'':'python'},
    include_package_data=True,
    ext_modules=[],
    options={
        'build': {
            'build_base': 'python/py_build'
        },
        'sdist': {
            'dist_dir': 'python/dist'
        },
    },
)


import torch
import time
import sys
import pickle

debug = 0

class Node:
    def __init__(self, state):
        self.state = state
        self.n_actions = state.count(' ')

        self.regret_sum = torch.zeros(self.n_actions)

        self.strategy_sum = torch.zeros(self.n_actions,1)

        self.strategy = torch.ones(self.n_actions,1)/self.n_actions

    def update_strat(self, weight):

        regrets = self.regret_sum
        #print(regrets)
        regrets[regrets < 0] = 0
        normalize = sum(regrets)
        #print(regrets)
        if normalize > 0:
            self.strategy[:,0] = regrets / normalize
        else:
            self.strategy = torch.ones(self.n_actions,1)/self.n_actions

        self.strategy_sum += self.strategy * weight

    def get_average_strategy(self):
        strategy = self.strategy_sum

        total = sum(strategy)
        strategy /= total
        return strategy

    def get_actions(self):
        return self.n_actions

class Trainer:

    def __init__(self):
        self.board="         "
        self.nodes = {}
        self.n_players = 2

    def reward(self, state):

        n_actions = state.count(' ')
        winner = None
        if state[0] == state[1] and state[1] == state[2] and state[0] != ' ': # first row
            winner = state[0]
        elif state[3] == state[4] and state[4] == state[5] and state[3] != ' ': # second row
            winner = state[3]
        elif state[6] == state[7] and state[7] == state[8] and state[6] != ' ': # third row
            winner = state[6]
        elif state[0] == state[4] and state[4] == state[8] and state[0] != ' ': # diag 2
            winner = state[0]
        elif state[2] == state[4] and state[4] == state[6] and state[2] != ' ': # diag 1
            winner = state[2]
        elif state[0] == state[3] and state[3] == state[6] and state[0] != ' ': # first column
            winner = state[0]
        elif state[1] == state[4] and state[4] == state[7] and state[1] != ' ': # second column
            winner = state[1]
        elif state[2] == state[5] and state[5] == state[8] and state[2] != ' ': # third column
            winner = state[2]
        if n_actions == 0:
            return torch.zeros(1, self.n_players)

        if winner != None:
            winner = int(winner)
            x = -torch.ones(1,self.n_players)
            x[0][winner] = self.n_players -1
            #print("x",x)
            return x

        return None

    def get_node(self, state):

        if state not in self.nodes:

          self.nodes[state] = Node(state)
          return self.nodes[state]
        return self.nodes[state]

    def cfr(self, state, turn, prob_get_to):
        n = turn
        turn+=1
        cur_player = n % self.n_players
        reward = self.reward(state)
        #print(reward)
        if reward != None:
            #print("resard,", reward)
            return reward

        node = self.get_node(state)
        strat = node.strategy
        #print("strategy:", strat)

        action_utils = torch.zeros(node.n_actions, self.n_players)

        cur_action = 0
        for act in range(len(state)):
            #find next space

            if state[act] == ' ':
                new_state = state[:act] + str(cur_player) + state[act+1:]

                #onny = torch.ones(self.n_players)
                #onny[cur_player] = strat[cur_action]

                #print(onny)
                #print(prob)

                next_cfr = self.cfr(new_state, turn, prob_get_to * strat[cur_action,0])
                #if debug > 1:
                #if state == '1   0  10':
                #  print ("|"+new_state+"|","cfr ret", next_cfr)
                #  print(cur_action)
                action_utils[cur_action,:] = next_cfr #1xnplayers
                #if state == '1   0  10':
                #  print("in",action_utils,strat)
                cur_action += 1

        #print("action, strat", action_utils, strat)
        util = torch.sum(torch.mul(action_utils, strat), dim=0, keepdim=True)
        if state == '1   0  10' and False:
          print(action_utils,strat)
          print(torch.mul(action_utils, strat))
          print(util)
          print("-----------------------")
        regret = action_utils[:,cur_player] - util[0,cur_player] # 1xn_action
        #if state == '1   0  10' or state == '1 01 0   ':
        #  print (state)
        #  print(node.strategy)
        #  print(node.regret_sum)
        if debug > 1:
            print("util",util)
            print("actionutil",action_utils)
            print("actionutil2",action_utils[:,cur_player])
            print("reg",regret)

        node.regret_sum += regret*prob_get_to
        #print("util", util)
        return util

    def train(self, n_iterations=50000):
        expected_game_value = 0
        for i in range(n_iterations):
            if i%3 == 1:
                print(i)

            expected_game_value += self.cfr('         ', 0, 1)

            #print(self.nodes['1   0  10'].regret_sum)
            #print(self.nodes['1 01 0   '].regret_sum)

            for _, v in self.nodes.items():
                v.update_strat(1)
        expected_game_value /= n_iterations
        #display_results(expected_game_value, self.nodes)

def save_obj(obj, name):
    with open('obj/'+ name + '.pkl', 'wb') as f:
        pickle.dump(obj, f, pickle.HIGHEST_PROTOCOL)

def load_obj(name):
    with open('obj/' + name + '.pkl', 'rb') as f:
        return pickle.load(f)

if __name__ == "__main__":
    time1 = time.time()
    train = 1
    trainer = None

    if train == 1:
        trainer = Trainer()
        trainer.train(n_iterations=10)
        save_obj(trainer.nodes, "cfr_save")
        print(trainer.nodes['1   0  10'].get_average_strategy())
        print(trainer.nodes['1   0  10'].strategy)
        print(trainer.nodes['1 01 0   '].get_average_strategy())
        print(trainer.nodes['1 01 0   '].strategy)
    else:
        nodes = load_obj("cfr_save")
        print(nodes['1   0  10'].get_average_strategy())
        print(nodes['1   0  10'].strategy)
        print(nodes['1 01 0   '].get_average_strategy())
        print(nodes['1 01 0   '].strategy)

    print(abs(time1 - time.time()))
    print("Done")


import time

from pymavlink import mavutil
# from iq_pymavlink_.arm import arm
# from iq_pymavlink_.takeoff import takeoff
# from iq_pymavlink_.land import land
# from iq_pymavlink_.speed_yaw import set_speed
# from iq_pymavlink_.get_autopilot_info import get_autopilot_info
# from iq_pymavlink_.wait_for_position_aiding import ekf_pos_aiding, wait_until_position_aiding

# from iq_pymavlink.unittests import test_all

# def mavlink_connect(connection_str: str, baud: int):
#     connection = mavutil.mavlink_connection(connection_str, baud)
#     connection.wait_heartbeat()
#     print(
#         f"Heartbeat from system (system {connection.target_system} component {connection.target_component})"
#     )
#     return connection

# connect = mavlink_connect("COM8", 115200)  # Подключение

# test_all.arm(connect, 1)
# arm(connect, 1)
# time.sleep(4)
# set_speed(connect, speed=3)
# takeoff(connect, 1)
# time.sleep(2)
# land(connect)
# time.sleep(4)
# arm(connect, 0)

the_connection = mavutil.mavlink_connection("/dev/ttyACM0", 57600)

the_connection.wait_heartbeat()
print("Heartbeat from system (system %u component %u)" % (the_connection.target_system, the_connection.target_component))

def arm(statys_arm):
    the_connection.mav.command_long_send(the_connection.target_system, the_connection.target_component,
                                         mavutil.mavlink.MAV_CMD_COMPONENT_ARM_DISARM, 15, statys_arm, 0, 0, 0, 0, 0, 0)

    msg = the_connection.recv_match(type="COMMAND_ACK", blocking=True)
    return print(msg)

def takeoff():
    the_connection.mav.command_long_send(the_connection.target_system, the_connection.target_component,
                                         mavutil.mavlink.SET_POSITION_TARGET_LOCAL_NED, 0, 0, 0, 9, 3576, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)

    msg = the_connection.recv_match(type="COMMAND_ACK", blocking=True)
    return print(msg)

def land():
    the_connection.mav.command_long_send(the_connection.target_system, the_connection.target_component,
                                         mavutil.mavlink.MAV_CMD_NAV_LAND, 0, 0, 0, 0, 0, 0, 0, 0)

    msg = the_connection.recv_match(type="COMMAND_ACK", blocking=True, timeout=10)

    if msg is None:
        print('No acknowledgment received within the timeout period.')
        return print(None)
    return print(msg)

# arm(1)
# print(get_autopilot_info(connection=the_connection))
# print(wait_until_position_aiding(the_connection))
# time.sleep(3)
# takeoff()
# time.sleep(5)
land()
time.sleep(5)
# land()
# time.sleep(5)
# arm(0)


# 두 정렬 리스트의 병합
# 정렬되어있는 두 리스트를 연결하라!

class Node:
    def __init__(self, val, next=None):
        self.val = val
        self.next = next

node1 = Node(1)
node2 = Node(2)
node3 = Node(4)
node1.next = node2
node2.next = node3

node4 = Node(1)
node5 = Node(3)
node6 = Node(4)
node4.next = node5
node5.next = node6

def mergeTwoLists(l1, l2):
    if l1 is None :
        return l2

    if l2 is None :
        return l1

    if l1.val <= l2.val :
        head = l1
        head.next = mergeTwoLists(l1.next, l2)
    else :
        head =l2
        head.next = mergeTwoLists(l1,l2.next)
    return head

mergeTwoLists(node1, node4)


# Our implementation of insert for the DynamicArray class, as given in Code Fragment 5.5, has the following inefficiency. In the case when a resize occurs, the resize operation takes time to copy all the elements from an old array to a new array, and then the subsequent loop in the body of insert shifts many of those elements. Give an improved implementation of the insert method, so that, in the cae of a resize, the elements are shifted into their final position during that operation, thereby avoiding the subsequent shifting.

import ctypes

class DynamicArray:
    """A dynamic array class akin to a simplified Python list."""

    def __init__(self):
        """Create an empty array."""
        self._n = 0                                     # count actual elements
        self._capacity = 1                              # default array capacity
        self._A = self._make_array(self._capacity)      # low-level array

    def __len__(self):
        "Return number of elements stored in the array."
        return self._n

    def __getitem__(self, k):
        "Return element at index k."
        if k < 0:
            self._A[(self._n-1)]
        elif 0 <= k < self._n:
            self._A[k]
        else:
            raise IndexError('invalid index')

    def insert(self, k, value):
        "Insert value at index k, shifting subsequent values rightward."
        # for simplicity, we assume 0 <= k <= n in this version
        if self._n == self._capacity:
            self._A = self._make_array(2 * self._capacity)
        for j in range(self._n, k, -1):
            self._A[j] = self._A[j-1]
        self._A[k] = value
        self._n += 1

    def append(self, obj):
        "Add object to end of the array."
        if self._n == self._capacity:           # not enough room
            self._resize(2 * self._capacity)    # so double capacity
        self._A[self._n] = obj
        self._n += 1

    def _resize(self,c):                        # nonpublic utility
        "Resize internal array to capacity c."
        B = self._make_array(c)                 # new (bigger) array
        for k in range(self._n):                # for each existing value
            B[k] = self._A[k]
        self._A = B                             # use the bigger array
        self._capacity = c

    def _make_array(self,c):                    # nonpublic utility
        "Return new array with capacity c."
        return (c * ctypes.py_object)()

if __name__ in '__main__':
    u = DynamicArray()
    for i in range(20):
        u.append(i)
    u.insert(k=4,value="a")
    for item in u:
        print(item)


# Block Swap Algo

def swap(arr, firstIndex, secondIndex, d):
    for i in range(d):
        temp = arr[firstIndex+i]
        arr[firstIndex+i] = arr[secondIndex+i]
        arr[secondIndex+i] = temp

def leftRotate(arr, d, n):
    if d == 0 or d ==n: return

    i = d
    j = n - d
    while (i != j):
        if(i < j):
            swap(arr, d-i, d+j-i, i)
            j -= i
        else:
            swap(arr, d-i, d, j)
            i -= j

    swap(arr, d-i, d, i);

n, d = map(int, input().split())

a = list(map(int, input().split()))
leftRotate(a, d, n)
print(' '.join(map(str,a)))


import json

import torch
import yaml
from torchvision.transforms import transforms
from tqdm import tqdm

from src.data.tooth_segmentation_dataset import ToothSegmentationDataset
from src.model.unet.unet import UNet
from src.utils.transforms import SquarePad

if __name__ == "__main__":
    with open("./src/model/unet/scripts/config.yml", "r") as f:
        config = yaml.safe_load(f)

    # Find out whether gpu is available
    device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')

    # Load data
    with open("data/final/train_quadrant_enumeration_disease_healthy_unpacked_test.json") as f:
        X = json.load(f)

    transform = transforms.Compose([
        SquarePad(),
        transforms.Resize(224, interpolation=transforms.InterpolationMode.BILINEAR)
    ])
    to_pil = transforms.ToPILImage()

    dataset = ToothSegmentationDataset(
        X,
        transform=transform
    )

    # Load model
    model = UNet.load_from_checkpoint(
        f"checkpoints/unet/version_66/checkpoints/epoch=epoch=20-val_loss=val_loss=0.23.ckpt",
        map_location=device
    )
    model.eval()

    # Predict for each sample
    prediction_classification_list = []
    for sample in tqdm(dataset, total=len(dataset)):
        input = sample["image"]
        file_name = sample["file_name"]
        label = sample["label"]

        with torch.no_grad():
            prediction = model(input.unsqueeze(0).to(device))
        prediction_classification_list.append(dict(
            file_name=file_name,
            label=label.cpu().tolist(),
            prediction=prediction["classification"].detach().cpu().tolist()))

    with open(f"output/unet_predict.json", "w") as f:
        json.dump(prediction_classification_list, f)


'''PACKAGE PROBLEM

You want to send your friend a package with different things.
Each thing you put inside the package has such parameters as index number,
weight and cost.
The package has a weight limit.
Your goal is to determine which things to put into the package so that the total
weight is less than or equal to the package limit and the total cost is as large
as possible.

You would prefer to send a package which weights less in case there is more than
one package with the same price.

INPUT SAMPLE:
Your program should accept as its first argument a path to a filename. The input
file contains several lines. Each line is one test case.

Each line contains the weight that the package can take (before the colon) and
the list of things you need to choose. Each thing is enclosed in parentheses
where the 1st number is a thing's index number, the 2nd is its weight and the
3rd is its cost. E.g.

81 : (1,53.38,$45) (2,88.62,$98) (3,78.48,$3) (4,72.30,$76) (5,30.18,$9) (6,46.34,$48)
8 : (1,15.3,$34)
75 : (1,85.31,$29) (2,14.55,$74) (3,3.98,$16) (4,26.24,$55) (5,63.69,$52) (6,76.25,$75) (7,60.02,$74) (8,93.18,$35) (9,89.95,$78)
56 : (1,90.72,$13) (2,33.80,$40) (3,43.15,$10) (4,37.97,$16) (5,46.81,$36) (6,48.77,$79) (7,81.80,$45) (8,19.36,$79) (9,6.76,$64)

OUTPUT SAMPLE:
For each set of things that you put into the package provide a list (items’
index numbers are separated by comma). E.g.

4
-
2,7
8,9
'''
def f(test='81 : (1,53.38,$45) (2,88.62,$98) (3,78.48,$3) (4,72.30,$76) (5,30.18,$9) (6,46.34,$48)'):#4
    max_weight, packages = test.rstrip('\n').split(' : ')
    max_weight = int(max_weight)
    packages = [p[1:-1].split(',') for p in packages.split()]
    for i in range(len(packages)):
        packages[i][1] = float(packages[i][1])
        packages[i][2] = int(packages[i][2][1:])
    packages = [p for p in packages if p[1] <= max_weight]
    solution = g(packages, max_weight, 0, [], 0)[1]
    if solution:
        print(','.join(solution))
    else:
        print('-')

def g(packages, rem_weight, value, arrangement, total_weight):
    max_value = value
    max_arrange = arrangement
    max_weight = total_weight
    for i in range(len(packages)):
        if packages[i][1] <= rem_weight:
            t_package = packages[:]
            t_arrange = arrangement[:]
            t_arrange.append(t_package.pop(i)[0])
            v = g(t_package, rem_weight - packages[i][1], value + packages[i][2], t_arrange, total_weight + packages[i][1])
            if v[0] > max_value or v[0] == max_value and round(v[2],2) < round(max_weight,2):
                max_value = v[0]
                max_arrange = v[1]
                max_weight = v[2]
    return (max_value, max_arrange, max_weight)


MENU = {
    "espresso": {
        "ingredients": {
            "water": 50,
            "coffee": 18,
        },
        "cost": 1.5,
    },
    "latte": {
        "ingredients": {
            "water": 200,
            "milk": 150,
            "coffee": 24,
        },
        "cost": 2.5,
    },
    "cappuccino": {
        "ingredients": {
            "water": 250,
            "milk": 100,
            "coffee": 24,
        },
        "cost": 3.0,
    }
}

resources = {
    "water": 300,
    "milk": 200,
    "coffee": 100,
}

def check_resources(drink):
    for ingredient, amount in MENU[drink]["ingredients"].items():
        if resources[ingredient] < amount:
            print(f"Sorry there is not enough {ingredient}")
            return False
    return True

def process_coin():
    print("Please insert coins.")
    quarter_input = int(input("How many quarters?")) * .25
    dime_input = int(input("How many dimes?")) * .1
    nickle_input = int(input("How many nickles?")) * .05
    penny_input = int(input("How many pennies?")) * .01
    return quarter_input + dime_input + nickle_input + penny_input

def make_coffee(drink_name):
    for ingredient, amount in MENU[drink_name]["ingredients"].items():
        resources[ingredient] -= amount
    global profit
    profit += MENU[drink_name]["cost"]
    print(f"Here is your {drink_name} ☕ Enjoy!")

profit = 0
machine_running = True
while machine_running:

    user_input = input("What would you like? (espresso/latte/cappuccino):").lower()

    acceptable_inputs = ["espresso", "latte", "cappuccino", "off", "report"]

    if user_input not in acceptable_inputs:
        print("Wrong input. Please enter correct input")

    if user_input == "off":
        print("Turning off machine. Good Bye")
        machine_running = False

    elif user_input == "report":
        print(f"Water: {resources['water']}ml")
        print(f"Milk: {resources['milk']}ml")
        print(f"Coffee: {resources['coffee']}g")
        print(f"Money: ${profit}")

    elif user_input in ["espresso", "latte", "cappuccino"]:
        drink = user_input
        if check_resources(drink):
            payment = process_coin()
            if payment > MENU[drink]["cost"]:
                change = round(payment - MENU[drink]["cost"], 2)
                print(f"Here is ${change} in change.")
                make_coffee(drink)
            else:
                print("Sorry. Not enough money. Money Refunded")