import numpy as np

class ticTacToe:
	"""
		Represents the game tic tac toe
	"""

	def __init__(self, player1, player2, size = 3, display = True):
		"""
			Size of the board is the square
		"""
		self.size = size
		self.board = np.zeros((size,size))
		self.display = display

		# Take the two players which can be
		self.players = {-1:player1, 1:player2}
		# Player which have to play
		self.playerId = -1

	def copy(self):
		"""
			Creates the copy of the current game
		"""
		copy = ticTacToe(None, None, self.size)
		copy.board = self.board.copy()
		copy.players = self.players
		copy.playerId = self.playerId
		return copy

	def printScreen(self, obj):
		"""
			Print the given obj at the screen iff self.display
		"""
		if self.display:
			print(obj)

	def alignment(self):
		"""
			Returns if there is size of the same player is aligned
		"""
		# Diagonals
		if abs(self.board.trace()) == self.size:
			return True
		if abs(np.fliplr(self.board).trace()) == self.size:
			return True

		# Rows
		if self.size in abs(np.sum(self.board, axis=1)):
			return True

		# Columns
		if self.size in abs(np.sum(self.board, axis=0)):
			return True

		return False

	def endGame(self):
		"""
			Returns True if the game is ended
		"""
		return self.alignment() or np.sum(abs(self.board)) == self.size**2

	def mapPosition(self, choice):
		"""
			Transforms the choice into a position tuple
		"""
		return (int((choice-1)/self.size), (choice-1)%self.size)

	def acceptableChoice(self, choice):
		"""
			Returns True iif the choice is possible
		"""
		if choice < 1 or choice > self.size**2 or self.board[self.mapPosition(choice)] != 0:
			return False
		else:
			return True

	def askMove(self, display):
		"""
			Asks the player to give a number between 1 and 9
		"""
		if display:
			self.printScreen("\nChoose a position as follow : \n{}".format(np.arange(1,self.size**2 + 1).reshape((self.size,self.size))))
		else:
			self.printScreen("Bad move, try another one!")

	def printBoard(self):
		"""
			Prints the boards
		"""
		self.printScreen(self.board)

	def play(self, position):
		"""
			Apply the move of the current player at the given position
			Change the current player
			The move has to be verified with acceptable choice
		"""
		self.board[self.mapPosition(position)] = self.playerId
		self.playerId *= -1

	def playGame(self):
		"""
			Create the full game until victory of a player
		"""
		while not(self.endGame()):
			choice = -1
			display = True
			while not self.acceptableChoice(choice):
				self.askMove(display)
				choice = self.players[self.playerId].getMove(self.board)
				display = False
			self.play(choice)
			self.printBoard()

		if self.alignment():
			# Minus the current player because of self.play
			self.printScreen("Player {} wins the game !".format(-self.playerId))
			return -self.playerId
		else :
			self.printScreen("Draw")
			return 0


#flatten

def flat(arr):
    result=[]
    for i in arr:
        if type(i) is list:
            result.extend(flat(i))
        else:
            result.append(i)
    return result

print(flat([1,2,[3,4],[[5]]]))


import sys
import logging
import logging.handlers

def setup_logging(logs_file):
	try:
		logger = logging.getLogger(__name__)

		# Set up logging
		# LoggingLevel options: CRITICAL (50), ERROR (40), WARNING (30), INFO (20), DEBUG (10), NOTSET (0)
		logger.setLevel("DEBUG")

		logFileHandler = logging.handlers.RotatingFileHandler(logs_file, maxBytes=102400, backupCount=9)
		#logFileHandler = logging.FileHandler(get_log_file())
		logger.addHandler(logFileHandler)

		logFormatter = logging.Formatter("%(asctime)s %(levelname)s %(message)s")
		logFileHandler.setFormatter(logFormatter)

		logConsoleHandler = logging.StreamHandler(sys.stdout)
		logConsoleHandler.setFormatter(logFormatter)
		logger.addHandler(logConsoleHandler)

		return logger
	except Exception as e:
		error_message = "Error setting up logging! " + str(e)
		print(error_message)
		raise


import random
import numpy as np
from scipy.special import expit as sigmoid

# A generic feedforward neural network; backprop implemented using Bishop's equations.
# based on https://github.com/mnielsen/neural-networks-and-deep-learning/blob/master/src/network.py, except using
# a proper softmax output layer (rather than sigmoid layer) for classification

class Network(object):
    def __init__(self, sizes):
        """The list ``sizes`` contains the number of neurons in the
        respective layers of the network.  For example, if the list
        was [2, 3, 1] then it would be a three-layer network, with the
        first (input) layer containing 2 neurons, the second layer 3
        neurons, and the third layer 1 neuron.  The biases and weights
        for the network are initialized randomly, using a Gaussian
        distribution with mean 0, and variance 1.
        We follow the convention in Bishop's book of incorporating
        bias parameters into the weights by defining an additional
        dummy input unit z_0 = 1 for each layer. """

        self.num_layers = len(sizes)
        self.sizes = sizes
        self.weights = [np.hstack((np.random.randn(y, 1), np.random.randn(y, x)/np.sqrt(x)))    # init bias separately
                        for x, y in zip(sizes[:-1], sizes[1:])]

    def SGD(self, training_data, epochs, mini_batch_size, eta,
            test_data=None):
        """Train the neural network using mini-batch stochastic
        gradient descent.  The ``training_data`` is a list of tuples
        ``(x, t)`` representing the training inputs and the desired
        outputs.  The other non-optional parameters are
        self-explanatory.  If ``test_data`` is provided then the
        network will be evaluated against the test data after each
        epoch, and partial progress printed out.  This is useful for
        tracking progress, but slows things down substantially."""

        training_data = list(training_data)
        n = len(training_data)

        if test_data:
            test_data = list(test_data)
            n_test = len(test_data)

        for j in range(epochs):
            random.shuffle(training_data)
            mini_batches = [training_data[k:k + mini_batch_size] for k in range(0, n, mini_batch_size)]
            for mini_batch in mini_batches:
                self.update_mini_batch(mini_batch, eta)
            if test_data:
                eval = self.evaluate(test_data)
                print("Epoch {} : {} / {}, loss = {}".format(j, eval[0], n_test, eval[1]))
            else:
                print("Epoch {} complete".format(j))

    def update_mini_batch(self, mini_batch, eta):
        """Update the network's weights and biases by applying
        gradient descent using backpropagation to a single mini batch.
        The ``mini_batch`` is a list of tuples ``(x, t)``, and ``eta``
        is the learning rate."""

        batch_grad = [np.zeros(w.shape) for w in self.weights]
        for x, t in mini_batch:
            grad = self.backprop(x, t)  # gradient estimate from one data point
            batch_grad = [w + dw for w, dw in zip(batch_grad, grad)]  # accumulate
        self.weights = [w - (eta / len(mini_batch)) * g
                        for w, g in zip(self.weights, batch_grad)]

    def feedforward(self, z):
        """Return the output of the network given input; "z" is a Dx1 numpy array representing outputs
        from previous layer (or simply the data input, when there's no previous layer)
        """

        for i,w in enumerate(self.weights):
            z = prepend_bias_unit(z)  # dummy input for bias
            a = np.dot(w, z)  # activation (i.e. weighted inputs), (5.2/5.8)
            if i == len(self.weights)-1: # last layer
                z = softmax(a)
            else:
                z = ReLU(a)
        return z

    def backprop(self, x, t):
        """Return a list of ndarrays the same shapes as those of self.weights
        containing the partial derivatives w.r.t weights, i.e. the gradient of
        the cost function C_x. x is a column (input) vector, t is a vector （one-hot) target"""

        # feedforward
        z = x
        zs = []  # list of layer outputs (including the "outputs" of the 0th (network input) layer
        activations = []    # list of weighted inputs (i.e. activations)
        for i,w in enumerate(self.weights):
            z = prepend_bias_unit(z)  # dummy input for bias
            zs.append(z)
            a = np.dot(w, z)  # activation (i.e. weighted inputs), (5.2/5.8)
            if i == len(self.weights) - 1: # last layer uses softmax
                z = softmax(a)
            else:
                z = ReLU(a)
            activations.append(a)

        # backwards error propagation
        y = z  # network (last layer) output
        delta = last_activation_error(z, t)  # derivatives with respect to the last (linear) activation (5.54)
        deltas = [delta]    # list of derivatives w.r.t activations
        for w, a in zip(self.weights[::-1], activations[-2::-1]):
            back_derivatives = ReLU_prime(a)  # using the previous layer's activation derivative
            back_errors = np.dot(w.T[1:], delta)  # bias weight is not involved in error inner-prod computation
            delta = back_derivatives * back_errors  # (5.56); a vector of delta_js for hidden units
            deltas.append(delta)

        # calculate all the partial derivatives w.r.t to weights going forward
        partials = []  # a list of matrices the same size as self.weights containing partial derivatives
        deltas.reverse()
        for d, z in zip(deltas, zs):  # multiply layer output error by layer input to get partial derivatives
            partials.append(np.outer(d, z))
        return partials

    def evaluate(self, test_data):
        """Return the number of test inputs for which the neural
        network outputs the correct result, as well as total loss. Note that the neural
        network's output is assumed to be the index of whichever
        neuron in the final layer has the highest activation."""
        test_loss = test_num_correct = 0
        for (x, t) in test_data:
            pred = self.feedforward(x)
            test_loss += -np.log(pred[t])   # cross-entropy cost for categorical output
            test_num_correct += int(np.argmax(pred) == t)

        # test_results = [np.argmax(self.feedforward(x)) for (x, y) in test_data]
        # return sum(int(x == y) for (x, y) in test_results)
        return test_num_correct, test_loss

#### Miscellaneous functions
def sigmoid_prime(z):
    """Derivative of the logistic sigmoid function."""
    return sigmoid(z) * (1 - sigmoid(z))

def prepend_bias_unit(a):
    """We fold the bias parameters into weights, so activation computed from each layer (except output layer)
    needs to be prefixed with a dummy input unit clamped at 1"""
    return np.vstack(([1], a))  # prepend bias unit as the zeroth element

def last_activation_error(y, t):
    """Compute cost derivatives with respect to the last activation dLdz; y is the vector of class scores (unnormalized
    log probabilities, y is the output vector of normalized class probabilities, t is the target 10x1 vector. """
    return y - t  # works for canonical response outputs (e.g. softmax/logistic/identity outputs with cross-entropy)

def ReLU(z):
    """Apply rectified linear unit on given vector"""
    return np.maximum(0., z)

