from django.db.models import Sum
from django.utils import timezone

from recipes.models import IngredientRecipe

def format_shopping_list(user):
    ingredients = (
        IngredientRecipe.objects.filter(recipe__cart__user=user)
        .values('ingredient__name', 'ingredient__measurement_unit')
        .annotate(amount=Sum('amount'))
    )
    local_time = timezone.localtime().strftime("%d/%m/%Y %H:%M")
    shopping_list = f'Список покупок {user.first_name} {local_time}\n\n'
    for ingredient in ingredients:
        shopping_list += (
            f'{ingredient["ingredient__name"]}: {ingredient["amount"]} '
            f'{ingredient["ingredient__measurement_unit"]}\n'
        )
    shopping_list += '\nFoodgram'
    return shopping_list


# Copyright 2023 The KubeEdge Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import json

from sedna.backend import set_backend
from sedna.common.file_ops import FileOps
from sedna.common.constant import KBResourceConstant
from sedna.common.class_factory import ClassFactory, ClassType

from sedna.algorithms.seen_task_learning.artifact import Task

__all__ = ('UnseenTaskProcessing', )

class UnseenTaskProcessing:
    '''
    Process unseen tasks given task update strategies

    Parameters:
    ----------
    estimator: Instance
        An instance with the high-level API that greatly simplifies
        machine learning programming. Estimators encapsulate training,
        evaluation, prediction, and exporting for your model.
    cloud_knowledge_management: Instance of class CloudKnowledgeManagement
    unseen_task_allocation: Dict
        Mining tasks of unseen inference sample.
    '''

    def __init__(self, estimator, unseen_task_allocation=None, **kwargs):
        self.estimator = estimator
        self.unseen_task_allocation = unseen_task_allocation or {
            "method": "UnseenTaskAllocationDefault"
        }
        self.inference_integrate = {"method": "DefaultInferenceIntegrate"}

        self.unseen_models = None
        self.unseen_extractor = None
        self.unseen_task_groups = None
        self.unseen_task_key = KBResourceConstant.UNSEEN_TASK.value
        self.task_group_key = KBResourceConstant.TASK_GROUPS.value
        self.extractor_key = KBResourceConstant.EXTRACTOR.value

    @staticmethod
    def _parse_param(param_str):
        if not param_str:
            return {}
        if isinstance(param_str, dict):
            return param_str
        try:
            raw_dict = json.loads(param_str, encoding="utf-8")
        except json.JSONDecodeError:
            raw_dict = {}
        return raw_dict

    def _unseen_task_allocation(self, samples):
        """
        Mining unseen tasks of inference sample
        base on task attribute extractor
        """
        method_name = self.unseen_task_allocation.get("method")
        extend_param = self._parse_param(
            self.unseen_task_allocation.get("param")
        )

        method_cls = ClassFactory.get_cls(ClassType.UTP, method_name)(
            task_extractor=self.unseen_extractor, **extend_param
        )
        return method_cls(samples=samples)

    def train(self):
        """
        Intialize unseen task groups

        Returns:
        res: Dict
            evaluation result.
        task_index: Dict or str
            unseen task index which includes models, samples, extractor
            and etc.
        """
        task_index = {
            self.extractor_key: None,
            self.task_group_key: []
        }

        res = {}
        return res, task_index

    def update(self, tasks, task_update_strategies, **kwargs):
        """
        Parameters:
        ----------
        tasks: List[Task]
            from the output of module task_update_decision
        task_update_strategies: Dict
            from the output of module task_update_decision

        Returns
        -------
        task_index : Dict
            updated unseen task index of knowledge base
        """
        task_index = {
            self.extractor_key: None,
            self.task_group_key: []
        }

        return task_index

    def predict(self, data, post_process=None, **kwargs):
        """
        Predict the result for unseen data.

        Parameters
        ----------
        data : BaseDataSource
            inference sample, see `sedna.datasources.BaseDataSource` for
            more detail.
        post_process: function
            function or a registered method,  effected after `estimator`
            prediction, like: label transform.

        Returns
        -------
        result : array_like
            results array, contain all inference results in each sample.
        tasks : List
            tasks assigned to each sample.
        """
        if callable(self.estimator):
            return self.estimator(), []

        if not self.unseen_task_groups and not self.unseen_models:
            self.load(kwargs.get("task_index"))

        tasks = []
        res = []
        for inx, df in enumerate(data.x):
            pred = self.estimator.predict([df])
            task = Task(entry=inx, samples=df)
            task.result = pred
            tasks.append(task)
            res.append(pred[0])
        return res, tasks

    def load(self, task_index):
        """
        load task_detail (tasks/models etc ...) from task index file.
        It'll automatically loaded during `inference` phases.

        Parameters
        ----------
        task_index_url : str
            task index file path.
        """
        assert task_index is not None, "task index url is None!!!"
        if isinstance(task_index, str):
            task_index = FileOps.load(task_index)

        self.unseen_extractor = \
            task_index[self.unseen_task_key][self.extractor_key]
        if isinstance(self.unseen_extractor, str):
            self.unseen_extractor = FileOps.load(self.unseen_extractor)
        self.unseen_task_groups = \
            task_index[self.unseen_task_key][self.task_group_key]
        self.unseen_models = \
            [task.model for task in self.unseen_task_groups]

    def _inference_integrate(self, tasks):
        """
        Aggregate inference results from target models
        """
        method_name = self.inference_integrate.get("method")
        extend_param = self._parse_param(
            self.inference_integrate.get("param"))
        method_cls = ClassFactory.get_cls(ClassType.STP, method_name)(
            models=self.unseen_models, **extend_param)
        return method_cls(tasks=tasks) if method_cls else tasks


import sys
import numpy
from PyQt5.QtWidgets import QApplication
from PyQt5.QtGui import QIntValidator, QDoubleValidator
from orangewidget import gui
from orangewidget.settings import Setting
from oasys.widgets import gui as oasysgui, congruence
from oasys.widgets.exchange import DataExchangeObject

from orangecontrib.xoppy.util.xoppy_xraylib_util import parse_formula
from orangecontrib.xoppy.widgets.gui.ow_xoppy_widget import XoppyWidget

import xraylib

class OWxf0(XoppyWidget):
    name = "F0"
    id = "orange.widgets.dataxf0"
    description = "Elastic Scattering Function"
    icon = "icons/xoppy_xf0.png"
    priority = 13
    category = ""
    keywords = ["xoppy", "xf0"]

    MAT_FLAG = Setting(0)
    DESCRIPTOR = Setting("Si")
    GRIDSTART = Setting(0.0)
    GRIDEND = Setting(8.0)
    GRIDN = Setting(100)
    DUMP_TO_FILE = Setting(0)  # No
    FILE_NAME = Setting("f0.dat")

    def build_gui(self):

        box = oasysgui.widgetBox(self.controlArea, self.name + " Input Parameters", orientation="vertical", width=self.CONTROL_AREA_WIDTH-5)

        idx = -1

        #widget index 1
        idx += 1
        box1 = gui.widgetBox(box)
        gui.comboBox(box1, self, "MAT_FLAG",
                     label=self.unitLabels()[idx], addSpace=False,
                    items=['Element(formula)', 'Mixture(formula)'],
                    valueType=int, orientation="horizontal", labelWidth=250)
        self.show_at(self.unitFlags()[idx], box1)

        #widget index 3
        idx += 1
        box1 = gui.widgetBox(box)
        oasysgui.lineEdit(box1, self, "DESCRIPTOR",
                     label=self.unitLabels()[idx], orientation="horizontal", addSpace=False)
        self.show_at(self.unitFlags()[idx], box1)

        #widget index 5
        idx += 1
        box1 = gui.widgetBox(box)
        oasysgui.lineEdit(box1, self, "GRIDSTART",
                     label=self.unitLabels()[idx], addSpace=False,
                    valueType=float, validator=QDoubleValidator(), orientation="horizontal", labelWidth=250)
        self.show_at(self.unitFlags()[idx], box1)

        #widget index 6
        idx += 1
        box1 = gui.widgetBox(box)
        oasysgui.lineEdit(box1, self, "GRIDEND",
                     label=self.unitLabels()[idx], addSpace=False,
                    valueType=float, validator=QDoubleValidator(), orientation="horizontal", labelWidth=250)
        self.show_at(self.unitFlags()[idx], box1)

        #widget index 7
        idx += 1
        box1 = gui.widgetBox(box)
        oasysgui.lineEdit(box1, self, "GRIDN",
                     label=self.unitLabels()[idx], addSpace=False,
                    valueType=int, validator=QIntValidator(), orientation="horizontal", labelWidth=250)
        self.show_at(self.unitFlags()[idx], box1)

        # widget index 8
        idx += 1
        box1 = gui.widgetBox(box)
        gui.comboBox(box1, self, "DUMP_TO_FILE",
                     label=self.unitLabels()[idx], addSpace=True,
                     items=["No", "Yes"],
                     orientation="horizontal")
        self.show_at(self.unitFlags()[idx], box1)

        # widget index 9
        idx += 1
        box1 = gui.widgetBox(box)
        gui.lineEdit(box1, self, "FILE_NAME",
                     label=self.unitLabels()[idx], addSpace=True)
        self.show_at(self.unitFlags()[idx], box1)

        gui.rubber(self.controlArea)

    def unitLabels(self):
         return ['material','formula','From q [sin(theta)/lambda]: ','To q [sin(theta)/lambda]: ','Number of q points',
                 'Dump to file','File name']

    def unitFlags(self):
         return ['True','self.MAT_FLAG  !=  2','True','True','True',
                 'True','self.DUMP_TO_FILE == 1']

    def get_help_name(self):
        return 'f0'

    def check_fields(self):
        self.DESCRIPTOR = congruence.checkEmptyString(self.DESCRIPTOR, "formula")
        self.GRIDSTART = congruence.checkPositiveNumber(self.GRIDSTART, "Q from")
        self.GRIDEND = congruence.checkStrictlyPositiveNumber(self.GRIDEND, "Q to")
        congruence.checkLessThan(self.GRIDSTART, self.GRIDEND, "Q from", "Q to")
        self.GRIDN = congruence.checkStrictlyPositiveNumber(self.GRIDN, "Number of q Points")

    def do_xoppy_calculation(self):
        out_dict = self.xoppy_calc_xf0()

        if "info" in out_dict.keys():
            print(out_dict["info"])

        calculated_data = DataExchangeObject("XOPPY", self.get_data_exchange_widget_name())

        try:
            calculated_data.add_content("xoppy_data", out_dict["data"].T)
            calculated_data.add_content("plot_x_col",0)
            calculated_data.add_content("plot_y_col",-1)
        except:
            pass
        try:
            calculated_data.add_content("labels",out_dict["labels"])
        except:
            pass
        try:
            calculated_data.add_content("info",out_dict["info"])
        except:
            pass

        return calculated_data

    def extract_data_from_xoppy_output(self, calculation_output):
        return calculation_output

    def get_data_exchange_widget_name(self):
        return "XF0"

    def getTitles(self):
        return ["f0"]

    def getXTitles(self):
        return ["q=sin(theta)/lambda [A^-1]"]

    def getYTitles(self):
        return ["f0 [electron units]"]

    def xoppy_calc_xf0(self):
        MAT_FLAG = self.MAT_FLAG
        DESCRIPTOR = self.DESCRIPTOR
        GRIDSTART = self.GRIDSTART
        GRIDEND = self.GRIDEND
        GRIDN = self.GRIDN

        qscale = numpy.linspace(GRIDSTART,GRIDEND,GRIDN)

        f0 = numpy.zeros_like(qscale)

        if MAT_FLAG == 0: # element
            descriptor = DESCRIPTOR
            for i,iqscale in enumerate(qscale):
                f0[i] = xraylib.FF_Rayl(xraylib.SymbolToAtomicNumber(descriptor),iqscale)
        elif MAT_FLAG == 1: # formula
            tmp = parse_formula(DESCRIPTOR)
            zetas = tmp["Elements"]
            multiplicity = tmp["n"]
            for j,jz in enumerate(zetas):
                for i,iqscale in enumerate(qscale):
                    f0[i] += multiplicity[j] * xraylib.FF_Rayl(jz,iqscale)
        elif MAT_FLAG == 2:
            raise Exception("Not implemented")

        if self.DUMP_TO_FILE:
            with open(self.FILE_NAME, "w") as file:
                try:
                    file.write("#F %s\n"%self.FILE_NAME)
                    file.write("\n#S 1 xoppy f0 results\n")
                    file.write("#N 2\n")
                    file.write("#L  q=sin(theta)/lambda [A^-1]  f0 [electron units]\n")
                    for j in range(qscale.size):
                        # file.write("%19.12e  "%energy[j])
                        file.write("%19.12e  %19.12e\n"%(qscale[j],f0[j]))
                    file.close()
                    print("File written to disk: %s \n"%self.FILE_NAME)
                except:
                    raise Exception("f0: The data could not be dumped onto the specified file!\n")

        #
        # return
        #
        return {"application":"xoppy","name":"f0","data":numpy.vstack((qscale,f0)),"labels":["q=sin(theta)/lambda [A^-1]","f0 [electron units]"]}

