from .core.protocol import Diagnostic
from .core.protocol import DiagnosticSeverity
from .core.protocol import DocumentUri
from .core.protocol import Range
from .core.protocol import Request
from .core.protocol import TextDocumentSyncKindFull
from .core.protocol import TextDocumentSyncKindNone
from .core.sessions import Session
from .core.sessions import SessionViewProtocol
from .core.settings import userprefs
from .core.types import Capabilities
from .core.types import debounced
from .core.types import Debouncer
from .core.types import FEATURES_TIMEOUT
from .core.typing import Any, Callable, Iterable, Optional, List, Dict, Tuple
from .core.views import DIAGNOSTIC_SEVERITY
from .core.views import diagnostic_severity
from .core.views import did_change
from .core.views import did_close
from .core.views import did_open
from .core.views import did_save
from .core.views import document_color_params
from .core.views import lsp_color_to_phantom
from .core.views import MissingUriError
from .core.views import range_to_region
from .core.views import region_to_range
from .core.views import text_document_identifier
from .core.views import will_save
from .semantic_highlighting import SemanticToken
from weakref import WeakSet
import sublime
import time

class PendingChanges:

    __slots__ = ('version', 'changes')

    def __init__(self, version: int, changes: Iterable[sublime.TextChange]) -> None:
        self.version = version
        self.changes = list(changes)

    def update(self, version: int, changes: Iterable[sublime.TextChange]) -> None:
        self.version = version
        self.changes.extend(changes)

class DiagnosticSeverityData:

    __slots__ = ('regions', 'regions_with_tag', 'annotations', 'scope', 'icon')

    def __init__(self, severity: int) -> None:
        self.regions = []  # type: List[sublime.Region]
        self.regions_with_tag = {}  # type: Dict[int, List[sublime.Region]]
        self.annotations = []  # type: List[str]
        _, _, self.scope, self.icon, _, _ = DIAGNOSTIC_SEVERITY[severity - 1]
        if userprefs().diagnostics_gutter_marker != "sign":
            self.icon = userprefs().diagnostics_gutter_marker

class SemanticTokensData:

    __slots__ = (
        'data', 'result_id', 'active_scopes', 'tokens', 'view_change_count', 'needs_refresh', 'pending_response')

    def __init__(self) -> None:
        self.data = []  # type: List[int]
        self.result_id = None  # type: Optional[str]
        self.active_scopes = []  # type: List[str]
        self.tokens = []  # type: List[SemanticToken]
        self.view_change_count = 0
        self.needs_refresh = False
        self.pending_response = None  # type: Optional[int]