def ReLU_prime(z):
    """Element-wise derivatives of ReLU with respect to input vector"""
    result = np.zeros_like(z)
    result[z>0] = 1
    return result

def softmax(z):
    """Compute the softmax of a vector (containing unnormalized log likelihood"""
    z-=z.max()  # to avoid numeric problems with exp
    return np.exp(z)/np.sum(np.exp(z))


import csv
from pathlib import Path
from trackman_html_constants import data_points
import os

class TrackmanOutput:
    def __init__(self, date, report_id, club):
        self.date = date
        self.file_name = 'out/' + club + '.csv'
        # stat headers - e.g. ball speed, club path, etc. Assume all the same for each club for now
        self.shots = []
        self.headers = ['Date', 'ReportId', 'ShotNum'] + data_points
        self.club = club
        self.report_id = report_id

    def write(self):
        file = Path(self.file_name)
        if file.is_file():
            self.shots = self.combine_existing_rows()
            os.remove(self.file_name)
        self.write_new_file()

    def combine_existing_rows(self):
        with open(self.file_name, 'r') as original_file:
            reader = csv.DictReader(original_file, fieldnames=self.headers)
            next(reader, None)  # skip header for existing file
            keys = {(self.report_id, self.date, shot['ShotNum']): shot for shot in self.shots}
            combined_shots = []
            for row in reader:
                key = (row['ReportId'], row['Date'], row['ShotNum'])
                if key in keys:
                    row.update(keys[key])
                    combined_shots.append(row)
                    del keys[key]
                else:
                    combined_shots.append(row)
            combined_shots.extend(keys.values())
            return combined_shots

    def write_new_file(self):
        with open(self.file_name, 'w') as output_file:
            writer = csv.DictWriter(output_file, delimiter=',', quotechar='|', quoting=csv.QUOTE_MINIMAL,
                                    fieldnames=self.headers)
            writer.writeheader()
            for shot in self.shots:
                writer.writerow(shot)

    def add_shot(self, stats):
        self.shots.append(stats)


# Configuration file for the Sphinx documentation builder.
#
# This file only contains a selection of the most common options. For a full
# list see the documentation:
# https://www.sphinx-doc.org/en/master/usage/configuration.html

# -- Path setup --------------------------------------------------------------

# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
#
import os
import sys
from smarts import VERSION

sys.path.insert(0, os.path.abspath(".."))

# -- Project information -----------------------------------------------------

project = "SMARTS"
copyright = "2021, Huawei Technologies."
author = "Huawei Noah's Ark Lab."

# The full version, including alpha/beta/rc tags
release = VERSION

# -- General configuration ---------------------------------------------------

# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = [
    "myst_parser",  # support Markdown-based documentation
    "sphinx.ext.autodoc",  # automatically extract docs from docstrings
    "sphinx.ext.coverage",  # to generate documentation coverage reports
    "sphinx.ext.extlinks",  # shorten external links
    "sphinx.ext.napoleon",  # support Numpy and Google doc style
    "sphinx.ext.todo",  # support for todo items
    "sphinx.ext.viewcode",  # link to sourcecode from docs
    "sphinx_rtd_theme",  # Read The Docs theme
    "sphinx_click",  # extract documentation from a `click` application
    "sphinxcontrib.apidoc",
    "sphinxcontrib.spelling",
]

extlinks = {
    "examples": (
        "https://github.com/huawei-noah/SMARTS/blob/master/examples/%s",
        "%s",
    ),
    "scenarios": (
        "https://github.com/huawei-noah/SMARTS/blob/master/scenarios/%s",
        "%s",
    ),
}

# Configuring automated generation of api documentation.
# See: https://github.com/sphinx-contrib/apidoc
apidoc_module_dir = ".."
apidoc_module_first = True
apidoc_excluded_paths = [
    "cli",
    "examples",
    "setup.py",
    "scenarios",
    "smarts/ros",
    "zoo/policies/interaction_aware_motion_prediction",
]
apidoc_extra_args = [
    "--force",
    "--separate",
    "--ext-viewcode",
    "--doc-project=SMARTS",
    "--maxdepth=2",
    "--templatedir=_templates/apidoc",
]
autodoc_mock_imports = [
    "av2",
    "cpuinfo",
    "cv2",
    "gymnasium",
    "lxml",
    "mdutils",
    "moviepy",
    "opendrive2lanelet",
    "pandas",
    "pathos",
    "PIL",
    "pynput",
    "ray",
    "rich",
    "tabulate",
    "tools",
    "torch",
]

todo_include_todos = True

# Add any paths that contain templates here, relative to this directory.
templates_path = ["_templates"]

# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
# This pattern also affects html_static_path and html_extra_path.
exclude_patterns = ["_build", "Thumbs.db", ".DS_Store"]

# -- Options for nit-pick (-n) ----------------------------------------------------

nitpick_ignore = {
    ("py:class", "optional"),
    ("py:class", "ellipsis"),
    ("py:class", "function"),
    # Most of these dynamic type ignores would go away in python>=3.10
    # See for more context: https:github.com/sphinx-doc/sphinx/issues/10090
    ("py:class", "Score"),
    ("py:class", "Done"),
    ("py:class", "CostFuncs"),
    ("py:class", "ActType"),
    ("py:class", "ObsType"),
    ("py:class", "smarts.env.gymnasium.wrappers.metric.utils.T"),
    ("py:class", "enum.Enum"),
}
nitpick_ignore_regex = {
    (r"py:.*", r"av2\..*"),
    (r"py:.*", r"google\.protobuf\..*"),
    (r"py:.*", r"grpc\..*"),
    (r"py:.*", r"gym\..*"),
    (r"py:.*", r"gymnasium\..*"),
    (r"py:.*", r"logging\..*"),
    (r"py:.*", r"multiprocessing\..*"),
    (r"py:.*", r"np\..*"),
    (r"py:.*", r"numpy\..*"),
    (r"py:.*", r"opendrive2lanelet\..*"),
    (r"py:.*", r"panda3d\..*"),
    (r"py:.*", r"pathlib\..*"),
    (r"py:.*", r"pybullet(_utils)?\..*"),
    (r"py:.*", r"re\..*"),
    (r"py:.*", r"shapely\..*"),
    (r"py:.*", r"sumo(lib)?\..*"),
    (r"py:.*", r"tornado\..*"),
    (r"py:.*", r"traci\..*"),
    (r"py:.*", r"typing(_extensions)?\..*"),
    (r"py:.*", r"configparser\..*"),
    (r"py:class", r".*\.?T"),
    (r"py:class", r".*\.?S"),
}

# -- Options for spelling ----------------------------------------------------
spelling_exclude_patterns = ["ignored_*", "**/*_pb2*"]
spelling_ignore_pypi_package_names = True
spelling_show_suggestions = True
spelling_suggestion_limit = 2
spelling_ignore_contributor_names = False
spelling_word_list_filename = ["spelling_wordlist.txt"]

# -- Options for HTML output -------------------------------------------------

# The theme to use for HTML and HTML Help pages.  See the documentation for
# a list of builtin themes.
#
# html_theme = 'alabaster'
html_theme = "sphinx_rtd_theme"

# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ["_static"]


#Exercise 3
#Write the script asking the user to give two integers and multiply them.
from sys import argv

number1 = int(input("Enter first integer"))
number2 = int(input("Enter second integer"))
print("The result of ",number1, number2, "is:", number1 * number2)

name = argv[1]
para_text = name + "is very good boy who helps everyone and also " + name + "participates in all the sports and cultural meet. " + name + "hobbies are playing virtual games and also watching movies."
print(para_text)

#Write the script for calculating area of trainagle ( ask user to enter base and height).

number1 = float(input("Enter Base value"))
number2 = float(input("Enter Height value"))
print("The result of ",number1, number2, "is:", (number1 * number2)/2)

#Write the script of the student form(name_of_student, class_studying, college_name, city_lives)
# that accepts as command line parameters and prints in specified format

student_name = argv[2]
class_value  = argv[3]
college_name = argv[4]
city_lives = argv[5]

print("student_name :",student_name," \n","Class :",class_value," \n","college_name :",college_name," \n","city_lives :",city_lives)


import types
import unittest
from _typeshed import ExcInfo
from collections.abc import Callable
from typing import Any, NamedTuple
from typing_extensions import TypeAlias

__all__ = [
    "register_optionflag",
    "DONT_ACCEPT_TRUE_FOR_1",
    "DONT_ACCEPT_BLANKLINE",
    "NORMALIZE_WHITESPACE",
    "ELLIPSIS",
    "SKIP",
    "IGNORE_EXCEPTION_DETAIL",
    "COMPARISON_FLAGS",
    "REPORT_UDIFF",
    "REPORT_CDIFF",
    "REPORT_NDIFF",
    "REPORT_ONLY_FIRST_FAILURE",
    "REPORTING_FLAGS",
    "FAIL_FAST",
    "Example",
    "DocTest",
    "DocTestParser",
    "DocTestFinder",
    "DocTestRunner",
    "OutputChecker",
    "DocTestFailure",
    "UnexpectedException",
    "DebugRunner",
    "testmod",
    "testfile",
    "run_docstring_examples",
    "DocTestSuite",
    "DocFileSuite",
    "set_unittest_reportflags",
    "script_from_examples",
    "testsource",
    "debug_src",
    "debug",
]

class TestResults(NamedTuple):
    failed: int
    attempted: int

OPTIONFLAGS_BY_NAME: dict[str, int]

def register_optionflag(name: str) -> int: ...

DONT_ACCEPT_TRUE_FOR_1: int
DONT_ACCEPT_BLANKLINE: int
NORMALIZE_WHITESPACE: int
ELLIPSIS: int
SKIP: int
IGNORE_EXCEPTION_DETAIL: int

COMPARISON_FLAGS: int

REPORT_UDIFF: int
REPORT_CDIFF: int
REPORT_NDIFF: int
REPORT_ONLY_FIRST_FAILURE: int
FAIL_FAST: int

REPORTING_FLAGS: int

BLANKLINE_MARKER: str
ELLIPSIS_MARKER: str

class Example:
    source: str
    want: str
    exc_msg: str | None
    lineno: int
    indent: int
    options: dict[int, bool]
    def __init__(
        self,
        source: str,
        want: str,
        exc_msg: str | None = None,
        lineno: int = 0,
        indent: int = 0,
        options: dict[int, bool] | None = None,
    ) -> None: ...
    def __hash__(self) -> int: ...
    def __eq__(self, other: object) -> bool: ...