if __name__ == "__main__":
    app = QApplication(sys.argv)
    w = OWxf0()
    w.show()
    app.exec()
    w.saveSettings()


from dataclasses import dataclass, asdict, astuple
import inspect

@dataclass(frozen=True, order=True)
class Comment:
    id: int
    text: str

def main():
    comment = Comment(1, "I subscribed")
    print(comment)
    print(asdict(comment))
    print(inspect.getmembers(comment))

if __name__ == '__main__':
    main()


#!/usr/bin/env python
import rospy
import numpy as np
from std_msgs.msg import Int32, Bool
from geometry_msgs.msg import PoseStamped, Pose, Point
from styx_msgs.msg import TrafficLightArray, TrafficLight
from styx_msgs.msg import Lane
from sensor_msgs.msg import Image
from cv_bridge import CvBridge
from light_classification.tl_classifier import TLClassifier
import tf
import cv2
import yaml
import math
import os

STATE_COUNT_THRESHOLD = 3

class TLDetector(object):
    def __init__(self):
        rospy.init_node('tl_detector')

        self.pose = None
        self.waypoints = None
        self.camera_image = None
        self.lights = []
        self.tl_waypoints = []
        self.has_image = False

        sub1 = rospy.Subscriber('/current_pose', PoseStamped, self.pose_cb, queue_size=1)
        sub2 = rospy.Subscriber('/base_waypoints', Lane, self.waypoints_cb, queue_size=1)

        '''
        /vehicle/traffic_lights helps you acquire an accurate ground truth data source for the traffic light
        classifier, providing the location and current color state of all traffic lights in the
        simulator. This state can be used to generate classified images or subbed into your solution to
        help you work on another single component of the node. This topic won't be available when
        testing your solution in real life so don't rely on it in the final submission.
        '''
        sub3 = rospy.Subscriber('/vehicle/traffic_lights', TrafficLightArray, self.traffic_cb, queue_size=1)
        sub6 = rospy.Subscriber('/image_color', Image, self.image_cb, queue_size=1, buff_size=100000)
        sub_record_gt = rospy.Subscriber('/record_training_data', Bool, self.gt_cb, queue_size=1)

        config_string = rospy.get_param("/traffic_light_config")
        self.config = yaml.load(config_string)

        self.upcoming_red_light_pub = rospy.Publisher('/traffic_waypoint',
                                                      Int32, queue_size=1)
        self.debug_img_pub = rospy.Publisher('/image_debug_zoomed',
                                             Image, queue_size=1)

        self.stop_line_positions = self.config['stop_line_positions']

        self.bridge = CvBridge()
        self.listener = tf.TransformListener()

        self.state = TrafficLight.UNKNOWN
        self.last_state = TrafficLight.UNKNOWN
        self.last_wp = -1
        self.state_count = 0
        self.prev_light_loc = None

        self.gen_train_data = False

        # data generator file count index
        self.file_index = 0
        self.target_encoding = 'rgb8'
        # mappings from each state to color
        self.states_map = {0: 'red', 1: 'yellow', 2: 'green'}

        fx = self.config['camera_info']['focal_length_x']

        if fx < 10:
            self.light_classifier = TLClassifier(True)
        else:
            self.light_classifier = TLClassifier(False)

        rospy.spin()

    def gt_cb(self, msg):
        self.gen_train_data = msg.data

    def pose_cb(self, msg):
        self.pose = msg

    def waypoints_cb(self, waypoints):
        self.waypoints = waypoints

    def traffic_cb(self, msg):
        self.lights = msg.lights

    def image_cb(self, msg):
        """Identifies red lights in the incoming camera image and publishes the index
            of the waypoint closest to the red light to /traffic_waypoint

        Args:
            msg (Image): image from car-mounted camera

        """
        self.has_image = True
        self.camera_image = msg
        light_wp, state = self.process_traffic_lights()

        '''
        Publish upcoming red lights at camera frequency.
        Each predicted state has to occur `STATE_COUNT_THRESHOLD` number
        of times till we start using it. Otherwise the previous stable state is
        used.
        '''
        if self.state != state:
            self.state_count = 0
            self.state = state
        elif self.state_count >= STATE_COUNT_THRESHOLD:
            self.last_state = self.state
            light_wp = light_wp if ((state == TrafficLight.RED) or (state == TrafficLight.YELLOW)) else -1
            self.last_wp = light_wp
            self.upcoming_red_light_pub.publish(Int32(light_wp))
        else:
            self.upcoming_red_light_pub.publish(Int32(self.last_wp))
        self.state_count += 1

    def get_closest_waypoint(self, pose):
        """Identifies the closest path waypoint to the given position
            https://en.wikipedia.org/wiki/Closest_pair_of_points_problem
        Args:
            pose (Pose): position to match a waypoint to

        Returns:
            int: index of the closest waypoint in self.waypoints

        """
        if self.waypoints is not None:
            wp_list = self.waypoints.waypoints
        else:
            return None
        # Create variables for nearest distance and neighbour
        neighbour_index = None
        neighbour_distance = 100000.0

        # Find Neighbour
        for i in range(len(wp_list)):
            wpi = wp_list[i].pose.pose.position
            distance = math.sqrt(
                (wpi.x - pose.position.x) ** 2 + (wpi.y - pose.position.y) ** 2 + (wpi.z - pose.position.z) ** 2)
            if distance < neighbour_distance:
                neighbour_index = i
                neighbour_distance = distance

        return neighbour_index

    def project_to_image_plane(self, point_in_world, trans, rot):
        """Project point from 3D world coordinates to 2D camera image location

        Args:
            point_in_world (Point): 3D location of a point in the world

        Returns:
            x (int): x coordinate of target point in image
            y (int): y coordinate of target point in image

        """

        fx = self.config['camera_info']['focal_length_x']
        fy = self.config['camera_info']['focal_length_y']
        image_width = self.config['camera_info']['image_width']
        image_height = self.config['camera_info']['image_height']

        # Center of the image
        # To be changed in simulator to compensate
        cx = image_width / 2
        cy = image_height / 2

        # if transform not received just send out mid point of image
        if (trans is None) or (rot is None):
            return (image_width / 2, image_height / 2)

        # Create a tf matrix
        tf_matrix = self.listener.fromTranslationRotation(trans, rot)

        # convert point_in_world to a numpy array
        pw_np = np.array([[point_in_world.x], [point_in_world.y], [point_in_world.z], [1.0]])

        # Transform to point in camera using the tf_matrix
        pc_np = np.dot(tf_matrix, pw_np)

        # get x,y and z values from the transformed point
        x_c = pc_np[2]
        y_c = pc_np[1]
        z_c = pc_np[0]

        # Convert to image co-ordinates using image params
        if fx < 10.0:
            fx = 2544
            fy = 2744
            cx = image_width / 2 - 30
            cy = image_height + 70

        u = int(-(fx / z_c) * y_c)
        v = int(-(fy / z_c) * x_c)

        # Translation to top left origin
        u = min(image_width, int(u + cx))
        v = min(image_height, int(v + cy))

        return (u, v)

    def dist_to_closest_stop_line(self):

        neighbour_distance = 1000000.0
        neighbour_index = 0
        curr_pose = self.pose.pose.position
        orientation = self.pose.pose.orientation
        for i in range(len(self.stop_line_positions)):
            light_pose = self.stop_line_positions[i]
            distance = math.sqrt(
                (light_pose[0] - curr_pose.x) ** 2 + (light_pose[1] - curr_pose.y) ** 2)
            if distance < neighbour_distance:
                neighbour_distance = distance
                neighbour_index = i

        # Check if neighbour is ahead or behind
        quat_np = (orientation.x, orientation.y, orientation.z, orientation.w)
        rpy = tf.transformations.euler_from_quaternion(quat_np)
        yaw = rpy[2]

        # Project a unit vector along orientation
        proj_distance = 1.0
        v1 = (proj_distance*math.cos(yaw), proj_distance*math.sin(yaw))
        v2 = (self.stop_line_positions[neighbour_index][0] - curr_pose.x, self.stop_line_positions[neighbour_index][1] - curr_pose.y)

        dot = np.dot(v1,v2)

        if dot < 0:
            neighbour_distance = -1

        return neighbour_distance

    def get_light_state(self, light_wp):
        """Determines the current color of the traffic light

        Args:
            light_wp (TrafficLight): index of light to classify

        Returns:
            int: ID of traffic light color (specified in styx_msgs/TrafficLight)

        """
        light = self.lights[light_wp].pose.pose.position
        if not self.has_image:
            self.prev_light_loc = None
            return TrafficLight.UNKNOWN

        cv_image = self.bridge.imgmsg_to_cv2(self.camera_image, self.target_encoding)

        # Zooming etc is only needed when we need to generate training data
        if self.gen_train_data:

            distance_to_light = self.dist_to_closest_stop_line()

            if not (0 < distance_to_light < 75):
                return TrafficLight.UNKNOWN

            # get transform between pose of camera and world frame
            trans = None
            rot = None
            try:
                now = rospy.Time.now()
                self.listener.waitForTransform("/base_link",
                                               "/world", now, rospy.Duration(1.0))
                (trans, rot) = self.listener.lookupTransform("/base_link",
                                                             "/world", now)

            except (tf.Exception, tf.LookupException, tf.ConnectivityException):
                rospy.logerr("Failed to find camera to map transform")

                if (trans is None) or (rot is None):
                    return TrafficLight.UNKNOWN

            # Use TL position from the message to figure out center in the image plane

            # Offset based on observation (The z value in the message seems to be for the top of the light
            light.z -= 0.6

            x_center, y_center = self.project_to_image_plane(light, trans, rot)

            # TODO use light location to zoom in on traffic light in image

            # Create a second light point which is 0.5 * (tl_width, tl_height ) away from the center
            # Add padding to have a slightly bigger bounding box
            # it should conceptually be fine for the deep learning pipeline as
            # The Neural Network should be able to extract away the
            light2 = light
            light2.y += 0.5  # width + padding
            light2.z += 1.0  # height + padding

            # Project the corner to the image plane as well
            x_corner, y_corner = self.project_to_image_plane(light2, trans, rot)

            # Get image parameters in the local variables so that bounding boxes can be capped by image dimensions
            image_width = self.config['camera_info']['image_width']
            image_height = self.config['camera_info']['image_height']

            # Figure out box half and full heights
            box_half_width = abs(x_corner - x_center)
            box_half_height = abs(y_corner - y_center)

            # Find top left corner
            tl_x = max(0, x_center - box_half_width)
            tl_y = max(0, y_center - box_half_height)

            # Find Bottom Right corner
            br_x = min(x_center + box_half_width, image_width - 1)
            br_y = min(y_center + box_half_height, image_height - 1)

            # save the training image and annotation
            self.generate_training_data(cv_image, image_width, image_height,
                self.lights[light_wp].state, tl_x, tl_y, int(box_half_width*2),
                int(box_half_height*2))

            # Image for debug_msgs
            new_image = cv_image
            # Draw the estimated bounding box
            cv2.rectangle(new_image, (tl_x, tl_y), (br_x, br_y), (0, 255, 0), 4)

            # create the message from the debug image
            img_msg = self.bridge.cv2_to_imgmsg(new_image, self.target_encoding)

            # publish the output
            self.debug_img_pub.publish(img_msg)

            # return Ground truth to be published on the message
            # return self.lights[light_wp].state

            return TrafficLight.UNKNOWN
        else:
            # Get classification
            if hasattr(self, "light_classifier"):
                light_state = self.light_classifier.get_classification(cv_image)
                img_msg = self.bridge.cv2_to_imgmsg(self.light_classifier.image_np_output, self.target_encoding)
                # publish the output
                self.debug_img_pub.publish(img_msg)
            else:
                light_state = TrafficLight.UNKNOWN

            return light_state

    # return ground truth light state
    def get_light_state_from_list(self, light_index):
        return self.lights[light_index].state

    def generate_training_data(self, image, image_width, image_height, state,
        x, y, w, h):

        # Setup
        data_folder = "../../../sim_training_data"
        annotation_folder = "../../../sim_training_data/annotations"

        # Check if this is the first loop
        if self.file_index == 0:

            # Check to see if there's a folder for containing the data
            if os.path.isdir(data_folder):
                training_files = os.listdir(data_folder)

                # Ensure we have an annotations folder
                if 'annotations' not in training_files:
                    os.makedirs(annotation_folder)
                else:
                    training_files.remove('annotations')

                # If there is, check and see if any training images are saved
                if len(training_files) > 0:
                    training_files.sort()
                    training_files.sort(key=len)
                    last_training_file = training_files[-1]
                    rospy.logwarn("The last file was {}".format(
                        last_training_file))
                    try:
                        last_index = int(last_training_file.split(".")[0])
                        self.file_index = last_index + 1
                    except:
                        raise ValueError(
                            "Couldn't understand the naming convention of {},\
                             was it created by the data generator?".format(
                                last_training_file))
            else:
                os.makedirs(data_folder)
                os.makedirs(annotation_folder)

        # Save a training image and annotation and update the file count index
        filename = "{0}/{1}.jpg".format(data_folder,
            str(self.file_index).zfill(4))
        annotation = """
{{
  "filename" : "{0}",
  "folder" : "sim_training_data",
  "image_w_h" : [
    {1},
    {2}
  ],
  "objects" : [
    {{
      "label" : "traffic_light-{3}",
      "x_y_w_h" : [
        {4},
        {5},
        {6},
        {7}
      ]
    }}
  ]
}}
""".format("{}.jpg".format(str(self.file_index).zfill(4)), image_width,
    image_height, self.states_map[state], x, y, w, h)
        cv2.imwrite(filename, image)
        with open(annotation_folder + "/" +
            str(self.file_index).zfill(4) + ".json", "w") as saveloc:
            saveloc.write(annotation)
        self.file_index += 1
        rospy.logwarn("Took an annotated traffic light training image")

    def process_traffic_lights(self):
        """Finds closest visible traffic light, if one exists, and determines its
            location and color

        Returns:
            int: index of waypoint closes to the upcoming traffic light (-1 if none exists)
            int: ID of traffic light color (specified in styx_msgs/TrafficLight)

        """
        light = None
        car_position = None

        if self.pose:
            car_position = self.get_closest_waypoint(self.pose.pose)

        # TODO find the closest visible traffic light (if one exists)

        neighbour_index = None
        neighbour_distance = 100000.0
        if self.waypoints is not None and car_position is not None:
            pose = self.waypoints.waypoints[car_position].pose.pose
        else:
            return -1, TrafficLight.UNKNOWN

        for i in range(len(self.lights)):
            lpi = self.lights[i].pose.pose.position

            distance = math.sqrt(
                (lpi.x - pose.position.x) ** 2 + (lpi.y - pose.position.y) ** 2 + (lpi.z - pose.position.z ** 2))
            if distance < neighbour_distance:
                neighbour_index = i
                neighbour_distance = distance

        light_wp = None
        if neighbour_index is not None:
            light = self.lights[neighbour_index].pose.pose.position
            light_wp = neighbour_index

        if light:
            state = self.get_light_state(light_wp)
            # state = self.get_light_state_from_list(light_wp)
            return light_wp, state

        return -1, TrafficLight.UNKNOWN