class SessionBuffer:
    """
    Holds state per session per buffer.

    It stores the URI, handles document synchronization for the buffer, and stores/receives diagnostics for the
    buffer. The diagnostics are then published further to the views attached to this buffer. It also maintains the
    dynamically registered capabilities applicable to this particular buffer.
    """

    def __init__(self, session_view: SessionViewProtocol, buffer_id: int, uri: DocumentUri) -> None:
        view = session_view.view
        self.opened = False
        # Every SessionBuffer has its own personal capabilities due to "dynamic registration".
        self.capabilities = Capabilities()
        self._session = session_view.session
        self._session_views = WeakSet()  # type: WeakSet[SessionViewProtocol]
        self._session_views.add(session_view)
        self.last_known_uri = uri
        self.id = buffer_id
        self.pending_changes = None  # type: Optional[PendingChanges]
        self.diagnostics = []  # type: List[Tuple[Diagnostic, sublime.Region]]
        self.data_per_severity = {}  # type: Dict[Tuple[int, bool], DiagnosticSeverityData]
        self.diagnostics_version = -1
        self.diagnostics_flags = 0
        self.diagnostics_are_visible = False
        self.last_text_change_time = 0.0
        self.total_errors = 0
        self.total_warnings = 0
        self.should_show_diagnostics_panel = False
        self.diagnostics_debouncer = Debouncer()
        self.color_phantoms = sublime.PhantomSet(view, "lsp_color")
        self.semantic_tokens = SemanticTokensData()
        self._check_did_open(view)
        self._session.register_session_buffer_async(self)

    def __del__(self) -> None:
        mgr = self.session.manager()
        if mgr:
            mgr.update_diagnostics_panel_async()
        self.color_phantoms.update([])
        # If the session is exiting then there's no point in sending textDocument/didClose and there's also no point
        # in unregistering ourselves from the session.
        if not self.session.exiting:
            # Only send textDocument/didClose when we are the only view left (i.e. there are no other clones).
            self._check_did_close()
            self.session.unregister_session_buffer_async(self)

    @property
    def session(self) -> Session:
        return self._session

    @property
    def session_views(self) -> 'WeakSet[SessionViewProtocol]':
        return self._session_views

    def _check_did_open(self, view: sublime.View) -> None:
        if not self.opened and self.should_notify_did_open():
            language_id = self.get_language_id()
            if not language_id:
                # we're closing
                return
            self.session.send_notification(did_open(view, language_id))
            self.opened = True
            self._do_color_boxes_async(view, view.change_count())
            self.do_semantic_tokens_async(view)
            self.session.notify_plugin_on_session_buffer_change(self)

    def _check_did_close(self) -> None:
        if self.opened and self.should_notify_did_close():
            self.session.send_notification(did_close(uri=self.last_known_uri))
            self.opened = False

    def get_uri(self) -> Optional[str]:
        for sv in self.session_views:
            return sv.get_uri()
        return None

    def get_language_id(self) -> Optional[str]:
        for sv in self.session_views:
            return sv.get_language_id()
        return None

    def get_view_in_group(self, group: int) -> sublime.View:
        for sv in self.session_views:
            view = sv.get_view_for_group(group)
            if view:
                return view
        return next(iter(self.session_views)).view

    @property
    def language_id(self) -> str:
        """
        Deprecated: use get_language_id
        """
        return self.get_language_id() or ""

    def add_session_view(self, sv: SessionViewProtocol) -> None:
        self.session_views.add(sv)

    def remove_session_view(self, sv: SessionViewProtocol) -> None:
        self._clear_semantic_token_regions(sv.view)
        self.session_views.remove(sv)

    def register_capability_async(
        self,
        registration_id: str,
        capability_path: str,
        registration_path: str,
        options: Dict[str, Any]
    ) -> None:
        self.capabilities.register(registration_id, capability_path, registration_path, options)
        view = None  # type: Optional[sublime.View]
        for sv in self.session_views:
            sv.on_capability_added_async(registration_id, capability_path, options)
            if view is None:
                view = sv.view
        if view is not None:
            if capability_path.startswith("textDocumentSync."):
                self._check_did_open(view)

    def unregister_capability_async(
        self,
        registration_id: str,
        capability_path: str,
        registration_path: str
    ) -> None:
        discarded = self.capabilities.unregister(registration_id, capability_path, registration_path)
        if discarded is None:
            return
        for sv in self.session_views:
            sv.on_capability_removed_async(registration_id, discarded)

    def get_capability(self, capability_path: str) -> Optional[Any]:
        if self.session.config.is_disabled_capability(capability_path):
            return None
        value = self.capabilities.get(capability_path)
        return value if value is not None else self.session.capabilities.get(capability_path)

    def has_capability(self, capability: str) -> bool:
        value = self.get_capability(capability)
        return value is not False and value is not None

    def text_sync_kind(self) -> int:
        value = self.capabilities.text_sync_kind()
        return value if value > TextDocumentSyncKindNone else self.session.text_sync_kind()

    def should_notify_did_open(self) -> bool:
        return self.capabilities.should_notify_did_open() or self.session.should_notify_did_open()

    def should_notify_will_save(self) -> bool:
        return self.capabilities.should_notify_will_save() or self.session.should_notify_will_save()

    def should_notify_did_save(self) -> Tuple[bool, bool]:
        do_it, include_text = self.capabilities.should_notify_did_save()
        return (do_it, include_text) if do_it else self.session.should_notify_did_save()

    def should_notify_did_close(self) -> bool:
        return self.capabilities.should_notify_did_close() or self.session.should_notify_did_close()

    def on_text_changed_async(self, view: sublime.View, change_count: int,
                              changes: Iterable[sublime.TextChange]) -> None:
        self.last_text_change_time = time.time()
        last_change = list(changes)[-1]
        if last_change.a.pt == 0 and last_change.b.pt == 0 and last_change.str == '' and view.size() != 0:
            # Issue https://github.com/sublimehq/sublime_text/issues/3323
            # A special situation when changes externally. We receive two changes,
            # one that removes all content and one that has 0,0,'' parameters.
            pass
        else:
            purge = False
            if self.pending_changes is None:
                self.pending_changes = PendingChanges(change_count, changes)
                purge = True
            elif self.pending_changes.version < change_count:
                self.pending_changes.update(change_count, changes)
                purge = True
            if purge:
                debounced(lambda: self.purge_changes_async(view), FEATURES_TIMEOUT,
                          lambda: view.is_valid() and change_count == view.change_count(), async_thread=True)

    def on_revert_async(self, view: sublime.View) -> None:
        self.pending_changes = None  # Don't bother with pending changes
        self.session.send_notification(did_change(view, view.change_count(), None))

    on_reload_async = on_revert_async

    def purge_changes_async(self, view: sublime.View) -> None:
        if self.pending_changes is not None:
            sync_kind = self.text_sync_kind()
            if sync_kind == TextDocumentSyncKindNone:
                return
            if sync_kind == TextDocumentSyncKindFull:
                changes = None
                version = view.change_count()
            else:
                changes = self.pending_changes.changes
                version = self.pending_changes.version
            try:
                notification = did_change(view, version, changes)
                self.session.send_notification(notification)
            except MissingUriError:
                return  # we're closing
            finally:
                self.pending_changes = None
            self._do_color_boxes_async(view, version)
            self.do_semantic_tokens_async(view)
            self.session.notify_plugin_on_session_buffer_change(self)

    def on_pre_save_async(self, view: sublime.View) -> None:
        if self.should_notify_will_save():
            self.purge_changes_async(view)
            # TextDocumentSaveReason.Manual
            self.session.send_notification(will_save(self.last_known_uri, 1))

    def on_post_save_async(self, view: sublime.View, new_uri: DocumentUri) -> None:
        if new_uri != self.last_known_uri:
            self._check_did_close()
            self.last_known_uri = new_uri
            self._check_did_open(view)
        else:
            send_did_save, include_text = self.should_notify_did_save()
            if send_did_save:
                self.purge_changes_async(view)
                self.session.send_notification(did_save(view, include_text, self.last_known_uri))
        if self.should_show_diagnostics_panel:
            mgr = self.session.manager()
            if mgr:
                mgr.show_diagnostics_panel_async()

    def some_view(self) -> Optional[sublime.View]:
        for sv in self.session_views:
            return sv.view
        return None

    def _if_view_unchanged(self, f: Callable[[sublime.View, Any], None], version: int) -> Callable[[Any], None]:
        """
        Ensures that the view is at the same version when we were called, before calling the `f` function.
        """
        def handler(*args: Any) -> None:
            view = self.some_view()
            if view and view.change_count() == version:
                f(view, *args)

        return handler

    # --- textDocument/documentColor -----------------------------------------------------------------------------------

    def _do_color_boxes_async(self, view: sublime.View, version: int) -> None:
        if self.session.has_capability("colorProvider"):
            self.session.send_request_async(
                Request.documentColor(document_color_params(view), view),
                self._if_view_unchanged(self._on_color_boxes_async, version)
            )

    def _on_color_boxes_async(self, view: sublime.View, response: Any) -> None:
        color_infos = response if response else []
        self.color_phantoms.update([lsp_color_to_phantom(view, color_info) for color_info in color_infos])

    # --- textDocument/publishDiagnostics ------------------------------------------------------------------------------

    def on_diagnostics_async(self, raw_diagnostics: List[Diagnostic], version: Optional[int]) -> None:
        data_per_severity = {}  # type: Dict[Tuple[int, bool], DiagnosticSeverityData]
        total_errors = 0
        total_warnings = 0
        should_show_diagnostics_panel = False
        view = self.some_view()
        if view is None:
            return
        change_count = view.change_count()
        if version is None:
            version = change_count
        if version == change_count:
            diagnostics_version = version
            diagnostics = []  # type: List[Tuple[Diagnostic, sublime.Region]]
            for diagnostic in raw_diagnostics:
                region = range_to_region(Range.from_lsp(diagnostic["range"]), view)
                severity = diagnostic_severity(diagnostic)
                key = (severity, len(view.split_by_newlines(region)) > 1)
                data = data_per_severity.get(key)
                if data is None:
                    data = DiagnosticSeverityData(severity)
                    data_per_severity[key] = data
                tags = diagnostic.get('tags', [])
                if tags:
                    for tag in tags:
                        data.regions_with_tag.setdefault(tag, []).append(region)
                else:
                    data.regions.append(region)
                diagnostics.append((diagnostic, region))
                if severity == DiagnosticSeverity.Error:
                    total_errors += 1
                elif severity == DiagnosticSeverity.Warning:
                    total_warnings += 1
                if severity <= userprefs().show_diagnostics_panel_on_save:
                    should_show_diagnostics_panel = True
            self._publish_diagnostics_to_session_views(
                diagnostics_version,
                diagnostics,
                data_per_severity,
                total_errors,
                total_warnings,
                should_show_diagnostics_panel
            )

    def _publish_diagnostics_to_session_views(
        self,
        diagnostics_version: int,
        diagnostics: List[Tuple[Diagnostic, sublime.Region]],
        data_per_severity: Dict[Tuple[int, bool], DiagnosticSeverityData],
        total_errors: int,
        total_warnings: int,
        should_show_diagnostics_panel: bool
    ) -> None:

        def present() -> None:
            self._present_diagnostics_async(
                diagnostics_version,
                diagnostics,
                data_per_severity,
                total_errors,
                total_warnings,
                should_show_diagnostics_panel
            )

        self.diagnostics_debouncer.cancel_pending()

        if self.diagnostics_are_visible:
            # Old diagnostics are visible. Update immediately.
            present()
        else:
            # There were no diagnostics visible before. Show them a bit later.
            delay_in_seconds = userprefs().diagnostics_delay_ms / 1000.0 + self.last_text_change_time - time.time()
            view = self.some_view()
            if view is None:
                return
            if view.is_auto_complete_visible():
                delay_in_seconds += userprefs().diagnostics_additional_delay_auto_complete_ms / 1000.0
            if delay_in_seconds <= 0.0:
                present()
            else:
                self.diagnostics_debouncer.debounce(
                    present,
                    timeout_ms=int(1000.0 * delay_in_seconds),
                    condition=lambda: bool(view and view.is_valid() and view.change_count() == diagnostics_version),
                    async_thread=True
                )

    def _present_diagnostics_async(
        self,
        diagnostics_version: int,
        diagnostics: List[Tuple[Diagnostic, sublime.Region]],
        data_per_severity: Dict[Tuple[int, bool], DiagnosticSeverityData],
        total_errors: int,
        total_warnings: int,
        should_show_diagnostics_panel: bool
    ) -> None:
        self.diagnostics_version = diagnostics_version
        self.diagnostics = diagnostics
        self.data_per_severity = data_per_severity
        self.diagnostics_are_visible = bool(diagnostics)
        self.total_errors = total_errors
        self.total_warnings = total_warnings
        self.should_show_diagnostics_panel = should_show_diagnostics_panel
        for sv in self.session_views:
            sv.present_diagnostics_async()

    # --- textDocument/semanticTokens ----------------------------------------------------------------------------------

    def do_semantic_tokens_async(self, view: sublime.View) -> None:
        if not userprefs().semantic_highlighting:
            return
        if not self.session.has_capability("semanticTokensProvider"):
            return
        # semantic highlighting requires a special rule in the color scheme for the View.add_regions workaround
        if "background" not in view.style_for_scope("meta.semantic-token"):
            return
        if self.semantic_tokens.pending_response:
            self.session.cancel_request(self.semantic_tokens.pending_response)
        self.semantic_tokens.view_change_count = view.change_count()
        params = {"textDocument": text_document_identifier(view)}  # type: Dict[str, Any]
        if self.semantic_tokens.result_id and self.session.has_capability("semanticTokensProvider.full.delta"):
            params["previousResultId"] = self.semantic_tokens.result_id
            request = Request.semanticTokensFullDelta(params, view)
            self.semantic_tokens.pending_response = self.session.send_request_async(
                request, self._on_semantic_tokens_delta_async, self._on_semantic_tokens_error_async)
        elif self.session.has_capability("semanticTokensProvider.full"):
            request = Request.semanticTokensFull(params, view)
            self.semantic_tokens.pending_response = self.session.send_request_async(
                request, self._on_semantic_tokens_async, self._on_semantic_tokens_error_async)
        elif self.session.has_capability("semanticTokensProvider.range"):
            params["range"] = region_to_range(view, view.visible_region()).to_lsp()
            request = Request.semanticTokensRange(params, view)
            self.semantic_tokens.pending_response = self.session.send_request_async(
                request, self._on_semantic_tokens_async, self._on_semantic_tokens_error_async)

    def _on_semantic_tokens_async(self, response: Optional[Dict]) -> None:
        if response:
            self.semantic_tokens.pending_response = None
            self.semantic_tokens.result_id = response.get("resultId")
            self.semantic_tokens.data = response["data"]
            self._draw_semantic_tokens_async()

    def _on_semantic_tokens_delta_async(self, response: Optional[Dict]) -> None:
        if response:
            self.semantic_tokens.pending_response = None
            self.semantic_tokens.result_id = response.get("resultId")
            if "edits" in response:  # response is of type SemanticTokensDelta
                for semantic_tokens_edit in response["edits"]:
                    start = semantic_tokens_edit["start"]
                    end = start + semantic_tokens_edit["deleteCount"]
                    del self.semantic_tokens.data[start:end]
                    data = semantic_tokens_edit.get("data")
                    if data:
                        self.semantic_tokens.data[start:start] = data
            elif "data" in response:  # response is of type SemanticTokens
                self.semantic_tokens.data = response["data"]
            else:
                return
            self._draw_semantic_tokens_async()

    def _on_semantic_tokens_error_async(self, error: dict) -> None:
        self.semantic_tokens.pending_response = None
        self.semantic_tokens.result_id = None

    def _draw_semantic_tokens_async(self) -> None:
        view = self.some_view()
        if view is None:
            return
        self.semantic_tokens.tokens.clear()
        scope_regions = dict()  # type: Dict[str, List[sublime.Region]]
        prev_line = 0
        prev_col_utf16 = 0
        for idx in range(0, len(self.semantic_tokens.data), 5):
            delta_line = self.semantic_tokens.data[idx]
            delta_start_utf16 = self.semantic_tokens.data[idx + 1]
            length_utf16 = self.semantic_tokens.data[idx + 2]
            token_type_encoded = self.semantic_tokens.data[idx + 3]
            token_modifiers_encoded = self.semantic_tokens.data[idx + 4]
            line = prev_line + delta_line
            col_utf16 = prev_col_utf16 + delta_start_utf16 if delta_line == 0 else delta_start_utf16
            a = view.text_point_utf16(line, col_utf16, clamp_column=False)
            b = view.text_point_utf16(line, col_utf16 + length_utf16, clamp_column=False)
            r = sublime.Region(a, b)
            prev_line = line
            prev_col_utf16 = col_utf16
            token_type, token_modifiers, scope = self.session.decode_semantic_token(
                token_type_encoded, token_modifiers_encoded)
            if scope is None:
                # We can still use the meta scope and draw highlighting regions for custom token types if there is a
                # color scheme rule for this particular token type.
                # This logic should not be cached (in the decode_semantic_token method) because otherwise new user
                # customizations in the color scheme for the scopes of custom token types would require a restart of
                # Sublime Text to take effect.
                # Note that the region keys for these scopes are not initialized in SessionView._initialize_region_keys.
                token_general_style = view.style_for_scope("meta.semantic-token")
                token_type_style = view.style_for_scope("meta.semantic-token.{}".format(token_type.lower()))
                if token_general_style["source_line"] != token_type_style["source_line"] or \
                        token_general_style["source_column"] != token_type_style["source_column"]:
                    if token_modifiers:
                        scope = "meta.semantic-token.{}.{}.lsp".format(token_type.lower(), token_modifiers[0].lower())
                    else:
                        scope = "meta.semantic-token.{}.lsp".format(token_type.lower())
            self.semantic_tokens.tokens.append(SemanticToken(r, token_type, token_modifiers))
            if scope:
                scope_regions.setdefault(scope, []).append(r)
        # don't update regions if there were additional changes to the buffer in the meantime
        if self.semantic_tokens.view_change_count != view.change_count():
            return
        for scope in self.semantic_tokens.active_scopes.copy():
            if scope not in scope_regions.keys():
                self.semantic_tokens.active_scopes.remove(scope)
                for sv in self.session_views:
                    sv.view.erase_regions("lsp_{}".format(scope))
        for scope, regions in scope_regions.items():
            if scope not in self.semantic_tokens.active_scopes:
                self.semantic_tokens.active_scopes.append(scope)
            for sv in self.session_views:
                sv.view.add_regions("lsp_{}".format(scope), regions, scope, flags=sublime.DRAW_NO_OUTLINE)

    def _clear_semantic_token_regions(self, view: sublime.View) -> None:
        for scope in self.semantic_tokens.active_scopes:
            view.erase_regions("lsp_{}".format(scope))

    def set_semantic_tokens_pending_refresh(self, needs_refresh: bool = True) -> None:
        self.semantic_tokens.needs_refresh = needs_refresh

    def get_semantic_tokens(self) -> List[SemanticToken]:
        return self.semantic_tokens.tokens

    # ------------------------------------------------------------------------------------------------------------------

    def __str__(self) -> str:
        return '{}:{}:{}'.format(self.session.config.name, self.id, self.get_uri())