class DocTest:
    examples: list[Example]
    globs: dict[str, Any]
    name: str
    filename: str | None
    lineno: int | None
    docstring: str | None
    def __init__(
        self,
        examples: list[Example],
        globs: dict[str, Any],
        name: str,
        filename: str | None,
        lineno: int | None,
        docstring: str | None,
    ) -> None: ...
    def __hash__(self) -> int: ...
    def __lt__(self, other: DocTest) -> bool: ...
    def __eq__(self, other: object) -> bool: ...

class DocTestParser:
    def parse(self, string: str, name: str = "<string>") -> list[str | Example]: ...
    def get_doctest(self, string: str, globs: dict[str, Any], name: str, filename: str | None, lineno: int | None) -> DocTest: ...
    def get_examples(self, string: str, name: str = "<string>") -> list[Example]: ...

class DocTestFinder:
    def __init__(
        self, verbose: bool = False, parser: DocTestParser = ..., recurse: bool = True, exclude_empty: bool = True
    ) -> None: ...
    def find(
        self,
        obj: object,
        name: str | None = None,
        module: None | bool | types.ModuleType = None,
        globs: dict[str, Any] | None = None,
        extraglobs: dict[str, Any] | None = None,
    ) -> list[DocTest]: ...

_Out: TypeAlias = Callable[[str], object]

class DocTestRunner:
    DIVIDER: str
    optionflags: int
    original_optionflags: int
    tries: int
    failures: int
    test: DocTest
    def __init__(self, checker: OutputChecker | None = None, verbose: bool | None = None, optionflags: int = 0) -> None: ...
    def report_start(self, out: _Out, test: DocTest, example: Example) -> None: ...
    def report_success(self, out: _Out, test: DocTest, example: Example, got: str) -> None: ...
    def report_failure(self, out: _Out, test: DocTest, example: Example, got: str) -> None: ...
    def report_unexpected_exception(self, out: _Out, test: DocTest, example: Example, exc_info: ExcInfo) -> None: ...
    def run(
        self, test: DocTest, compileflags: int | None = None, out: _Out | None = None, clear_globs: bool = True
    ) -> TestResults: ...
    def summarize(self, verbose: bool | None = None) -> TestResults: ...
    def merge(self, other: DocTestRunner) -> None: ...

class OutputChecker:
    def check_output(self, want: str, got: str, optionflags: int) -> bool: ...
    def output_difference(self, example: Example, got: str, optionflags: int) -> str: ...

class DocTestFailure(Exception):
    test: DocTest
    example: Example
    got: str
    def __init__(self, test: DocTest, example: Example, got: str) -> None: ...

class UnexpectedException(Exception):
    test: DocTest
    example: Example
    exc_info: ExcInfo
    def __init__(self, test: DocTest, example: Example, exc_info: ExcInfo) -> None: ...

class DebugRunner(DocTestRunner): ...

master: DocTestRunner | None

def testmod(
    m: types.ModuleType | None = None,
    name: str | None = None,
    globs: dict[str, Any] | None = None,
    verbose: bool | None = None,
    report: bool = True,
    optionflags: int = 0,
    extraglobs: dict[str, Any] | None = None,
    raise_on_error: bool = False,
    exclude_empty: bool = False,
) -> TestResults: ...
def testfile(
    filename: str,
    module_relative: bool = True,
    name: str | None = None,
    package: None | str | types.ModuleType = None,
    globs: dict[str, Any] | None = None,
    verbose: bool | None = None,
    report: bool = True,
    optionflags: int = 0,
    extraglobs: dict[str, Any] | None = None,
    raise_on_error: bool = False,
    parser: DocTestParser = ...,
    encoding: str | None = None,
) -> TestResults: ...
def run_docstring_examples(
    f: object,
    globs: dict[str, Any],
    verbose: bool = False,
    name: str = "NoName",
    compileflags: int | None = None,
    optionflags: int = 0,
) -> None: ...
def set_unittest_reportflags(flags: int) -> int: ...

class DocTestCase(unittest.TestCase):
    def __init__(
        self,
        test: DocTest,
        optionflags: int = 0,
        setUp: Callable[[DocTest], Any] | None = None,
        tearDown: Callable[[DocTest], Any] | None = None,
        checker: OutputChecker | None = None,
    ) -> None: ...
    def runTest(self) -> None: ...
    def format_failure(self, err: str) -> str: ...
    def __hash__(self) -> int: ...
    def __eq__(self, other: object) -> bool: ...

class SkipDocTestCase(DocTestCase):
    def __init__(self, module: types.ModuleType) -> None: ...
    def test_skip(self) -> None: ...

class _DocTestSuite(unittest.TestSuite): ...

def DocTestSuite(
    module: None | str | types.ModuleType = None,
    globs: dict[str, Any] | None = None,
    extraglobs: dict[str, Any] | None = None,
    test_finder: DocTestFinder | None = None,
    **options: Any,
) -> _DocTestSuite: ...

class DocFileCase(DocTestCase): ...

def DocFileTest(
    path: str,
    module_relative: bool = True,
    package: None | str | types.ModuleType = None,
    globs: dict[str, Any] | None = None,
    parser: DocTestParser = ...,
    encoding: str | None = None,
    **options: Any,
) -> DocFileCase: ...
def DocFileSuite(*paths: str, **kw: Any) -> _DocTestSuite: ...
def script_from_examples(s: str) -> str: ...
def testsource(module: None | str | types.ModuleType, name: str) -> str: ...
def debug_src(src: str, pm: bool = False, globs: dict[str, Any] | None = None) -> None: ...
def debug_script(src: str, pm: bool = False, globs: dict[str, Any] | None = None) -> None: ...
def debug(module: None | str | types.ModuleType, name: str, pm: bool = False) -> None: ...


#encoding:UTF-8
# czy study python
from collections import Counter
# 怎样找出一个序列中出现次数最多的元素呢？
# collections.Counter 类就是专门为这类问题而设计的，它甚至有一个有用的 most_common() 方法直接给了你答案。
words = [
    'look', 'into', 'my', 'eyes', 'look', 'into', 'my', 'eyes',
    'the', 'eyes', 'the', 'eyes', 'the', 'eyes', 'not', 'around', 'the',
    'eyes', "don't", 'look', 'around', 'the', 'eyes', 'look', 'into',
    'my', 'eyes', "you're", 'under'
    ]

word_counts = Counter(words)
# 出现频率最高的 3 个单词
top_three = word_counts.most_common(3)
print(top_three)
# Outputs [('eyes', 8), ('the', 5), ('look', 4)]
print( word_counts['not'])
# 1


from collections import namedtuple

DataIngestionConfig=namedtuple("DataIngestionConfig",
["raw_data_dir","ingested_train_dir","ingested_test_dir"])

#DataValidationConfig
DataValidationConfig = namedtuple("DataValidationConfig", ["schema_file_path","report_file_path","report_page_file_path"])

#datapipelineconfig
TrainingPipelineConfig = namedtuple("TrainingPipelineConfig", ["artifact_dir"])


from rest_framework.response import Response
from portal.serializers.task_serializer import TaskSerializer
from portal.models.task import Task
from portal.models.module import Module
from portal.helpers.request_response_helper import sendResponse
from rest_framework.views import APIView
from rest_framework.decorators import action
import json
from django.contrib.auth import get_user_model
from portal.helpers.filter_helper import filter_query

User = get_user_model()

filter_fields = [ {"value": "name", "type": "contains"},
                 {"value": "status", "type": "equal"},
                 {"value": "due_date", "type": "range"},
                 {"value": "started_on", "type": "range"},
                 {"value": "user", "type": "equal"},
                 ]

class TaskView(APIView):
    serializer_class = TaskSerializer
    queryset = Task.objects.all()
    http_method_names = ['get', 'head', 'post', 'put', 'patch']

    @action(detail=True, methods=['get'])
    def get(self, request):
        id = None
        try:
            id = request.GET.get("id")
        except:
            print("id not present")
        if not id:
            task = Task.objects.all()
            serializer = TaskSerializer(task, many=True)
        else:
            task = Task.objects.get(pk=id)
            serializer = TaskSerializer(task, many=False)
        if request.GET.get("custom_filter"):
            manager = Task.objects
            projects = filter_query(request,filter_fields,manager)
            serializer = TaskSerializer(projects, many=True)

        return Response(serializer.data)

    @action(detail=True, methods=['post'])
    def post(self, request, *args, **kwargs):
        try:
            request = request.body.decode('utf-8')
            request = json.loads(request)
            module = Module.objects.get(pk=request['module'])
            user = User.objects.get(pk=request['user'])
            task = Task.objects.create(name=request['name'], description=request['description'], due_date=request['due_date'], started_on=request['started_on'], module=module, user=user)
            task.save()
            return Response({"status": True})
        except Exception as e:
            print(e)
            return Response({"status": False})

    @action(detail=True, methods=['put'])
    def put(self, request, *args, **kwargs):
        try:
            request = request.body.decode('utf-8')
            request = json.loads(request)
            update_fields = request['update_fields']
            # Convert Dictionary to positional arguments
            Task.objects.filter(pk=request['id']).update(**update_fields)
            return Response({"status": True})
        except Exception as e:
            print(e)
            return Response({"status": False})


import torch
from get_loader import show_image
import matplotlib.pyplot as plt
from torch.optim.lr_scheduler import ReduceLROnPlateau
from utils.utils import best_bleu_cap
import torchvision.transforms as transforms

# Training function that calculates the average train loss at each epoch
def train(criterion, model, optimizer, loader, device):

    total_samples = 0
    total_loss = 0.0
    model.train()

    for batch_idx, (images, captions,_) in enumerate(loader):
        images = images.to(device)
        captions = captions.to(device)
        batch_size = images.size(0)
        total_samples += batch_size
        optimizer.zero_grad()
        outputs = model(images, captions)
        loss = criterion(outputs.view(-1, outputs.size(-1)), captions.view(-1))
        loss.backward()
        optimizer.step()
        total_loss += loss.item() * batch_size

    average_loss = total_loss / total_samples
    return average_loss