if __name__ == '__main__':
    try:
        TLDetector()
    except rospy.ROSInterruptException:
        rospy.logerr('Could not start traffic node.')


palavras_reservadas = ['ABSTRACT', 'ASSERT', 'BOOLEAN', 'BREAK', 'BYTE', 'CASE', 'CATCH',
          'CHAR', 'CLASS', 'CONST', 'CONTINUE', 'DEFAULT', 'DO', 'DOUBLE', 'ELSE',
          'ENUM', 'EXTENDS', 'FINAL', 'FINALLY', 'FLOAT', 'FOR', 'IF', 'GOTO',
          'IMPLEMENTS', 'IMPORT', 'INSTANCEOF', 'INT', 'INTERFACE', 'LONG', 'NATIVE',
          'NEW', 'PACKAGE', 'PRIVATE', 'PROTECTED', 'PUBLIC', 'RETURN', 'SHORT', 'STATIC',
          'STRICTFP', 'SUPER', 'SWITCH', 'SYNCHRONIZED', 'THIS', 'THROW', 'THROWS', 'TRANSIENT',
          'TRY', 'VOID', 'VOLATILE', 'WHILE', 'MAIN', 'STRING', 'LENGTH', 'SYSTEM', 'OUT',
          'PRINTLN', 'SYSTEM.OUT.PRINTLN']

'''
#Palavras Reservadas
t_ABSTRACT = r'\abstract'
t_ASSERT = r'\assert'
t_BOOLEAN = r'\boolean'
t_BREAK = r'\break'
t_BYTE = r'\byte'
t_CASE = r'\case'
t_CATCH = r'\catch'
t_CHAR = r'\char'
t_CLASS = r'\class'
t_CONST = r'\const'
t_CONTINUE = r'\continue'
t_DEFAULT = r'\default'
t_DO = r'\do'
t_DOUBLE = r'\double'
t_ELSE = r'\else'
t_ENUM = r'\enum'
t_EXTENDS = r'\extends'
t_FINAL = r'\final'
t_FINALLY = r'\finally'
t_FLOAT = r'\float'
t_FOR = r'\for'
t_IF = r'\if'
t_GOTO = r'\goto'
t_IMPLEMENTS = r'\implements'
t_IMPORT = r'\import'
t_INSTANCEOF = r'\instanceof'
t_INT = r'\int'
t_INTERFACE = r'\interface'
t_LONG = r'\long'
t_NATIVE = r'\native'
t_NEW = r'\new'
t_PACKAGE = r'\package'
t_PRIVATE = r'\private'
t_PROTECTED = r'\protected'
t_PUBLIC = r'\public'
t_RETURN = r'\return'
t_SHORT = r'\short'
t_STATIC = r'\static'
t_STRICTFP = r'\strictfp'
t_SUPER = r'\super'
t_SWITCH = r'\switch'
t_SYNCHRONIZED = r'\synchronized'
t_THIS = r'\this'
t_THROW = r'\throw'
t_THROWS = r'\throws'
t_TRANSIENT = r'\transient'
t_TRY = r'\try'
t_VOID = r'\void'
t_VOLATILE = r'\volatile'
t_WHILE = r'\while'
t_MAIN = r'\main'
t_STRING = r'\string'
t_LENGTH = r'\length'
t_SYSTEM = r'\system'
t_OUT = r'\out'
t_PRINTLN = r'\println'
t_SYSTEM_OUT_PRINTLN = r'\system.out.println'
'''

for palavra in palavras_reservadas:
    print("'"+palavra.lower()+"':'"+palavra+"',")


def return_set_from_range(range_str):
    range_list = list(map(int, range_str.split(',')))
    return set(range(min(range_list), max(range_list) + 1))

lines = int(input())

longest = {'len': 0, 'intersection_set': set()}

for _ in range(lines):
    ranges = input().split('-')
    intersection = return_set_from_range(ranges[0]).intersection(return_set_from_range(ranges[1]))
    if len(intersection) > longest['len']:
        longest['len'] = len(intersection)
        longest['intersection_set'] = intersection