import sys
from PyQt5.QtWidgets import QApplication, QWidget, QMainWindow, QTableWidget, QTableWidgetItem
from table1 import Ui_MainWindow

class MyWidget(QMainWindow, Ui_MainWindow):
    def __init__(self):
        super().__init__()
        self.setupUi(self)
        self.pushButton.clicked.connect(self.run)
        f = ''
        xn = 0
        n = 0
        s = 0
        self.tableWidget.setHorizontalHeaderLabels(['Точка x', 'Значение f в точке х'])
        self.tableWidget.resizeColumnsToContents()

    def run(self):

        f = self.lineEdit.text()
        xn = int(self.lineEdit_2.text())
        n = int(self.lineEdit_3.text())
        s = int(self.lineEdit_4.text())
        self.tableWidget.setRowCount(n)
        print(f,xn,n,s)
        k = 0
        for x in range(xn,xn+n*s+1,s):
            print(eval(f))
            self.tableWidget.setItem(k, 0, QTableWidgetItem(str(x)))
            self.tableWidget.setItem(k, 1, QTableWidgetItem(str(eval(f))))
            k = k+1

app = QApplication(sys.argv)
ex = MyWidget()
ex.show()
sys.exit(app.exec_())


"""Helper functions for plotting."""
from cycler import cycler as _cycler
import matplotlib.pyplot as _plt
import numpy as _np
import sympy as _sp