# Function to train and generate captions at the same time to analyze how the model learns
# and improves its captions predictions with the pass of the epochs
def train_and_visualize_caps(epoch, train_dataloader, val_dataloader, model, optimizer, criterion, vocab, val_df, device):
    print_every = 400
    total_loss = 0
    total_samples = 0
    model.train()
    for batch_idx, (image, captions,_) in enumerate(iter(train_dataloader)):
        images, captions = image.to(device), captions.to(device)
        batch_size = images.size(0)
        total_samples += batch_size
        optimizer.zero_grad()
        outputs = model(images, captions)

        # Calculate the batch loss.
        loss = criterion(outputs.view(-1, outputs.size(-1)), captions.view(-1))
        loss.backward()
        optimizer.step()
        total_loss += loss.item() * batch_size
        if (batch_idx + 1) % print_every == 0:
            print("Train Epoch: {} Batch [{}/{}]\tLoss: {:.5f}".format(epoch,
            batch_idx + 1, len(train_dataloader), loss.item()
        ))
            #Generate the caption
            model.eval()
            with torch.no_grad():
                dataiter = iter(val_dataloader)
                img,captions_val,img_dir = next(dataiter)
                df_filtered = val_df.loc[val_df['image'] == img_dir[0], 'caption']
                original_captions = [caption.lower() for caption in df_filtered] # List of all the original captions
                features = model.encoder(img[0:1].to(device))
                caps = model.decoder.generate_caption(features.unsqueeze(0),vocab=vocab)
                pred_caption = ' '.join(caps)
                pred_caption = ' '.join(pred_caption.split()[1:-1]) # To erase SOS and EOS tokens from predicted caption
                original_caption, bleu_score = best_bleu_cap(original_captions, pred_caption) # Call to function in utils.py
                print("Best original caption (1 out of 5):", original_caption)
                print("Predicted caption:", pred_caption)
                print("BLEU score :", bleu_score)
                show_image(img[0],title=pred_caption)
            model.train()

    average_loss = total_loss / total_samples
    print("Train Epoch: {} - Training set:  AVERAGE TRAINING LOSS: {:.5f}".format(epoch, average_loss))
    return average_loss


"""Turna

Turna is a control flow graph (CFG) reconstructor for RISC-V architecture.

It performs hybrid CFG reconstruction. It analyzes RISC-V assembly code with
the help of trace information generated by gem5 architecture simulator. After
analysis, Turna detects basic blocks of the program and reconstructs its CFG.
The CFG is printed to command line as text and drawn to pdf file as
a directed graph.

Turna takes two types of input files. Assembly file of the program and
trace files of the program. To create the CFG of a program perform
the following steps:

1. Create the assembly file of the program's executable file by the help of
objdump tool which is delivered with the RISC-V compiler toolchain.
2. Give ".dump" extension to the assembly file.
3. Create trace files of the program by using gem5 architecture simulator.
4. Give ".trc" extension to the trace files.
5. Put above mentioned files to the working directory of Turna.
6. Run Turna.
7. The text outuput is going to be shown in command line interface, and the
graphical output is created as a pdf file in the working directory.

Turna Defaults
- Line numbers in Turna starts with 0.
- Addresses of instructions are in hexadecimal format and does not include
additional symbols like "0x", "h", etc. A sample address is "100c8".

"""

# To measure the running time
from time import time

# Assembly tools of Turna which includes functions that help processing
# assembly file.
import asm_tools

# Trace tools of Turna which includes functions that help processing
# trace files.
import trace_tools

# Type hints support regarding collections
from typing import List, Set, Dict, Tuple, Optional

# List sorting
from operator import itemgetter

# Directory listing
from os import linesep, listdir

# Graph operations
import networkx
from networkx.drawing.nx_agraph import graphviz_layout, to_agraph

# Graph visualization
import pygraphviz

# Line numbers of starting points of basic blocks.
# In this list each item represents the start of a basic block.
start_list: List[int] = []

# Line numbers of end points and line numbers of targets of basic blocks.
# In this list each item represents the end of a basic block. The first element
# of the item is the line number of the end of a basic block. The other elements
# (if present) of the item represent the targets of the basic block.
end_list: List[List[int]] = []

# This is the stack like data structure which holds the starting line numbers
# of functions which will be visited and processed for basic block
# detection. During the analysis when we encounter a function we add it to this
# list. When we visit a function we pop that function from this list.
will_be_visited_fn_list = []

# Conditional branch instructions
branch_inst = ["beq", "bne", "blt", "bltu", "bge", "bgeu", "beqz", "bnez", "bltz", "blez", "bgtz", "bgez", "bgt", "bgtu", "ble", "bleu"]

# Unconditional jump instruction
jump_inst = ["ret", "jal", "j", "jalr", "jr"]

# The set of nodes which have already been added to the the control flow graph
# of the program.
# Each item in the set is an integer which represents the starting point of a
# basic block. By the help of this set, we know if a node is already in the
# control flow graph or not. We use this set in the creation of the control
# flow graph to prevent duplicate entries.
cfg_set = set()

# Starting line number of the root node of the graph.
root_node = 0

# Performance analysis variable. We write values to these variables.
# During the running of the program, the values are written to those variables.
# At the end of the program perfoance values ara calculated and printed.
# Look at the entry point of the program.
milliseconds_start = 0
milliseconds_analysis = 0
milliseconds_print_cfg = 0
milliseconds_draw_pdf_cfg = 0
total_node_count = 0
total_edge_count = 0

def main() -> None:
    """Main function of Turna.

    This function is called by the entry point of the Turna. This function
    searches the current directory for assembly file and trace files of the
    program and then calls analyse function for program structure analysis.
    """

    # Assembly file
    assembly_file: str = None

    # List of trace files.
    trace_files: List[str] = []

    # listdir function returns a list of strings which represent file names.
    for file_name in listdir("./"):
        if file_name.endswith(".trc"):
            trace_files.append(file_name)
        elif file_name.endswith(".dump"):
            assembly_file = file_name

    # If there is no trace file, raise exception.
    if not trace_files:
        raise Exception("Trace files are not found. Please make sure at least a "
                        "trace file is present with \".trc\" extension in the "
                        "current working directory.")

    # If there is no assembly file, raise exception.
    if assembly_file == None:
        raise Exception("Assembly file is not found. Please make sure an assembly "
                        "file is present with \".dump\" extension in the current "
                        "working directory.")

    analyse(assembly_file, trace_files)

def analyse(assembly_file: str, trace_files: list) -> None:
    """Analyses the contents of the assembly file.

    This function is the main function who starts and manages basic block
    detection operation.

    Parameters
    ----------
    assembly_file : str
        Name of the assembly file of the program.
    trace_files : list of str
        List of names of the trace files of the program.
    """

    visited_fn_list = []

    # Performance analysis variable. We write values to these variables.
    # At the end of the program perfoance values ara calculated and printed.
    # Look at the entry point of the program.
    global milliseconds_analysis
    global milliseconds_print_cfg
    global milliseconds_draw_pdf_cfg
    global total_node_count
    global total_edge_count

    global start_list
    global end_list
    global will_be_visited_fn_list

    with open(assembly_file) as f:
        content = f.read()
    f.closed

    assembly_code = content.splitlines()

    # Find main function and add to it to the will be visited function list.
    # It is the first function in this list.
    line_no = asm_tools.get_function_start("main", assembly_code)
    will_be_visited_fn_list.append(line_no)

    while(will_be_visited_fn_list):

        line_no = will_be_visited_fn_list.pop()

        # If the starting line number of the function is not in visited function
        # list then add it to the list and process the related function.
        if (line_no not in visited_fn_list):
            visited_fn_list.append(line_no)
            process_fn(line_no, assembly_code, trace_files)

    # Sort start list.
    start_list = sorted(start_list)

    end_list.sort(key = itemgetter(0))
    #print(f"End list: {end_list}")
    # After making sure duplicate items are not in the end_list remove remove_duplicates function.
    #remove_duplicates()
    #print(f"End list: {end_list}")
    check_targets(assembly_code)

    if (len(start_list) != len(end_list)):
        raise Exception("Error: Lengths of the start list and end list do not match!")

    # Create directed graph.
    cfg = networkx.DiGraph()
    root_node = asm_tools.get_function_start('main', assembly_code)
    create_di_graph(cfg, -1, root_node)

    # Configure the graph.
    cfg.graph['node']={'shape':'box', 'fontname':'sans', 'margin':'0.07', 'width':'0.1', 'height':'0.1'}
    # cfg.graph['edges']={'arrowsize':'1.0'}

    # Get node and edge count of the graph for performance/statistics.
    total_node_count = cfg.number_of_nodes()
    total_edge_count = cfg.number_of_edges()

    cfg_graph = to_agraph(cfg)
    milliseconds_analysis = int(time() * 1000)
    print(cfg_graph)
    milliseconds_print_cfg = int(time() * 1000)
    cfg_graph.layout('dot')
    cfg_graph.draw('cfg.pdf')
    milliseconds_draw_pdf_cfg = int(time() * 1000)

def add_item_to_end_list(end_point: int, target: List[int] = None) -> None:
    """Adds an item to the end list.

    Each item of this list may be a list depending on the end point.
    The first element of the item is the line number of the end point of a basic
    block. The following elemnents of the item are the line numbers of targets
    of the end point of the basic block. When the end point of a basic block is
    found this function is called to add it to start_list.

    This function first checks if the item is in the list or not.

    If the item is in the list its targets are checked not added. If the targets are also
    in the list this function returns. If the target(s) are not present they are
    added.

    If the item is not in the list, it is added with all of its targets.

    This function does not return a value.

    Parameters
    ----------
    end_point: int
        The line number of the end of a basic block which will be added to
        start_list.
    target: list of int
        The list of line numbers of the targets of the end point.
    """

    global end_list
    item_found: bool = False
    item_no: int = -1

    # Check if the end_point is alread in the end_list.
    for item in end_list:
        if item[0] == end_point:
            item_found = True
            break

    # If the list is empty or the end_point is not in the list add it.
    if item_found == False:
        end_list.append([end_point])

    # If there is no target information there is nothing more to do. Just return.
    if target is None:
        return

    # Find the index of the end_point.
    for index, item in enumerate(end_list):
        if item[0] == end_point:
            item_no = index
            break

    # Add targets to the end_point.
    for target_item in target:
        if target_item not in end_list[item_no]:
            end_list[item_no].append(target_item)

def add_item_to_start_list(starting_point: int) -> None:
    """Adds an item to the start list.

    The item is the the line number of the starting point of the basic block.
    When the starting point of a basic block is found this function is called to
    add it to start_list.

    This function first checks if the item is already in the list or not. If
    the item is in the list it is not added. If it is not in the list it is
    added.

    This function does not return a value.

    Parameters
    ----------
    starting_point : int
        The line number of the start of a basic block which will be added to
        start_list.
    """

    global start_list

    # If the item is not already in the start_list add it.
    if starting_point not in start_list:
        start_list.append(starting_point)