print(f"Longest intersection is", sorted(list(longest['intersection_set'])), f"with length {longest['len']}")

Python_Advanced/Advanced/02. Tuples and Sets/06. Longest Intersection.py


# -*- coding: utf-8 -*-
# @Author: zhq
# @Date:   2018-04-08 21:03:39
# @Last Modified by:   zhq
# @Last Modified time: 2018-04-08 21:11:11

# 通过 resolution 选项控制分辨率（步长）
# 通过 tickinterval 选项设置刻度

root = Tk()
Scale(root, from_ = 0, to = 50, tickinterval = 5, length = 200,\
    resolution = 5, orient = VERTICAL).pack()

Scale(root, from_ = 0, to = 200, tickinterval = 10, length = 600,\
    orient = HORIZONTAL).pack()

mainloop()


import numpy as np
from keras.models import *
from keras.layers import *
from keras.layers.local import *
from keras.optimizers import *
from keras.utils import plot_model

def BN():
    return BatchNormalization()

def relu():
    return PReLU(alpha_initializer='ones',shared_axes=[1,2])

def mult_res(inputs,n=0,bn=True):
    x=inputs
    for i in range(n):
        x=res(x,bn)
    if bn and n==0:
        x=BN()(x)
    return x

def res(inputs,bn=True):
    n=int(inputs.shape[-1])

    # x=CoordinateChannel2D()(inputs)
    x=(inputs)

    c1=relu()(Conv2D(n,3, padding='same')(x))
    c2=relu()(Conv2D(n,3, padding='same')(c1))
    m=add([c2,inputs])
    if bn:
        m=BN()(m)
    return m

def down(t,inputs,bn=True):
    a=Conv2D(t,5,strides=2, padding='same')(inputs)
    c1=relu()(a)
    return (mult_res(c1,bn=bn))

def up(t,inputs,bn=True):
    c1=(relu()(Conv2DTranspose(t,5,strides=2, padding='same')(inputs)))
    return (mult_res(c1,bn=bn))

def 圖像卷積(inputs):
    c32 = down(32,inputs)
    c16 = down(64,c32)
    c8 = down(128,c16)
    c4 = down(256,c8,bn=False)

    return c4

def 圖像卷積模型():
    i=Input(shape=(64,64,3))
    c32 = down(32,i)
    c16 = down(64,c32)
    c8 = down(128,c16)
    c4 = down(256,c8,bn=False)
    o = Activation('sigmoid')(Flatten()(c4))
    return Model(inputs=i,outputs=o)

def 反卷到水印(inputs,水印強度=0.016,噪聲強度=1/1024):

    c8 = up(256,inputs)
    c16 = up(128,c8)
    c32 = up(64,c16)
    c64 = up(32,c32,bn=False)

    predict = Activation('sigmoid')(Conv2D(3,1)(c64))

    l=Lambda(lambda x: x*水印強度)(predict)

    return GaussianNoise(噪聲強度)(l)

def 製造模型():
    圖輸入 = Input(shape=(64,64,3))
    碼輸入 = Input(shape=(64*64,))
    特徵 = 圖像卷積(圖輸入)

    特徵和碼 = concatenate([特徵,Reshape([4,4,256])(碼輸入)])
    水印 = 反卷到水印(特徵和碼)

    終圖 = add([圖輸入,水印])

    解碼 = 圖像卷積模型()
    解碼的碼 = 解碼(終圖)

    全模型 = Model(inputs=[圖輸入,碼輸入],outputs=解碼的碼)
    嵌入 = Model(inputs=[圖輸入,碼輸入],outputs=終圖)
    全模型.summary()

    adam = Adam(lr=1e-4,amsgrad=True)
    rms = RMSprop(lr=4e-4)
    全模型.compile(loss='binary_crossentropy',optimizer=adam, metrics=['binary_accuracy','mse'])

    plot_model(全模型, to_file='model.png', show_shapes=True, show_layer_names=True)
    plot_model(解碼, to_file='model2.png', show_shapes=True, show_layer_names=True)
    return 全模型, 嵌入, 解碼

if __name__=='__main__':
    製造模型()


import numpy as np
import sklearn.preprocessing as prep
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
import Autocoder as au

def standard_scale(X_train, X_test):
    preprocessor = prep.StandardScaler().fit(X_train)
    X_train = preprocessor.transform(X_train)
    X_test = preprocessor.transform(X_test)

    return X_train, X_test

#从样本集中随机取连续的batch size个样本

def get_random_block_from_data(data,batch_size):
    start_index = np.random.randint(0, len(data)-batch_size)
    return data[start_index:(start_index + batch_size)]

mnist=input_data.read_data_sets("G:/TensorFlow/", one_hot=True)
X_train, X_test = standard_scale(mnist.train.images, mnist.test.images)
n_samples = int(mnist.train.num_examples)
training_epochs = 3
batch_size = 128
display_step = 1

autocoder = au.AdditiveGaussianNoiseAutoencoder(n_input=784, n_hidden=200, optimizer=tf.train.AdamOptimizer(learning_rate=0.001),
                                                 scale=0.01)

for epoch in range(training_epochs):
    avg_cost = 0.
    total_batch = int(n_samples/batch_size)
    for i in range(total_batch):
        batch_xs = get_random_block_from_data(X_train, batch_size)
        cost = autocoder.partial_fit(batch_xs)
        avg_cost += cost/n_samples * batch_size
    if epoch % display_step==0:
        print("Epoch:", '%04d' % (epoch + 1), "cost=", "{:.9f}".format(avg_cost))

print("Total cost:" + str(autocoder.calc_total_cost(X_test)))


#!/user/bin/python
# -*- coding=utf-8 -*-

# 设计一个算法来计算你所能获取的最大利润。你可以尽可能地完成更多的交易（多次买卖一支股票）。
#
# 注意：你不能同时参与多笔交易（你必须在再次购买前出售掉之前的股票）。

class Solution:
    def maxProfit(self, prices):
        profit = 0
        for i in range(1, len(prices)):
            tmp = prices[i] - prices[i - 1]
            if tmp > 0: profit += tmp
        return profit


# conftest.py
from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession
from sqlalchemy.orm import sessionmaker
from helpers.session_context import SessionContext
from models import Base
import models.factory as model_factorys
import pytest_asyncio
from helpers.api_token import ApiToken
import business

# Define your in-memory SQLite test database URL
TEST_DATABASE_URL = "sqlite+aiosqlite:///:memory:"

@pytest_asyncio.fixture(scope="function")
async def overridden_get_db():

    # Create the async engine for the in-memory SQLite database
    engine = create_async_engine(TEST_DATABASE_URL, echo=False)

    # Create the tables in the database
    async with engine.begin() as conn:
        await conn.run_sync(Base.metadata.create_all)

    # Create a sessionmaker
    AsyncSessionLocal = sessionmaker(
        bind=engine,
        class_=AsyncSession,
        expire_on_commit=False
    )

    # Create a new session for the test
    async with AsyncSessionLocal() as session:
        yield session

    # After the test is done, drop all the tables
    async with engine.begin() as conn:
        await conn.run_sync(Base.metadata.drop_all)

    # Dispose the engine
    await engine.dispose()

@pytest_asyncio.fixture(scope="function")
async def api_key_fixture(overridden_get_db: AsyncSession):
    session_context = SessionContext(dict(),overridden_get_db)
    customer = await model_factorys.CustomerFactory.create_async(overridden_get_db)
    customer_bus_obj = await business.CustomerBusObj.get(session_context,customer_obj_instance=customer)
    tac_bus_obj = await business.TacBusObj.get(session_context,tac_id=customer.tac_id)
    pac_bus_obj = await business.PacBusObj.get(session_context,pac_id=tac_bus_obj.pac_id)
    api_dict = {'CustomerCode': str(customer.code),
                'TacCode': str(tac_bus_obj.code),
                'PacCode': str(pac_bus_obj.code),
                'UserName': customer.email}
    test_api_key = ApiToken.create_token(api_dict, 1)
    return test_api_key


#######PYTHON CODE FOR IMD PREPARED BY LEKSHMI S#########
########## https://doi.org/10.5281/zenodo.5674826 ############

############################READING A NETCDF4 FILE USING XARRAY######################################
##########################Import necessary Modules###################
import xarray as xr

##########Read the dataset using xarray##########################
filename="E:/Python_DEMO_Scripts/Sample_Data/_Clim_Pred*.nc"
da=xr.open_mfdataset(filename)
#print(da)

############Read the individual variables in the dataset########
rf=da.RAINFALL
lat=da.LATITUDE
lon=da.LONGITUDE
#print(lon)

################ Subsetting in all dimensions###################
da1=da.sel(TIME=slice('2019-11-01','2020-03-31'),LATITUDE=slice(7.5,20.5),LONGITUDE=slice(68.0,90.5))
#print(da1)

#####################Choosing a few months######################
mamj = da.TIME.dt.month.isin(range(3, 7))       #Reading March-June
da2=da.sel(TIME=mamj)
#print(da2)

##########Choosing pre-defined seasons in xarray using groupby#########
da3=da.groupby("TIME.season")["MAM"]        #Choosing MAM
#print(da3)

da4=da.groupby("TIME.season")["MAM"].mean(dim="TIME")   #Calculating Seasonal Mean
print(da4)


# !usr/bin/python3
# -*- coding: utf-8 -*-
"""Utilities used in clustering.

Author:Sacha Beniamine.
"""
try:
    from matplotlib import pyplot

    plt = pyplot
    matplotlib_loaded = True
except:
    matplotlib_loaded = False

try:
    import networkx as nx

    nx_loaded = True
except:
    nx_loaded = False

import numpy as np
import re