def plot_slopes_1d(slopes, values, grid, scale=1, ax=None, **kwargs):
    """Plot incoming and outging slopes for 1D spline."""
    if ax is None:
        ax = _plt.gca()
    slopes = _np.asarray(slopes)
    for slopes, values, grid, pivot in (
            [slopes[::2], values[:-1], grid[:-1], 'tail'],
            [slopes[1::2], values[1:], grid[1:], 'tip']):
        lengths = _np.sqrt(1 + slopes**2)
        ax.quiver(
            grid, values, 1 / lengths, slopes / lengths,
            scale=scale, scale_units='x', angles='xy', color='lightgrey',
            pivot=pivot, **kwargs)

def plot_spline_1d(spline, ax=None, samples=100, **kwargs):
    """Plot a one-dimensional spline."""
    if ax is None:
        ax = _plt.gca()
    times = _np.linspace(spline.grid[0], spline.grid[-1], samples)
    ax.plot(times, spline.evaluate(times), **kwargs)
    ax.scatter(spline.grid, spline.evaluate(spline.grid))

def plot_tangent_2d(tangent, vertex, color='lightgrey', outgoing=True,
                    scale=1, ax=None, **kwargs):
    """Plot outgoing or incoming 2D tangent."""
    if ax is None:
        ax = _plt.gca()
    ax.quiver(
        *vertex, *tangent,
        scale=scale, scale_units='xy', angles='xy', color=color,
        pivot='tail' if outgoing else 'tip', **kwargs)
    if outgoing:
        endpoint = _np.add(vertex, tangent)
    else:
        endpoint = _np.subtract(vertex, tangent)
    # Plot an invisible point at the end of the tangent vector
    # to make sure the vector is visible when the plot is autoscaled.
    # NB: Selecting a (unused) color to not disturb the color cycle.
    ax.scatter(*endpoint, marker='', color='green')