def create_di_graph(cfg: networkx.DiGraph, previous_node: int,
                    current_node: int) -> None:
    """Creates control flow graph of the program.

    Note: This function is a recursive function.

    In control flow graph a node represents a basic block, and an edge
    represents the connection between two basic blocks. Starting line number of
    a basic block is the id of the node which represents that basic block.

    Previous node and current node are id numbers of two nodes. In other words
    they are starting line numbers of two basic blocks. Current node is the new
    node which will be added to the cfg. This function works as follows:

    1. It adds a new node to the cfg with the current_node id number. It updates
    the information of the node with the values from start_list and end_list.
    2. It adds an edge between the current node and previous node. Current node
    is one of the targets of previous node.
    3. It checks the targets of the current node (newly added basic block) by
    looking at end_list. If there is a target information it calls itself again.
    In the new call, the id number of newly added node (current_node) will be
    passed as previous_node argument, and the target of the newly added node
    will be passed as current_node argument.

    Parameters
    ----------
    cfg : directed graph
        This is the control flow graph of the program.
    previous_node : int
        The id number of the previous node. In other words the starting line
        number of the previous basic block.
    current_node : int
        The id number of the current node. In other words the starting line
        number of the current basic block. This node will be added to the
        control flow graph.
    """

    index = 0

    if (current_node in cfg_set) & (previous_node != -1):
        cfg.add_edge(previous_node, current_node)
        return

    for i in range(0, len(start_list)):
        if (start_list[i] == current_node):
            index = i

    cfg.add_node(current_node)
    cfg_set.add(current_node)

    if (previous_node != -1):
        cfg.add_edge(previous_node, current_node)

    cfg.nodes[current_node]['label'] = "Start: " + str(start_list[index]) + "; End: " + str(end_list[index][0])
    cfg.nodes[current_node]['start'] = start_list[index]
    cfg.nodes[current_node]['end'] = end_list[index][0]
    for i1 in range(1, len(end_list[index])):
        target = 'target' + str(i1)
        #print(target)
        cfg.nodes[current_node][target] = "null"

    for i2 in range(1, len(end_list[index])):
        target = 'target' + str(i2)
        #print(target)
        cfg.nodes[current_node][target] = end_list[index][i2]
        create_di_graph(cfg, current_node, end_list[index][i2])

def remove_duplicates() -> None:
    """Detects and removes the duplicate elements in the end_list.

    This function is called after analyzing the assembly code. During detection
    we don't check duplicate end points. Therefore, after analyzing the file
    there may be duplicate elements in the end_list. This function checks and
    removes them.

    This function does not return a value. Instead it makes required
    modifications to end_list.
    """

    result = -1
    while(True):
        if (result != -1):
            del(end_list[result])
            result = -1

        found = False
        for index_1, item_1 in enumerate(end_list):
            for index_2, item_2 in enumerate(end_list):
                if ((item_1[0] == item_2[0]) & (index_1 != index_2)):
                    found = True
                    if (len(item_1) >= len(item_2)):
                        result = index_2
                    else:
                        result = index_1
                    break

            if (found):
                break

        if (result == -1):
            break

def check_targets(assembly_code: list) -> None:
    """Checks the targets of basic blocks.

    This function is called afeter analyzing the assembly code. It is used to
    check the targets of basic blocks. It detects targets of basic blocks which
    are not detected until now. This only happens if a basic block's target is
    the next line of the same basic block.

    Iterate all of the items in the end_list. The items of the end_list
    represent end points of basic blocks. First element of an item is the line
    number of the end point of a basic block. Other elements of an item are the
    targets of the basic block.

    If an item has not target information (basic block has not any
    target) and is not the end of the main function, the next line of the item
    should be the target of the item (the target of the basic block should be
    the next line).

    1. If the length of an item is 1 the item has not target information.
    2. If the line number of an item (item[0]) is different from the line number
    of the end of main function, the item is not the end of the main function.
    In this case the next line of the item is the target of the item (basic
    block).

    This function does not return a value. Instead it makes required
    modifications to end_list.

    Parameters
    ----------
    assembly_code : list of str
        Assembly code of the program. This is needed to find the line number of
        the last instruction of the main function.
    """

    # Find the line number of the last instruction of main function.
    main_function_end = asm_tools.get_function_end('main', assembly_code)

    for index, item in enumerate(end_list):
        if (len(item) == 1):
            if (item[0] != main_function_end):
                item = [item[0], item[0] + 1]
                end_list[index] = item

def process_fn(line_no: int, assembly_code: list, trace_files: list) -> None:
    """Detects basic blocks in a given funtion.

    Traverses a function in assembly code line by line and detects basic blocks.

    First it checks if the is null or not. If the line is null this means the
    end of the function is reached. In this case returns. If the line is not
    null the line is tokenized and analyzed.

    If the length of the tokens is less than 3 the line is not a valid
    instruction. In this case processing continues with the next line.

    If the line is a "ret" (return from subroutine) instruction starting and
    end points of basic blocks are detected and written in start_list and
    end_list respectively.

    If the line is a branch or jump instruction the related functions which
    process them is called.

    This function does not return a value. Instead it adds the line numbers of
    the detected starting and end points of basic blocks to the start_list and
    end_list.

    Parameters
    ----------
    line_no : int
        Starting line number of the function which is going to be processed.
    assembly_code : list of str
        Assembly code of the program.
    trace_files : list of file
        List of trace files of the program.
    """

    global start_list
    global end_list

    # Start of a funtion is always the start of a basic block.
    add_item_to_start_list(line_no)

    index = line_no - 1
    while(True):
        index = index + 1

        if (assembly_code[index] == ""):
            # Reached end of the function.
            return

        tokens = assembly_code[index].split()
        # tokens[0] -> address:
        # tokens[1] -> hexadecimal code of machine language instruction
        # tokens[2] -> mnemonic
        # tokens[3] -> operands

        if (len(tokens) < 3):
            # Not a valid instruction. Continue with next line.
            continue

        elif (tokens[2] in branch_inst):
            process_branch_inst(index, tokens, assembly_code)

        elif (tokens[2] in jump_inst):
            process_jump_inst(index, tokens, assembly_code, trace_files)

def process_branch_inst(line_no: int, tokens: list, assembly_code: list) -> None:
    """Detects basic block starting and end points from given branch instruction.

    Processes a given branch instrcution. Depending on the instruction, it
    detects the startng and end points of basic blocks. This is achieved by the
    help of the rule set.

    This function does not return a value. Instead it adds the line numbers of
    the detected starting and end points of basic blocks to the start_list and
    end_list.

    Parameters
    ----------
    line_no : int
        Line number of the branch instruction which will be processed.
    tokens : list of str
        The branch instruction line which will be processed.
    assembly_code : list of str
        Assembly code of the program.
    """

    operands = tokens[3].split(',')

    # operands[2] -> target address
    if (len(operands) == 2):
        target_line_no = asm_tools.address_to_line_no(operands[1], assembly_code)
    elif (len(operands) == 3):
        target_line_no = asm_tools.address_to_line_no(operands[2], assembly_code)

    # The line of the current branch instruction is the end of a basic block.
    # Branch instructions have two targets.
    # The subsequent line and the branch target are the targets of the branch
    # instruction. We add all this together to the end list.
    add_item_to_end_list(line_no, [line_no + 1, target_line_no])

    # Previous line of the target of a branch instruction is also the end of
    # a basic block.
    add_item_to_end_list(target_line_no - 1)

    # The subsequent line of a branch instruction is the start of basic block.
    add_item_to_start_list(line_no + 1)

    # The target line of a branch instruction is the start of a basic block.
    add_item_to_start_list(target_line_no)

def process_jump_inst(line_no: int, tokens: list, assembly_code: list,
                      trace_files: list) -> None:
    """Detects basic block starting and end points from given jump instruction.

    Processes a given jump instrcution. Depending on the instruction, it
    detects the starting and end points of basic blocks. This is achieved by the
    help of the rule set.

    This function does not return a value. Instead it adds the line numbers of
    the detected starting and end points of basic blocks to the start_list and
    end_list.

    Parameters
    ----------
    line_no : int
        Line number of the jump instruction which will be processed.
    tokens : list of str
        The jump instruction line which will be processed.
    assembly_code : list of str
        Assembly code of the program.
    trace_files : list of file
        List of trace files of the program.
    """

    global will_be_visited_fn_list

    if (tokens[2] == 'ret'):
        # If the ret instruction is in the main function then just add that line
        # the end list. Otherwise do nothing. Because we add other functions'
        # ret instructions to the end list during function call detection in
        # jal and jalr instructions.
        fn = asm_tools.get_function_name(assembly_code[line_no].split()[0][:-1], assembly_code)
        if (fn == "main"):
            add_item_to_end_list(line_no)

    elif (tokens[2] == 'jal'):
        operands = tokens[3].split(',')

        # operands[1] -> target address
        # Sample code: jal	ra,101c4 <main>

        target_line_no = asm_tools.address_to_line_no(operands[1], assembly_code)

        # The line of the jal instruction is the end of a basic block.
        add_item_to_end_list(line_no, [target_line_no])

        # Next line of the jal instruction is the start of a basic block.
        add_item_to_start_list(line_no + 1)

        # Target line of the jal instruction is the start of a basic block.
        add_item_to_start_list(target_line_no)

        # Target of the jal instruction is a function.
        will_be_visited_fn_list.append(target_line_no)

        # Find the end point (ret instruction) of the target function. Its
        # return point is the next line of the jal instruction. Add this info
        # to the end list.
        # Turna now detects the target of ret instruction
        # by the help of jal instruction in assembly code. Although ret is
        # a indirect jump instruction there is no need to search for the
        # target of ret instrucion in trace files.
        target_fn = asm_tools.get_function_name(operands[1], assembly_code)
        target_fn_end = asm_tools.get_function_end(target_fn, assembly_code)
        add_item_to_end_list(target_fn_end, [line_no + 1])

    elif (tokens[2] == 'jalr'):

        # tokens[0][:-1] is the address of the jalr instruction.
        target_line_no = find_target(tokens[0][:-1], assembly_code, trace_files)

        if (target_line_no == -1):
            raise Exception("Error: Could not find the target of jalr instruction on line " + line_no)

        # The line of the jalr instruction is the end of a basic block.
        add_item_to_end_list(line_no, [target_line_no])

        # Next line of the jalr instruction is the start of a basic block.
        add_item_to_start_list(line_no + 1)

        # Target line of the jalr instruction is the start of a basic block.
        add_item_to_start_list(target_line_no)

        # Target of the jalr instruction is a function.
        will_be_visited_fn_list.append(target_line_no)

        # Find the end point (ret instruction) of the target function. Its
        # return point is the next line of the jal instruction. Add this info
        # to the end list.
        # Turna now detects the target of ret instruction
        # by the help of jal instruction in assembly code. Although ret is
        # a indirect jump instruction there is no need to search for the
        # target of ret instrucion in trace files.
        # assembly_code[target_line_no].split()[0][:-1] is the address of the
        # target line number. get_function_name of asm_tools.py expects address
        # value.
        target_fn = asm_tools.get_function_name(assembly_code[target_line_no].split()[0][:-1], assembly_code)
        target_fn_end = asm_tools.get_function_end(target_fn, assembly_code)
        add_item_to_end_list(target_fn_end, [line_no + 1])

    elif (tokens[2] == 'j'):

        # No need to split. Fourth token in the line of a j instruction is
        # the target address
        target_line_no = asm_tools.address_to_line_no(tokens[3], assembly_code)

        add_item_to_start_list(line_no + 1)
        add_item_to_start_list(target_line_no)

        add_item_to_end_list(line_no, [target_line_no])

        # Previous line of the target of a j instruction is also the end of
        # a basic block.
        add_item_to_end_list(target_line_no - 1)

    elif (tokens[2] == 'jr'):

        add_item_to_start_list(line_no + 1)

        target_line_no = find_target(tokens[0][:-1], assembly_code, trace_files)
        if (target_line_no == -1):
            print("Error: Could not find the target of jr instruction on line " + line_no)
        else:
            add_item_to_start_list(target_line_no)

            # Previous line of the target of a jr instruction is also the end of
            # a basic block.
            add_item_to_end_list(target_line_no - 1)

        add_item_to_end_list(line_no, [target_line_no])