class Node(object):
    """Represent an inflection class tree.

    Attributes:
        labels (list): labels of all the leaves under this node.
        children (list): direct children of this node.
        attributes (dict): attributes for this node.
            Currently, three attributes are expected:
            size (int): size of the group represented by this node.
            DL (float): Description length for this node.
            color (str): color of the splines from this node to its children, in a format usable by pyplot.
            Currently, red ("r") is used when the node didn't decrease Description length, blue ("b") otherwise.
            macroclass (bool): Is the node in a macroclass ?
            macroclass_root (bool): Is the node the root of a macroclass ?

            The attributes "_x" and "_rank" are reserved,
            and will be overwritten by the draw function.
    """

    def __init__(self, labels, children=None, **kwargs):
        """Node constructor.

        Arguments:
            labels (iterable): labels of all the leaves under this node.
            children (list): direct children of this node.
            kwargs: any other keyword argument will be added as node attributes.
             Note that certain algorithm expect the Node to have (int) "size",
             (str) "color", (bool) "macroclass", or (float) "DL" attributes.

            The attributes "_x" and "_rank" are reserved,
            and will be overwritten by the draw function.
        """
        self.labels = sorted(labels)
        self.children = children if children else []
        self.attributes = kwargs

    def __str__(self):
        """Return a repr string for Nodes."""
        attrs = " - ".join("{}={}".format(key, self.attributes[key]) for key in self.attributes)
        return "< Node object - " + ", ".join(self.labels) + " - " + attrs + ">"

    def macroclasses(self, parent_is_macroclass=False):
        """Find all the macroclasses nodes in this tree"""
        self_is_macroclass = self.attributes["macroclass"]
        if not parent_is_macroclass and self_is_macroclass:
            labels = self.labels
            return {labels[0]: labels}
        elif self.children:
            macroclasses_under = {}
            for child in self.children:
                child_macroclasses = child.macroclasses(parent_is_macroclass=self_is_macroclass)
                macroclasses_under.update(child_macroclasses)
            return macroclasses_under
        return {}

    def _recursive_xy(self):
        if self.attributes.get("_y", None) is None:
            y = 1
            if len(self.children) > 0:
                xs, ys = zip(*[child._recursive_xy() for child in self.children])
                y += max(ys)
                x = sum(xs) / len(self.children)
                self.attributes["_x"] = x
            self.attributes["_y"] = y
        return self.attributes["_x"], self.attributes["_y"]

    def _erase_xy(self):
        self.attributes["_x"] = None
        self.attributes["_y"] = None
        for child in self.children:
            child._erase_xy()

    def compute_xy(self, tree_placement=False, pos=None):
        if "_y" in self.attributes and self.attributes["_y"] is not None:
            self._erase_xy()

        if tree_placement:  #  For trees
            leaves = self.leaves()
            x = 0
            step = 10
            for leaf in leaves:
                leaf.attributes["_x"] = x
                x += step
            self._recursive_xy()
        else:
            if pos is None:
                pos = nx.drawing.nx_agraph.graphviz_layout(self.to_networkx(), prog='dot')
            for node in self:
                node.attributes["_x"], node.attributes["_y"] = pos[tuple(node.labels)]

    def to_networkx(self):
        if not nx_loaded:
            raise ImportError("Can't convert to networkx, because it couldn't be loaded.")
        G = nx.DiGraph()
        for node in self:
            name = tuple(node.labels)
            G.add_node(name, **node.attributes)
            for child in node.children:
                childname = tuple(child.labels)
                G.add_edge(name, childname)
        return G

    def __iter__(self):
        visited = set()
        agenda = [self]
        while agenda:
            node = agenda.pop(0)
            if node not in visited:
                visited.add(node)
                agenda = node.children + agenda
                yield node

    def leaves(self):
        return filter(lambda x: not bool(x.children), self)

    def __repr__(self):
        """Return the inflection class tree as a string with parenthesis.

        Assumes size, DL and color attributes,
        with color = "r" if this is above a macroclass.

        Example:
            In the label, fields are separated by "#" as such::

                (<labels>#<size>#<DL>#<color> )
        """
        labels = "&".join(self.labels)
        ignore = ["_rank", "_x", "macroclass", "macroclass_root"]
        attributes = "#".join(
            "{}={}".format(key, str(self.attributes[key]).replace(" ", "_")) for key in sorted(self.attributes) if
            key not in ignore)
        children_str = [repr(child) for child in self.children]
        string = "(" + labels + "#" + attributes + " ".join([""] + children_str) + " )"

        return string

    def _recursive_to_latex(self, n, nodelabel=None, macroclasses=False, leavesfunc=None):
        """Return the nodes of a latex string.

        Arguments:
            n : depth of the node (affects indents).
            nodelabel: The name of the attribute to write on the nodes.
                Defaults to "size". No attribute written if its value is None.
            macroclasses: If True, the macroclasses will be bolded,
                and the arcs above them will be gray.
            leavesfunc (fun):
                A function that will be applied to leaves
                before writing them down. Takes a Node, returns a str.
        """
        if not nodelabel:
            def nodelabel(node):
                return node.attributes["size"]
        if not leavesfunc:
            def leavesfunc(n):
                return n.labels[0]
        if n > 0 and macroclasses:
            if self.attributes["macroclass"]:
                style = "\edge[color=black!20]; "
            else:
                style = "\edge[thick]; "
        else:
            # root
            style = ""

        fill_values = {"tabs": "    " * (n + 2), "style": style,
                       "comment": ", ".join("{}={}".format(key, self.attributes[key]) for key in self.attributes)}
        if self.children and len(self.children) > 0:
            template = "{tabs}{style}[.{{{label}}} %{comment}\n{children}{tabs}]\n"

            fill_values["label"] = nodelabel(self)

            children = (child._recursive_to_latex(n + 1, nodelabel=nodelabel,
                                                  leavesfunc=leavesfunc)
                        for child in self.children)

            fill_values["children"] = "".join(sorted(children, key=len))
        else:
            template = "{tabs}{style}[.{{{label}}} ]%{comment}\n"
            fill_values["label"] = leavesfunc(self)

        return template.format(**fill_values)

    def to_latex(self, nodelabel=None, vertical=True, level_dist=50,
                 square=True, leavesfunc=lambda n: n.labels[0], scale=1):
        """Return a latex string, compatible with tikz-qtree

        Arguments:
            nodelabel: The name of the attribute to write on the nodes.
            vertical: Should the tree be drawn vertically ?
            level_dist: Distance between levels.
            square: Should the arcs have a squared shape ?
            leavesfunc (fun):
                A function that will be applied to leaves
                before writing them down. Takes a Node, returns a str.
            scale (int): defaults to 1. tikzpicture scale argument.
        """
        tikzset = ["level distance={}pt, ".format(level_dist)]
        if vertical and square:
            tikzset += ["edge from parent/.style={draw,",
                        "\n\t\tedge from parent path={(\\tikzparentnode.south)",
                        "\n\t\t-- +(0,-8pt)",
                        "\n\t\t-| (\\tikzchildnode)}}"]
        if not vertical:
            tikzset += ["execute at begin node=\\strut, ",
                        "grow'=right, ",
                        "every tree node/.style={anchor=base west}, "]

            if square:
                tikzset += ["edge from parent/.style={draw,",
                            "\n\t\tedge from parent path={(\\tikzparentnode.east)",
                            "\n\t\t-- +(0.2,0) |- (\\tikzchildnode.west)}}"]

        strings = ["\\begin{tikzpicture}[scale=",
                   str(scale),
                   "]\n",
                   "\t\\tikzset{",
                   "".join(tikzset),
                   "}",
                   "\n\t\t\\Tree",
                   # trim first indent, it's before "\Tree" already
                   self._recursive_to_latex(0, nodelabel=nodelabel,
                                            leavesfunc=leavesfunc)[2:],
                   "\\end{tikzpicture}"]

        return "".join(strings)

    def draw(self, horizontal=False, square=False,
             leavesfunc=lambda n: n.labels[0],
             nodefunc=None,label_rotation=None,
             annotateOnlyMacroclasses=False, point=None,
             edge_attributes=None, interactive=False, lattice=False, pos=None, **kwargs):
        """Draw the tree as a dendrogram-style pyplot graph.

        Example::

                                      square=True        square=False

                                     │  ┌──┴──┐         │    ╱╲
            horizontal=False         │  │   ┌─┴─┐       │   ╱  ╲
                                     │  │   │   │       │  ╱   ╱╲
                                     │  │   │   │       │ ╱   ╱  ╲
                                     │__│___│___│       │╱___╱____╲

                                    │─────┐             │⟍
                                    │───┐ ├             │  ⟍
            horizontal=True         │   ├─┘             │⟍ ⟋
                                    │───┘               │⟋
                                    │____________       │____________

        Arguments:
            horizontal (bool):
                Should the tree be drawn with leaves on the y axis ?
                (Defaults to False: leaves on x axis).
            square (bool):
                Should the tree splines be squared with 90° angles ?
                (Defauls to False)
            leavesfunc (fun):
                A function that will be applied to leaves
                before writing them down. Takes a Node, returns a str.
            nodefunc (fun):
                A function that will be applied to nodes
                to annotate them. Takes a Node, returns a str.
            keep_above_macroclass (bool):
                For macroclass history trees: Should the edges above macroclasses be drawn ?
                (Defaults to True).
            annotateOnlyMacroclasses : For macroclass history trees:
                If `True` and nodelabel isn't `None`,
                only the macroclasses nodes are annotated.
            point (fun):
                A function that maps a node to point attributes.
            edge_attributes (fun):
                A function that maps a pair of nodes to edge attributes.
                    By default, use the parent's color and "-" linestyle for nodes,
                    "--" for leaves.
            interactive (bool):
                Whether this is destined to create an interactive plot.
            lattice (bool):
                Whether this node is a lattice rather than a tree.
            pos (dict):
                A dictionnary of node label to x,y positions.
                Compatible with networkx layout functions.
                If absent, use networkx's graphviz layout.
        """
        tree_placement = not lattice

        self.compute_xy(pos=pos, tree_placement=tree_placement)

        if not matplotlib_loaded:
            return str(self)
        else:
            def annotate(node):
                should_annotate = (not annotateOnlyMacroclasses) or \
                                  node.attributes["macroclass_root"]
                if should_annotate and nodefunc is not None:
                    return str(nodefunc(node))
                return ""

            def default_edge_attributes(node, child):
                attributes = {"linestyle": "-" if node.children else "--",
                              "color": node.attributes.get("color", "#333333")}
                if edge_attributes is not None:
                    attributes.update(edge_attributes(node, child))
                return attributes

            if horizontal:
                leafoffset = (-5, 0) #TODO: this is not used anymore
                textoffset = (5, 0)
                lva = "center"
                lha = "right"
                va = "center"
                ha = "left"
                r = 0

                def coords(node):
                    return node.attributes["_y"], node.attributes["_x"]
            else:
                lva = "top"
                lha = "right"
                va = "bottom"
                ha = "center"
                leafoffset = (0, -3) #TODO: This is not used anymore
                textoffset = (0, 5)
                r = 45

                def coords(node):
                    return node.attributes["_x"], node.attributes["_y"]
            if label_rotation is not None:
                r = label_rotation

            ax = plt.gca()
            # bg = ax.patch.get_facecolor()

            lines = []
            all_nodes = []

            for node in self:
                this_x, this_y = coords(node)

                # Plot the arcs
                for child in node.children:
                    child_x, child_y = coords(child)
                    attr = default_edge_attributes(node, child)
                    if square:
                        if horizontal:
                            l = ax.plot((this_x, this_x, child_x), (this_y, child_y, child_y), **attr)
                        else:
                            l = ax.plot((this_x, child_x, child_x), (this_y, this_y, child_y), **attr)
                    else:
                        l = ax.plot((this_x, child_x), (this_y, child_y), **attr)
                    lines.extend(l)

                # Plot the point
                if point is not None:
                    coll = ax.scatter((this_x,), (this_y,), **point(node))
                    lines.append(coll)

                # Write annotations
                if node.labels:
                    # tmp = node.labels
                    #node.labels = list(microclass)
                    f = nodefunc if node.children else leavesfunc
                    plt.annotate(f(node), xy=(this_x, this_y), xycoords='data', va=lva, ha=lha, rotation=r)
                    # node.labels = tmp
                else:
                    text = annotate(node)
                    if text is not None:
                        plt.annotate(text, xy=(this_x, this_y), va=va, ha=ha, textcoords='offset points',
                                     xytext=textoffset)

                all_nodes.append(node)

            # Scale axes
            ax.autoscale()

            if interactive:
                if horizontal:
                    ax.margins(x=0.3, y=0.1)
                else:
                    ax.margins(y=0.3, x=0.1)

            plt.tick_params(
                axis='both',  # changes apply to the x-axis
                which='both',  # both major and minor ticks
                top='off',  # ticks along the top edge
                bottom='off',  # ticks along the bottom edge
                right='off',  # ticks along the right edge
                left='off',  # ticks along the left edge
                labelbottom='off'
            )
            plt.yticks([], [])
            plt.xticks([], [])
        return lines, all_nodes