def plot_tangents_2d(tangents, vertices, color='lightgrey',
                     scale=1, ax=None, **kwargs):
    """Plot outgoing and incoming tangents for 2D spline."""
    if ax is None:
        ax = _plt.gca()
    tangents = _np.asarray(tangents)
    vertices = _np.asarray(vertices)
    for i in range(len(vertices) - 1):
        plot_tangent_2d(tangents[2 * i], vertices[i], color=color, **kwargs)
        plot_tangent_2d(
            tangents[2 * i + 1], vertices[i + 1], color=color, outgoing=False,
            **kwargs)

def plot_spline_2d(spline, dots_per_second=15, marker='.', linestyle='',
                   chords=True, ax=None, **kwargs):
    """Plot a two-dimensional spline."""
    if ax is None:
        ax = _plt.gca()
    total_duration = spline.grid[-1] - spline.grid[0]
    dots = int(total_duration * dots_per_second) + 1
    times = spline.grid[0] + _np.arange(dots) / dots_per_second
    ax.plot(
        *spline.evaluate(spline.grid).T,
        color='lightgrey',
        linestyle=(':' if chords else ''),
        marker='x',
        markeredgecolor='black',
    )
    ax.plot(
        *spline.evaluate(times).T,
        marker=marker,
        linestyle=linestyle,
        **kwargs)
    ax.axis('equal')