def find_target(source_address: str, assembly_code: list,
                trace_files: list) -> int:
    """Finds the line number of the target address of an indirect jump
    instruction by the help of trace files.

    This is achived by processing trace files. Firstly the source address
    of jump instruction is found in the trace files. The subsequent line
    is the target of the jump instruction. The address information in the
    subsequent line is extracted. Then, the code line which starts with this
    address is searched in the assembly file. This code line is the target of
    the jump instruction and the beginning of a basic block. The line number
    of this code line is returned.

    If source address of the jump instruction is not found in the trace files,
    this means that the path was not taken. In this case an error is raised. The
    error is raised by the "get_next_address" function in the trace_tools file.

    If the target address of the jump instruction is not found the assembly file
    an error is raised. The error is raised by the "address_to_line_no" function
    in the trace_tools file.

    Parameters
    ----------
    source_address : str
        The source address which will be searched in trace files.
    assembly_code : list of str
        Assembly code in which the line number of the target address will be
        searched.
    trace_files : list of file
        List of trace files in which the source address will be searched.

    Returns
    -------
    line_no : int
        The line number of the target address. Positive integer if successful,
        raises error otherwise
    """

    target_address = trace_tools.get_next_address(source_address, trace_files)
    line_no = asm_tools.address_to_line_no(target_address, assembly_code)

    return line_no

if __name__ == "__main__":
    """Entry point of the Turna.
    """

    milliseconds_start = int(time() * 1000)
    main()
    milliseconds_end = int(time() * 1000)

    print("CFG Creation Time : ", milliseconds_analysis - milliseconds_start, "ms")
    print("CFG Printing Time : ", milliseconds_print_cfg - milliseconds_analysis, "ms")
    print("CFG Drawing (PDF) Time : ", milliseconds_draw_pdf_cfg - milliseconds_print_cfg, "ms")
    print("Total Running Time : ", milliseconds_end - milliseconds_start, "ms")
    print("Total Node Count : ", total_node_count)
    print("Total Edge Count : ", total_edge_count)


class Solution:
    def numOfSubarrays(self, arr: List[int], k: int, threshold: int) -> int:
        # subarray니까 정렬은 못 쓰고
        # 그냥 슬라이딩 윈도우로 순회하면서 봐야할 듯?
        # 계산을 재활용할 방법이... 그냥 빠지는거 빼고 들어오는거 더해서 값이 k * threshold 보다 큰지 보면 될 듯?

        # 일단 첫번째는 스페셜 케이스로 미리 계산하자
        # array를 만들 필요도 없구나..? sum만 계산하면 됨.
        TARGET = k * threshold
        ans = 0

        sub_sum = 0
        for i in range(k):
            sub_sum += arr[i]

        if sub_sum >= TARGET:
            ans += 1

        for i in range(k, len(arr)):
            sub_sum = sub_sum - arr[i - k] + arr[i]
            if sub_sum >= TARGET:
                ans += 1

        return ans


import pickle, collections
from urllib.parse import urlsplit

dp = {}
video_counts = {}
frame_counts = {}

file = r'C:\Users\crrat\PycharmProjects\StreamCrawler\logs\projectfreetv_us_sources.p'
output = open(r'C:\Users\crrat\PycharmProjects\StreamCrawler\FilteredResults\projectfreetv_output', 'w+')

try:
    dp = pickle.load( open(file, 'rb'))
except pickle.UnpicklingError as p:
    print("Unpickling Error :: " + p.__cause__)
except BaseException as e:
    print("Other error :: " + e.__cause__)

frames = dp["iframe"]
videos = dp["video"]

output.write("IFrame Data :: %s\n" % frames.__len__())
output.write("----------------------------------------------\n")
for frame in frames:
    host = urlsplit(frame).hostname.replace('http://', '')

    if host in frame_counts.keys():
        frame_counts[host] += 1
    else:
        frame_counts[host] = 1

ord_frames = collections.OrderedDict(sorted(frame_counts.items()))

for key in ord_frames:
    output.write('%s :: %s\n' % (key, frame_counts[key]))
output.write('----------------------------------------------\n')


#!/usr/bin/env python3
"""Script for rendering config for topologies defined by a YAML file"""
from argparse import ArgumentParser, Namespace
import yaml
from jinja2 import Template

def main(args: Namespace):
    """First method called when ran as a script"""
    with open(args.topology_file, "r") as fp_:
        render(
            data=yaml.safe_load(fp_),
            path_to_j2=args.template if args.template else "ios-classic-ospf.j2",
        )

def render(data: dict, path_to_j2: str):
    """Renders given Jinja2 template with given data (dict)

    Args:
        data: Dict object containing structured data valid for given Jinja template
        path_to_j2: Filepath to Jinja template
    """
    with open(path_to_j2) as file_:
        print(Template(file_.read()).render(data))

if __name__ == "__main__":
    parser = ArgumentParser(description="Render templates for node config")
    parser.add_argument("topology_file", type=str, help="YAML defining topology")
    parser.add_argument(
        "--template", type=str, help="Use a custom template. Default: ./ios-classic-ospf.j2"
    )
    main(parser.parse_args())


#  연산자

#7차시
a = int(input())

print('%0.2f inch =>  %0.2f cm' %(a, a*2.54))

#8차시
a=int(input())

print('%0.2f kg =>  %0.2f lb' %(a, a*2.2046))

#흐름과 제어 -if

#17차시
text = input()

if text.islower():
    text_1 = text.upper()
else:
    text_1 = text.lower()

print('%s(ASCII: %d) => %s(ASCII: %d)' %(text, ord(text), text_1, ord(text_1)))

#19차시
a=[]