def string_to_node(string, legacy_annotation_name=None):
    """Parse an inflection tree written as a string.

    Example:
        In the label, fields are separated by "#" as such::

         (<labels>#<size>#<DL>#<color> (... ) (... ) )

    Returns:
        inflexClass.Node: The root of the tree
    """
    legacy = False
    if "=" not in string:
        legacy = True

    def parse_node(line):
        splitted = line[1:].split("#")
        labels = splitted[0]
        attributes = dict(attr.split("=") for attr in splitted[1:])
        return labels, attributes

    def parse_node_legacy(item):
        item = item[1:].split("#")
        return item

    stack = []
    # plus robuste que de splitter sur l'espace, autorise les espaces dans les lexèmes & attributs
    items = re.split(" (?=[()])", string)

    if legacy_annotation_name:
        annotation_name = legacy_annotation_name
    else:
        annotation_name = "DL"
    for item in items:

        if item[0] == "(":

            if legacy:
                # Backward compatibility mode
                labels, size, annotation, color = parse_node_legacy(item)
                if not color:
                    color = "c"
                if not annotation:
                    annotation = ""
                attributes = {"size": float(size),
                              annotation_name: annotation,
                              "color": color,
                              "macroclass": color == "r"}
            else:
                labels, attributes = parse_node(item)
                if 'color' not in attributes:
                    attributes['color'] = "c"
                attributes['macroclass'] = attributes['color'] != 'r'
            labels = sorted(labels.split("&"))
            attributes['macroclass_root'] = False
            if annotation_name in attributes:
                try:
                    attributes[annotation_name] = float(attributes[annotation_name])
                except ValueError:
                    pass  #  only convert numbers

            stack.append(Node(labels, **attributes))

        if item[0] == ")":
            if len(item) > 1:
                print("Warning, bad format ! #{}#".format(item))
            if len(stack) > 1:
                child = stack.pop(-1)
                parent = stack[-1]
                # Macroclass are one level below the red :
                child.attributes['macroclass_root'] = parent.attributes['color'] == 'r' and \
                                                      child.attributes['color'] != 'r'
                stack[-1].children.append(child)
            else:
                return stack[0]

    if len(stack) > 1:
        print("Warning, unmatched parenthesis or no root ! ", stack)

    print(stack[0])
    return stack[0]

def find_microclasses(paradigms):
    """Find microclasses in a paradigm (lines with identical rows).

    This is useful to identify an exemplar of each inflection microclass,
    and limit further computation to the collection of these exemplars.

    Arguments:
        paradigms (pandas.DataFrame):
            a dataframe containing inflectional paradigms.
            Columns are cells, and rows are lemmas.

    Return:
        microclasses (dict).
            classes is a dict. Its keys are exemplars,
            its values are lists of the name of rows identical to the exemplar.
            Each exemplar represents a macroclass.

            >>> classes
            {"a":["a","A","aa"], "b":["b","B","BBB"]}

    """
    grouped = paradigms.fillna(0).groupby(list(paradigms.columns))
    mc = {}

    for name, group in grouped:
        members = list(group.index)
        exemplar = min(members, key=lambda string: len(string))
        mc[exemplar] = members

    return mc

def find_min_attribute(tree, attr):
    """Find the minimum value for an attribute in a tree.

    Arguments:
        tree (Node): The tree in which to find the minimum attribute.
        attr (str): the attribute's key."""
    agenda = [tree]
    mini = np.inf
    while agenda:
        node = agenda.pop(0)
        if node.children:
            agenda.extend(node.children)
        if attr in node.attributes and float(node.attributes[attr]) < mini:
            mini = node.attributes[attr]

    return mini


#!/usr/bin/env python3

import sys

inputs = sys.stdin.readlines()

for i in range(len(inputs)):
    n = int(inputs[i].strip())

    numbers = [x for x in range(2, n + 1)]

    primes = [x for x in numbers if all(x % y != 0 for y in range(2, int(x ** 0.5) + 1))]
    print("Primes:", primes)


from src.TestCaseGenerator import *

input_variables = [Var("a", 16, "B"), Var("b", 16, "B"), Var("sel", 1, "B")]
output_variables = [Var("out", 16, "B")]

# args = [a, b, sel]
# It is guaranteed that the input is 16 bits at most
def mux16_logic(args):
    a = args[0]
    b = args[1]
    sel = args[2]
    out = []
    out.append(args[16])
    return out

generate(name="Mux16", numCases=10, inVars=input_variables, outVars=output_variables, function=mux16_logic)


import os
import iota.harness.api as api
from iota.harness.infra.glopts import GlobalOptions as GlobalOptions

source_file = api.GetTopDir() + '/iota/images/arm-iperf'

def Main(step):
    if GlobalOptions.skip_setup:
        return api.types.status.SUCCESS

    req = api.Trigger_CreateExecuteCommandsRequest(serial = True)
    api.ChangeDirectory("iperf")

    for naples_host in api.GetNaplesHostnames():
        api.CopyToNaples(naples_host, [source_file], "")
        api.Trigger_AddNaplesCommand(req, naples_host, "mv /arm-iperf /usr/bin/iperf")

    resp = api.Trigger(req)

    for cmd in resp.commands:
        api.PrintCommandResults(cmd)
        if cmd.exit_code != 0:
            result = api.types.status.FAILURE

    return api.types.status.SUCCESS


from collections import deque
n , m = map(int,input().split())
a = [list(map(int,list(input()))) for _ in range(n)]
group  = [[0]*m for _ in range(n)]

dx = [0,0,1,-1]
dy = [1,-1,0,0]
group[0][0] = 1

def bfs (x,y) :
    q = deque()
    q.append((x,y))

    while q :
        x , y = q.popleft()
        cnt = group[x][y]
        for k in range(4) :
            nx , ny = x+dx[k] , y+dy[k]
            if (0 <= nx < n) and (0 <= ny < m) :
                if (a[nx][ny] == 1 ) and (group[nx][ny] == 0 ):
                    q.append((nx,ny))
                    group[nx][ny] = cnt + 1

bfs(0,0)
print(group)


# Problem Description: https://practice.geeksforgeeks.org/problems/max-level-sum-in-binary-tree/1

class Node:
    def __init__(self, value):
        self.data = value
        self.left = None
        self.right = None

class Tree:
    def createNode(self, data):
        return Node(data)

    def insert(self, node, data, ch):
        if node is None:
            return self.createNode(data)
        if (ch == 'L'):
            node.left = self.insert(node.left, data, ch)
            return node.left
        else:
            node.right = self.insert(node.right, data, ch)
            return node.right

    def search(self, lis, data):
        # if root is None or root is the search data.
        for i in lis:
            if i.data == data:
                return i

def maxLevelSum(root):
    if(not root):
        return(0)

    result = root.data
    q = []
    q.append(root)
    while(q != []):

        total = 0
        for _ in range(len(q)):
            temp = q[0]
            del q[0]

            total += temp.data

            if(temp.left):
                q.append(temp.left)
            if(temp.right):
                q.append(temp.right)

        result = max(total, result)
    return(result)

if __name__ == '__main__':
    t = int(input())
    for i in range(t):
        n = int(input())
        arr = input().strip().split()
        if n == 0:
            print(1)
            continue
        tree = Tree()
        lis = []
        root = None
        root = tree.insert(root, int(arr[0]), 'L')
        lis.append(root)
        k = 0
        for j in range(n):
            ptr = None
            ptr = tree.search(lis, int(arr[k]))
            lis.append(tree.insert(ptr, int(arr[k+1]), arr[k+2]))
            k += 3
        print(maxLevelSum(root))


from odoo import api, models

class PurchaseRequisitionCreateAlternative(models.TransientModel):
    _inherit = 'purchase.requisition.create.alternative'

    @api.model
    def _get_alternative_line_value(self, order_line):
        res_line = super()._get_alternative_line_value(order_line)
        if order_line.sale_line_id:
            res_line['sale_line_id'] = order_line.sale_line_id.id

        return res_line


from ariadne import convert_kwargs_to_snake_case

from main import db
from models.postModel import Post

@convert_kwargs_to_snake_case
def resolve_create_post(obj, info, title, body):
    try:
        post = Post(
            title=title, body=body
        )
        db.session.add(post)
        db.session.commit()
        payload = {
            "success": True,
            "post": post.to_dict()
        }
    except ValueError:
        payload = {
            "success": False,
            "errors": ["Erreur !"]
        }

    return payload

@convert_kwargs_to_snake_case
def resolve_update_post(obj, info, post_id, title, body):
    try:
        post = Post.query.get(post_id)
        post.title = title
        post.body = body
        db.session.add(post)
        db.session.commit()
        payload = {
            "success": True,
            "post": post.to_dict()
        }
    except AttributeError:  # post not found
        payload = {
            "success": False,
            "errors":  [f"Post matching id {post_id} was not found"]
        }

    return payload

@convert_kwargs_to_snake_case
def resolve_delete_post(obj, info, post_id):
    try:
        post = Post.query.get(post_id)
        db.session.delete(post)
        db.session.commit()
        payload = {"success": True}

    except AttributeError:
        payload = {
            "success": False,
            "errors": [f"Post matching id {post_id} not found"]
        }

    return payload


import os,sys
parentdir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0,parentdir)