def grid_lines(x=None, y=None, ax=None):
    if ax is None:
        ax = _plt.gca()
    if x is not None:
        ax.set_xticks(x)
        ax.xaxis.grid(True)
    if y is not None:
        ax.set_yticks(y)
        ax.yaxis.grid(True)
    ax.spines['top'].set_visible(False)
    ax.spines['right'].set_visible(False)
    ax.spines['bottom'].set_visible(False)
    ax.spines['left'].set_visible(False)
    ax.xaxis.set_ticks_position('none')
    ax.yaxis.set_ticks_position('none')

def latexify(expr):
    """Convert SymPy expression to LaTeX string.

    Strings are passed through unchanged.

    """
    if isinstance(expr, str):
        return expr
    # \boldsymbol is not available, see:
    # https://github.com/matplotlib/matplotlib/issues/1366
    return _sp.latex(expr, mode='inline').replace(r'\boldsymbol', r'\mathbf')

def plot_sympy(*args, ax=None, **kwargs):
    """Plot a SymPy expression into a Matplotlib plot."""
    from matplotlib.collections import LineCollection
    if ax is None:
        ax = _plt.gca()
    for line in _sp.plot(*args, show=False, **kwargs):
        x, y = line.get_points()
        # if the function is constant, SymPy only emits one value:
        x, y = _np.broadcast_arrays(x, y)
        ax.plot(x, y)
    ax.autoscale()

def plot_basis(*args, ax=None, parameter=_sp.Symbol('t'), labels=None):
    """Plot a polynomial basis (given as SymPy expressions)."""
    if ax is None:
        ax = _plt.gca()
    ax.set_prop_cycle(_plt.rcParams['axes.prop_cycle'][:5] + _cycler(
        linestyle=['-', '--', ':', '-.', (0, (4.5, 1.5, 1, 1.5, 1, 1.5))]))
    plot_sympy(*args, (parameter, 0, 1))
    grid_lines([0, 1], [0, 1], ax=ax)
    if labels is None:
        labels = args
    if labels:
        ax.legend([latexify(l) for l in labels])
    ax.set_xlabel(latexify(parameter), labelpad=-4)
    ax.set_ylabel('weight')

def plot_x_3_to_6(points, ax):
    """Plot labels x3 to x6."""
    options = dict(
        ha="center",
        va="center",
        bbox=dict(
            boxstyle='circle,pad=0.1',
            fc=(1, 1, 1, 0.6),
            ec='none',
        ),
    )
    ax.text(*points[0], r'$\mathbf{x}_3$', **options)
    ax.text(*points[1], r'$\mathbf{x}_4$', **options)
    ax.text(*points[2], r'$\mathbf{x}_5$', **options)
    ax.text(*points[3], r'$\mathbf{x}_6$', **options)
    # Plot invisible points to make sure autoscaling doesn't crop the text
    ax.scatter(*points.T, marker='', c='chartreuse')

def show_animation(ani, default_mode='reflect'):
    display({
        'text/html': ani.to_jshtml(default_mode=default_mode),
        'text/plain': 'Animations can only be shown in HTML output, sorry!',
    }, raw=True)


import random
from django.db import transaction
from django.core.management.base import BaseCommand
from questions.models import Question, Profile, Tag, Answer, Like
from django.db.models import Max, Min
from faker import Faker
from random import choice

fake = Faker()
paths = ['images/Anton.jpg', 'images/Danil.jpg', 'images/MiSa.jpg']
tags = ['linear-algebra', 'matrices', 'permutations', 'combinatorics', 'calculus', 'real-analysis', 'integration']
unames = ['Anton', 'MiSa', 'Danil', 'Vlad', 'Ann', 'Sawa', 'Dinar']

class Command(BaseCommand):

    def add_arguments(self, parser):
        parser.add_argument('--questions', type=int)
        parser.add_argument('--users', type=int)
        parser.add_argument('--tags', type=int)
        parser.add_argument('--answers', type=int)

    # @transaction.atomic()
    def handle(self, *args, **options):
        users_cnt = options['users']
        questions_cnt = options['questions']
        answers_cnt = options['answers']
        tags_cnt = options['tags']

        if users_cnt is not None:
            self.generate_users(users_cnt)

        if answers_cnt is not None:
            self.generate_answers(answers_cnt)

        if tags_cnt is not None:
            self.generate_tags(tags_cnt)

        if questions_cnt is not None:
            self.generate_questions(questions_cnt)

    def generate_users(self, users_cnt):
        print(f"GENERATE USERS {users_cnt}")
        for i in range(users_cnt):
            name = choice(unames)
            p = Profile.objects.create(first_name=name,
                                       last_name=name,
                                       username=name + str(fake.random_int(1, 1024)),
                                       photo=choice(paths))
            p.set_password('123456')
            p.save()

    def generate_tags(self, tags_cnt):
        print(f"GENERATE TAGS {tags_cnt}")
        for i in range(tags_cnt):
            t = Tag(text=fake.word())
            t.save()

    def generate_questions(self, questions_cnt):
        print(f"GENERATE QUESTIONS {questions_cnt}")
        ans = list(Answer.objects.all())
        ts  = list(Answer.objects.all())
        for i in range(questions_cnt):
            q = Question.objects.create(
                author=choice(Profile.objects.all()),
                title=fake.sentence(),
                content='\n'.join(fake.sentences(fake.random_int(1, 5))),
                rate=fake.random_int(1, 100),
                id=Question.objects.all().count() + 1)
            l = Like(positive=fake.random_int(1, 100), negative=-fake.random_int(1, 100))
            l.content_object = q
            l.save()
            q.rate = l.positive + l.negative
            q.save()
            for j in range(1, fake.random_int(2, 5)):
                q.answers.add(choice(ans))
            for j in range(1, fake.random_int(2, 5)):
                q.tags.add(choice(ts))

    def generate_answers(self, answers_cnt):
        print(f"GENERATE ANSWERS {answers_cnt}")
        ps = list(Profile.objects.all())
        for i in range(answers_cnt):
            a = Answer.objects.create(
                author=choice(ps),
                content=fake.sentence())
            l = Like(positive=fake.random_int(1, 100), negative=-fake.random_int(1, 100))
            l.content_object = a
            l.save()
            a.rate = l.positive + l.negative
            a.save()


