# Time Complexity : O(log(m*n))
# function definition
def searchIn2DArray(arr, target):
    # number of rows
    m = len(arr)
    if m == 0:
        return False
    # number of column
    n = len(arr[0])
    left, right = 0, m*n-1
    # binary search logic
    while left <= right :
        mid = left + (right - left) // 2
        # row_number --> mid // n
        # column_number --> mid % n
        mid_element = arr[mid//n][mid%n]
        if target == mid_element:
            return True
        elif target < mid_element:
            right = mid - 1
        else:
            left = mid + 1
    return False

# Driver code
arr = [[1, 3, 5, 7], [10, 11, 16, 20], [23, 30, 34, 60]]
target = 30
result = searchIn2DArray(arr, target)
print(result)


from typing import Dict, Any, Optional, List, Union
from urllib import parse

from simnet.client.base import BaseClient
from simnet.client.routes import YSULOG_URL
from simnet.models.genshin.transaction import BaseTransaction, TransactionKind, ItemTransaction, Transaction
from simnet.utils.lang import create_short_lang_code

class TransactionClient(BaseClient):
    """Transaction component."""

    async def request_transaction(
        self,
        endpoint: str,
        authkey: str,
        *,
        method: str = "GET",
        lang: Optional[str] = None,
        params: Optional[Dict[str, Any]] = None,
    ) -> Dict[str, Any]:
        """Make a request towards the transaction log endpoint.

        Args:
            endpoint (str): The endpoint to make the request to.
            authkey (str): The authkey to use for the request.
            method (str, optional): The HTTP method to use. Defaults to "GET".
            lang (str, optional): The language to use for the request. Defaults to None.
            params (Dict[str, Any], optional): The parameters to use for the request. Defaults to None.
        """
        params = dict(params or {})

        base_url = YSULOG_URL.get_url(self.region)
        url = base_url / endpoint

        params["authkey_ver"] = 1
        params["sign_type"] = 2
        params["authkey"] = parse.unquote(authkey)
        params["lang"] = create_short_lang_code(lang or self.lang)

        return await self.request_lab(url, method=method, params=params)

    async def _get_transaction_page(
        self,
        end_id: int,
        kind: str,
        authkey: str,
        *,
        lang: Optional[str] = None,
    ) -> List[BaseTransaction]:
        """Get a single page of transactions.

        Args:
            end_id (int): The ID of the last transaction to get.
            kind (str): The kind of transaction to get.
            authkey (str): The authkey to use for the request.
            lang (str, optional): The language to use for the request. Defaults to None.
        """
        kind = TransactionKind(kind)
        endpoint = "Get" + kind.value.capitalize() + "Log"

        data = await self.request_transaction(
            endpoint,
            lang=lang,
            authkey=authkey,
            params=dict(end_id=end_id, size=20),
        )

        transactions: List[BaseTransaction] = []
        for trans in data["list"]:
            model = ItemTransaction if "name" in trans else Transaction
            transactions.append(model(**trans, kind=kind, lang=lang or self.lang))

        return transactions

    async def transaction_log(
        self,
        authkey: str,
        kind: Optional[Union[str, List[str]]] = None,
        *,
        limit: Optional[int] = None,
        lang: Optional[str] = None,
        end_id: int = 0,
    ) -> List[BaseTransaction]:
        """Get the transaction log of a user.

        Arg:
            authkey (str): The authkey to use for the request.
            kind (Union[str, List[str]], optional): The kind of transaction to get. Defaults to None.
            limit (int, optional): The maximum number of transactions to get. Defaults to None.
            lang (str, optional): The language to use for the request. Defaults to None.
            end_id (int, optional): The ID of the last transaction to get. Defaults to 0.
        """
        kinds = kind or ["primogem", "crystal", "resin", "artifact", "weapon"]

        if isinstance(kinds, str):
            kinds = [kinds]

        iterators: List[BaseTransaction] = []
        for value in kinds:
            iterator = await self._get_transaction_page(end_id, value, lang=lang, authkey=authkey)
            iterators.extend(iterator)

        return iterators[: min(len(iterators), limit)] if limit else iterators


from random import randint

class BoardExcept(Exception):
    pass

class BoardOutExcept(BoardExcept):
    def __str__(self):
        print()
        return "Упс, Вы не попали в игровое поле :(\nКоординаты должны быть меньше 7-ми.\nПожалуйста, переходите."

class BoardUsedExcept(BoardExcept):
    def __str__(self):
        return "Вы сюда уже стреляли.\nПереходите еще раз."

class BoardWrongShipExcept(BoardExcept):
    pass

class Dot:
    def __init__(self, coordx, coordy):
        self.coordx = coordx
        self.coordy = coordy

    def __eq__(self, other):     # метод, сравнивающий содерживое клеток между собой
        return self.coordx == other.coordx and self.coordy == other.coordy

    def __repr__(self):           # метод, выдающий список клеток в консоль
        return f"Dot({self.coordx}, {self.coordy})"

class Ship:
    def __init__(self, len, nose, orient, alive):
        self.len= len           # длина корабля в клетках
        self.nose = nose        # положение "носа" корабля
        self.orient = orient    # ориентация корабля (горизонтальная при "0", вертикальная при "1"
        self.alive = alive      # количество еще живых клеток корабля

    @property
    def dots(self):
        ship_dots = []
        for i in range(self.len):
            cur_x = self.nose.coordx  # координата "x" клетки
            cur_y = self.nose.coordy  # координата "y" клетки

            if self.orient == 1:
                cur_x += i

            elif self.orient == 0:
                cur_y += i

            ship_dots.append(Dot(cur_x, cur_y))

        return ship_dots

    def shooten(self, shot):
        return shot in self.dots

class Board:
    def __init__(self, hid = False, size = 6):
        self.hid = hid
        self.size = size
        self.count = 0

        self.field = [[" "] * size for _ in range(size)]

        self.busy = []
        self.ships = []

    def __str__(self):
        res = ""
        res += "  | 1 | 2 | 3 | 4 | 5 | 6 |"
        print('___________________________')
        for i, row in enumerate(self.field):
            res += f"\n---------------------------\n{i + 1} | " +  " | ".join(row) + " | "

        if self.hid:
            res = res.replace("П", " ")
        return res

    def out(self, d):
        return  not((0 <= d.coordx < self.size) and (0 <= d.coordy < self.size))

    def contour(self, ship, verb = False):
        near = [(-1, -1), (-1, 0), (-1, 1), (0, -1), (0, 0), (0, 1), (1, -1), (1, 0), (1, 1)]

        for d in ship.dots:
            for dx, dy in near:
                cur = Dot(d.coordx + dx, d.coordy + dy)
                #self.field[cur.coordx][cur.coordy] = "!"
                if not(self.out(cur)) and cur not in self.busy:
                    if verb:
                        self.field[cur.coordx][cur.coordy] = "-"
                    self.busy.append(cur)

    def add_ship(self, ship):
        for d in ship.dots:
            if self.out(d) or d in self.busy:
                raise BoardWrongShipExcept()
        for d in ship.dots:
            self.field[d.coordx][d.coordy] = "П"
            self.busy.append(d)

        self.ships.append(ship)
        self.contour(ship)

    def shot(self, d):
        if self.out(d):
             raise BoardOutExcept()

        if d in self.busy:
             raise BoardUsedExcept()

        self.busy.append(d)

        for ship in self.ships:
            if ship.shooten(d):
                ship.alive -= 1
                self.field[d.coordx][d.coordy] = "!"
                if ship.alive == 0:
                    self.count += 1
                    self.contour(ship, verb = True)
                    print("Ого! Корабль уничтожен!")
                    return  False
                else:
                    print("Ой, корабль ранен!")
                    return True

        self.field[d.coordx][d.coordy] = "-"
        print("Мимо")
        return False

    def begin(self):
        self.busy = []

class Game:
    def __init__(self, size = 6):
        self.size = size
        pl = self.random_board()
        co = self.random_board()
        co.hid = True

        self.ai = AI(co, pl)
        self.us = User(pl, co)

    def try_board(self):
        lens = [3, 2, 2, 1, 1, 1, 1]
        board = Board(size = self.size)
        attempts = 0
        for l in lens:
            while True:
                attempts += 1
                if attempts > 2000:
                    return None
                ship = Ship(l, Dot(randint(0, self.size), randint(0, self.size)), randint(0, 1), l)
                try:
                    board.add_ship(ship)
                    break
                except BoardWrongShipExcept:
                    pass
        board.begin()
        return board

    def random_board(self):
        board = None
        while board is None:
            board = self.try_board()
        return  board

    def loop(self):
        num = 0
        while True:
            print()
            print("   - Поле ПОЛЬЗОВАТЕЛЯ -")
            print(self.us.board)
            print("_" * 27)
            print()
            print("      - Поле КОМПА -")
            print(self.ai.board)
            print("_" * 27)
            if num % 2 == 0:
                #print("Ходит чел")
                repeat = self.us.move()
            else:
                print("Ходит комп")
                repeat = self.ai.move()
            if repeat:
                num -= 1

            if self.ai.board.count == 7:
                print()
                print("_" * 36)
                print("Пользователь выиграл! ПОЗДРАВЛЯЕМ!!!")
                break

            if self.us.board.count == 7:
                print()
                print("_" * 40)
                print("КОМП выиграл! А тебе надо потренироваться:(")
                break
            num += 1

class Player:
    def __init__(self, board, enemy):
        self.board = board
        self.enemy = enemy

    def ask(self):
        raise NotImplementedError()

    def move(self):
        while True:
            try:
                target = self.ask()
                repeat = self.enemy.shot(target)
                return repeat
            except BoardExcept as e:
                print(e)

class User(Player):
    def ask(self):
        while True:
            print()
            cords = input("   Ходит ПОЛЬЗОВАТЕЛЬ\nВведите координаты X и Y\nчерез пробел и нажмите Enter:  ").split()

            if len(cords) != 2:
                print("Введите 2 координаты через пробел")
                continue

            x, y = cords

            if not(x.isdigit()) or not (y.isdigit()):
                print()
                print("Пожалуйста,Вводите только числа от 1 до 6!\nПопробуйте еще раз")
                continue

            x, y = int(x), int(y)
            return Dot(x - 1, y - 1)

class AI(Player):
    def ask(self):
        d = Dot(randint(0,5), randint(0,5))
        print(f"Минуточку, ход ПК: {d.coordx+1} {d.coordy+1}")
        return d

print("_____________________________________")
print("Добро пожаловать в игру 'МОРСКОЙ БОЙ'\n\n     Формат ввода: x  y, где\n х - координата Х, а y - координата Y")
print("_____________________________________")

g = Game()
g.loop()

Морской бой.py

Морской бой.py


class Solution:
    def minimumMountainRemovals(self, nums: List[int]) -> int:
        #num( lis ending at this index )   + lds(starting at this index)

        @cache
        def lis(idx):
            if idx == 0:
                return 1
            res = 1
            for i in range(idx-1,-1,-1):
                if nums[i] < nums[idx] :
                    res = max(res, lis(i) + 1)
            return res

        @cache
        def lds(idx):
            if idx == len(nums) - 1:
                return 1
            res = 1
            for i in range(idx+1,len(nums)):
                if nums[idx] > nums[i]:
                    res = max(res, lds(i) + 1)
            return res
        res  = float('inf')
        for i in range(1,len(nums) - 1):
            if lis(i) == 1 or lds(i) ==1:
                continue
            res = min(res, len(nums) - lis(i) - lds(i) +  1 )
            # print(res)
        return res


from django.contrib import admin
from django.urls import path,include
from . import views
urlpatterns = [
    path('', views.display,name="display"),
    path('dis',views.d1,name="inner_page"),
    path('bookt',views.booktic,name="booktic"),
    path('cancelt',views.cantic,name="cantic"),
    path('ticdet',views.ticket_details,name="ticdetails"),
     path('tcavail',views.avreq,name="tic_Avail")
]


"""Basic network-building tools"""

from __future__ import print_function
from __future__ import division

import numpy as np
import tensorflow as tf
from .regularization import Regularization

class Layer(object):
    """Implementation of fully connected neural network layer

    Attributes:
        scope (str): name scope for variables and operations in layer
        input_dims (list): inputs to layer
        output_dims (list): outputs of layer
        outputs (tf Tensor): output of layer
        num_inh (int): number of inhibitory units in layer
        weights_ph (tf placeholder): placeholder for weights in layer
        biases_ph (tf placeholder): placeholder for biases in layer
        weights_var (tf Tensor): weights in layer
        biases_var (tf Tensor): biases in layer
        weights (numpy array): shadow variable of `weights_var` that allows for
            easier manipulation outside of tf sessions
        biases (numpy array): shadow variable of `biases_var` that allows for
            easier manipulation outside of tf sessions
        activation_func (tf activation function): activation function in layer
        reg (Regularization object): holds regularizations values and matrices
            (as tf constants) for layer
        ei_mask_var (tf constant): mask of +/-1s to multiply output of layer
        ei_mask (list): mask of +/-1s to multiply output of layer; shadows
            `ei_mask_tf` for easier manipulation outside of tf sessions
        pos_constraint (bool): positivity constraint on weights in layer
        log (bool): use tf summary writers on layer output

    """

    def __init__(
            self,
            scope=None,
            input_dims=None,  # this can be a list up to 3-dimensions
            filter_dims=None,
            output_dims=None,
            activation_func='relu',
            weights_initializer='trunc_normal',
            biases_initializer='zeros',
            reg_initializer=None,
            num_inh=0,
            pos_constraint=False,
            log_activations=False):
        """Constructor for Layer class

        Args:
            scope (str): name scope for variables and operations in layer
            input_dims (int or list): dimensions of input data
            output_dims (int or list): dimensions of output data
            activation_func (str, optional): pointwise function applied to
                output of affine transformation
                ['relu'] | 'sigmoid' | 'tanh' | 'identity' | 'softplus' |
                'elu' | 'quad'
            weights_initializer (str, optional): initializer for the weights
                ['trunc_normal'] | 'normal' | 'zeros'
            biases_initializer (str, optional): initializer for the biases
                'trunc_normal' | 'normal' | ['zeros']
            reg_initializer (dict, optional): see Regularizer docs for info
            num_inh (int, optional): number of inhibitory units in layer
            pos_constraint (bool, optional): True to constrain layer weights to
                be positive
            log_activations (bool, optional): True to use tf.summary on layer
                activations

        Raises:
            TypeError: If `variable_scope` is not specified
            TypeError: If `inputs` is not specified
            TypeError: If `num_inputs` or `num_outputs` is not specified
            ValueError: If `num_inh` is greater than total number of units
            ValueError: If `activation_func` is not a valid string
            ValueError: If `weights_initializer` is not a valid string
            ValueError: If `biases_initializer` is not a valid string

        """

        # check for required inputs
        if scope is None:
            raise TypeError('Must specify layer scope')
        if input_dims is None or output_dims is None:
            raise TypeError('Must specify both input and output dimensions')

        self.scope = scope

        # Make input, output, and filter sizes explicit
        if isinstance(input_dims,list):
            while len(input_dims) < 3:
                input_dims.append(1)
        else:
            input_dims = [input_dims,1,1]
        if isinstance(output_dims,list):
            while len(output_dims) < 3:
                output_dims.append(1)
            num_outputs = output_dims[0]*output_dims[1]*output_dims[2]
        else:
            num_outputs = output_dims
            output_dims = [output_dims,1,1]

        self.input_dims = input_dims
        self.output_dims = output_dims
        # default to have N filts for N outputs in base layer class
        self.num_filters = num_outputs
        if filter_dims is None:
            filter_dims = input_dims
        num_inputs = filter_dims[0] * filter_dims[1] * filter_dims[2]
        self.filter_dims = filter_dims

        # resolve activation function string
        if activation_func == 'relu':
            self.activation_func = tf.nn.relu
        elif activation_func == 'sigmoid':
            self.activation_func = tf.sigmoid
        elif activation_func == 'tanh':
            self.activation_func = tf.tanh
        elif activation_func == 'lin':
            self.activation_func = tf.identity
        elif activation_func == 'linear':
            self.activation_func = tf.identity
        elif activation_func == 'softplus':
            self.activation_func = tf.nn.softplus
        elif activation_func == 'quad':
            self.activation_func = tf.square
        elif activation_func == 'elu':
            self.activation_func = tf.nn.elu
        elif activation_func == 'exp':
            self.activation_func = tf.exp
        else:
            raise ValueError('Invalid activation function ''%s''' %
                             activation_func)

        # create excitatory/inhibitory mask
        if num_inh > num_outputs:
            raise ValueError('Too many inhibitory units designated')
        self.ei_mask = [1] * (num_outputs - num_inh) + [-1] * num_inh

        # save positivity constraint on weights
        self.pos_constraint = pos_constraint

        # use tf's summary writer to save layer activation histograms
        if log_activations:
            self.log = True
        else:
            self.log = False

        # Set up layer regularization
        self.reg = Regularization(
            input_dims=filter_dims,
            num_outputs=num_outputs,
            vals=reg_initializer)

        # Initialize weight values
        weight_dims = (num_inputs, num_outputs)
        if weights_initializer == 'trunc_normal':
            init_weights = np.random.normal(size=weight_dims, scale=0.1)
        elif weights_initializer == 'normal':
            init_weights = np.random.normal(size=weight_dims, scale=0.1)
        elif weights_initializer == 'zeros':
            init_weights = np.zeros(shape=weight_dims, dtype='float32')
        else:
            raise ValueError('Invalid weights_initializer ''%s''' %
                             weights_initializer)
        if pos_constraint is True:
            init_weights = np.maximum(init_weights, 0)
        # Initialize numpy array that will feed placeholder
        self.weights = init_weights.astype('float32')

        # Initialize bias values
        bias_dims = (1, num_outputs)
        if biases_initializer == 'trunc_normal':
            init_biases = np.random.normal(size=bias_dims, scale=0.1)
        elif biases_initializer == 'normal':
            init_biases = np.random.normal(size=bias_dims, scale=0.1)
        elif biases_initializer == 'zeros':
            init_biases = np.zeros(shape=bias_dims, dtype='float32')
        else:
            raise ValueError('Invalid biases_initializer ''%s''' %
                             biases_initializer)
        # Initialize numpy array that will feed placeholder
        self.biases = init_biases.astype('float32')

        # Define tensorflow variables as placeholders
        self.weights_ph = None
        self.weights_var = None
        self.biases_ph = None
        self.biases_var = None
        self.outputs = None

    # END Layer.__init__

    def _define_layer_variables(self):
        # Define tensor-flow versions of variables (placeholder and variables)
        with tf.name_scope('weights_init'):
            self.weights_ph = tf.placeholder_with_default(
                self.weights,
                shape=self.weights.shape,
                name='weights_ph')
            self.weights_var = tf.Variable(
                self.weights_ph,
                dtype=tf.float32,
                name='weights_var')

        # Initialize biases placeholder/variable
        with tf.name_scope('biases_init'):
            self.biases_ph = tf.placeholder_with_default(
                self.biases,
                shape=self.biases.shape,
                name='biases_ph')
            self.biases_var = tf.Variable(
                self.biases_ph,
                dtype=tf.float32,
                name='biases_var')

        # Check for need of ei_mask
        if np.sum(self.ei_mask) < len(self.ei_mask):
            self.ei_mask_var = tf.constant(
                self.ei_mask, dtype=tf.float32, name='ei_mask')
        else:
            self.ei_mask_var = None

    # END Layer._define_layer_variables

    def build_graph(self, inputs, params_dict=None):

        with tf.name_scope(self.scope):
            self._define_layer_variables()

            # Define computation
            if self.pos_constraint:
                pre = tf.add(tf.matmul(
                    inputs,
                    tf.maximum(0.0, self.weights_var)), self.biases_var)
            else:
                pre = tf.add(
                    tf.matmul(inputs, self.weights_var), self.biases_var)

            if self.ei_mask_var is not None:
                post = tf.multiply(self.activation_func(pre), self.ei_mask_var)
            else:
                post = self.activation_func(pre)

            self.outputs = post

        if self.log:
            tf.summary.histogram('act_pre', pre)
            tf.summary.histogram('act_post', post)
    # END layer._define_network

    def assign_layer_params(self, sess):
        """Read weights/biases in numpy arrays into tf Variables"""
        sess.run(
            [self.weights_var.initializer, self.biases_var.initializer],
            feed_dict={self.weights_ph: self.weights,
                       self.biases_ph: self.biases})

    def write_layer_params(self, sess):
        """Write weights/biases in tf Variables to numpy arrays"""
        self.weights = sess.run(self.weights_var)
        if self.pos_constraint is True:
            self.weights = np.maximum(self.weights, 0)
        self.biases = sess.run(self.biases_var)

    def define_regularization_loss(self):
        """Wrapper function for building regularization portion of graph"""
        with tf.name_scope(self.scope):
            return self.reg.define_reg_loss(self.weights_var)

    def set_regularization(self, reg_type, reg_val):
        """Wrapper function for setting regularization"""
        return self.reg.set_reg_val(reg_type, reg_val)

    def assign_reg_vals(self, sess):
        """Wrapper function for assigning regularization values"""
        self.reg.assign_reg_vals(sess)

    def get_reg_pen(self, sess):
        """Wrapper function for returning regularization penalty struct"""
        return self.reg.get_reg_penalty(sess)


import cv2
import numpy as np
import math
import time
import pandas as pd
import matplotlib.path as mplPath
from sklearn.cluster import DBSCAN
import matplotlib.pyplot as plt

cap = cv2.VideoCapture('car5.mp4')
_, frame = cap.read()
W = frame.shape[1]
H = frame.shape[0]
frame = cv2.resize(frame, (W // 2, H // 2))
first_frame = frame.copy()
height = frame.shape[0]
width = frame.shape[1]
fgbg = cv2.createBackgroundSubtractorMOG2(detectShadows=True)

roi_corners = [
    [[120, 300], [160, 200], [280, 200], [295, 300]],
    [[450, 300], [350, 200], [475, 200], [625, 300]]
]
data = []
frame_counter = 0
fps = 0
counter = 0
car_count = 0
moments = []
angle_array = []

def roi(image, roi_corners):
    mask = np.zeros_like(image)
    for roi_corner in roi_corners:
        polygons = np.array(roi_corner, np.int32)
        polygons = polygons.reshape((-1, 1, 2))
        cv2.polylines(mask, [polygons], True, (255, 255, 255), 3)
        cv2.fillPoly(mask, [polygons], (255, 255, 255))
        masked_image = cv2.bitwise_and(image, mask)
    return masked_image

def filter_mask(img):
    kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (2, 2))
    # Fill any small holes
    closing = cv2.morphologyEx(img, cv2.MORPH_CLOSE, kernel)
    # Remove noise
    opening = cv2.morphologyEx(closing, cv2.MORPH_OPEN, kernel)
    # Dilate to merge adjacent blobs
    dilation = cv2.dilate(opening, kernel, iterations=2)
    return dilation

def main():
    global frame_counter, fps, counter, car_count, time_start, data, moments, angle_array
    while True:
        if frame_counter == 0:
            time_start = time.time()
        frame_counter += 1  # measure fps

        success, frame = cap.read()
        if not success:
            print("***ERROR*** Can't read frame")
            break
        frame = cv2.resize(frame, (W // 2, H // 2))  # resize for better fps
        roi_img = roi(frame, roi_corners)
        fgMask = fgbg.apply(roi_img)
        _, fgMask = cv2.threshold(fgMask, 200, 255, cv2.THRESH_BINARY)
        fgMask = filter_mask(fgMask)
        cnt_img = fgMask.copy()
        cnt_img = cv2.cvtColor(cnt_img, cv2.COLOR_GRAY2BGR)
        cnt_img1 = fgMask.copy()
        cnt_img1 = cv2.cvtColor(cnt_img1, cv2.COLOR_GRAY2BGR)

        # find contours
        contours, hierarchy = cv2.findContours(fgMask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_TC89_L1)
        center = None
        for (i, contour) in enumerate(contours):
            (x, y, w, h) = cv2.boundingRect(contour)
            contour_valid = (w >= 25) and (
                    h >= 25) and (w <= 60) and (h <= 60)
            if not contour_valid:
                continue
            else:
                epsilon = 0.000001 * cv2.arcLength(contour, False)
                contour = cv2.approxPolyDP(contour, epsilon, False)
                M = cv2.moments(contour)
                if M["m00"] != 0:
                    center = (int(M["m10"] / M["m00"]), int(M["m01"] / M["m00"]))
                if center is not None:
                    moments.append(center)
                    cv2.circle(first_frame, center, 3, (0, 0, 255), -1)

        # get time elapsed until 1 second, compute FPS
        time_elapsed = time.time() - time_start
        if time_elapsed >= 1.0:
            fps = frame_counter
            frame_counter = 0

        cv2.putText(frame, "FPS: " + str(fps), (10, 15), cv2.FONT_HERSHEY_COMPLEX, 0.5, 0, 2)
        cv2.imshow('f_frame', first_frame)
        cv2.imshow('cnt_img', cnt_img)
        cv2.imshow('cnt_img1', cnt_img1)
        cv2.imshow('frame', frame)

        k = cv2.waitKey(1) & 0xff
        if k == ord('q'):
            break
        if k == ord('p'):
            cv2.waitKey(0)
        counter += 1

    cap.release()
    cv2.destroyAllWindows()

    moment_arr = np.array(moments)
    # angle_arr = np.array(angle_array)

    # DBSCAN - clustering algo
    db = DBSCAN(eps=5, min_samples=25).fit(moment_arr)
    # eps: the maximum distance between two samples for one to be considered as in the neighborhood of the other
    labels = db.labels_
    n_clusters_ = len(set(labels)) - (1 if -1 in labels else 0)
    print('Estimated number of clusters: %d' % n_clusters_)

    y_db = db.fit_predict(moment_arr)
    # print(y_db)
    # display
    plt.scatter(moment_arr[y_db == 0, 0], moment_arr[y_db == 0, 1], c='red')
    plt.scatter(moment_arr[y_db == 1, 0], moment_arr[y_db == 1, 1], c='black')
    plt.scatter(moment_arr[y_db == 2, 0], moment_arr[y_db == 2, 1], c='blue')
    plt.scatter(moment_arr[y_db == 3, 0], moment_arr[y_db == 3, 1], c='cyan')
    plt.scatter(moment_arr[y_db == 4, 0], moment_arr[y_db == 4, 1], c='olive')
    plt.scatter(moment_arr[y_db == 5, 0], moment_arr[y_db == 5, 1], c='purple')
    # plt.scatter(moment_arr[y_db == 6, 0], moment_arr[y_db == 6, 1], c='brown')
    # plt.scatter(moment_arr[y_db == 7, 0], moment_arr[y_db == 7, 1], c='green')
    # plt.scatter(moment_arr[y_db == 8, 0], moment_arr[y_db == 8, 1], c='orange')
    plt.gca().invert_yaxis()

    # put all angles in an array
    list1 = []
    list2 = []
    list3 = []
    list4 = []
    list5 = []
    list6 = []
    for i in range(1, len(y_db)):
        if y_db[i] == 0:
            list1.append(angle_array[i])
        elif y_db[i] == 1:
            list2.append(angle_array[i])
        elif y_db[i] == 2:
            list3.append(angle_array[i])
        elif y_db[i] == 3:
            list4.append(angle_array[i])
        elif y_db[i] == 4:
            list5.append(angle_array[i])
        elif y_db[i] == 5:
            list6.append(angle_array[i])

    print('red', np.mean(np.array(list1)))
    print('black', np.mean(np.array(list2)))
    print('blue', np.mean(np.array(list3)))
    print('cyan', np.mean(np.array(list4)))
    print('olive', np.mean(np.array(list5)))
    print('purple', np.mean(np.array(list6)))

    plt.show()

if __name__ == '__main__':
    main()


import pandas as pd

from workplaces.workplace import WorkPlace

class MongoLoader:

    def __init__(self, wp,
                 dataset: str = None,
                 fname: str = None):
        self.wp = wp
        self.dataset = dataset
        self.fname = fname
        self.source_type = 'mongo'

    def load_data(self,
                  dataset_source: str,
                  dataset_name: str, version_name=None, transport_type=None):
        """Loads data from db
        """
        if version_name and not transport_type:
            # print(1, version_name)
            # print(self.wp.db.db[dataset_name].find_one().keys())
            data = [x for x in self.wp.db.db[dataset_name].find(
                {'version': version_name})]
        elif transport_type and not version_name:
            # print(1, version_name)
            # print(self.wp.db.db[dataset_name].find_one().keys())
            data = [x for x in self.wp.db.db[dataset_name].find(
                {'transport_type': transport_type})]
        elif transport_type and version_name:
            # print(20)
            data = [x for x in self.wp.db.db[dataset_name].find(
                {'version': version_name})]
            # print(len(data))

            data = [x for x in data if x['transport_type'] == transport_type]
            # print(len(data))

        else:
            # print(2)
            data = [x for x in self.wp.db.db[dataset_name].find()]

        if dataset_name in self.wp.config['dataset_load_convert_func'].keys():

            convert_func = self.wp.config['dataset_load_convert_func'][dataset_name]
            res = convert_func(data)
        else:
            res = data
        return res

    def save_data(self,
                  dataset,
                  collection_name: str, version_name=None, transport_type=None, ** kwargs):
        if collection_name not in self.wp.db.db.list_collection_names():
            collection = self.wp.db.db.create_collection(
                collection_name)
        else:
            collection = self.wp.db.db[collection_name]
        if isinstance(dataset, pd.DataFrame):
            if 'inv_col_names' in kwargs:
                dataset = dataset[[x for x in dataset.columns
                                   if x not in kwargs['inv_col_names']]]

            df_numpy = dataset.to_numpy()
            Column_Index_Dictionary = dict(zip(list(range(0, len(dataset.columns))),
                                               dataset.columns))

            insert_list = []

            for each in df_numpy:
                row = {}
                for i, val in enumerate(each):
                    row[Column_Index_Dictionary[i]] = val
                insert_list.append(row)
        elif isinstance(dataset, list):
            insert_list = dataset
        elif isinstance(dataset, dict):
            # print('is_dict')
            insert_list = [{key: val} for key, val in dataset.items()]

        if version_name and not transport_type:
            # print(10)

            _insert_list = []
            # print('saver', len(insert_list))

            # x_0 = insert_list[0]
            # print(x_0.keys())
            for x in insert_list:

                for key, val in x.items():
                    _item = {key: val,
                             'version': version_name}

                    # val.update({'version': version_name})
                    _insert_list.append(_item)

            insert_list = _insert_list
            # print('saver after updating version', len(_insert_list))

        elif transport_type and not version_name:
            # print(3)
            # print(11)
            # print('saver before updating transport_type', len(insert_list))

            _insert_list = []

            # x_0 = insert_list[0]
            # print(x_0.keys())
            for x in insert_list:

                for key, val in x.items():
                    _item = {key: val,
                             'transport_type': transport_type}

                    # val.update({'version': version_name})
                    _insert_list.append(_item)

            insert_list = _insert_list
            # print('saver after updating transport_type', len(_insert_list))
        elif transport_type and version_name:

            _insert_list = []

            # x_0 = insert_list[0]
            # print(x_0.keys())
            for x in insert_list:

                for key, val in x.items():
                    _item = {key: val,
                             'transport_type': transport_type,
                             'version': version_name}

                    # val.update({'version': version_name})
                    _insert_list.append(_item)

            insert_list = _insert_list

        collection.insert_many(insert_list)


#!/usr/bin/python3
# convert a string into tokens, tokens are items such as operators, numbers, and
# parentheses.  Operators are: *,/,^,-and+
# each token should be a parenthesis, an operator, or a number.  Any sequence
# of consecutive digits should be treated as one number token
import re

def string_to_token(user_string):
    more_than_one_digit = False
    token_list=[]
    num = ""
    digit = 0
    for i in range(0, len(user_string)):
        if re.fullmatch('[\*\-\+\/\(\)\=]',user_string[i]):
            if digit > 0:
                token_list.append(num)
                digit = 0
                num=""
            token_list.append(user_string[i])
#            print("'[\*\-\+\/\(\)\=]',user_string[i]: %s" %user_string[i])
#            print("digit: %d" %digit)
        elif re.fullmatch('[0-9]',user_string[i]):
#            print("[0-9]',user_string[i]): %s" % user_string[i])
            num = num + user_string[i]
#            print("[0-9]'...num: %s" % num)
#            token_list.append(num)
            digit = digit + 1
#            print("digit: %d" %digit)
            if i == (len(user_string)-1):
                token_list.append(num)
    return token_list

def main():
    user_input = input("Enter a math expression: ")
    result = string_to_token(user_input)
    print(result)

if __name__ == "__main__":
    main()


import os

from django.conf import settings
from django.core.management.base import NoArgsCommand

from Plugins.ckeditor.views import get_image_files
from Plugins.ckeditor.utils import get_thumb_filename
from Plugins.ckeditor.image_processing import get_backend

class Command(NoArgsCommand):
    """
    Creates thumbnail files for the CKEditor file image browser.
    Useful if starting to use django-ckeditor with existing images.
    """

    def handle_noargs(self, **options):
        if getattr(settings, 'CKEDITOR_IMAGE_BACKEND', None):
            backend = get_backend()
            for image in get_image_files():
                if not os.path.isfile(get_thumb_filename(image)):
                    self.stdout.write("Creating thumbnail for {0}".format(image))
                    try:
                        backend.create_thumbnail(image)
                    except Exception as e:
                        self.stdout.write("Couldn't create thumbnail for {0}: {1}".format(image, e))
            self.stdout.write("Finished")
        else:
            self.stdout.write("No thumbnail backend is enabled")


from collections import Counter

M1 = 10 ** 9 + 7
M2 = 10 ** 9 + 33
p1 = 10 ** 9 + 9
p2 = 10 ** 9 + 87
pw1 = [1] * 26
pw2 = [1] * 26
for i in range(1, 26):
    pw1[i] = p1 * pw1[i - 1]
    pw2[i] = p2 * pw2[i - 1]
    pw1[i] %= M1
    pw2[i] %= M2

class Solution:
    def mins(self, stickers, i, n, rem, rctr, h1, h2):
        if rctr == 0:
            return 0
        if i >= n:
            return float('inf')
        key = (i, h1, h2)
        if key in self.cache:
            return self.cache[key]
        a = self.mins(stickers, i + 1, n, rem, rctr, h1, h2)
        newrem = Counter(rem)
        done = True
        for c in stickers[i]:
            if newrem[c] > 0:
                done = False
                h1 = (h1 + M1 - pw1[ord(c) - ord('a')]) % M1
                h2 = (h2 + M2 - pw2[ord(c) - ord('a')]) % M2
                newrem[c] -= 1
                rctr -= 1
        b = 1 + self.mins(stickers, i + int(done), n, newrem, rctr, h1, h2)
        res = min(a, b)
        self.cache[key] = res
        return res

    def minStickers(self, stickers: List[str], target: str) -> int:
        chars = set(target)
        self.cache = {}
        stickers = [s for s in stickers if len(set.intersection(set(s), chars)) > 0]
        res = self.mins(stickers, 0, len(stickers), Counter(target), len(target), 0, 0)
        if res == float('inf'):
            return -1
        return res


# -*- coding: utf-8 -*-
# Authors: Alexandre Gramfort <alexandre.gramfort@inria.fr>
#          Joan Massich <mailsik@gmail.com>
#
# License: BSD Style.

import numpy as np

from ...utils import verbose
from ._utils import _fetch_one, _data_path, TEMAZEPAM_SLEEP_RECORDS
from ._utils import _check_subjects

data_path = _data_path  # expose _data_path(..) as data_path(..)

BASE_URL = 'https://physionet.org/physiobank/database/sleep-edfx/sleep-telemetry/'  # noqa: E501

@verbose
def fetch_data(subjects, recording=[b'Placebo', 'temazepam'],
               path=None, force_update=False,
               update_path=None, base_url=BASE_URL, verbose=None):
    """Get paths to local copies of PhysioNet Polysomnography dataset files.

    This will fetch data from the publicly available subjects from PhysioNet's
    study of Temazepam effects on sleep [1]_. This corresponds to
    a set of 22 subjects. Subjects had mild difficulty falling asleep
    but were otherwise healthy.

    See more details in the `physionet website
    <https://physionet.org/physiobank/database/sleep-edfx/>`_.

    Parameters
    ----------
    subjects : list of int
        The subjects to use. Can be in the range of 0-21 (inclusive).
    path : None | str
        Location of where to look for the PhysioNet data storing location.
        If None, the environment variable or config parameter
        ``MNE_DATASETS_PHYSIONET_SLEEP_PATH`` is used. If it doesn't exist,
        the "~/mne_data" directory is used. If the Polysomnography dataset
        is not found under the given path, the data
        will be automatically downloaded to the specified folder.
    force_update : bool
        Force update of the dataset even if a local copy exists.
    update_path : bool | None
        If True, set the MNE_DATASETS_EEGBCI_PATH in mne-python
        config to the given path. If None, the user is prompted.
    %(verbose)s

    Returns
    -------
    paths : list
        List of local data paths of the given type.

    Notes
    -----
    For example, one could do:

        >>> from mne.datasets import sleep_physionet
        >>> sleep_physionet.temazepam.fetch_data(subjects=[1]) # doctest: +SKIP

    This would download data for subject 0 if it isn't there already.

    References
    ----------
    .. [1] B Kemp, AH Zwinderman, B Tuk, HAC Kamphuisen, JJL Oberyé. Analysis
           of a sleep-dependent neuronal feedback loop: the slow-wave
           microcontinuity of the EEG. IEEE-BME 47(9):1185-1194 (2000).
    .. [2] Goldberger AL, Amaral LAN, Glass L, Hausdorff JM, Ivanov PCh,
           Mark RG, Mietus JE, Moody GB, Peng C-K, Stanley HE. (2000)
           PhysioBank, PhysioToolkit, and PhysioNet: Components of a New
           Research Resource for Complex Physiologic Signals.
           Circulation 101(23):e215-e220

    See Also
    --------
    :func:`mne.datasets.sleep_physionet.age.fetch_data`
    """
    records = np.loadtxt(TEMAZEPAM_SLEEP_RECORDS,
                         skiprows=1,
                         delimiter=',',
                         usecols=(0, 3, 6, 7, 8, 9),
                         dtype={'names': ('subject', 'record', 'hyp sha',
                                          'psg sha', 'hyp fname', 'psg fname'),
                                'formats': ('<i2', '<S15', 'S40', 'S40',
                                            '<S22', '<S16')}
                         )

    _check_subjects(subjects, 22)

    path = data_path(path=path, update_path=update_path)
    params = [path, force_update, base_url]

    fnames = []
    for subject in subjects:  # all the subjects are present at this point
        for idx in np.where(records['subject'] == subject)[0]:
            if records['record'][idx] == b'Placebo':
                psg_fname = _fetch_one(records['psg fname'][idx].decode(),
                                       records['psg sha'][idx].decode(),
                                       *params)
                hyp_fname = _fetch_one(records['hyp fname'][idx].decode(),
                                       records['hyp sha'][idx].decode(),
                                       *params)
                fnames.append([psg_fname, hyp_fname])

    return fnames


'''
expEYES program
Author  : Ajith Kumar B.P, bpajith@gmail.com
License : GNU GPL version 3
'''
import gettext
gettext.bindtextdomain("expeyes")
gettext.textdomain('expeyes')
_ = gettext.gettext

from tkinter import *
import expeyes.eyes as eyes, expeyes.eyeplot as eyeplot, expeyes.eyemath as eyemath, time, math, sys

TIMER = 100
WIDTH  = 800   # width of drawing canvas
HEIGHT = 400   # height
delay = 10			# Time interval between samples
NP = 1000			# Number of samples
data = [ [], [] ]
outmask = 1
looping = False

def capture():
	global data, outmask, looping, NP, delay
	if looping == True:
		msgwin.config(text = _('Already Running'))
		return
	p.write_outputs(outmask)
	time.sleep(0.5)
	t, v = p.capture(0,NP,delay)
	p.write_outputs(0)
	g.delete_lines()
	g.line(t,v)
	data = t,v
	fa = eyemath.fit_sine(t,v)
	if fa != None:
		rms = p.rms(v)
		pa = fa[1]
		s = _('CH0 : %5.1f V , %5.1f Hz ') %(rms, pa[1]*1000)
		msgwin.config(text = s)

def update():
	global data, looping
	if looping == False:
		return
	t, v = p.capture(0,NP,delay)
	g.delete_lines()
	g.line(t,v)
	data = t,v
	root.after(TIMER, update)

def start():
	global outmask, looping
	outmask = 0
	if M1.get() == 1:
		outmask |= 1
	if M2.get() == 1:
		outmask |= 2
	p.write_outputs(outmask)

	if LOOP.get() == 1:
		if looping == False:
			root.after(TIMER, update)
			looping = True
	else:
		p.write_outputs(0)
		looping = False

def do_fft():
	global data, delay, NP
	if data == [ [], [] ]: return
	fr,tr = eyemath.fft(data[1], delay * 0.001)
	p.save([ [fr,tr] ], 'FFT.dat')
	p.grace([ [fr,tr] ], _('freq'), _('power'))
	msgwin.config(text = _('Fourier transform Saved to FFT.dat.'))

def save():
	global data
	s = fn.get()
	if s == '':
		return
	p.save([data], s)
	msgwin.config(text = _('Data saved to file ')+s)

def xmgrace():		# Send the data to Xmgrace
	global data
	p.grace([data], _('milliSeconds'), _('Volts'))

def quit():
	p.write_outputs(0)
	sys.exit()

p = eyes.open()
p.loadall_calib()
root = Tk()
Canvas(root, width = WIDTH, height = 5).pack(side=TOP)  # Some space at the top
g = eyeplot.graph(root, width=WIDTH, height=HEIGHT)	# make plot objects using draw.disp
g.setWorld(0,-5, NP * delay * 0.001, 5,_('mS'),_('V'))

if p == None:
	g.text(0, 0,_('EYES Hardware Not Found. Check Connections and restart the program'),1)
	root.mainloop()
	sys.exit()
p.set_voltage(1,5)

cf = Frame(root, width = WIDTH, height = 10)
cf.pack(side=TOP,  fill = BOTH, expand = 1)

M1 = IntVar()
cb1 = Checkbutton(cf,text =_('Buzzer1'), command = start,variable=M1, fg = 'red')
cb1.pack(side=LEFT, anchor = SW)
M1.set(1)
M2 = IntVar()
cb1 = Checkbutton(cf,text =_('Buzzer2'), command = start, variable=M2, fg = 'red')
cb1.pack(side=LEFT, anchor = SW)
M2.set(0)

b = Button(cf,text =_('Capture'), command=capture)
b.pack(side=LEFT, anchor = SW)
LOOP = IntVar()
cb1 = Checkbutton(cf,text =_('FreeRUN'), command = start, variable=LOOP, fg = 'red')
cb1.pack(side=LEFT, anchor = SW)
LOOP.set(0)

b = Button(cf,text =_('Save to'), command=save)
b.pack(side=LEFT, anchor = SW)
fn = Entry(cf,width = 10, bg = 'white')
fn.pack(side=LEFT, anchor = SW)
fn.insert(END,'cap.dat')
b = Button(cf,text =_('QUIT'), command=quit)
b.pack(side=RIGHT, anchor = SW)
b = Button(cf,text =_('Xmgrace'), command=xmgrace)
b.pack(side=RIGHT, anchor = SW)
b = Button(cf,text =_('FFT'), command=do_fft)
b.pack(side=LEFT, anchor = SW)

mf = Frame(root)				# Message Frame below command frame.
mf.pack(side=TOP, anchor = SW)
msgwin = Label(mf,text = _('Messages'), fg = 'blue')
msgwin.pack(side=LEFT, anchor = SW)
root.title(_('EYES: Sound Experiments'))
root.mainloop()


from absl.testing import absltest
from bsuite.baselines.utils import sequence

import dm_env
from dm_env import specs
import numpy as np

class BufferTest(absltest.TestCase):
  """Tests for the sequence buffer class."""

  def test_buffer(self):
    # Given a buffer and some dummy data...
    max_sequence_length = 10
    obs_shape = (3, 3)
    buffer = sequence.Buffer(
        obs_spec=specs.Array(obs_shape, dtype=np.float),
        action_spec=specs.Array((), dtype=np.int),
        max_sequence_length=max_sequence_length)
    dummy_step = dm_env.transition(observation=np.zeros(obs_shape), reward=0.)

    # If we add `max_sequence_length` items to the buffer...
    for _ in range(max_sequence_length):
      buffer.append(dummy_step, 0, dummy_step)

    # Then the buffer should now be full.
    self.assertTrue(buffer.full())

    # Any further appends should throw an error.
    with self.assertRaises(ValueError):
      buffer.append(dummy_step, 0, dummy_step)

    # If we now drain this trajectory from the buffer...
    trajectory = buffer.drain()

    # The `observations` sequence should have length `T + 1`.
    self.assertLen(trajectory.observations, max_sequence_length + 1)

    # All other sequences should have length `T`.
    self.assertLen(trajectory.actions, max_sequence_length)
    self.assertLen(trajectory.rewards, max_sequence_length)
    self.assertLen(trajectory.discounts, max_sequence_length)

    # The buffer should now be empty.
    self.assertTrue(buffer.empty())

    # A second call to drain() should throw an error, since the buffer is empty.
    with self.assertRaises(ValueError):
      buffer.drain()

    # If we now append another transition...
    buffer.append(dummy_step, 0, dummy_step)

    # And immediately drain the buffer...
    trajectory = buffer.drain()

    # We should have a valid partial trajectory of length T=1.
    self.assertLen(trajectory.observations, 2)
    self.assertLen(trajectory.actions, 1)
    self.assertLen(trajectory.rewards, 1)
    self.assertLen(trajectory.discounts, 1)

if __name__ == '__main__':
  absltest.main()


'''
시간 초과가 나니까
pop이나 reverse는 굳이..

import sys
input=sys.stdin.readline

N=int(input())
Box=[]
for i in range(N):
    s=int(input())
    #애초에 여기서 거꾸로 들어가면 오류가 덜 남
    if len(Box)>0:
        for i in range(len(Box)-1,-1,-1):
            if int(Box[i])<=s:
                Box.pop(i)
    Box.append(s)
print(len(Box))

'''

import sys
input=sys.stdin.readline

N=int(input())
Box=[]
for i in range(N):
    s=int(input())
    Box.append(s)
visible_stick=1
length=Box[-1]
for i in range(N-1,-1,-1):
    if Box[i]>length:
        visible_stick+=1
        length=Box[i]
print(visible_stick)


from typing import Callable, TypeVar

from typing_aliases import Binary, Nullary, Quaternary, Ternary, Unary
from typing_extensions import ParamSpec

from wraps.future import Future

__all__ = (
    "FutureCallable",
    "FutureNullary",
    "FutureUnary",
    "FutureBinary",
    "FutureTernary",
    "FutureQuaternary",
    "FutureIdentity",
    "FutureInspect",
    "FuturePredicate",
)

P = ParamSpec("P")

T = TypeVar("T")
U = TypeVar("U")
V = TypeVar("V")
W = TypeVar("W")

R = TypeVar("R")

FutureCallable = Callable[P, Future[R]]
FutureNullary = Nullary[Future[R]]
FutureUnary = Unary[T, Future[R]]
FutureBinary = Binary[T, U, Future[R]]
FutureTernary = Ternary[T, U, V, Future[R]]
FutureQuaternary = Quaternary[T, U, V, W, Future[R]]

FutureIdentity = FutureUnary[T, T]
FutureInspect = FutureUnary[T, None]
FuturePredicate = FutureUnary[T, bool]


#!/usr/bin/env python
import pigpio
from threading import Thread

class Decoder(Thread):
	def __init__(self, pi, gpioA, gpioB, callback=None):
		if not pi.connected:
			raise IOError("Can't connect to pigpio")
		self.pi = pi
		self.gpioA = gpioA
		self.gpioB = gpioB
		self.callback = callback

		self.levA = 0
		self.levB = 0

		self.lastGpio = None

		self.pi.set_mode(gpioA, pigpio.INPUT)
		self.pi.set_mode(gpioB, pigpio.INPUT)

		self.pi.set_pull_up_down(gpioA, pigpio.PUD_UP)
		self.pi.set_pull_up_down(gpioB, pigpio.PUD_UP)

		self.cbA = self.pi.callback(gpioA, pigpio.EITHER_EDGE, self._pulse)
		self.cbB = self.pi.callback(gpioB, pigpio.EITHER_EDGE, self._pulse)

		Thread.__init__(self)
		self.daemon = True

	def _pulse(self, gpio, level, tick):
		if gpio == self.gpioA and not level == 2:
			self.levA = level
		else:
			self.levB = level

		if gpio != self.lastGpio: # debounce
			self.lastGpio = gpio
			if gpio == self.gpioA and level == self.levB:
					self.callback(1)
			elif gpio == self.gpioA and not level == self.levB:
					self.callback(-1)
			elif gpio == self.gpioB and level == self.levA:
					self.callback(-1)
			elif gpio == self.gpioB and not level == self.levA:
					self.callback(1)

	def cancel(self):
		self.cbA.cancel()
		self.cbB.cancel()

	def run(self):
		pass

if __name__ == "__main__":

	import time
	import pigpio
	import rotary_encoder

	pos = 0

	def callback(step):
		global pos
		pos += step
		print("pos={}".format(pos))

	pi = pigpio.pi()
	decoder = rotary_encoder.decoder(pi, 7, 8, callback)
	decoder.start()
	time.sleep(300)
	decoder.cancel()
	decoder.join()
	pi.stop()


import subprocess
from typing import Optional

def sub_com(command, input_pipe=None) -> Optional[str]:
    stderr = ""
    # subprocess communicate
    # https://stackoverflow.com/questions/11269575/how-to-hide-output-of-subprocess-in-python-2-7

    # Command Should be None, guard for False for sanity
    if command is None or command is False:
        return None
    try:
        response = subprocess.Popen(command, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
                                    shell=True)
        if input_pipe is None or input_pipe is False:
            stdout, stderr = response.communicate()
            stdout = stdout.decode()
            stderr = stderr.decode()
        else:
            stdout, stderr = response.communicate(input=input_pipe.encode())
            stdout = stdout.decode()
            stderr = stderr.decode()
        if stderr != '':
            raise OSError
    except OSError as e:
        print("SUB COM ERROR")

        # stdout = False
        return None
    return stdout


import copy

import torch
import torch.utils
import os
from utils.utils import load_pickle
from utils.replay_buffer import ReplayBufferBarrier as ReplayBuffer
import numpy as np
from utils.plotter_reacher import plot_results
from utils.models import GaussianDiffusion as ProbDiffusion
from diffuser.models.temporal import TemporalUnet, ValueFunction
from utils.models import ValueDiffusion
from utils.trainer import train_ProbDiffusion as train
from utils.trainer import train_ValueDiffusion as train_valuefunction
from utils.trainer import train_CbfDiffusion as train_cbfdiffusion
from utils.trainer import test_ValueDiffusion as test_valuefunction
from utils.trainer import test_ProbDiffusion as test_probdiffusion
from utils.trainer import test_CbfDiffusion as test_cbfdiffusion
import gc
from datetime import datetime
import argparse

parser = argparse.ArgumentParser()

parser.add_argument('--batch-size', type=int, default=50,
                    help='Batch size.')
parser.add_argument('--num-epochs', type=int, default=100,
                    help='Number of training epochs.')
parser.add_argument('--learning-rate', type=float, default=2e-4,
                    help='Learning rate.')
parser.add_argument('--reg-coefficient', type=float, default=0.0,
                    help='L2 regularization coefficient.')

parser.add_argument('--training', default=True,
                    help='Train the models.')
parser.add_argument('--plotting', default=True,
                    help='Plot the results.')
parser.add_argument('--num-samples-plot', type=int, default=200,
                    help='Number of independent sampling from the distribution.')

parser.add_argument('--hidden-dim', type=int, default=256,
                    help='Number of hidden units in MLPs.')
parser.add_argument('--action-dim', type=int, default=2,
                    help='Dimensionality of the action space.')
parser.add_argument('--state-dim', type=int, default=8,
                    help='Dimensionality of the true state space.')
parser.add_argument('--sequence-length', type=int, default=16,
                    help='Sequence length.')
parser.add_argument('--diffusion-steps', type=int, default=50,
                    help='Number of diffusion steps.')
parser.add_argument('--num-classes', type=int, default=2,
                    help='Number of classes (safe and unsafe).')
parser.add_argument('--experiment', type=str, default='Reacher',
                    help='Experiment.')
parser.add_argument('--model-type', type=str, default='ProbDiffusion',
                    help='Model type.')
parser.add_argument('--training-dataset', type=str, default='reacher_train.pkl',
                    help='Training dataset.')
parser.add_argument('--testing-dataset', type=str, default='reacher_test.pkl',
                    help='Testing dataset.')
parser.add_argument('--log-interval', type=int, default=10,
                    help='How many batches to wait before saving')
parser.add_argument('--plot-interval', type=int, default=50,
                    help='How many batches to wait before plotting')
parser.add_argument('--seed', type=int, default=1,
                    help='Random seed (default: 1).')
parser.add_argument('--use-attention', default=True,
                    help='Use attention layer in temporal U-net.')
parser.add_argument('--train-value', default=True,
                    help='Train value function or not.')
parser.add_argument('--train-cbfvalue', default=True,
                    help='Train cbf value function or not.')
parser.add_argument('--load', default=False,
                    help='Load trained model.')
parser.add_argument('--load-value', default=False,
                    help='Load pre-trained value function or not.')
parser.add_argument('--load-cbfvalue', default=False,
                    help='Load pre-trained cbf value function or not.')
args = parser.parse_args()

seed = args.seed
torch.manual_seed(seed)
np.random.seed(seed)
if torch.cuda.is_available():
    torch.cuda.empty_cache()
    print('CUDA available:', torch.cuda.is_available())
    torch.cuda.manual_seed(args.seed)

# training hyperparameters
batch_size = args.batch_size
max_epoch = args.num_epochs

training = args.training
plotting = args.plotting
num_samples_plot = args.num_samples_plot

# learning rate
lr = args.learning_rate
reg_coef = args.reg_coefficient

# build model
act_dim = args.action_dim
state_dim = args.state_dim
h_dim = args.hidden_dim
sequence_length = args.sequence_length
num_classes = args.num_classes

# experiment and model type
exp = args.experiment
mtype = args.model_type
training_dataset = args.training_dataset
testing_dataset = args.testing_dataset

log_interval = args.log_interval
plot_interval = args.plot_interval

load = args.load
use_attention = args.use_attention

train_value = args.train_value
load_value = args.load_value

train_cbfvalue = args.train_cbfvalue
load_cbfvalue = args.load_cbfvalue

def main(exp='Reacher', mtype='ProbDiffusion', training_dataset='reacher_train.pkl', testing_dataset='reacher_test.pkl'):

    # load data
    directory = os.path.dirname(os.path.abspath(__file__))

    folder = os.path.join(directory + '/data', training_dataset)
    folder_test = os.path.join(directory + '/data', testing_dataset)

    data = load_pickle(folder)
    data_test = load_pickle(folder_test)

    now = datetime.now()
    save_pth_dir = directory + '/results/' + str(exp) + '/' + str(mtype)
    if not os.path.exists(save_pth_dir):
        os.makedirs(save_pth_dir)

    horizon = sequence_length
    observation_dim = state_dim
    action_dim = act_dim
    transition_dim = observation_dim + action_dim
    nr_diffusion_steps = args.diffusion_steps

    model = TemporalUnet(horizon, transition_dim, dim=32, dim_mults=(1, 2, 4, 8), attention=use_attention)

    diffusion = ProbDiffusion(model, horizon, observation_dim, action_dim, n_timesteps=nr_diffusion_steps,
        loss_type='l2', clip_denoised=False, predict_epsilon=False,
        action_weight=1.0, loss_discount=1.0, loss_weights=None)

    ema_diffusion = copy.deepcopy(diffusion)

    if load:
        checkpoint = torch.load(save_pth_dir + '/ProbDiff_Model_best.pth')
        diffusion.model.load_state_dict(checkpoint['model'])
        ema_diffusion.model.load_state_dict(checkpoint['ema_model'])

    if train_value:
        value_model = ValueFunction(horizon, transition_dim, dim=32, dim_mults=(1, 2, 4, 8), attention=use_attention,
                                    final_sigmoid=False)
        value_diffusion = ValueDiffusion(value_model, horizon, observation_dim, action_dim,
                                         n_timesteps=nr_diffusion_steps, loss_type='value_l2', clip_denoised=False,
                                         predict_epsilon=False, action_weight=1.0, loss_discount=1.0, loss_weights=None)
        ema_value_diffusion = copy.deepcopy(value_diffusion)
        if load_value:
            checkpoint = torch.load(save_pth_dir + '/ValueDiff_Model_best.pth')
            value_diffusion.model.load_state_dict(checkpoint['model'])
            ema_value_diffusion.model.load_state_dict(checkpoint['ema_model'])

    if train_cbfvalue:
        cbf_model = ValueFunction(horizon, transition_dim, dim=32, dim_mults=(1, 2, 4, 8), attention=use_attention,
                                  out_dim=num_classes*horizon, final_sigmoid=True)
        cbf_diffusion = ValueDiffusion(cbf_model, horizon, observation_dim, action_dim, n_timesteps=nr_diffusion_steps,
                                       loss_type='cross_entropy', clip_denoised=False, predict_epsilon=False,
                                       action_weight=1.0, loss_discount=1.0, loss_weights=None)
        ema_cbf_diffusion = copy.deepcopy(cbf_diffusion)
        if load_cbfvalue:
            checkpoint = torch.load(save_pth_dir + '/CbfDiff_Model_best.pth')
            cbf_diffusion.model.load_state_dict(checkpoint['model'])
            ema_cbf_diffusion.model.load_state_dict(checkpoint['ema_model'])

    if torch.cuda.is_available():
        diffusion = diffusion.cuda()
        ema_diffusion = ema_diffusion.cuda()
        if train_value or load_value:
            value_diffusion = value_diffusion.cuda()
            ema_value_diffusion = ema_value_diffusion.cuda()
        if train_cbfvalue or load_cbfvalue:
            cbf_diffusion = cbf_diffusion.cuda()
            ema_cbf_diffusion = cbf_diffusion.cuda()
        gc.collect()

    # Use the adam optimizer
    optimizer = torch.optim.AdamW([
        {'params': diffusion.parameters()},
        ], lr=lr, weight_decay=reg_coef)

    if train_value:
        # Value optimizer
        value_optimizer = torch.optim.AdamW([
            {'params': value_diffusion.parameters()},
            ], lr=lr, weight_decay=reg_coef)

    if train_cbfvalue:
        # Cbf value optimizer
        cbf_optimizer = torch.optim.AdamW([
            {'params': cbf_diffusion.parameters()},
            ], lr=lr, weight_decay=reg_coef)

    counter = 0
    train_loader = ReplayBuffer(act_dim=act_dim, size=len(data), state_dim=state_dim)
    for d in data:
        train_loader.store(d[0].astype('float32'),
                           d[1].astype('float32'),
                           d[2],
                           d[3].astype('float32'),
                           d[4],
                           d[5])
        counter += 1

    print(counter)

    test_loader = ReplayBuffer(act_dim=act_dim, size=len(data_test), state_dim=state_dim)
    counter_t = 0
    for dt in data_test:
        test_loader.store(dt[0].astype('float32'),
                          dt[1].astype('float32'),
                          dt[2],
                          dt[3].astype('float32'),
                          dt[4],
                          dt[5])
        counter_t += 1
    print(counter_t)

    if training:
        best_loss_value = 1e6
        best_loss_dyn = 1e6
        best_loss_cbf = 1e6
        for epoch in range(0, max_epoch):
            diffusion.train()
            train(epoch=epoch, batch_size=batch_size, nr_data=counter, train_loader=train_loader, num_timesteps=horizon,
                  optimizer=optimizer, diffusion=diffusion, ema_diffusion=ema_diffusion)

            with torch.no_grad():
                test_loss_dyn = test_probdiffusion(epoch=epoch, batch_size=batch_size, nr_data=counter,
                                                   test_loader=test_loader, num_timesteps=horizon,
                                                   ema_diffusion=ema_diffusion)
                if test_loss_dyn < best_loss_dyn:
                    best_loss_dyn = test_loss_dyn
                    print("save best dyn model!")
                    torch.save({'model': diffusion.model.state_dict(), 'ema_model': ema_diffusion.model.state_dict()},
                               save_pth_dir + '/ProbDiff_Model_best.pth')
            if train_value:
                value_diffusion.train()
                train_valuefunction(epoch=epoch, batch_size=batch_size, nr_data=counter, train_loader=train_loader,
                                    num_timesteps=horizon, optimizer=value_optimizer, diffusion=value_diffusion,
                                    ema_diffusion=ema_value_diffusion)

                with torch.no_grad():
                    test_loss_value = test_valuefunction(epoch=epoch, batch_size=batch_size, nr_data=counter, test_loader=test_loader,
                                                         num_timesteps=horizon, ema_diffusion=ema_value_diffusion)
                    if test_loss_value < best_loss_value:
                        best_loss_value = test_loss_value
                        print("save best value model!")
                        torch.save({'model': value_diffusion.model.state_dict(), 'ema_model': ema_value_diffusion.model.state_dict()},
                                   save_pth_dir + '/ValueDiff_Model_best.pth')
            if train_cbfvalue:
                cbf_diffusion.train()
                train_cbfdiffusion(epoch=epoch, batch_size=batch_size, nr_data=counter, train_loader=train_loader,
                                   num_timesteps=horizon, optimizer=cbf_optimizer, diffusion=cbf_diffusion,
                                   ema_diffusion=ema_cbf_diffusion)

                with torch.no_grad():
                    test_loss_cbf = test_cbfdiffusion(epoch=epoch, batch_size=batch_size, nr_data=counter, train_loader=train_loader,
                                       num_timesteps=horizon, ema_diffusion=ema_cbf_diffusion)
                    if test_loss_cbf < best_loss_cbf:
                        best_loss_cbf = test_loss_cbf
                        print("save best cbf model!")
                        torch.save({'model': cbf_diffusion.model.state_dict(),
                                    'ema_model': ema_cbf_diffusion.model.state_dict()},
                                   save_pth_dir + '/CbfDiff_Model_best.pth')

            if epoch % plot_interval == 0:
                diffusion.eval()
                ema_diffusion.eval()
                with torch.no_grad():
                    plot_results(diffusion=diffusion, ema_diffusion=ema_diffusion, test_loader=test_loader,
                                 save_dir=save_pth_dir, num_timesteps=horizon, true_dyn=True, epoch=epoch)

        # save model after training is completed
        torch.save({'model': diffusion.model.state_dict(), 'ema_model': ema_diffusion.model.state_dict()},
                   save_pth_dir +'/ProbDiff_Model_latest.pth')
        if train_value:
            torch.save({'model': value_diffusion.model.state_dict(),
                        'ema_model': ema_value_diffusion.model.state_dict()}, save_pth_dir + '/ValueDiff_Model_latest.pth')
        if train_cbfvalue:
            torch.save({'model': cbf_diffusion.model.state_dict(),
                        'ema_model': ema_cbf_diffusion.model.state_dict()}, save_pth_dir + '/CbfDiff_Model_latest.pth')

    if plotting:
        diffusion.eval()
        ema_diffusion.eval()
        with torch.no_grad():
            plot_results(diffusion=diffusion, ema_diffusion=ema_diffusion, test_loader=test_loader,
                         save_dir=save_pth_dir, num_timesteps=horizon, true_dyn=True, epoch=max_epoch)

if __name__ == "__main__":

    main(exp=exp, mtype=mtype, training_dataset=training_dataset, testing_dataset=testing_dataset)
    print('Finished Training the DDPM models!')


import cv2
import numpy as np

def direction_detect(detected_both, yolo_yellow_cones_center, yolo_red_cones_center, yolo_slopes_yellow, yolo_slopes_red):
    direction = [0,0] # -2 = very left; -1 = left; 0 = straight; 1 = right; 2 = very right

    #very left
    thres_for_very_left_yellow = 0.01
    thres_for_very_left_red = 0.01

    #left
    thres_for_left_yellow = 0.1
    thres_for_left_red = 0.5

    #straight
    thres_for_straight_yellow = [-0.4, -0.2]
    thres_for_straight_red = [0.2, 0.4]

    #right
    thres_for_right_yellow = -0.5
    thres_for_right_red = -0.1

    #very right
    thres_for_very_left_yellow = -0.01
    thres_for_very_left_red = -0.01

    '''
    thres_array = []
    if yolo_slopes_red[0] > thres_for_straight_red[0] and yolo_slopes_red[1] > thres_for_straight_red[0] :  #straight or left turn
      if yolo_slopes_yellow[0] <= thres_for_straight_yellow[0] and yolo_slopes_yellow[1] <= thres_for_straight_yellow[0]:  #straight
        direction = 0
        if yolo_slopes_red[0]
    '''

    yolo_slope_difference_yellow = yolo_slopes_yellow[0] - yolo_slopes_yellow[1]
    yolo_slope_difference_red= yolo_slopes_red[0] - yolo_slopes_red[1]
    if yolo_slope_difference_yellow <= 0.04: # gental slopes change
      avg_slope_yellow = (yolo_slopes_yellow[0] + yolo_slopes_yellow[1])/2
      # straight
      if avg_slope_yellow > thres_for_straight_yellow[0] and avg_slope_yellow <= thres_for_straight_yellow[1]:
        direction[0] = 0
      # very left
      if yolo_slope_difference_red <= 0.04: # gental slopes change
        avg_slope_red = (yolo_slopes_red[0] + yolo_slopes_red[1])/2
        if avg_slope_red > -thres_for_very_left_red or avg_slope_red <= thres_for_very_left_red:
          direction[0] = -2

def apex_detect(detected_both, yolo_yellow_cones_center, yolo_red_cones_center, yolo_slopes_yellow, yolo_slopes_red):
    yolo_slopes_checker_red = 0
    yolo_slopes_checker_yellow = 0
    if len(yolo_slopes_yellow) == 2:
      yolo_slope_difference_yellow = abs(yolo_slopes_yellow[0] - yolo_slopes_yellow[1])
      yolo_slopes_checker_yellow = 1
    else:
      yolo_slopes_checker_yellow = 0

    if len(yolo_slopes_red) == 2:
      yolo_slope_difference_red = abs(yolo_slopes_red[0] - yolo_slopes_red[1])
      yolo_slopes_checker_red = 1
    else:
      yolo_slopes_checker_red = 0

    if yolo_slopes_checker_red + yolo_slopes_checker_yellow == 2:
      print(yolo_slope_difference_yellow)
      if yolo_slope_difference_red >= 0.1 or yolo_slope_difference_yellow >= 0.1:
        print("sharp turn")
        if yolo_slope_difference_red >= 0.1:
          cx, cy = yolo_red_cones_center[1]
          cv2.drawMarker(detected_both, (cx, cy), (255,0,255), cv2.MARKER_TRIANGLE_UP, 10,1,1 )
          cv2.putText(detected_both, "APEX", (cx, cy - 5), cv2.FONT_HERSHEY_SIMPLEX, 0.5,(255,100,255), 2)

        if yolo_slope_difference_yellow >= 0.1:
          cx, cy = yolo_yellow_cones_center[1]
          cv2.drawMarker(detected_both, (cx, cy), (255,0,255), cv2.MARKER_TRIANGLE_UP, 10,1,1 )
          cv2.putText(detected_both, "APEX", (cx, cy - 5), cv2.FONT_HERSHEY_SIMPLEX, 0.5,(255,100,255), 2)

    return detected_both


import turtle
myTurtle = turtle.Turtle()
command = ""
#Loop until the user's command is 'end'
while not command == "end":
    #Get the user's command
    command = input("Enter a command (turn, forward, end): ")
    #Check if the command is 'turn'
    if command == "turn":
        #Get the angle if so
        angle = input("Enter the angle: ")
        #Execute the turn
        myTurtle.right(int(angle))
    #Check if the command is 'forward'
    elif command == "forward":
        #Get the distance if so
        distance = input("Enter distance: ")
        #Execute the move
        myTurtle.forward(int(distance))
    #Check if the command is 'shape'
    elif command == "shape":
        #Get the number of sides to draw
        numSides = int(input("Enter the number of sides (3 or more): "))
        #Get the side length to draw
        sideLength = int(input("Enter the length of each side: "))
        #Draw the shape: forward sideLength, rotated 360/numSides, repeat numSides times
        for _ in range(0, numSides):
            myTurtle.forward(sideLength)
            myTurtle.right(360/numSides)
    #Checks if the command is 'end'
    elif command == "end":
        #Skip if so; the loop won't repeat again if command == "end"
        pass
    else:
        print("Invalid command! Please enter 'turn' or 'forward'.")


from math import *
def isprime(n):
    if n==0 or n==1:
        return False
    sq=int(sqrt(n))
    for i in range (2,sq+1):
        if n%i==0:
            return False
    return True

n=int(input())
m=int(input())
c=0
for j in range(n,m+1):
    if isprime(j):
        c+=1
        print(j)


import os
import pandas as pd

from divvy.ml_logic.data_import import get_divvy_data, get_weather_data
from divvy.ml_logic.cleaning import compute_geohash_stations,weather_cleaning, cleaning_divvy_gen,cleaning_divvy_gen_agg, merge_divvy_weather, features_target
from divvy.ml_logic.preprocessor import transform_time_features, preprocess_features, target_process

raw_weather_df = get_weather_data()
clean_weather_df = weather_cleaning(raw_weather_df)

divvy_q1_2021 = get_divvy_data(2021,"Q1")

divvy_q2_2021 = get_divvy_data(2021,"Q2")
divvy_q3_2021 = get_divvy_data(2021,"Q3")
divvy_q4_2021 = get_divvy_data(2021,"Q4")

rides_df = pd.concat([divvy_q1_2021,divvy_q2_2021, divvy_q3_2021,divvy_q4_2021])

rides_df = rides_df[rides_df["start_station_name"].isnull()==False]
rides_df['started_at']=pd.to_datetime(rides_df['started_at'])
rides_df['hourly_data_started'] = rides_df.started_at.dt.round('60min')

rides_df = rides_df[["start_station_name","ride_id","hourly_data_started"]]
rides_df.rename(columns={"start_station_name":"station_name"}, inplace=True)

precision_level= int(os.environ.get("PRECISION_LEVEL"))
geohash_station_df = compute_geohash_stations(precision = precision_level)

rides_df = rides_df.merge(geohash_station_df, on="station_name", how="left")

rides_df["date"]= pd.to_datetime(rides_df["hourly_data_started"]).dt.date
rides_df["nb_rides"]=1

rides_df_daily_geohash = rides_df.groupby(by=["geohash","date"])["nb_rides"].sum().reset_index()
rides_df_daily = rides_df.groupby(by=["date"])["nb_rides"].sum().reset_index()

clean_weather_df["date"]= pd.to_datetime(clean_weather_df["hourly_data"]).dt.date
avg_weather_df = clean_weather_df.groupby(by=["date"])["temp",
                                                    "pressure",
                                                    'humidity',
                                                    'wind_speed',
                                                    'wind_deg',
                                                    "clouds_all"].mean().reset_index()

rides_df_daily_geohash.to_csv("raw_data/rides_df_daily_geohash_2021.csv", index=False)

rides_df_daily.to_csv("raw_data/rides_df_daily_2021.csv", index=False)
avg_weather_df.to_csv("raw_data/avg_temp.csv", index=False)


import pandas as pd
import sys

from logzero import logger

import matplotlib.pyplot as plt

from sklearn.preprocessing import StandardScaler, PolynomialFeatures
from sklearn.linear_model import Lasso, LinearRegression, LogisticRegression
from sklearn.tree import DecisionTreeRegressor, DecisionTreeClassifier
from sklearn import tree
from sklearn.metrics import f1_score, accuracy_score

class SurrogateModel:
    def __init__(self, config):
        self.config = config

        self.models = config["surrogate"]["models"]
        self.model_types_str = []
        self.model_types = []
        self.model_kwargs = []
        self.categorical_features = self.config["data"]["categorical_features"]
        self.numerical_features = self.config["data"]["numerical_features"]
        for model_str, kwargs in self.models.items():
            self.model_types_str.append(model_str)
            self.model_types.append(getattr(sys.modules[__name__], model_str))
            if isinstance(kwargs, dict):
                self.model_kwargs.append(kwargs)
            else:
                self.model_kwargs.append({})

        if "prediction_data_path" in self.config["data"]:
            csv_filepath = self.config["data"]["prediction_data_path"]
            data = pd.read_csv(csv_filepath, sep=";")
            data = data.dropna()
            self.X, self.y, self.y_cat = (
                data.drop(
                    [
                        self.config["output"]["y_pred_proba"],
                        self.config["output"]["y_pred_cat"],
                    ],
                    axis=1,
                ),
                data[self.config["output"]["y_pred_proba"]],
                data[self.config["output"]["y_pred_cat"]],
            )
        else:
            csv_filepath = self.config["data"]["inputs"]
            data = pd.read_csv(csv_filepath, sep=";")
            data = data.dropna()
            self.X, self.y, self.y_cat = (
                data.drop([config["data"]["y_pred"], config["data"]["y_true"]], axis=1),
                data[config["data"]["y_pred"]],
                (
                    data[config["data"]["y_pred"]] > config["surrogate"]["threshold"]
                ).astype(int),
            )

        csv_read = (
            "Evaluating own black box model with surrogate models"
            if "prediction_data_path" in self.config["data"]
            else "Evaluating original black box model with surrogate models"
        )
        logger.info(f"{csv_read}")

    def preprocess(self):
        self.X = pd.get_dummies(
            self.X, columns=self.config["data"]["categorical_features"]
        )
        scaler = StandardScaler()
        self.X_fit = scaler.fit_transform(self.X)

    def evaluate_Lasso(self, model, y_true):
        logger.info(f"Getting evaluation for Lasso model")
        r2 = model.score(self.X_fit, y_true)
        for i in range(len(self.X.columns)):
            logger.debug(f"Coef of feature {self.X.columns[i]}: {model.coef_[i]}")
        return r2

    def evaluate_LogisticRegression(self, model, y_true):
        logger.info(f"Getting evaluation for LogisticRegression model")
        y_pred = model.predict(self.X_fit)
        f1 = f1_score(y_pred, y_true)
        df = pd.DataFrame(data=[self.X.columns, model.coef_[0]]).transpose()
        return f1

    def evaluate_DecisionTreeRegressor(self, model, y_true):
        logger.info(f"Getting evaluation for DecisionTree model")
        r2 = model.score(self.X_fit, y_true)
        plt.rcParams["figure.figsize"] = (20, 20)
        plt.rcParams["figure.dpi"] = 75
        display = tree.plot_tree(
            model,
            filled=True,
            fontsize=8.5,
            feature_names=list(self.X.columns),
        )
        plt.savefig(self.config["output"]["tree_vis"])
        text_representation = tree.export_text(
            model, feature_names=list(self.X.columns)
        )
        with open(self.config["output"]["tree_text"], "w") as text_file:
            text_file.write(text_representation)
        return r2

    def evaluate_DecisionTreeClassifier(self, model, y_true):
        y_pred = model.predict(self.X_fit)
        f1 = f1_score(y_pred, y_true)
        acc = y_true == y_pred
        self.evaluate_DecisionTreeRegressor(model, y_true)
        return f1

    def get_y_col(self, model_type):
        if model_type in ["DecisionTreeRegressor", "Lasso"]:
            return self.y
        return self.y_cat

    def train(self):
        res = {}
        self.preprocess()
        for i, model_type in enumerate(self.model_types):
            model = model_type(**self.model_kwargs[i])
            y = self.get_y_col(self.model_types_str[i])
            model.fit(self.X_fit, y)
            eval_func = getattr(self, "evaluate_" + self.model_types_str[i])
            score = eval_func(model, y)
            res[self.model_types_str[i]] = score

        logger.info(f"Model Outputs: {res}")


# Kyle Wenzel
# January 7th, 2021
# GPA Program
import os
import webbrowser
import time
os.system('cls' if os.name == 'nt' else 'clear')
print("Welcome to the GPA program! ")

freshmancount = 0
sophomorecount = 0
juniorcount = 0
seniorcount = 0
gpaaverage = 0
gpatotal = 0
gpaticker = 0
ahigh = ""
bhigh = ""
ehigh = 0
alow = ""
blow = ""
elow = 100

students = [["White", "Snow", 9, "F", 3.56],
            ["Sprat", "Jack", 12, "M", 2.0],
            ["Contrary", "Mary", 9, "F", 3.674],
            ["Dumpty", "Humpty", 11, "M", 2.342],
            ["Bunny", "Easter", 10, "M", 4.233],
            ["Wonderland", "Alice", 10, "F", 3.755],
            ["Bunyon", "Paul", 11, "M", 1.434],
            ["Penny", "Henny", 9, "F", 2.54],
            ["Hatter", "Mad", 11, "M", 4.522],
            ["Munk", "Chip", 10, "M", 3.0],
            ["Hood", "Red Riding", 10, "F", 3.137],
            ["Bunny", "Bugs", 11, "M", 2.12],
            ["Duck", "Daffy", 11, "M", 3.564],
            ["Ant", "Atom", 12, "M", 3.333],
            ["Mouse", "Mickey", 10, "M", 3.975],
            ["Brown", "Charlie", 9, "M", 1.25]]
sophomores = []
print("{:^30}".format("GPA Menu"))
print("{:<5}{:<10}".format("\n1.", "School List"))
print("{:<5}{:<10}".format("2.", "Sophomores"))
print("{:<5}{:<10}".format("3.", "Juniors"))
print("{:<5}{:<10}".format("4.", "Above Average Students"))
print("{:<5}{:<10}".format("5.", "Alphabetical List"))
print("{:<5}{:<10}".format("6.", "Highest and Lowest GPA"))
print("{:<5}{:<10}".format("7.", "Find Student"))
print("{:<5}{:<10}".format("8.", "Exit"))
print("\nPlease enter an option from the menu:")

selection = int(input("\nPlease enter your selection. "))

if selection == 1:
    # School List
    os.system('cls' if os.name == 'nt' else 'clear')
    print("You have selected: School List")
    ynselection1 = input("Is this correct (y/n)? ")
    if ynselection1.lower() == "y" or ynselection1.lower() == "yes":
        os.system('cls' if os.name == 'nt' else 'clear')
    elif ynselection1.lower() == "n" or ynselection1.lower() == "no":
        print("Don't worry, we all make mistakes")
        print("Please restart the program after it exits")
        exit()
    else:
        os.system('cls' if os.name == 'nt' else 'clear')
        print("You broke something")
        print("No need to be upset, You can just try again")
        webbrowser.open("https://youtu.be/eY52Zsg-KVI")
        exit()
    print("\nAll Students")
    print("-"*90)
    for entry in students:
        a, b, c, d, e = entry
        print("{:<30}{:<30}{:<30}".format(b, a, c))
        if c == 9:
            freshmancount += 1
        elif c == 10:
            sophomorecount += 1
        elif c == 11:
            juniorcount += 1
        elif c == 12:
            seniorcount += 1
    print("")
    print("Freshman:", freshmancount)
    print("Sophomores:", sophomorecount)
    print("Juniors:", juniorcount)
    print("Seniors:", seniorcount)
elif selection == 2:
    # Sophomores
    print("You have selected: Sophomores")
    ynselection1 = input("Is this correct (y/n)? ")
    if ynselection1.lower() == "y" or ynselection1.lower() == "yes":
        os.system('cls' if os.name == 'nt' else 'clear')
    elif ynselection1.lower() == "n" or ynselection1.lower() == "no":
        print("Don't worry, we all make mistakes")
        print("Please restart the program after it exits")
        exit()
    else:
        os.system('cls' if os.name == 'nt' else 'clear')
        print("You broke something")
        print("No need to be upset, You can just try again")
        exit()
        webbrowser.open("https://youtu.be/eY52Zsg-KVI")
    print("Sophomores")
    print("-"*15)
    for entry in students:
        a, b, c, d, e = entry
        if c == 10:
            print(b, a)
elif selection == 3:
    # Juniors
    print("You have selected: Juniors")
    ynselection1 = input("Is this correct (y/n)? ")
    if ynselection1.lower() == "y" or ynselection1.lower() == "yes":
        os.system('cls' if os.name == 'nt' else 'clear')
    elif ynselection1.lower() == "n" or ynselection1.lower() == "no":
        print("Don't worry, we all make mistakes")
        print("Please restart the program after it exits")
        exit()
    else:
        os.system('cls' if os.name == 'nt' else 'clear')
        print("You broke something")
        print("No need to be upset, You can just try again")
        exit()
        webbrowser.open("https://youtu.be/eY52Zsg-KVI")
    print("Juniors")
    print("-"*15)
    for entry in students:
        a, b, c, d, e = entry
        if c == 11:
            print(b, a)
elif selection == 4:
    # Above Average Students
    print("You have selected: Above Average Students")
    for entry in students:
        a, b, c, d, e = entry
        gpaticker += 1
        gpatotal += e
    gpaaverage = gpatotal / gpaticker
    print("{:<30}{:<30}{:<30}".format("First Name", "Last Name", "GPA"))
    print("-"*90)
    for entry in students:
        a, b, c, d, e = entry
        if e > gpaaverage:
            print("{:<30}{:<30}{:<30}".format(b, a, e))
elif selection == 5:
    # Alphabetical List
    print("You have selected: Alphabetical List")
    print("I spent almost 2 hours trying to figure this one out,")
    print("I couldn't figure it out")
    print("So instead, I present to you: My favorite video on the internet")
    time.sleep(4)
    os.system('cls' if os.name == 'nt' else 'clear')
    print("Now playing: Impractical Engineering by Uncle Dane")
    webbrowser.open("https://youtu.be/YgtSWCt5MgU")
elif selection == 6:
    # Highest and Lowest GPA
    print("You have selected: Highest and Lowest GPA")
    ynselection1 = input("Is this correct (y/n)? ")
    if ynselection1.lower() == "y" or ynselection1.lower() == "yes":
        os.system('cls' if os.name == 'nt' else 'clear')
    elif ynselection1.lower() == "n" or ynselection1.lower() == "no":
        print("Don't worry, we all make mistakes")
        print("Please restart the program after it exits")
        exit()
    else:
        os.system('cls' if os.name == 'nt' else 'clear')
        print("You broke something")
        print("No need to be upset, You can just try again")
        exit()
        webbrowser.open("https://youtu.be/eY52Zsg-KVI")
    for entry in students:
        a, b, c, d, e = entry
        if ehigh < e:
            ehigh = e
            ahigh = a
            bhigh = b
        if elow > e:
            elow = e
            alow = a
            blow = b
    print("The student with the highest GPA is", bhigh, ahigh)
    print("The student with the lowest GPA", blow, alow)
elif selection == 7:
    # Find Student
    print("You have selected: Find Student")
    ynselection1 = input("Is this correct (y/n)? ")
    if ynselection1.lower() == "y" or ynselection1.lower() == "yes":
        os.system('cls' if os.name == 'nt' else 'clear')
    elif ynselection1.lower() == "n" or ynselection1.lower() == "no":
        print("Don't worry, we all make mistakes")
        print("Please restart the program after it exits")
        exit()
    else:
        os.system('cls' if os.name == 'nt' else 'clear')
        print("You broke something")
        print("No need to be upset, You can just try again")
        exit()
        webbrowser.open("https://youtu.be/eY52Zsg-KVI")
    searchterma = input("Please enter the last name of the student you want to search for. ")
    for entry in students:
        a, b, c, d, e = entry
        if searchterma.lower() == a.lower():
            fullname = b, a
            print("{:<20}{:<20}{:<20}{:<20}{:<20}".format(b, a, c, d, e))
elif selection == 8:
    # Exit
    print("You have selected: Exit")
    print("Goodbye")
    os.system('cls' if os.name == 'nt' else 'clear')
else:
    # Error
    os.system('cls' if os.name == 'nt' else 'clear')
    print("You broke something")
    print("No need to be upset, You can just try again")
    webbrowser.open("https://youtu.be/eY52Zsg-KVI")

input("\nPress enter to exit...")
os.system('cls' if os.name == 'nt' else 'clear')


import os

def join_collection(directory: str):
    items = set()
    for filename in os.listdir(directory):
        if not filename.endswith('.processed'):
            continue
        with open(os.path.join(directory, filename), 'r') as f:
            items |= set(f)
    if len(items) == 0:
        return
    with open(directory + '.processed', 'w') as f:
        f.write('\n'.join(sorted(items)))

def main():
    for directory in os.listdir('.'):
        if not os.path.isdir(directory):
            continue
        join_collection(directory)

if __name__ == '__main__':
    main()


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Oct 21 20:09:08 2021

######################
##### read h5 ########
######################
# 1.read h5-file
h5_file = h5py.File(files[1],'r')

# 2.show all keys in h5-file
h5_file.keys()

# 3.循环读取所有 keys in h5-file
for key in h5_file.keys():
    onekey = key
    onekey_name = h5_file[key].name

# 4.已知某个group的 key "NN"
h5_file["NN"]
h5_file["NN"].keys()
f_dict = dict(h5_file["NN"])
f_dict.keys() # 所有的keyword

# 5.读取 group 的 datasets
data = f_dict["data"][()] # 建议
data = f_dict["data"].value # data 是 numpy 的 ndarray 多维数组模式
trace = data[0] # 某一道数据

# 6.读取 group 的 Int Float 类型
baz = f_dict["baz"].value
baz = h5_file["NN"]["baz"].value

# 7.读取 group 的 字符串
# encode的作用是将unicode编码转换成其他编码的字符串，如str2.encode(‘utf8’)，表示将unicode编码的字符串str2转换成utf8编码
comp = h5_file["NN"]["comp"].value[0].decode('utf-8')

# 8. 关闭文件
f_dict.close()

######################
##### write h5 ########
######################

@author: yf
"""
#%%
import numpy as np
import h5py
import os
import glob

#%% 1. set parameter
file = "../../data/BJ.081_BJ.084__2020_04_11_00_00_00T2021_04_13_00_00_00__all.jld2"
chan = "NN"
dt = 0.005

#%% 2. read h5
# open file
f = h5py.File(file,'r')

# read data
data = f[chan]["data"][0]

# read parameters
azi = f[chan]["azi"][()]
baz = f[chan]["baz"][()]
maxlag = f[chan]["maxlag"][()]
cc_len = f[chan]["cc_len"][()]
cc_step = f[chan]["cc_step"][()]
corr_type = f[chan]["corr_type"][()]
comp = f[chan]["comp"][()]
dist = f[chan]["dist"][()]   # dist = f[chan]["dist"].value
lat = f[chan]["lat"][()]
lon = f[chan]["lon"][()]
N_glob = f[chan]["N_glob"][()]
N_read = f[chan]["N_read"][()]
N_good = f[chan]["N_good"][()]
name = f[chan]["name"][()][0].decode('utf-8')

# close h5-file
f.close()


#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
易盾反垃圾云服务视频点播离线结果获取接口python示例代码
接口文档: http://dun.163.com/api.html
python版本：python3.7
运行:
    1. 修改 SECRET_ID,SECRET_KEY,BUSINESS_ID 为对应申请到的值
    2. $ python video_callback.py
"""
__author__ = 'yidun-dev'
__date__ = '2019/11/27'
__version__ = '0.2-dev'

import hashlib
import time
import random
import urllib.request as urlrequest
import urllib.parse as urlparse
import json
from gmssl import sm3, func

class VideoCallbackAPIDemo(object):
    """视频点播离线结果获取接口示例代码"""

    API_URL = "http://as.dun.163.com/v4/video/callback/results"
    VERSION = "v4"

    def __init__(self, secret_id, secret_key, business_id):
        """
        Args:
            secret_id (str) 产品密钥ID，产品标识
            secret_key (str) 产品私有密钥，服务端生成签名信息使用
            business_id (str) 业务ID，易盾根据产品业务特点分配
        """
        self.secret_id = secret_id
        self.secret_key = secret_key
        self.business_id = business_id

    def gen_signature(self, params=None):
        """生成签名信息
        Args:
            params (object) 请求参数
        Returns:
            参数签名md5值
        """
        buff = ""
        for k in sorted(params.keys()):
            buff += str(k) + str(params[k])
        buff += self.secret_key
        if "signatureMethod" in params.keys() and params["signatureMethod"] == "SM3":
            return sm3.sm3_hash(func.bytes_to_list(bytes(buff, encoding='utf8')))
        else:
            return hashlib.md5(buff.encode("utf8")).hexdigest()

    def check(self):
        """请求易盾接口
        Returns:
            请求结果，json格式
        """
        params = {}
        params["secretId"] = self.secret_id
        params["businessId"] = self.business_id
        params["version"] = self.VERSION
        params["timestamp"] = int(time.time() * 1000)
        params["nonce"] = int(random.random() * 100000000)
        # params["signatureMethod"] = "SM3"  # 签名方法，默认MD5，支持SM3
        params["signature"] = self.gen_signature(params)

        try:
            params = urlparse.urlencode(params).encode()
            request = urlrequest.Request(self.API_URL, params)
            content = urlrequest.urlopen(request, timeout=10).read()
            return json.loads(content)
        except Exception as ex:
            print("调用API接口失败:", str(ex))

if __name__ == "__main__":
    """示例代码入口"""
    SECRET_ID = "your_secret_id"  # 产品密钥ID，产品标识
    SECRET_KEY = "your_secret_key"  # 产品私有密钥，服务端生成签名信息使用，请严格保管，避免泄露
    BUSINESS_ID = "your_business_id"  # 业务ID，易盾根据产品业务特点分配
    api = VideoCallbackAPIDemo(SECRET_ID, SECRET_KEY, BUSINESS_ID)

    ret = api.check()

    code: int = ret["code"]
    msg: str = ret["msg"]
    if code == 200:
        resultArray: list = ret["result"]
        if len(resultArray) == 0:
            print("暂无回调数据")
        else:
            for result in resultArray:
                antispam: dict = result["antispam"]
                status: int = antispam["status"]
                if status != 0:  # 异常，异常码定义见官网文档
                    print("视频异常, status: %s" % status)
                    continue
                taskId: str = antispam["taskId"]
                callback: str = antispam["callback"]
                pictureArray: list = antispam["pictures"]
                for picture in pictureArray:
                    pictureType: int = picture["type"]
                    url: str = picture["url"]
                    startTime: int = picture["startTime"]
                    endTime: int = picture["endTime"]
                    labels: list = picture["labels"]
                    for labelItem in labels:
                        label: int = labelItem["label"]
                        level: int = labelItem["level"]
                        rate: str = labelItem["rate"]
                        subLabels: list = labelItem["subLabels"]
    else:
        print("ERROR: code=%s, msg=%s" % (ret["code"], ret["msg"]))