import xmind
from xmind.core.markerref import MarkerId
xmind_name="thread"
w = xmind.load(os.path.dirname(os.path.abspath(__file__))+"\\"+xmind_name+".xmind")
s2=w.createSheet()
s2.setTitle("ConcurrentLinkedQueue")
r2=s2.getRootTopic()
r2.setTitle("ConcurrentLinkedQueue")

content={
'介绍':[
    '使用CAS算法(入队和出队使用)实现的无界非阻塞队列',
    {'入队时':[
        '新元素被插入队列末尾'
    ]},
    {'出队时':[
        '从队列头部获取一个元素'
    ]},
],
'结构':[
    '单向链表:每个元素包装成一个Node节点',
    '两个volatile类型的Node节点:存放队列的首、尾节点',
    {'Node':[
        'item(volatile):存放节点的值(头、尾节点都是指向item为null的哨兵节点)',
        'next:存放链表的下一个节点'
    ]}
],
'方法':[
    {'offer':[
        '在队列末尾添加一个元素,使用CAS无阻塞算法'
    ]},
    {'add':[
        '在链表末尾添加一个元素，内部调用offer操作'
    ]},
    {'poll':[
        '在队列头部获取并移除一个元素，如队列为空则返回null'
    ]},
    {'peek':[
        '获取队列头部一个元素（只获取不移除），如队列为空则返回null',
        '第一次执行peek或者first操作把head指向第一个真正的队列元素'
    ]},
    {'size':[
        '计算当前队列元素个数，在并发环境下不是很有用，因为CAS没有加锁'
    ]},
    {'remove':[
        '如队列里存在该元素则删除,存在多个删除第一个并返回true，否则返回false'
    ]}
],
'应用':[
    {'Tomcat中NioEndPoint的实现':[
        {'Acceptor':[
            '套接字接受线程(Socket acceptor thread)',
            '接受用户请求并把请求封装为事件任务放入Poller队列',
            '一个Connector里面只有一个Acceptor'
        ]},
        {'Poller':[
            '套接字处理线程(Socket poller thread)，Poller内部有一个队列',
            'Poller线程从自己的队列里获取具体的事件任务，将其交给Worker进行处理',
            'Poller线程的个数与处理器的核数有关'
        ]},
        {'Worker':[
            '实际处理请求的线程',
            'Worker是组件名字',
            '真正任务执行者是SocketProcessor'
        ]},
        '使用ConcurrentLinkedQueue队列把接受请求与处理请求操作进行解耦，实现异步处理'
    ]},
    {'多生产者-单消费者模型':[
        {'生产者——Acceptor线程':[
            {'接受客户端发来的连接请求并将其放入Poller的事件队列':[
                '1.无限循环等待客户端连接',
                '2.控制客户端请求连接数量，如果连接数量达到设置阈值，当前请求会被挂起',
                '3.从TCP缓存获取一个完成三次握手的套接字，如当前没有，线程会被阻塞挂起',
                '4.获取到一个连接套接字后,封装为事件任务，放入poller队列'
            ]},
        ]},
        {'消费者——Poller线程':[
            {'从事件队列里面获取事件并进行处理':[
                '1.从事件队列获取事件',
                '2.遍历感兴趣的channel并对感兴趣的事件进行处理'
            ]},
        ]},
        {'注意':[
            'ConcurrentLinkedQueue是无界队列,需合理队列大小免造成OOM'
        ]}
    ]}
]

}

#构建xmind
xmind.build(content,r2)
#保存xmind
xmind.save(w,os.path.dirname(os.path.abspath(__file__))+"\\"+xmind_name+".xmind")


import numpy as np
from scipy.sparse import csr_matrix
from scipy.sparse.linalg import bicg, gmres, spsolve, bicgstab

import matplotlib.pyplot as plt
from matplotlib import ticker, cm

class SDE:
    """ First order solver """
    def __init__(self, right_side, dirichlet, newman):
        """
            Initialize functions for the right side
            and boundary conditions.
        """

        self.f = right_side
        self.g_d = dirichlet
        self.g_n = newman

    def _newman_cond(
            self, i, j,
            where_put, num_i, mode):

        """
            Used to fill in Newton boundary conditions.
        """

        x_i = i * self.h
        y_j = j * self.h

        if (i == self.n - 1) and (j == self.n - 1):

            if mode == 1:
                self.fg[self.n*j + i] = self.g_n(x_i, y_j) / self.h

                self.a[where_put] = -self.C
                self.a[where_put + 1] = -self.A
                self.a[where_put + 2] = self.A + self.C

                self.ja[where_put] = num_i - self.n
                self.ja[where_put + 1] = num_i - 1
                self.ja[where_put + 2] = num_i

                self.ia[num_i + 1] = self.ia[num_i] + 3
                where_put += 3

            if mode == 2:
                self.fg[self.n*j + i] = self.A * self.h * np.pi

                self.a[where_put] = self.C
                self.a[where_put + 1] = self.A
                self.a[where_put + 2] = self.B / 2

                self.ja[where_put] = num_i - self.n
                self.ja[where_put + 1] = num_i - 1
                self.ja[where_put + 2] = num_i

                self.ia[num_i + 1] = self.ia[num_i] + 3
                where_put += 3

        else:
            if i == self.n - 1:
                self.fg[self.n*j + i] = self.g_n(x_i, y_j) / self.h
                self.a[where_put] = self.A
                self.a[where_put + 1] = -self.A

                self.ja[where_put] = num_i
                self.ja[where_put + 1] = num_i - 1

                self.ia[num_i + 1] = self.ia[num_i] + 2
                where_put += 2

            else:
                self.fg[self.n*j + i] = self.g_n(x_i, y_j) / self.h
                self.a[where_put] = self.C
                self.a[where_put + 1] = -self.C

                self.ja[where_put] = num_i
                self.ja[where_put + 1] = num_i - self.n

                self.ia[num_i + 1] = self.ia[num_i] + 2
                where_put += 2
        return where_put

    def _nnz(self):
        """
            Count the number of nonzero enrties in a matrix
        """

        return 5 * self.n**2 - 14*self.n + 14

    def construct_system(self, eps=1, n=32, mode=1):
        """
            Create sparse matrix for discretization, right side
            and true solution
            Input parameters:
                - "eps" - 1 or 10 or 100
                - "n" - size of 1d mesh
                - "mode" - 1 or 2 order in n*n point
        """

        self.n = n
        self.eps = eps
        d_x = 1 # coef for C second derivative by x
        d_y = eps # coef for C second derivative by y
        self.h = 1 / (n - 1) # step through mesh
        self.A = -d_x / self.h**2
        self.C = -d_y / self.h**2
        self.B = 2 * (d_x + d_y) / self.h**2
        nn = n**2
        nnz = self._nnz()

        self.fg = np.empty(nn) # right side
        self.x_true = np.empty(nn) # actual solution
        self.a = np.empty(nnz) # values for sparse matrix
        self.ja = np.empty(nnz) # column indices for sparse matrix
        self.ia = np.empty(nn + 1) # row indices for sparse matrix
        self.ia[0] = 0

        where_put = 0 # to iterate over arrays with values of matrix
        num_i = 0 # to moderate row/equation of a matrix
        for j in range(n):
            y_j = j * self.h
            for i in range(n):
                x_i = i * self.h
                if (i == 0) or (j == 0):
                    # Dirichlet conditions:
                    self.fg[n*j + i] = self.g_d(x_i, y_j) # fill the right side

                    self.a[where_put] = 1.0
                    self.ja[where_put] = num_i
                    self.ia[num_i + 1] = self.ia[num_i] + 1
                    where_put += 1

                elif (i == n - 1) or (j == n - 1):
                    # Newman conditions:
                    where_put = self._newman_cond(
                        i,
                        j,
                        where_put,
                        num_i,
                        mode=mode
                    )
                else:
                    # Equations from discretization:
                    self.fg[n*j + i] = self.f(x_i, y_j, eps) # fill the right side

                    self.a[where_put] = self.C
                    self.a[where_put + 1] = self.A
                    self.a[where_put + 2] = self.B
                    self.a[where_put + 3] = self.A
                    self.a[where_put + 4] = self.C

                    self.ja[where_put] = num_i - n
                    self.ja[where_put + 1] = num_i - 1
                    self.ja[where_put + 2] = num_i
                    self.ja[where_put + 3] = num_i + 1
                    self.ja[where_put + 4] = num_i + n

                    self.ia[num_i + 1] = self.ia[num_i] + 5
                    where_put += 5
                num_i += 1
                self.x_true[n*j + i] = np.cos(np.pi * y_j) * np.sin(np.pi * x_i)

    def solve(self, tol=1e-08, maxiter=20000):
        """
            Solve discretized system with BiCG.
            Input parameters:
                - "tol" - tolerence for the error
                - "maxiter" - needed to tune iterations properly
        """

        nn = self.n**2
        mtx = csr_matrix((self.a, self.ja, self.ia), shape=(nn, nn))
        self.x_appr, info = bicg(mtx, self.fg, x0=np.zeros(nn), tol=tol, maxiter=maxiter)
        if info > 0:
            print("Iterations number: ", info)
            self.iter = info
        return info

    def plot_err(self):
        """
            Plot error between our and actual solution
        """

        #  Define the number of regions for smoothness:
        lev_region = 10

        z = np.abs(self.x_appr - self.x_true).reshape(self.n, self.n)
        fig, ax = plt.subplots()
        cs = ax.contourf(
            z,
            levels = lev_region,
        )
        cbar = fig.colorbar(cs)
        plt.show()

    def c_h_norm(self):
        """ Max norm error of true and approximate solution """
        return np.max(np.abs(self.x_appr - self.x_true))

    def l_2h_norm(self):
        """ Max norm error of true and approximate solution """
        sq_err = (self.x_appr - self.x_true)**2
        integ = Integrate(self.n, sq_err)
        x = np.array([i * self.h for i in range(self.n)] * (self.n))
        y = np.sort([x * self.h for x in list(range(self.n)) * (self.n)])
        xyc = np.vstack((x, y, sq_err)).T
        integ.int_all(xyc)
        return np.sqrt(integ.int_value)