n = int(input())
inpList = []
for i in range(n):
  inpList.append(input())
def solve(inp):
  cout = ''
  stack = []
  for i in inp:
    if i.isalpha():
      cout += i
    elif i in ['*', '-', '+', '/','^']:
      stack.append(i)
    elif i == ')':
      cout += stack.pop()
  return cout
for i in inpList:
  print(solve(i))


from django import template
import re

from hitcount.models import Hit

register = template.Library()

def find_url(string):
    # findall() has been used
    # with valid conditions for urls in string
    #urls = re.findall('http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+] | [! * \(\),] | (?: %[0-9a-fA-F][0-9a-fA-F]))+', string)
    urls = re.findall('https?://[^\s]+', string)
    #urls = re.findall('https?://(?:[-\w.]|(?:%[\da-fA-F]{2}))+', string)
    return urls

@register.filter(is_safe=True)
def url(value):
    url = find_url(value)
    newvalue = value
    for url_string in url:
        newurlstring = ""+url_string+""
        newvalue = newvalue.replace(url_string, newurlstring)
    return newvalue

@register.filter(is_safe=True)
def ordreTri(value):
    newvalue = value.replace('_', ' ').replace('-', '')
    return newvalue

@register.filter(is_safe=True)
def sansOrdreTri(value):
    newvalue = value.replace('ordreTri', 'prec')
    newvalue = newvalue.replace('page=', 'old=')
    return newvalue

# @register.filter(is_safe=True)
# def dejavu(article, user):
#     newvalue = Hit.objects.filter(hitcount_content_object=article, user=user)
#     return newvalue.count


#import matplotlib.pyplot as plt
import numpy as np
import numbers
import pywt
import scipy
import skimage.color as color
from skimage.restoration import (denoise_wavelet, estimate_sigma)
from skimage import data, img_as_float
from skimage.util import random_noise
from skimage.measure import compare_psnr
from include import *

def _wavelet_threshold(image, wavelet, ncoeff = None, threshold=None, mode='soft', wavelet_levels=None):

    wavelet = pywt.Wavelet(wavelet)

    # original_extent is used to workaround PyWavelets issue #80
    # odd-sized input results in an image with 1 extra sample after waverecn
    original_extent = [slice(s) for s in image.shape]

    # Determine the number of wavelet decomposition levels
    if wavelet_levels is None:
        # Determine the maximum number of possible levels for image
        dlen = wavelet.dec_len
        wavelet_levels = np.min(
            [pywt.dwt_max_level(s, dlen) for s in image.shape])

        # Skip coarsest wavelet scales (see Notes in docstring).
        wavelet_levels = max(wavelet_levels - 3, 1)

    coeffs = pywt.wavedecn(image, wavelet=wavelet, level=wavelet_levels)
    # Detail coefficients at each decomposition level
    dcoeffs = coeffs[1:]

    a = []
    for level in dcoeffs:
        for key in level:
            a += [np.ndarray.flatten(level[key])]
    a = np.concatenate(a)
    a = np.sort( np.abs(a) )

    sh = coeffs[0].shape
    basecoeffs = sh[0]*sh[1]
    threshold = a[- (ncoeff - basecoeffs)]

    # A single threshold for all coefficient arrays
    denoised_detail = [{key: pywt.threshold(level[key],value=threshold,
                                mode=mode) for key in level} for level in dcoeffs]

    denoised_coeffs = [coeffs[0]] + denoised_detail
    return pywt.waverecn(denoised_coeffs, wavelet)[original_extent]

def denoise_wavelet(image, ncoeff=None, wavelet='db1', mode='hard',
                    wavelet_levels=None, multichannel=False,
                    convert2ycbcr=False):

    image = img_as_float(image)

    if multichannel:
        if convert2ycbcr:
            out = color.rgb2ycbcr(image)
            for i in range(3):
                # renormalizing this color channel to live in [0, 1]
                min, max = out[..., i].min(), out[..., i].max()
                channel = out[..., i] - min
                channel /= max - min
                out[..., i] = denoise_wavelet(channel, wavelet=wavelet,ncoeff=ncoeff,
                                              mode=mode,
                                              wavelet_levels=wavelet_levels)

                out[..., i] = out[..., i] * (max - min)
                out[..., i] += min
            out = color.ycbcr2rgb(out)
        else:
            out = np.empty_like(image)
            for c in range(image.shape[-1]):
                out[..., c] = _wavelet_threshold(image[..., c],ncoeff=ncoeff,
                                                 wavelet=wavelet, mode=mode,
                                                 wavelet_levels=wavelet_levels)
    else:
        out = _wavelet_threshold(image, wavelet=wavelet, mode=mode,ncoeff=ncoeff,
                                 wavelet_levels=wavelet_levels)

    clip_range = (-1, 1) if image.min() < 0 else (0, 1)
    return np.clip(out, *clip_range)