for i in range(100,301):
    if (i // 100) % 2 ==0 and (i // 10) % 2 ==0 and (i % 2) ==0:
        a.append(i)

print(','.join(repr(i) for i in a))


from fastapi import APIRouter

from models.pet import CreatePet

router = APIRouter(tags=["pets"], prefix="/pets")

@router.get("")
async def get_all_pets():
    return {"pets": ["pet1", "pet2"]}

@router.post("")
async def create_pet(pet: CreatePet):
    return {"msg": "pet created", "animal": pet.animal, "name": pet.name}


# 计算所有左叶子结点的和，深度遍历加一起即可。
# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
    s = 0

    def sumOfLeftLeaves(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        if not root:
            return 0
        self.dsf(root, False)
        return self.s

    def dsf(self, node, flag):
        if flag and not node.left and not node.right:
            self.s += node.val
        if node.left:
            self.dsf(node.left, True)
        if node.right:
            self.dsf(node.right, False)


"""
exif writer:
    (1) opens a file:
    (2) changes it's name
    (3) reads and edit's exif data
    (4) saves vile with new name
"""
# import the necessary packages
import piexif
import PIL
from PIL import Image,ImageChops
#from Pillow import Image,ImageChops
from PIL.ExifTags import TAGS
#from Pillow.ExifTags import TAGS
import matplotlib.pyplot as plt
import tkinter
from tkinter import *
from tkinter import filedialog
import seaborn as sns
import os
import cv2
from DateTime import DateTime
from datetime import datetime
import pandas as pd
import numpy as np
import math
import matplotlib.pyplot as plt
import csv
import scipy
from scipy.ndimage.filters import gaussian_filter

root = tkinter.Tk()

def get_directory_name(caption):
    dirname = tkinter.filedialog.askdirectory(parent=root,initialdir="/",title=caption)
    if len(dirname ) > 0:
        print (' You chose %s' % dirname)
    return dirname

def get_file_name(caption):
    file = tkinter.filedialog.askopenfile(parent=root,mode='rb',title=caption)
    if file != None:
        data = file.read()
    #file.close()
    print (' I got %d bytes from this file.' % len(data))
    return file

def save_file_name(caption):
    myFormats = [
    ('Windows Bitmap','*.bmp'),
    ('Portable Network Graphics','*.png'),
    ('JPEG / JFIF','*.jpg'),
    ('CompuServer GIF','*.gif'),
    ]
    fileName = tkfiledialog.asksaveasfilename(parent=root,filetypes=myFormats ,title=caption)
    if len(fileName ) > 0:
        print ('Now saving under %s' % nomFichier)
    return fileName

# gets the file meta data for an image file
def get_exif(fn):
    ret = {}
    i = PIL.Image.open(fn)
    info = i._getexif()
    for tag, value in info.items():
        decoded = TAGS.get(tag, tag)
        ret[decoded] = value
    return ret

# gets gps data in decimal degrees from image meta data
def get_gps_deg(exf):
    GPS = []
    gps = exf['GPSInfo']
    GPS0 = float(gps[2][0][0])/float(gps[2][0][1]) + float(gps[2][1][0])/(60.*float(gps[2][1][1])) + float(gps[2][2][0])/(3600*float(gps[2][2][1]))
    if (gps[1] == u'S'):
        GPS0 = -GPS0
    GPS.append(GPS0)
    GPS1 = float(gps[4][0][0])/float(gps[4][0][1]) + float(gps[4][1][0])/(60.*float(gps[4][1][1])) + float(gps[4][2][0])/(3600*float(gps[4][2][1]))
    if (gps[3] == u'W'):
        GPS1 = -GPS1
    GPS.append(GPS1)
    GPS2 = float(gps[6][0])/float(gps[6][1])
    GPS.append(GPS2)
    return GPS

def problem_1():

    # Get first file to process
    print ('Please Browse  image ')
    ImageFile = get_file_name('Select Image File')

    # Get output file directory and file name
    print ('browse for directory to store output file')
    output_Dir = get_directory_name('select output directory')
    output_filename = input(' Enter output file name: ')
    output_file = output_Dir + '/' + output_filename + '.JPEG'

    # Read exif data
    img1 = PIL.Image.open(ImageFile)

    exif_dict = piexif.load(img1.info["exif"])
    w, h = img1.size
    exif_dict["0th"][piexif.ImageIFD.XResolution] = (w, 1)
    exif_dict["0th"][piexif.ImageIFD.YResolution] = (h, 1)

    for ifd in ("0th", "Exif", "GPS", "1st"):
        for tag in exif_dict[ifd]:
            print(piexif.TAGS[ifd][tag]["name"], exif_dict[ifd][tag])

    exif_dict['New_Key'] = 999
    print("\n exif_dict['New_Key']",exif_dict['New_Key'])

    #exif_dict['GPSAltitude'] = (341424, 1000)
    exif_dict['GPS'][piexif.GPSIFD.GPSAltitude] = (140, 1)
    print("\n ******exif_dict['GPSAltitude******']",exif_dict['GPSAltitude'][piexif.GPSIFD.GPSAltitude])

    exif_bytes = piexif.dump(exif_dict)

    #piexif.insert(exif_bytes,output_file)
    img1.save(output_file,exif=exif_bytes)
    img1.close()

    #Read copied file's metadata

    img2 = PIL.Image.open(output_file)
    exif_dict_2 = piexif.load(img2.info["exif"])
    w, h = img2.size
    exif_dict_2["0th"][piexif.ImageIFD.XResolution] = (w, 1)
    exif_dict_2["0th"][piexif.ImageIFD.YResolution] = (h, 1)

    print('\n ##### revised metadata #####')

    #for ifd in ("0th", "Exif", "GPS", "1st"):
    for ifd in (exif_dict_2):
        try:
            for tag in exif_dict_2[ifd]:
                print(piexif.TAGS[ifd][tag]["name"], exif_dict_2[ifd][tag])
        except:
            pass

    img2.close()

def main():
    problem_1()
    #problem_2()

    return

main()
"""
if __name__ == "main":
     # execute only if run as a script
     main()
"""


import logging
import os
import random
import sys
import requests
from environs import Env
from requests.exceptions import MissingSchema, HTTPError

class VkApiError(Exception):
    pass

def raise_vk_api_error(response):
    if response.get('error'):
        raise VkApiError(f'Something wrong with vk api:\n{response["error"]}')

def get_comics_amount():
    xkcd_api_url = 'https://xkcd.com/info.0.json'
    response = requests.get(xkcd_api_url)
    response.raise_for_status()
    response_extraction = response.json()
    return response_extraction['num']

def download_img(img_url, name, dir_path):

    img_path = os.path.join(dir_path, name)

    response = requests.get(img_url)
    response.raise_for_status()

    with open(img_path, 'wb') as img:
        img.write(response.content)

def get_wall_upload_server(group_id, access_token):

    server_url = 'https://api.vk.com/method/photos.getWallUploadServer/'
    params = {
        'access_token': access_token,
        'group_id': group_id,
        'v': '5.131'
    }

    response = requests.get(server_url, params=params)
    response.raise_for_status()
    response_extraction = response.json()
    raise_vk_api_error(response_extraction)
    logging.info('Get url for upload image')
    return response_extraction['response']['upload_url']

def send_photo_to_server(url, dir_path, photo):

    img_path = os.path.join(dir_path, photo)
    with open(img_path, 'rb') as file:
        files = {
            'photo': file,
        }
        response = requests.post(url, files=files)
    response.raise_for_status()
    response_extraction = response.json()
    raise_vk_api_error(response_extraction)
    logging.info('Send image to vk server')
    params_from_server = [
        response_extraction.get('server'),
        response_extraction.get('photo'),
        response_extraction.get('hash'),
    ]
    if all(params_from_server):
        return params_from_server
    else:
        print('Something wrong with send photo to server')

def save_photo_to_wall(
        group_id, access_token, server, photo, vk_hash
):

    wall_photo_url = 'https://api.vk.com/method/photos.saveWallPhoto/'
    params = {
        'server': server,
        'photo': photo,
        'hash': vk_hash,
        'group_id': group_id,
        'access_token': access_token,
        'v': '5.131',
    }

    response = requests.post(wall_photo_url, params=params)
    response.raise_for_status()
    response_extraction = response.json()
    raise_vk_api_error(response_extraction)
    logging.info('Save image to vk wall')

    params_from_wall = [
        response_extraction['response'][0].get('owner_id'),
        response_extraction['response'][0].get('id'),
    ]

    return params_from_wall

def post_photo_to_wall(
        access_token, message, group_id, owner_id, media_id
):
    wall_post_url = 'https://api.vk.com/method/wall.post/'
    attachments = f'photo{owner_id}_{media_id}'
    params = {
        'owner_id': f'-{group_id}',
        'from_group': 1,
        'message': message,
        'attachments': attachments,
        'access_token': access_token,
        'v': '5.131',
    }

    response = requests.post(wall_post_url, params=params)
    response.raise_for_status()
    response_extraction = response.json()
    raise_vk_api_error(response_extraction)

    logging.info('Image successfully posted!')

    return response.json()

def download_xkcd_img(dir_name, comics_id):
    os.makedirs(dir_name, exist_ok=True)

    comics_url = f'https://xkcd.com/{comics_id}/info.0.json'

    response = requests.get(comics_url)
    response.raise_for_status()
    comics_extraction = response.json()

    comics_img_url = comics_extraction['img']
    comics_img_comment = comics_extraction['alt']
    comics_img_name = f'{comics_id}.png'

    download_img(comics_img_url, comics_img_name, dir_name)

    return comics_img_comment, comics_img_name

def post_photo(
        dir_name, photo, img_comment, group_id, access_token,
):
    img_server_url = get_wall_upload_server(group_id, access_token)
    server_response = send_photo_to_server(img_server_url, dir_name, photo)
    wall_response = save_photo_to_wall(
        group_id, access_token, *server_response
    )

    post_photo_to_wall(
        access_token, img_comment, group_id, *wall_response
    )

if __name__ == '__main__':

    logging.basicConfig(stream=sys.stdout, level=logging.INFO)

    env = Env()
    env.read_env()

    vk_access_token = env('VK_ACCESS_TOKEN')
    vk_group_id = env('VK_GROUP_ID')
    vk_img_dir = env('VK_IMG_DIR')

    comics_amount = get_comics_amount()
    random_comics_id = random.randint(1, comics_amount)

    try:
        comics_img_comment, comics_img_name = download_xkcd_img(
            vk_img_dir, random_comics_id
        )
    except (KeyError, MissingSchema, HTTPError) as e:
        logging.error(f'Error with download img from xkcd:\n{e}')
    else:
        try:
            post_photo(
                vk_img_dir, comics_img_name, comics_img_comment, vk_group_id, vk_access_token
            )
        except HTTPError as e:
            logging.error(f'Error with posted img to vk wall:\n{e}')

        finally:
            os.remove(os.path.join(vk_img_dir, comics_img_name))


from _random import Random
from sys import stdout
from sys import argv
from os import system
import msvcrt as ms

def loadf():
	from sys import argv

	try:
		with open(argv[1]) as f:
			code = []

			for line in f.read().split("\n"):
				code.append(line.strip().split())

			return tuple(code)
	except:
		return

system("color")
data, c = loadf(), 0

if data is None:
	exit(1)

def check(no):
	if len(x) <= no:
		print("\x1b[31;1mNot enough arguments at line %s (must be at least %s)\x1b[0m" % (c + 1, no))
		system("pause > nul")
		exit(1)

def inp():
	key = ms.getch()
	if key == b"\xe0" or key == b"\x00":
		m = ms.getch()
		if m[0] < 128:
			return m[0] + 128
		else:
			return m[0] + 64
	return key[0]

def num(x):
	r = 0
	for i in x:
		r *= 16
		r += int(i, 4)
	return r

def v(a, b):
	return int(a, 4) * 16 + int(b, 4)

r = Random()
rand = r.getrandbits

stack = []
carry = 0

labels = {}
ints = []

idx = 0
for x in data:
	if x:
		ints.append(x[0])
		if x[0] == "10":
			labels[num(x[1:])] = idx
	else:
		ints.append("")
	idx += 1

d = {
	0: 30, 1: 34, 2: 32, 3: 36, 4: 31, 5: 35, 6: 33, 7: 37,
	8: 90, 9: 94, 10: 92, 11: 96, 12: 91, 13: 95, 14: 93, 15: 97,
	16: 40, 17: 44, 18: 42, 19: 46, 20: 41, 21: 45, 22: 43, 23: 47,
	24: 100, 25: 104, 26: 102, 27: 106, 28: 101, 29: 105, 30: 103, 31: 107,
	32: 0, 33: 1, 34: 4, 35: 7
}
del idx

try:
	while c < len(data):
		x = data[c]
		t = ints[c]

		if t == "00":
			check(2)
			n = v(x[1], x[2])
			stack.append(n)

		elif t == "01":
			if stack:
				for z in range(num(x[1:])):
					stack.pop(-1)

		elif t == "02":
			if stack:
				for z in range(num(x[1:])):
					stack.append(stack[-1])

		elif t == "03":
			if len(stack) > 1:
				stack.append(stack.pop(-2))

		elif t == "11":
			lb = num(x[1:])
			if lb in labels:
				c = labels[lb]

		elif t == "12":
			stack.append(carry)

		elif t == "13":
			check(1)
			if len(stack) > 1:
				if x[1] == "00":
					b, a = stack.pop(-1), stack.pop(-1)
					stack.append((a + b) % 256)
					carry = (a + b) // 256
				elif x[1] == "01":
					b, a = stack.pop(-1), stack.pop(-1)
					stack.append((a - b) % 256)
					carry = (a - b) // 256
				elif x[1] == "02":
					b, a = stack.pop(-1), stack.pop(-1)
					stack.append((a * b) % 256)
					carry = (a * b) // 256
				elif x[1] == "03":
					b, a = stack.pop(-1), stack.pop(-1)
					stack.append((a // b) % 256)
					carry = 0
				elif x[1] == "10":
					b, a = stack.pop(-1), stack.pop(-1)
					stack.append((a % b) % 256)
					carry = 0
				elif x[1] == "11":
					b, a = stack.pop(-1), stack.pop(-1)
					stack.append((a ** b) % 256)
					carry = (a ** b) // 256
				elif x[1] == "12":
					b, a = stack.pop(-1), stack.pop(-1)
					stack.append(int(a ** (1 / b)) % 256)
					carry = 0
				elif x[1] == "13":
					b, a = stack.pop(-1), stack.pop(-1)
					stack.append((a & b) % 256)
					carry = 0
				elif x[1] == "20":
					b, a = stack.pop(-1), stack.pop(-1)
					stack.append((a | b) % 256)
					carry = 0
				elif x[1] == "21":
					b, a = stack.pop(-1), stack.pop(-1)
					stack.append((a ^ b) % 256)
					carry = 0

		elif t == "20":
			check(1)
			if len(stack) > 1:
				a, b = stack[-2], stack[-1]

				skip, f = c, 0
				while 1:
					if ints[skip] == "20":
						f += 1
					elif ints[skip] == "21":
						f -= 1
					if not f:
						break
					skip += 1

				if x[1] == "00":
					if not (a == b):
						c = skip
				if x[1] == "01":
					if not (a != b):
						c = skip
				if x[1] == "02":
					if not (a > b):
						c = skip
				if x[1] == "03":
					if not (a < b):
						c = skip
				if x[1] == "10":
					if not (a >= b):
						c = skip
				if x[1] == "11":
					if not (a <= b):
						c = skip

		elif t == "22":
			stack.append(rand(8))

		elif t == "23":
			r.seed(num(x[1:]))

		elif t == "30":
			check(1)
			if x[1] == "00":
				print(chr(stack.pop(-1)), end="")
				stdout.flush()
			elif x[1] == "10":
				print(bin(stack.pop(-1))[2:], end="")
				stdout.flush()
			elif x[1] == "11":
				print(oct(stack.pop(-1))[2:], end="")
				stdout.flush()
			elif x[1] == "12":
				print(stack.pop(-1), end="")
				stdout.flush()
			elif x[1] == "13":
				print(hex(stack.pop(-1))[2:], end="")
				stdout.flush()

		elif t == "31":
			check(1)
			if int(x[1], 4):
				system("pause > nul")
			else:
				stack.append(inp())

		elif t == "32":
			check(2)
			n = v(x[1], x[2])
			if n in d:
				print("\x1b[%sm" % (d[n]), end="")
			elif n == 40:
				system("cls")
			else:
				check(3)
				if n == 36:
					print("\x1b[%sA" % int(x[3], 4), end="")
				elif n == 37:
					print("\x1b[%sB" % int(x[3], 4), end="")
				elif n == 38:
					print("\x1b[%sC" % int(x[3], 4), end="")
				elif n == 39:
					print("\x1b[%sD" % int(x[3], 4), end="")

		elif t == "33":
			print(eval(" ".join(x[1:])), end="")
			stdout.flush()

		c = c + 1
except KeyboardInterrupt:
	pass
except:
	print("\x1b[31;1mSomething went wrong...\nPlease check syntax of your code\x1b[0m")
	system("pause > nul")
	exit(1)

print("\x1b[0m")


from django.shortcuts import render, reverse, redirect, get_object_or_404
from django.contrib.auth.decorators import login_required
from django.contrib import messages
from .forms import PaymentForm, OrderForm
from .models import OrderLineItem
from django.conf import settings
from django.utils import timezone
from books.models import Book
import stripe

stripe.api_key = settings.STRIPE_SECRET

@login_required
def checkout(request):
    if request.method == "POST":
        order_form = OrderForm(request.POST)
        payment_form = PaymentForm(request.POST)

        if order_form.is_valid() and payment_form.is_valid():
            order = order_form.save(commit=False)
            order.date = timezone.now()
            order.user = request.user
            order.save()

            cart = request.session.get("cart", {})
            total = 0

            for id, quantity in cart.items():
                book = get_object_or_404(Book, pk=id)
                total += quantity * book.price
                order_line_item = OrderLineItem(
                    order=order,
                    book=book,
                    quantity=quantity
                )
                order_line_item.save()

            try:
                customer_buying = stripe.Charge.create(
                    amount=int(total * 100),
                    currency="EUR",
                    description=request.user.email,
                    card=payment_form.cleaned_data["stripe_id"]
                )
            except stripe.error.CardError:
                messages.error(request, "Sorry your card has been denied!")

            if customer_buying.paid:
                messages.error(request, "Payment was successful!")
                request.session["cart"] = {}
                return redirect(reverse("books"))
            else:
                messages.error(request, "Payment was unsuccessful!")
        else:
            print(payment_form.errors)
            messages.error(
                request,
                "Sorry we were unable to process a payment with that card!"
            )
    else:
        payment_form = PaymentForm()
        order_form = OrderForm()

    return render(request, "checkout.html", {
        "order_form": order_form,
        "payment_form": payment_form,
        "publishable": settings.STRIPE_PUBLISHABLE
    })


#!/usr/bin/env python

from random import choice, shuffle
import sys

PROB_LETTER = 0.7
PROB_SPACE  = 0.98
PROB_LINE   = 1.0

if __name__ == '__main__':
    if len(sys.argv) == 2:
        max_size = int(sys.argv[1])
    else:
        max_size = 1 << 30
    letters = []
    for i in range(65, 91):
        letters.append(chr(i))
    for i in range(97, 123):
        letters.append(chr(i))
    for i in range(5):
        letters.append(' ')
    letters.append('\n')
    shuffle(letters)

    for i in range(int(max_size / len(letters)) + 1):
        # sys.stdout.write(choice(letters))
        sys.stdout.write(''.join(letters))
        shuffle(letters)


__author__ = 'Judge'
'''373. Partition Array by Odd and Even

Partition an integers array into odd number first and even number second.

Example
Given [1, 2, 3, 4], return [1, 3, 2, 4]

'''
class Solution:
    """
    @param: nums: an array of integers
    @return: nothing
    """
    def partitionArray(self, nums):
        # write your code here
        offset = 0
        for i, v in enumerate(nums):
            if v % 2 == 0:
                offset += 1
            else:
                nums[i], nums[i-offset] = nums[i-offset], nums[i]

        return nums


#! /usr/bin/env python
#  -*- coding: utf-8 -*-
#
# This file is part of windows_tools package

"""
windows_tools is a meta package for various windows related functions

Versioning semantics:
    Major version: backward compatibility breaking changes
    Minor version: New functionality
    Patch version: Backwards compatible bug fixes

"""

__intname__ = "windows_tools"
__author__ = "Orsiris de Jong"
__copyright__ = "Copyright (C) 2018-2023 Orsiris de Jong"
__description__ = "Toolset for antivirus, NTFS/ReFS ACLs, file ownership, registry, user handling...Well a lot of stuff"
__licence__ = "BSD 3 Clause"
__version__ = "2.4.0"
__build__ = "2023082901"

# Make sure we declare this file as namespace holder
try:
    __import__("pkg_resources").declare_namespace(__name__)
except ImportError:
    from pkgutil import extend_path

    __path__ = extend_path(__path__, __name__)


from testing import Test
from space_optimized_process_profiles import processing

users_prefix = 'users/'
objects_prefix = 'objects/'

use = Test(processing())

print (use.test_object.predict(0, 7, 0.))

print(use.test_on_all())


#Zadanie 1
#Napisz program, który symuluje odbijanie się kuli od
#krawędzi na stole bilardowym (krawędzie obiektu box). Prędkość
#startowa losowa (kierunek, wartość). Zakładamy, że uderzenia o
#bandy, ani tarcie nie powodują utraty energii (kąt padania równy
#kątowi odbicia, wartość prędkości bez zmian).

from vpython import *
import random

scene.center = vector(-4,-3,0)
scene.forward = vector(-1.13539,-0.0172799,-1.18385)
scene.up = vector(1,1,1)
scene.width = 1800
scene.height = 850

w1 = box(pos = vector(0,0,0), size=vector(8,4,0.2), texture=textures.wood)

w2 = box(pos = vector(0,2,0.25), size=vector(8,0.2,0.5), texture=textures.wood)
w3 = box(pos = vector(4,0,0.25), size=vector(0.2,4,0.5), texture=textures.wood)
w5 = box(pos = vector(0,-2,0.25), size=vector(8,0.2,0.5), texture=textures.wood)
w6 = box(pos = vector(-4,0,0.25), size=vector(0.2,4,0.5), texture=textures.wood)

l1 = box(pos = vector(3.5,1.5,-1), size=vector(0.5,0.5,2), texture=textures.wood)
l2 = box(pos = vector(3.5,-1.5,-1), size=vector(0.5,0.5,2), texture=textures.wood)
l3 = box(pos = vector(-3.5,1.5,-1), size=vector(0.5,0.5,2), texture=textures.wood)
l4 = box(pos = vector(-3.5,-1.5,-1), size=vector(0.5,0.5,2), texture=textures.wood)

ball = sphere(pos=vector(0.3,0.3,0.3), radius=0.2, color=color.white)
ball.velocity = vector(1,1,0)
dt=0.01

while(1):
    #print(scene.forward)
    rate(100)
    ball.pos = ball.pos + ball.velocity*dt
    print(ball.pos)
    if ball.pos.x < -3.7:
        ball.velocity.x = random.uniform(1, 2.5)
    if ball.pos.x > 3.7:
        ball.velocity.x = random.uniform(-1, -2.5)
    if ball.pos.y < -1.7:
        ball.velocity.y = random.uniform(1, 2.5)
    if ball.pos.y > 1.7:
        ball.velocity.y = random.uniform(-1, -2.5)