class SDE2(SDE):
    """ Second order solver """
    def _newman_cond(
            self, i, j,
            where_put, num_i, mode):

        """
            Used to fill in Newton boundary conditions.
        """

        x_i = i * self.h
        y_j = j * self.h

        if (i == self.n - 1) and (j == self.n - 1):
            if mode == 1:
                self.fg[self.n*j + i] = self.g_n(x_i, y_j) / self.h

                self.a[where_put] = -self.C
                self.a[where_put + 1] = -self.A
                self.a[where_put + 2] = self.A + self.C

                self.ja[where_put] = num_i - self.n
                self.ja[where_put + 1] = num_i - 1
                self.ja[where_put + 2] = num_i

                self.ia[num_i + 1] = self.ia[num_i] + 3
                where_put += 3

            if mode == 2:
                self.fg[self.n*j + i] = (
                    self.A * self.h * np.pi
                    + self.f(x_i, y_j, self.eps) * 0.5
                )

                self.a[where_put] = self.C
                self.a[where_put + 1] = self.A
                self.a[where_put + 2] = self.B / 2

                self.ja[where_put] = num_i - self.n
                self.ja[where_put + 1] = num_i - 1
                self.ja[where_put + 2] = num_i

                self.ia[num_i + 1] = self.ia[num_i] + 3
                where_put += 3

        else:
            if i == self.n - 1:
                self.fg[self.n*j + i] = (
                    self.g_n(x_i, y_j) / self.h
                    - self.f(x_i, y_j, self.eps) / 2
                )

                self.a[where_put] = self.A + self.C
                self.a[where_put + 1] = -self.A
                self.a[where_put + 2] = -self.C / 2
                self.a[where_put + 3] = -self.C / 2

                self.ja[where_put] = num_i
                self.ja[where_put + 1] = num_i - 1
                self.ja[where_put + 2] = num_i - self.n
                self.ja[where_put + 3] = num_i + self.n

                self.ia[num_i + 1] = self.ia[num_i] + 4
                where_put += 4

            else:
                self.fg[self.n*j + i] = (
                    self.g_n(x_i, y_j) / self.h
                    - self.f(x_i, y_j, self.eps) / 2
                )

                self.a[where_put] = self.A + self.C
                self.a[where_put + 1] = -self.C
                self.a[where_put + 2] = -self.A / 2
                self.a[where_put + 3] = -self.A / 2

                self.ja[where_put] = num_i
                self.ja[where_put + 1] = num_i - self.n
                self.ja[where_put + 2] = num_i - 1
                self.ja[where_put + 3] = num_i + 1

                self.ia[num_i + 1] = self.ia[num_i] + 4
                where_put += 4

        return where_put

    def _nnz(self):
        return 5 * self.n**2 - 10*self.n + 6

class Act:
    """ Better interface solver class """
    def __init__(self, f, g_d, g_n):
        """
            Initialize functions for the right side
            and boundary conditions.
        """
        self.f = f
        self.g_d = g_d
        self.g_n = g_n

    def act(self,
            solver, eps=1,
            n=128, mode=1,
            tol=1e-08, maxiter=100000):

        """
            Use chosen solver class for SD problem.
            Input parameters:
                - "solver" - SDE/SDE2
                - "eps" - used for d_y setting
                - "n"- number of 1d points
                - "mode" - Newman conditions
                        edge point 1/2 order approximation
                - "tol" - used for solving SLE
                - "maxiter" - bound on iterations made(need for the task)
        """

        self.sde = solver(self.f, self.g_d, self.g_n)
        self.sde.construct_system(eps=eps, n=n, mode=mode)
        self.sde.solve(tol=tol, maxiter=maxiter)

    def act_norms(self,
            solver, eps=1,
            n=128, mode=1,
            tol=1e-08, maxiter=100000):

        """
            Use chosen solver class for SD problem.
            Input parameters:
                - "solver" - SDE/SDE2
                - "eps" - used for d_y setting
                - "n"- number of 1d points
                - "mode" - Newman conditions
                        edge point 1/2 order approximation
                - "tol" - used for solving SLE
                - "maxiter" - bound on iterations made(need for the task)
        """

        self.sde = solver(self.f, self.g_d, self.g_n)
        self.sde.construct_system(eps=eps, n=n, mode=mode)
        self.sde.solve(tol=tol, maxiter=maxiter)
        print(f"Ch norm = {self.sde.c_h_norm()};\n"
                + f"L2h norm = {self.sde.l_2h_norm()}")

    def act_plot(self,
            solver, eps=1,
            n=128, mode=1,
            tol=1e-08, maxiter=100000):

        """
            Use chosen solver class for SD problem.
            Input parameters:
                - "solver" - SDE/SDE2
                - "eps" - used for d_y setting
                - "n"- number of 1d points
                - "mode" - Newman conditions
                        edge point 1/2 order approximation
                - "tol" - used for solving SLE
                - "maxiter" - bound on iterations made(need for the task)
        """

        self.sde = solver(self.f, self.g_d, self.g_n)
        self.sde.construct_system(eps=eps, n=n, mode=mode)
        self.sde.solve(tol=tol, maxiter=maxiter)
        self.sde.plot_err()

class Integrate:
    """ Integration through triangles with bilinear functions """
    def __init__(self, n, vals):
        """
            Capture baricenter coordinates and weights
        """

        self.n = n
        self.vals = vals
        self.h = 1 / (n - 1)

        # MAGIC NUMBERS!!!:

        w1 = 0.205950504760887
        w2 = 0.063691414286223

        a11 = 0.124949503233232
        a12 = 0.437525248383384
        a13 = a12

        a21 = 0.797112651860071
        a22 = 0.165409927389841
        a23 = 0.037477420750088

        self.w = np.array(3*[w1] + 6*[w2])
        self.a = np.array(
            [
                [a11, a12, a13],
                [a12, a11, a13],
                [a12, a13, a11],

                [a21, a22, a23],
                [a21, a23, a22],
                [a22, a21, a23],
                [a22, a23, a21],
                [a23, a22, a21],
                [a23, a21, a22],
            ]
        )

    def _phi(self, points_sq):
        """
            Used to produce bilinear approximation
            on a square.
        """

        bones = []
        for i in points_sq:
            bones.append([i[0]*i[1], i[0], i[1], 1])
        A = np.array(bones)
        coefs = np.linalg.solve(A, points_sq[:, 2])
        def hi(x, y):
            return np.array([x*y, x, y, 1]).dot(coefs)
        return hi

    def _n_xy(self, points_tri):
        """ Give x, y coordinates by baricenters """
        #xy = np.array([[i[0] for i in points_tri], [i[1] for i in points_tri]])
        return points_tri[:, [0, 1]].T @ self.a.T

    def _int_tri(self, points_tri, elem):
        """ Integrate over triangle """
        xy = self._n_xy(points_tri)
        add_them = 0.0
        for i in range(9):
            add_them = self.w[i] * elem(xy[0, i], xy[1, i])

        return add_them * 0.5 * self.h**2

    def _int_sq(self, points_sq):
        """ Integrate over square """
        elem = self._phi(points_sq)
        summation = 0.0
        summation += self._int_tri(points_sq[[0,1,2]], elem)
        summation += self._int_tri(points_sq[[1,2,3]], elem)
        return summation

    def int_all(self, xyc):
        """
            Integrate mesh.
            Input parameters:
                - "xyc" - numpy.ndarray [x, y, z],
                    where x, y, z define columns of
                    x, y coordinates and z values in (x, y) points
                    Like: [
                            [0, 0, 1.25],
                            [1, 0, 2.34],
                            [0, 1, 4.3],
                            [1, 1, 5.12]
                          ] - [0, 1]*[0, 1] square.
        """

        self.int_value = 0.0
        for j in range(self.n):
            for i in range(self.n):
                if (i <= self.n - 2) and (j <= self.n - 2):
                    self.int_value += self._int_sq(
                        xyc[[i + j*self.n,
                             i + 1 + j*self.n,
                             i + self.n + j*self.n,
                             i + self.n + 1 + j*self.n]]
                    )

def plot(f, g_d, g_n, eps=1, solver=SDE, mode=1, n=[32, 64, 128], to="Report/pictures/new.png"):
    #  Define the number of regions for smoothness:
    fig, axs = plt.subplots(2, 2, figsize=(14, 8))
    fig.suptitle(f'Let d_y = eps = {eps}', fontsize=16)
    actor = Act(f, g_d, g_n)

    # First graph
    actor.act(
        solver=solver, eps=eps,
        n=n[0], mode=mode,
        tol=1e-08,
    )
    z = np.abs(actor.sde.x_appr - actor.sde.x_true).reshape(actor.sde.n, actor.sde.n)
    cs = axs[0, 0].contourf(
            z,
            levels = 20,
    )
    fig.colorbar(cs, ax=axs[0,0])
    axs[0, 0].set_title(f'Error plot(n={n[0]})')

    # Second graph
    actor.act(
        solver=solver, eps=eps,
        n=n[1], mode=mode,
        tol=1e-08,
    )
    z = np.abs(actor.sde.x_appr - actor.sde.x_true).reshape(actor.sde.n, actor.sde.n)
    cs = axs[0, 1].contourf(
            z,
            levels = 20,
    )
    fig.colorbar(cs, ax=axs[0,1])
    axs[0, 1].set_title(f'Error plot(n={n[1]})')

    # Third graph
    actor.act(
        solver=solver, eps=eps,
        n=n[2], mode=mode,
        tol=1e-08,
    )
    z = np.abs(actor.sde.x_appr - actor.sde.x_true).reshape(actor.sde.n, actor.sde.n)
    cs = axs[1, 0].contourf(
            z,
            levels = 20,
    )
    fig.colorbar(cs, ax=axs[1,0])
    axs[1, 0].set_title(f'Error plot(n={n[2]})')

    #Forth graph
    solution = actor.sde.x_appr.reshape(actor.sde.n, actor.sde.n)
    cs = axs[1, 1].contourf(
            solution,
            levels = 100,
    )
    fig.colorbar(cs, ax=axs[1,1])
    axs[1, 1].set_title('Approximate solution (n=128)')

    fig.savefig(to)


'''
Thoughts:

Initialise prevMax and prevMin using nums[0]
Let res = nums[0]
Since if nums has only one element, we shall return the first element

Iterate nums from the second element, if there is any
currMax might arise from the product of prevMax and n, prevMin and n or n itself, which also applies on currMin
Update res before assigning currMax and currMin to prevMax and prevMin for the next iteration

'''

class Solution:
	def maxProduct(self, nums):
		# currMax, currMin = nums[0], nums[0]
		prevMax, prevMin = nums[0], nums[0]
		res = nums[0]

		for n in nums[1:]:
			currMax = max(prevMax * n, prevMin * n, n)
			currMin = min(prevMax * n, prevMin * n, n)

			res = max(res, currMax)

			prevMax, prevMin = currMax, currMin

		return res

nums = [2, 3, -2, -3, 4]

inst = Solution()
print(inst.maxProduct(nums))


from odoo import models, api

class ResPartner(models.Model):
    _inherit = "res.users"

    # os_enable_email_receivable field is declared in res.parter, but included here in the special fields, so can be modified by all internal users,
    # without being Administrator. This works like this because res.users has _inherits = {'res.partner': 'partner_id'} and odoo manage this cases in a spacial way
    @api.model
    def _register_hook(self):
        super()._register_hook()
        self.SELF_WRITEABLE_FIELDS.extend([
            'os_enable_email_receivable'
        ])
        self.SELF_READABLE_FIELDS.extend([
            'os_enable_email_receivable'
        ])