#!/usr/bin/python

import time

from mininet.net import Containernet
from mininet.node import Controller
from mininet.cli import CLI
from mininet.link import TCLink
from mininet.log import info, setLogLevel

setLogLevel('info')

network = Containernet(controller=Controller)

info('*** Adding controller\n')
network.addController('c0')

info('*** Adding docker containers\n')

planemqxDocker = network.addDocker(
	'broker',
	ip='10.0.0.252',
	dimage='planemqx:latest',
	dcmd="/run-all.sh",
	ports=[1883, 18083, 8883, 8083, 8084, 8780,8880,8780],
	port_bindings={1883: 1883, 18083: 18083, 8883: 8883, 8083: 8083, 8084: 8084, 8780: 8780, 8880: 8880, 8780: 8780},
)

publisherDocker = network.addDocker(
	'publisher',
	ip='10.0.0.251',
	dimage="mqtt-publishers:latest",
	ports=[1883],
	ports_binding={1883: 1883},
	environment={"url": "tcp://10.0.0.252:1883", "topic": "my-custom-topic", "count": "50", "interval": "1", "size": "50000"}
)

subscriberDocker = network.addDocker(
	'subscriber',
	ip='10.0.0.253',
	dimage="mqtt-subscribers:latest",
	ports=[1883],
	ports_binding={1883: 1883},
	environment={"url": "tcp://10.0.0.252:1883", "topic": "my-custom-topic", "count": "50"}
)

info('*** Adding switches\n')
publisherSwitch = network.addSwitch('s1')
planemqxSwitch = network.addSwitch('s2')
subscriberSwitch = network.addSwitch('s3')

info('*** Creating links\n')
network.addLink(publisherDocker, publisherSwitch)
network.addLink(publisherSwitch, planemqxSwitch)
network.addLink(planemqxDocker, planemqxSwitch)
network.addLink(subscriberDocker, subscriberSwitch)
network.addLink(planemqxSwitch, subscriberSwitch, cls=TCLink, bw=8)		#Change bandwidth here (in Mbps)

info('*** Starting network\n')
network.start()
network.ping([publisherDocker, planemqxDocker])
network.ping([planemqxDocker, subscriberDocker])
network.ping([publisherDocker, subscriberDocker])

info('*** Setting up experiment')
time.sleep(5)
info('*** Running CLI\n')
CLI(network)
info('*** Stopping network')
network.stop()


# -*- coding: utf-8 -*-
"""
Created on Wed Jan 27 15:54:15 2016

@author: Michael Lin_2
"""

import pandas as pd
import numpy as np
import random
from sklearn import datasets

temp = datasets.load_iris()
iris = pd.DataFrame()
iris['sepal_length'] = temp.data[:,0]
iris['sepal_width'] = temp.data[:,1]
iris['petal_length'] = temp.data[:,2]
iris['petal_width'] = temp.data[:,3]
iris['target'] = temp.target
iris['target_flower'] = ''
# iris['target_flower'].replace(0, 'setosa', inplace = True)
# iris['target_flower'].replace(1, 'versicolor', inplace = True)
# iris['target_flower'].replace(2, 'virginica', inplace = True)

for i in range(len(iris['target'])):
    if iris['target'][i] == 0:
        iris['target_flower'][i] = 'setosa'
    elif iris['target'][i] == 1:
        iris['target_flower'][i] = 'versicolor'
    else:
        iris['target_flower'][i] = 'virginica'

s_length = iris['sepal_length'].tolist()
s_width = iris['sepal_width'].tolist()

x1 = np.average(iris['sepal_length'].tolist())
x2 = np.average(iris['sepal_width'].tolist())

k = 11
length = random.uniform(min(iris['sepal_length']), max(iris['sepal_length']))
width = random.uniform(min(iris['sepal_width']), max(iris['sepal_width']))

prediction = k_neighbor (data = iris, x1 = length, x2 = width, K=k)

print('The prediction for length {0:.2f} and width {1:.2f} using K = {2} is likely to be {3}'.format(length, width, k, prediction))

######################### K-Neighbor Function ########################

def k_neighbor (data, x1, x2, K = 10):
    data['distance'] = 0.00

    len_dis = 0
    wid_dis = 0

    for i in range(len(data['target'])):
        len_dis = (data['sepal_length'][i] - x1)**2
        wid_dis = (data['sepal_width'][i] - x2)**2
        data['distance'][i] = np.sqrt(len_dis + wid_dis)

    data_sorted = data.sort_values(by='distance', ascending=False)
    data_sorted = data_sorted.reset_index()

    setosa_count = 0
    versicolor_count = 0
    virginica_count = 0

    for i in range(K):
        if data_sorted['target_flower'][i] == 'setosa':
            setosa_count += 1
        elif data_sorted['target_flower'][i] == 'versicolor':
            versicolor_count += 1
        else:
            virginica_count += 1

    prediction = 'unknown'
    if (setosa_count > versicolor_count) and (setosa_count > virginica_count):
        prediction = 'setosa'
    elif (versicolor_count > setosa_count) and (versicolor_count > virginica_count):
        prediction = 'versicolor'
    elif (virginica_count > setosa_count) and (virginica_count > versicolor_count):
        prediction = 'virginica'
    else:
        prediction = 'unknown'

    return prediction