import numpy as np
import matplotlib.pyplot as plt
import torch.nn.functional as F
import torch.nn as nn
import glob
import os, sys
import torch
from torch.utils.data import Dataset, DataLoader
from torchvision import transforms, utils
import cv2
import json
import argparse
from scipy.stats import multivariate_normal
from skimage.transform import resize
import random
import torchvision.transforms.functional as TF
import torchvision.transforms as T
import PIL
import kornia

class Keypoint_dataset(Dataset):
    '''
    Keypoint dataset for training
    '''

    def __init__(self, dataset_path, train, resize_dimension = 64, transform = None):

        self.train = train
        self.resize_dimension = resize_dimension
        self.transform = transform
        self.name_dictionary = self.load_names(dataset_path, train)
        print("Number of images: ", len(self.name_dictionary["images"]))
        print('Data retrieved')

    def __len__(self):

        return len(self.name_dictionary["images"])

    def __getitem__(self, index):

        prob_rotate = random.random()
        prob_crop = random.random()

        keypoint_view = np.load(self.name_dictionary["keypoints"][index])
        image_view = (cv2.cvtColor(cv2.imread(self.name_dictionary["images"][index]),cv2.COLOR_BGR2RGB) * 255).astype("uint8")
        h, w, c = image_view.shape
        image_view = resize(image_view, (self.resize_dimension, self.resize_dimension), preserve_range=True)[:, :, :3].astype("uint8")

        # print(image_view.astype("uint8"))
        keypoint_view[:, 0] = keypoint_view[:, 0] * self.resize_dimension / w
        keypoint_view[:, 1] = keypoint_view[:, 1] * self.resize_dimension / h

        alpha = 180#random.randint(-35, 35)
        angle_rot = alpha * np.pi / 180
        rot_mat = np.array([
            [np.cos(angle_rot), -np.sin(angle_rot)],
            [np.sin(angle_rot), np.cos(angle_rot)]
        ])

        if prob_rotate > 0.5:
            keypoint_view[:, 0] = keypoint_view[:, 0] - 32
            keypoint_view[:, 1] = keypoint_view[:, 1] - 32
            keypoint_view[:,:2] = keypoint_view[:,:2] @ rot_mat
            keypoint_view[:, 0] = keypoint_view[:, 0] + 32
            keypoint_view[:, 1] = keypoint_view[:, 1] + 32

        data = {}
        data["views"] = image_view
        data["heatmaps"] = self.generate_target_heatmaps_batch(keypoint_view, (self.resize_dimension, self.resize_dimension))
        data["keypoints"] = keypoint_view

        transform_tensor = self.ToTensor()
        data = transform_tensor(data, self.resize_dimension, train = self.train)

        ## Adding the random transformations here
        if prob_rotate > 0.5:
            data["views"] = T.ToPILImage(mode="RGB")(data["views"])
            data["views"] = TF.rotate(data["views"], alpha)
            data["views"] = T.ToTensor()(data["views"])

        if prob_crop > 0.8:
            window = random.randint(16,32)
            top = random.randint(0, 64-window)
            left = random.randint(0, 64-window)
            data["views"][:,top:top+window,left:left+window] = 0.0
            data["heatmaps"][:,top:top+window,left:left+window] = data["heatmaps"][:,top:top+window,left:left+window]*.0

        return data

    def generate_heatmap(self, kp, image_size):
        '''
        Generate a single heatmap
        '''

        pos = np.dstack(np.mgrid[0:image_size[0]:1, 0:image_size[1]:1])
        # kp => x, y, visibility
        rv = multivariate_normal(mean=[kp[1], kp[0]], cov = [1,1])
        heatmap = rv.pdf(pos)

        heatmap = heatmap / heatmap.max()

        if kp[2] == 0:
            heatmap *= 0

        return heatmap

    def generate_target_heatmaps_batch(self, kps, image_size):
        '''
        Generate target heatmaps from keypoints
        '''
        heatmaps = []

        for i in range(kps.shape[0]):
            heatmaps.append(self.generate_heatmap(kps[i, :], image_size))

        target_heatmap = np.stack(heatmaps, axis = 0)

        return target_heatmap

    def load_names(self, path, train = 1):
        '''
        Load names of image, mask, and camera pose file names
        '''
        if train == 1:
            data_file_name = 'train.txt'
        elif train == 2:
            data_file_name = 'val.txt'
        else:
            data_file_name = 'test.txt'

        file_path = os.path.join(path, data_file_name)

        fp = open(file_path, 'r')

        images = []
        keypoints = []

        for line in fp:

            fields = line.split('/')
            directory_name = fields[0]
            image_name = fields[1]

            image_number = int(image_name.split("_")[1])
            keypoint_name = "frame_%08d_KeyPoints.npy" % image_number

            images.append(os.path.join(path, directory_name, image_name).split("\n")[0])
            keypoints.append(os.path.join(path, directory_name, keypoint_name))

        return {"images": images, "keypoints": keypoints}

    class ToTensor(object):

        def __call__(self, data_dictionary, resize_dimension = 64, train = 1):

            if train == 1:
                data_augmentation_transform = transforms.Compose([
                                            transforms.ToPILImage(),
                                            #transforms.ColorJitter(brightness=0.0, contrast=0.05, saturation=0.05, hue = 0.3),
                                            transforms.ColorJitter(brightness=0.3, contrast=0.2, saturation=0.05, hue = 0.3),
                                            transforms.ToTensor(),
                                            transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
                ])
            else:
                data_augmentation_transform = transforms.Compose([
                                            transforms.ToPILImage(),
                                            transforms.ToTensor(),
                                            transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
                ])
            # data_sample["heatmaps"] = ((data_dictionary["heatmaps"]))
            # data_sample["views"] = tensor_transform(resize_transform(pil_transform(data_dictionary["views"])))

            data_sample = {}
            #print(data_dictionary["views"].shape)

            data_sample["views"] = (data_augmentation_transform(data_dictionary["views"]))
            data_sample["heatmaps"] = torch.from_numpy(data_dictionary["heatmaps"])
            # data_sample["views"] = torch.from_numpy(data_dictionary["views"].transpose(2, 0, 1)) / 255.0
            data_sample["keypoints"] = torch.from_numpy(data_dictionary["keypoints"])
            return data_sample

def keypoint_visualizer(im, kps):

    plt.imshow(im)

    for i in range(kps.shape[0]):

        # If visibility is 1 display point in red
        if kps[i, 2] == 1:
            plt.plot(kps[i, 0], kps[i, 1], 'ro')
        else:
            plt.plot(kps[i, 0], kps[i, 1], 'bo')

    plt.show()

if __name__ == "__main__":

    ################################## Argument parser ###########################################################

    parser = argparse.ArgumentParser()
    parser.add_argument("--dataset", help="Dataset path", required=True)
    args = parser.parse_args()

    ##############################################################################################################

    dataset_path = args.dataset

    data_set = Keypoint_dataset(dataset_path, train = 1)
    data_loader = DataLoader(data_set, batch_size = 2, shuffle=True)

    data = data_set[20]

    # print(data["views"].min())
    # print(data["keypoints"].numpy())
    plt.subplot(121)
    plt.imshow(data["heatmaps"][2])
    plt.subplot(122)
    plt.imshow(data["views"].permute(1, 2, 0))
    plt.show()
    # keypoint_visualizer(data["views"].permute(1, 2, 0), data["keypoints"].numpy())

    # for batch, data_sample in enumerate(data_loader):
        # print(batch, data_sample["views"].min())


import sqlite3

contact = sqlite3.connect('./static_files/test_db.db3', check_same_thread=False)
cursor = contact.cursor()

def select_id_column(column_name):
    id_column = contact.execute("SELECT user_id "
                                "FROM users_data")
    ls = []
    for ch in id_column.fetchall():
        ls.append(ch[0])
    return ls

def report_column(colum_name):
    selected_column = contact.execute(f"SELECT {colum_name} "
                                      f"FROM users_data")
    st = ''
    for i in selected_column.fetchall():
        st = st + i[0] + '\n'
    return st

def db_table(user_id: int, user_name: str,
             user_surname: str, username: str,
             email: str, b_day: str):
    cursor.execute('INSERT INTO users_data '
                   '(user_id, user_name, user_surname,'
                   'username, email, b_day) '
                   'VALUES (?,?,?,?,?,date(?))',
                   (user_id, user_name, user_surname,
                    username, email, b_day))
    contact.commit()

def write_id(table, filename: str, file_id: str, hashes: str, bb, size: int, duration: int):
    id_column = contact.execute(f"SELECT hashes FROM {table}")
    ls = []
    for ch in id_column.fetchall():
        ls.append(ch[0])
    if hashes not in ls:
        try:
            if table == 'music':
                cursor.execute(f'INSERT INTO {table} '
                               f'(filename, file_id, hashes, bb, size, duration) '
                               f'VALUES (?, ?, ?, ?, ?, ?)', (filename, file_id, hashes, bb, size, duration))
                contact.commit()
            elif table == 'photos_file_id':
                cursor.execute(f'INSERT INTO {table} '
                               f'(file_id, hashes) '
                               f'VALUES (?, ?)',
                               (file_id, hashes))
                contact.commit()
            return True
        except sqlite3.IntegrityError:
            return False
    else:
        return False

def get_table_name():
    cursor.execute('SELECT name '
                   'FROM sqlite_master '
                   'WHERE type="table"')
    return cursor.fetchall()[1::]   # get all tables from BD

def get_photos_id():
    raw_list = cursor.execute('SELECT file_id '
                   'FROM photos_file_id')
    ls = raw_list.fetchall()
    id_ls = [ch[0] for ch in ls]
    return id_ls

def deleting_data():
    try:
        cursor.execute('DELETE FROM photos_file_id')
        contact.commit()
        return 'All data was deleted.'
    except sqlite3.Error:
        return 'Something is wrong.'


A = []
for n in input().split():
    A.append(int(n))

# A = []
# with open('sequence.txt') as f:
#     data = f.read()
#     for n in data.split():
#         A.append(int(n))

def lenOfIrregEx(A):
    if len(A) < 2:
        return len(A)

    signs = []
    for i in range(1,len(A)):
        if A[i-1] > A[i]:
            signs.append(">")
        elif A[i-1] < A[i]:
            signs.append("<")
        else:
            signs.append("=")

    best = 0
    if A[0] != A[1]:
        count = 2
    else:
        count = 1
    prev = signs[0]
    for i in range(1, len(signs)):
        if signs[i] == prev or signs[i] == "=":
            if count > best:
                best = count
            if A[i] != A[i+1]:
                count = 2
            else:
                count = 1
        elif signs[i] != prev:
            count += 1
        prev = signs[i]
    if count > best:
        best = count
    return best

print(lenOfIrregEx(A))


# Definition for singly-linked list.
class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next

class Solution:
    def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
        listLength1,listLength2 = 0,0
        iter1,iter2 = l1, l2
        list1, list2, list3 = [], [], []
        while iter1:
            list1.append(iter1.val)
            iter1 = iter1.next
            listLength1 += 1
        while iter2:
            list2.append(iter2.val)
            iter2 = iter2.next
            listLength2 += 1
        if listLength1 < listLength2:
            l1, l2, list1, list2 = l2, l1, list2, list1
        list2.extend([0]*(len(list1)-len(list2)))
        carryOver = 0
        for i in range(len(list1)):
            list3.append(((list1[i]+list2[i])%10+carryOver) % 10)
            if (list1[i]+list2[i]+carryOver)>=10:
                carryOver = 1
            else:
                carryOver = 0
        if (carryOver): list3.append(1)
        head = tmp = ListNode(0)
        for i in list3:
            tmp.next = ListNode(i)
            tmp = tmp.next
        return head.next


from copy import deepcopy

def follow_slp(grid, x, y, dx, dy):
    if dx == 0 and dy == 0:
        return "L"

    x += dx
    y += dy

    while x >= 0 and x < len(grid[0]) and y >= 0 and y < len(grid) and grid[y][x] == ".":
        x += dx
        y += dy

    if not (x >= 0 and x < len(grid[0]) and y >= 0 and y < len(grid)):
        return "L"
    return grid[y][x]

def step(grid):
    cpy = deepcopy(grid)
    for y in range(len(grid)):
        for x in range(len(grid[0])):
            full = 0

            for dy in range(-1, 2):
                for dx in range(-1, 2):
                    full += follow_slp(grid, x, y, dx, dy) == "#"

            if grid[y][x] == "L" and not full:
                cpy[y][x] = "#"
            elif grid[y][x] == "#" and full >= 5:
                cpy[y][x] = "L"

    return cpy

grid = []
with open("input.txt") as f:
    for line in f:
        grid.append(list(line.strip()))

    while True:
        ngrid = step(grid)
        changed = False
        for y in range(len(grid)):
            for x in range(len(grid[0])):
                changed = changed or grid[y][x] != ngrid[y][x]
        if not changed:
            break
        grid = ngrid

ans = 0
for y in range(len(grid)):
    for x in range(len(grid[0])):
        ans += grid[y][x] == "#"
print(ans)


'''
Created on 16.11.2011

@author: michi
'''
from PyQt4.QtCore import pyqtSlot, QDateTime
from PyQt4.QtNetwork import QNetworkReply, QNetworkRequest

from ems.qt4.location.maps.tiled.geotiledmapreply import GeoTiledMapReply

class GeoMapReplyNokia(GeoTiledMapReply):

    _m_reply = QNetworkReply

    def __init__(self, reply, request, parent=None):
        '''
        @param reply: QNetworkReply
        @type reply: QNetworkReply
        @param request: GeoTiledMapRequest
        @type request: GeoTiledMapRequest
        @param parent: Parent QObject
        @type parent: QObject
        '''
        GeoTiledMapReply.__init__(self, request, parent=parent)

        self._m_reply = reply
        self._m_reply.setParent(self)
        self._m_reply.finished.connect(self._networkFinished)
        self._m_reply.error.connect(self._networkError)
        self._m_reply.destroyed.connect(self._replyDestroyed)

    def networkReply(self):
        '''
        @rtype: QNetworkReply
        '''
        return self._m_reply

    def abort(self):
        if not self._m_reply:
            return
        self._m_reply.abort()

    @pyqtSlot()
    def _replyDestroyed(self):
        self._m_reply = None

    @pyqtSlot()
    def _networkFinished(self):
        if not self._m_reply:
            return

        if self._m_reply.error() != QNetworkReply.NoError:
            return

        fromCache = self._m_reply.attribute(QNetworkRequest.SourceIsFromCacheAttribute)
        self._setCached(fromCache.toBool())

        if not self.isChached():
            cache = self._m_reply.manager().cache()
            if cache:
                metaData = cache.metaData(self._m_reply.url())
                exp = QDateTime.currentDateTime()
                exp = exp.addDays(14)
                metaData.setExpirationDate(exp)
                cache.updateMetaData(metaData)

        self._setMapImageData(self._m_reply.readAll())
        self.setMapImageFormat("PNG")
        self._setFinished(True)

        self._m_reply.deleteLater()
        self._m_reply = None

    def _networkError(self, error):
        if not self._m_reply:
            return

        if error != QNetworkReply.OperationCanceledError:
            self._setError(GeoTiledMapReply.CommunicationError,
                           self._m_reply.errorString())
        self._setFinished(True)
        self._m_reply.deleteLater()
        self._m_reply = None


import cv2
import numpy as np

model_name = 'bvlc_googlenet.caffemodel'
prototxt_name = 'deploy.prototxt'

def detectAndDisplay(frame):
    model = cv2.dnn.readNetFromCaffe(prototxt_name, model_name);
    blob = cv2.dnn.blobFromImage(cv2.resize(frame, (300, 300)), 1.0,
                                 (300, 300), (104.0, 177.0, 123.0))
    model.setInput(blob)
    detections = model.forward()

    for i in range(0, detections.shape[2]):

        confidence = detections[0, 0, i, 2]
        min_confidence = 0.05;

        if confidence > min_confidence:
            box = detections[0, 0, i, 3:7] * np.array([width, height, width, height])
            (startX, startY, endX, endY) = box.astype("int")
            print(confidence, startX, startY, endX, endY)

            text = "{:.2f}%".format(confidence * 100)
            y = startY - 10 if startY - 10 > 10 else startY + 10
            cv2.rectangle(frame, (startX, startY), (endX, endY),
                          (0, 255, 0), 2)
            cv2.putText(frame, text, (startX, y),
                        cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 1)

    cv2.imshow("Face Detection by dnn", frame)

img = cv2.imread('photo/afv.jpg')
(height, width) = img.shape[:2]
detectAndDisplay(img)

cv2.waitKey(0)
cv2.destroyAllWindows()


from tools.DataSetGraph import ReadPolyData, WritePolyData, LoadOBJFile
import pdb
from os import path
import argparse
from tools.LandmarkingUtils import RunInference
from tools.PhotoAnalysisTools import AlignPatientToTemplate, GenerateSphericalMapOfData, ComputeFromSphericalImage

def ReadImage(imagefilename):
    if imagefilename.endswith('.obj'):
        image = LoadOBJFile(imagefilename)
    else:
        image = ReadPolyData(imagefilename)
    return image

def PlaceLandmarks(image, crop=True, verbose = True, crop_percentage = 0.4):
    '''
    Inputs:
        data_filename: String pointing to the 3D photogram
        crop: Option to crop the 3D photogram if the image includes shoulders, etc.
            Image must be close cropped around the neck!
    '''
    #VTK xml reader
    if verbose:
        print('Placing craniofacial landmarks...')
    #run the inference
    landmarks = RunInference(image, crop=crop, crop_percentage = crop_percentage)
    return landmarks, image

def ComputeHSAandRiskScore(image, landmarks, age, sex, verbose = True):
    '''
    Inputs:
        image: vtk polydata of the 3D photogram
        landmarks: landmarks generated by PlaceLandmarks
        age: age of patient in days
        sex: 0 for female, 1 for male
    '''
    #now, compute the HSA index and risk score!
    if verbose:
        print('Aligning image to template...')
    output_mesh, transform = AlignPatientToTemplate(image, landmarks)
    if verbose:
        print('Generating spherical image...')
    spherical_image = GenerateSphericalMapOfData(output_mesh, transform)
    if verbose:
        print('Computing risk score and HSA index...')
    riskScore, HSA_index = ComputeFromSphericalImage(spherical_image, age, sex)
    return riskScore, HSA_index

def ValidVTP(param):
    _, ext = path.splitext(param)
    if (ext.lower() not in ('.vtp','.obj','.vtk')) or not (path.isfile(param)):
        raise argparse.ArgumentTypeError('File must be a valid VTK PolyData file (.vtp) or OBJ file (.obj)')
    return param

def ConstructArguments():
    parser = argparse.ArgumentParser(description='Process 3D photogram')
    ## Required arguments
    parser.add_argument('--input_filename', metavar = 'input_filename', required = True, type = ValidVTP,
        help='Input data path')

    parser.add_argument('--age', required = True, type = float, metavar = 'age',
        help='Age of the patient in days.')

    parser.add_argument('--sex', required = True, type = str, metavar = 'sex', choices = ['M','F'],
        help='Sex of the patient (F is female, M is male).')

    parser.add_argument('--verbose', action='store_true', help='Print out information during the processing steps.' )

    parser.add_argument('--crop_image',action='store_true', help = 'Option to crop the data to ensure the shoulders are not included in the photogram.')
    parser.add_argument('--crop_percentage',action = 'store',default=0.4, type = float,
                        help = 'Percentage of the image to crop out. Adjust this parameter between 0-1 to control cropping amount.')
    return parser

def ParseArguments():
    parser = ConstructArguments()
    return parser.parse_args()

if __name__ == "__main__":
    #parse the arguments, python automatically takes the system args
    args = ParseArguments()
    #first, let's start with the landmarks
    image = ReadImage(args.input_filename)
    landmarks, image = PlaceLandmarks(image, crop=args.crop_image, verbose=args.verbose, crop_percentage = args.crop_percentage)
    #now the metrics!
    riskScore, HSA_index = ComputeHSAandRiskScore(image, landmarks, args.age, args.sex, verbose=args.verbose)
    print(f'Results calculated from the image: {args.input_filename}\n\tCraniosynostosis Risk Score: {riskScore:0.2f}%\n\tHead Shape Anomaly Index: {HSA_index:0.2f}')


from django import forms
from .models import Post,Category

#adding category manually
#but we want to
#choices = [('coding','coding'),('sports','sports'),('entertainment',	'entertainment')]

# call it from our database
choices=Category.objects.all().values_list('name','name')

choices_list = []

for items in choices:
   choices_list.append(items)

#class for posting our "posts"
class PostForm(forms.ModelForm):
   class Meta:
      model = Post
      fields = ('title','title_page','author','category','body','snippet','headr_images')

      title_style ={
         'class': 'form-control',
         'placeholder': "Type title",

      }
      title_page_style ={
         'class': 'form-control',
         'placeholder': "Type Title Page"
      }
      author_style ={
         'class': 'form-control',
         'value':'',
         'id':'author_filed',
         'type':'hidden'

      }

      body_style={
         'class': 'form-control',
         'placeholder': "type here full post.."
      }

      category_style={
         'class': 'form-control',
         'placeholder': "Select category"
      }
      snippet_style = {
         'class': 'form-control',
         'placeholder': "write sort snippet of your post !"
      }

      widgets={
         'title':forms.TextInput(attrs=title_style),
         'title_page':forms.TextInput(attrs=title_page_style),
         'author': forms.TextInput(attrs=author_style),
         #'author':forms.Select(attrs=author_style),
         'category': forms.Select(choices=choices_list,attrs=category_style),
         'body':forms.Textarea(attrs=body_style),
         'snippet': forms.Textarea(attrs=snippet_style)
      }

class PostFormUpdate(forms.ModelForm):
   class Meta:
      model = Post
      fields = ('title','title_page','body','snippet')

      title_style ={
         'class': 'form-control'
      }
      title_page_style ={
         'class': 'form-control'
      }

      body_style={
         'class': 'form-control'
      }

      snippet_style = {
         'class': 'form-control',
         'placeholder': "write sort snippet of your post !"
      }

      widgets={
         'title':forms.TextInput(attrs=title_style),
         'title_page':forms.TextInput(attrs=title_page_style),
         'body':forms.Textarea(attrs=body_style),
         'snippet': forms.Textarea(attrs=snippet_style)
      }


import functools
import operator

import flax
from flax import nn
from flax import optim
import jax
from jax import lax
from jax import random
import jax.numpy as jnp

@flax.struct.dataclass
class TrainState:
  step: int
  optimizer: optim.Optimizer
  model_state: nn.Collection

class MLP(nn.Module):
  """A simple MLP."""

  def apply(self,
            x,
            condition=None,
            net_depth=8,
            net_width=256,
            net_depth_condition=1,
            net_width_condition=128,
            activation=nn.relu,
            skip_layer=4,
            alpha_channel=1,
            rgb_channel=3):
    """Multi-layer perception for nerf.

    Args:
      x: jnp.ndarray(float32), [batch, n_samples, feature], points.
      condition: jnp.ndarray(float32), [batch, feature], if not None, this
        variable will be part of the input to the second part of the MLP
        concatenated with the output vector of the first part of the MLP. If
        None, only the first part of the MLP will be used with input x. In the
        original paper, this variable is the view direction.
      net_depth: int, the depth of the first part of MLP.
      net_width: int, the width of the first part of MLP.
      net_depth_condition: int, the depth of the second part of MLP.
      net_width_condition: int, the width of the second part of MLP.
      activation: function, the activation function used in the MLP.
      skip_layer: int, add a skip connection to the output vector of every
        skip_layer layers.
      alpha_channel: int, the number of alpha_channels.
      rgb_channel: int, the number of rgb_channels.

    Returns:
      raw: jnp.ndarray(float32), [batch, n_samples, rgb_channel+alpha_channel].
    """
    feature_dim = x.shape[-1]
    n_samples = x.shape[1]
    x = x.reshape([-1, feature_dim])
    dense_layer = functools.partial(
        nn.Dense, kernel_init=jax.nn.initializers.glorot_uniform())

    inputs = x
    for i in range(net_depth):
      x = dense_layer(x, net_width)
      x = activation(x)
      if i % skip_layer == 0 and i > 0:
        x = jnp.concatenate([x, inputs], axis=-1)
    sigma = dense_layer(x, alpha_channel)
    if condition is not None:
      # Output of the first part of MLP.
      bottleneck = dense_layer(x, net_width)
      # Broadcast condition from [batch, feature] to
      # [batch, n_samples, feature] since all the samples along the same ray
      # has the same viewdir.
      condition = jnp.tile(condition[:, None, :], (1, n_samples, 1))
      # Collapse the [batch, n_samples, feature] tensor to
      # [batch * n_samples, feature] so that it can be feed into nn.Dense.
      condition = condition.reshape([-1, condition.shape[-1]])
      x = jnp.concatenate([bottleneck, condition], axis=-1)
      # Here use 1 extra layer to align with the original nerf model.
      for i in range(net_depth_condition):
        x = dense_layer(x, net_width_condition)
        x = activation(x)
    rgb = dense_layer(x, rgb_channel)
    return (jnp.concatenate([rgb, sigma], axis=-1).reshape(
        [-1, n_samples, rgb_channel + alpha_channel]))

def sample_along_rays(key, rays, n_samples, near, far, randomized, lindisp):
  """Stratified sampling along the rays.

  Args:
    key: jnp.ndarray, random generator key.
    rays: jnp.ndarray(float32), [batch_size, 6].
    n_samples: int.
    near: float, near clip.
    far: float, far clip.
    randomized: bool, use randomized stratified sampling.
    lindisp: bool, sampling linearly in disparity rather than depth.

  Returns:
    z_vals: jnp.ndarray, [batch_size, n_samples], sampled z values.
    points: jnp.ndarray, [batch_size, n_samples, 3], sampled points.
  """
  origins = rays[Ellipsis, 0:3]
  directions = rays[Ellipsis, 3:6]
  batch_size = origins.shape[0]

  t_vals = jnp.linspace(0., 1., n_samples)
  if not lindisp:
    z_vals = near * (1. - t_vals) + far * t_vals
  else:
    z_vals = 1. / (1. / near * (1. - t_vals) + 1. / far * t_vals)
  if randomized:
    mids = .5 * (z_vals[Ellipsis, 1:] + z_vals[Ellipsis, :-1])
    upper = jnp.concatenate([mids, z_vals[Ellipsis, -1:]], -1)
    lower = jnp.concatenate([z_vals[Ellipsis, :1], mids], -1)
    t_rand = random.uniform(key, [batch_size, n_samples])
    z_vals = lower + (upper - lower) * t_rand
  else:
    # Broadcast z_vals to make the returned shape consistent.
    z_vals = jnp.broadcast_to(z_vals[None, Ellipsis], [batch_size, n_samples])

  return (z_vals, (origins[Ellipsis, None, :] +
                   z_vals[Ellipsis, :, None] * directions[Ellipsis, None, :]))

def posenc(x, deg):
  """Positional Encoding.

  Args:
    x: jnp.ndarray, variables to be encoded. Note that x should be in [-pi, pi].
    deg: int the degree of encoding.

  Returns:
    encoded: jnp.ndarray, encoded variables.
  """
  if deg == 0:
    return x
  # Vectorize the computation of the high-frequency (sin, cos) terms.
  # We use the trigonometric identity: cos(x) = sin(x + pi/2)
  cos_to_sin_shift = jnp.pi / 2
  pre_sin_terms = functools.reduce(
      operator.iconcat,
      [[2**i * x, 2**i * x + cos_to_sin_shift] for i in range(deg)], [])
  pre_sin_array = jnp.concatenate(pre_sin_terms, axis=-1)
  encoded = jnp.concatenate([x] + [jnp.sin(pre_sin_array)], axis=-1)
  return encoded

def volumetric_rendering(raw, z_vals, dirs, white_bkgd):
  """Volumetric Rendering Function.

  Args:
    raw: jnp.ndarray(float32), [batch_size, n_samples, 4].
    z_vals: jnp.ndarray(float32), [batch_size, n_samples].
    dirs: jnp.ndarray(float32), [batch_size, 3].
    white_bkgd: bool.

  Returns:
    rgb: jnp.ndarray(float32), [batch_size, 3].
    disp: jnp.ndarray(float32), [batch_size].
    acc: jnp.ndarray(float32), [batch_size].
    weights: jnp.ndarray(float32), [batch_size, n_samples]
  """
  eps = 1e-10
  rgb = nn.sigmoid(raw[Ellipsis, :3])
  sigma = nn.relu(raw[Ellipsis, 3])
  dists = jnp.concatenate([
      z_vals[Ellipsis, 1:] - z_vals[Ellipsis, :-1],
      jnp.broadcast_to([1e10], z_vals[Ellipsis, :1].shape)
  ], -1)
  dists = dists * jnp.linalg.norm(dirs[Ellipsis, None, :], axis=-1)
  alpha = 1.0 - jnp.exp(-sigma * dists)
  accum_prod = jnp.concatenate([
      jnp.full_like(alpha[Ellipsis, :1], 1., alpha.dtype),
      jnp.cumprod(1.0 - alpha[Ellipsis, :-1] + eps, axis=-1)
  ],
                               axis=-1)
  weights = alpha * accum_prod

  rgb = (weights[Ellipsis, None] * rgb).sum(axis=-2)
  depth = (weights * z_vals).sum(axis=-1)
  sum_weights = weights.sum(axis=-1)
  disp = 1. / jnp.maximum(eps,
                          jnp.where(sum_weights > eps, depth / sum_weights, 0.))
  acc = weights.sum(axis=-1)
  if white_bkgd:
    rgb = rgb + (1. - acc[Ellipsis, None])
  return rgb, disp, acc, weights

def piecewise_constant_pdf(key, bins, weights, n_samples, randomized):
  """Piecewise-Constant PDF sampling.

  Args:
    key: jnp.ndarray(float32), [2,], random number generator.
    bins: jnp.ndarray(float32), [batch_size, n_bins + 1].
    weights: jnp.ndarray(float32), [batch_size, n_bins].
    n_samples: int, the number of samples.
    randomized: bool, use randomized samples.

  Returns:
    z_samples: jnp.ndarray(float32), [batch_size, n_samples].
  """
  eps = 1e-5

  # Get pdf
  weights += eps  # prevent nans
  pdf = weights / weights.sum(axis=-1, keepdims=True)
  cdf = jnp.cumsum(pdf, axis=-1)
  cdf = jnp.concatenate([jnp.zeros(list(cdf.shape[:-1]) + [1]), cdf], axis=-1)

  # Take uniform samples
  if randomized:
    u = random.uniform(key, list(cdf.shape[:-1]) + [n_samples])
  else:
    u = jnp.linspace(0., 1., n_samples)
    u = jnp.broadcast_to(u, list(cdf.shape[:-1]) + [n_samples])

  # Invert CDF. This takes advantage of the fact that `bins` is sorted.
  mask = (u[Ellipsis, None, :] >= cdf[Ellipsis, :, None])

  def minmax(x):
    x0 = jnp.max(jnp.where(mask, x[Ellipsis, None], x[Ellipsis, :1, None]), -2)
    x1 = jnp.min(jnp.where(~mask, x[Ellipsis, None], x[Ellipsis, -1:, None]), -2)
    x0 = jnp.minimum(x0, x[Ellipsis, -2:-1])
    x1 = jnp.maximum(x1, x[Ellipsis, 1:2])
    return x0, x1

  bins_g0, bins_g1 = minmax(bins)
  cdf_g0, cdf_g1 = minmax(cdf)

  denom = (cdf_g1 - cdf_g0)
  denom = jnp.where(denom < eps, 1., denom)
  t = (u - cdf_g0) / denom
  z_samples = bins_g0 + t * (bins_g1 - bins_g0)

  # Prevent gradient from backprop-ing through samples
  return lax.stop_gradient(z_samples)

def sample_pdf(key, bins, weights, rays, z_vals, n_samples, randomized):
  """Hierarchical sampling.

  Args:
    key: jnp.ndarray(float32), [2,], random number generator.
    bins: jnp.ndarray(float32), [batch_size, n_bins + 1].
    weights: jnp.ndarray(float32), [batch_size, n_bins].
    rays: jnp.ndarray(float32), [batch_size, 6].
    z_vals: jnp.ndarray(float32), [batch_size, n_coarse_samples].
    n_samples: int, the number of samples.
    randomized: bool, use randomized samples.

  Returns:
    z_vals: jnp.ndarray(float32),
      [batch_size, n_coarse_samples + n_fine_samples].
    points: jnp.ndarray(float32),
      [batch_size, n_coarse_samples + n_fine_samples, 3].
  """
  z_samples = piecewise_constant_pdf(key, bins, weights, n_samples, randomized)
  origins = rays[Ellipsis, 0:3]
  directions = rays[Ellipsis, 3:6]
  # Compute united z_vals and sample points
  z_vals = jnp.sort(jnp.concatenate([z_vals, z_samples], axis=-1), axis=-1)
  return z_vals, (
      origins[Ellipsis, None, :] + z_vals[Ellipsis, None] * directions[Ellipsis, None, :])

def noise_regularize(key, raw, noise_std, randomized):
  """Regularize the density prediction by adding gaussian noise.

  Args:
    key: jnp.ndarray(float32), [2,], random number generator.
    raw: jnp.ndarray(float32), [batch_size, n_samples, 4].
    noise_std: float, std dev of noise added to regularize sigma output.
    randomized: bool, add noises if randomized is True.

  Returns:
    raw: jnp.ndarray(float32), [batch_size, n_samples, 4], updated raw.
  """
  if (noise_std is not None) and randomized:
    unused_key, key = random.split(key)
    noise = random.normal(key, raw[Ellipsis, 3:4].shape, dtype=raw.dtype) * noise_std
    raw = jnp.concatenate([raw[Ellipsis, :3], raw[Ellipsis, 3:4] + noise], axis=-1)
  return raw


'''
Логические операции
>, >=, <, <=, ==, !=
not, and, or - не путать с &, |, ^
is, is not, in, not in
gen
'''

'''
a = 1 < 4 and 5 > 2
print(a)
'''

'''
func = 1
T = 4
x = 2
print(func<T>(x))
'''

'''
f = 1 > 2 or 4 < 6

print(f)
'''

f = [1, 2, 3, 4]
# print(f)
# print(2 in f)
is_odd = not f[0] % 2
print(is_odd)


class Field():
    def __init__(self, block_width, block_height, screen_width, screen_height):
        self.block_width = block_width
        self.block_height = block_height
        self.screen_width = screen_width
        self.screen_height = screen_height
        self.field_dict = []
        self.calculate_blocks(screen_width, screen_height)
        self.get_block_coords()

    def calculate_blocks(self, screen_width, screen_height):
        self.columns = int(screen_width / self.block_width)
        self.rows = int(screen_height / self.block_height)

    def get_block_coords(self):
        for x in range(self.columns):
            self.field_dict.append([])
            for y in range(self.rows):
                self.field_dict[x].append([])
                x1 = self.block_width * y
                x2 = x1 + self.block_width
                y1 = self.block_height * x
                y2 = y1 + self.block_height
                self.field_dict[x][y] = {'x1' : x1, 'y1' : y1, 'x2' : x2, 'y2' : y2, 'block' : 0}


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

import os
import re
import stat
import sys

from gslib.exception import CommandException
from gslib.exception import InvalidUrlError
from gslib.utils import system_util
from gslib.utils import text_util

# Matches provider strings of the form 'gs://'
PROVIDER_REGEX = re.compile(r'(?P<provider>[^:]*)://$')
# Matches bucket strings of the form 'gs://bucket'
BUCKET_REGEX = re.compile(r'(?P<provider>[^:]*)://(?P<bucket>[^/]*)/{0,1}$')
# Matches object strings of the form 'gs://bucket/obj'
OBJECT_REGEX = re.compile(
    r'(?P<provider>[^:]*)://(?P<bucket>[^/]*)/(?P<object>.*)')
# Matches versioned object strings of the form 'gs://bucket/obj#1234'
GS_GENERATION_REGEX = re.compile(r'(?P<object>.+)#(?P<generation>[0-9]+)$')
# Matches versioned object strings of the form 's3://bucket/obj#NULL'
S3_VERSION_REGEX = re.compile(r'(?P<object>.+)#(?P<version_id>.+)$')
# Matches file strings of the form 'file://dir/filename'
FILE_OBJECT_REGEX = re.compile(r'([^:]*://)(?P<filepath>.*)')
# Regex to determine if a string contains any wildcards.
WILDCARD_REGEX = re.compile(r'[*?\[\]]')

RELATIVE_PATH_SYMBOLS = frozenset(['.', '..'])

class StorageUrl(object):
  """Abstract base class for file and Cloud Storage URLs."""

  def Clone(self):
    raise NotImplementedError('Clone not overridden')

  def IsFileUrl(self):
    raise NotImplementedError('IsFileUrl not overridden')

  def IsCloudUrl(self):
    raise NotImplementedError('IsCloudUrl not overridden')

  def IsStream():
    raise NotImplementedError('IsStream not overridden')

  def IsFifo(self):
    raise NotImplementedError('IsFifo not overridden')

  def CreatePrefixUrl(self, wildcard_suffix=None):
    """Returns a prefix of this URL that can be used for iterating.

    Args:
      wildcard_suffix: If supplied, this wildcard suffix will be appended to the
                       prefix with a trailing slash before being returned.

    Returns:
      A prefix of this URL that can be used for iterating.

    If this URL contains a trailing slash, it will be stripped to create the
    prefix. This helps avoid infinite looping when prefixes are iterated, but
    preserves other slashes so that objects with '/' in the name are handled
    properly.

    For example, when recursively listing a bucket with the following contents:
      gs://bucket// <-- object named slash
      gs://bucket//one-dir-deep
    a top-level expansion with '/' as a delimiter will result in the following
    URL strings:
      'gs://bucket//' : OBJECT
      'gs://bucket//' : PREFIX
    If we right-strip all slashes from the prefix entry and add a wildcard
    suffix, we will get 'gs://bucket/*' which will produce identical results
    (and infinitely recurse).

    Example return values:
      ('gs://bucket/subdir/', '*') becomes 'gs://bucket/subdir/*'
      ('gs://bucket/', '*') becomes 'gs://bucket/*'
      ('gs://bucket/', None) becomes 'gs://bucket'
      ('gs://bucket/subdir//', '*') becomes 'gs://bucket/subdir//*'
      ('gs://bucket/subdir///', '**') becomes 'gs://bucket/subdir///**'
      ('gs://bucket/subdir/', '*') where 'subdir/' is an object becomes
           'gs://bucket/subdir/*', but iterating on this will return 'subdir/'
           as a BucketListingObject, so we will not recurse on it as a subdir
           during listing.
    """
    raise NotImplementedError('CreatePrefixUrl not overridden')

  def _WarnIfUnsupportedDoubleWildcard(self):
    """Warn if ** use may lead to undefined results."""
    # Accepted 'url_string' values with '**', where '^' = start, and '$' = end.
    # - ^**$
    # - ^**/
    # - /**$
    # - /**/
    if not self.object_name:
      return
    delimiter_bounded_url = self.delim + self.object_name + self.delim
    split_url = delimiter_bounded_url.split(
        '{delim}**{delim}'.format(delim=self.delim))
    removed_correct_double_wildcards_url_string = ''.join(split_url)
    if '**' in removed_correct_double_wildcards_url_string:
      # Found a center '**' not in the format '/**/'.
      # Not using logger.warning b/c it's too much overhead to pass the logger
      # object to every StorageUrl.
      sys.stderr.write(
          '** behavior is undefined if directly preceeded or followed by'
          ' with characters other than / in the cloud and {} locally.'.format(
              os.sep))

  @property
  def url_string(self):
    raise NotImplementedError('url_string not overridden')

  @property
  def versionless_url_string(self):
    raise NotImplementedError('versionless_url_string not overridden')

  def __eq__(self, other):
    return isinstance(other, StorageUrl) and self.url_string == other.url_string

  def __hash__(self):
    return hash(self.url_string)

class _FileUrl(StorageUrl):
  """File URL class providing parsing and convenience methods.

    This class assists with usage and manipulation of an
    (optionally wildcarded) file URL string.  Depending on the string
    contents, this class represents one or more directories or files.

    For File URLs, scheme is always file, bucket_name is always blank,
    and object_name contains the file/directory path.
  """

  def __init__(self, url_string, is_stream=False, is_fifo=False):
    self.scheme = 'file'
    self.delim = os.sep
    self.bucket_name = ''
    # If given a URI that starts with "<scheme>://", the object name should not
    # include that prefix.
    match = FILE_OBJECT_REGEX.match(url_string)
    if match and match.lastindex == 2:
      self.object_name = match.group(2)
    else:
      self.object_name = url_string
    # On Windows, the pathname component separator is "\" instead of "/". If we
    # find an occurrence of "/", replace it with "\" so that other logic can
    # rely on being able to split pathname components on `os.sep`.
    if system_util.IS_WINDOWS:
      self.object_name = self.object_name.replace('/', '\\')
    self.generation = None
    self.is_stream = is_stream
    self.is_fifo = is_fifo

    self._WarnIfUnsupportedDoubleWildcard()

  def Clone(self):
    return _FileUrl(self.url_string)

  def IsFileUrl(self):
    return True

  def IsCloudUrl(self):
    return False

  def IsStream(self):
    return self.is_stream

  def IsFifo(self):
    return self.is_fifo

  def IsDirectory(self):
    return (not self.IsStream() and not self.IsFifo() and
            os.path.isdir(self.object_name))

  def CreatePrefixUrl(self, wildcard_suffix=None):
    return self.url_string

  @property
  def url_string(self):
    return '%s://%s' % (self.scheme, self.object_name)

  @property
  def versionless_url_string(self):
    return self.url_string

  def __str__(self):
    return self.url_string

class _CloudUrl(StorageUrl):
  """Cloud URL class providing parsing and convenience methods.

    This class assists with usage and manipulation of an
    (optionally wildcarded) cloud URL string.  Depending on the string
    contents, this class represents a provider, bucket(s), or object(s).

    This class operates only on strings.  No cloud storage API calls are
    made from this class.
  """

  def __init__(self, url_string):
    self.scheme = None
    self.delim = '/'
    self.bucket_name = None
    self.object_name = None
    self.generation = None
    provider_match = PROVIDER_REGEX.match(url_string)
    bucket_match = BUCKET_REGEX.match(url_string)
    if provider_match:
      self.scheme = provider_match.group('provider')
    elif bucket_match:
      self.scheme = bucket_match.group('provider')
      self.bucket_name = bucket_match.group('bucket')
    else:
      object_match = OBJECT_REGEX.match(url_string)
      if object_match:
        self.scheme = object_match.group('provider')
        self.bucket_name = object_match.group('bucket')
        self.object_name = object_match.group('object')
        if self.object_name == '.' or self.object_name == '..':
          raise InvalidUrlError('%s is an invalid root-level object name' %
                                self.object_name)
        if self.scheme == 'gs':
          generation_match = GS_GENERATION_REGEX.match(self.object_name)
          if generation_match:
            self.object_name = generation_match.group('object')
            self.generation = generation_match.group('generation')
        elif self.scheme == 's3':
          version_match = S3_VERSION_REGEX.match(self.object_name)
          if version_match:
            self.object_name = version_match.group('object')
            self.generation = version_match.group('version_id')
      else:
        raise InvalidUrlError(
            'CloudUrl: URL string %s did not match URL regex' % url_string)

    if url_string[(len(self.scheme) + len('://')):].startswith(self.delim):
      raise InvalidUrlError(
          'Cloud URL scheme should be followed by colon and two slashes: "://".'
          ' Found: "{}"'.format(url_string))

    self._WarnIfUnsupportedDoubleWildcard()

  def Clone(self):
    return _CloudUrl(self.url_string)

  def IsFileUrl(self):
    return False

  def IsCloudUrl(self):
    return True

  def IsStream(self):
    raise NotImplementedError('IsStream not supported on CloudUrl')

  def IsFifo(self):
    raise NotImplementedError('IsFifo not supported on CloudUrl')

  def IsBucket(self):
    return bool(self.bucket_name and not self.object_name)

  def IsObject(self):
    return bool(self.bucket_name and self.object_name)

  def HasGeneration(self):
    return bool(self.generation)

  def IsProvider(self):
    return bool(self.scheme and not self.bucket_name)

  def CreatePrefixUrl(self, wildcard_suffix=None):
    prefix = StripOneSlash(self.versionless_url_string)
    if wildcard_suffix:
      prefix = '%s/%s' % (prefix, wildcard_suffix)
    return prefix

  @property
  def bucket_url_string(self):
    return '%s://%s/' % (self.scheme, self.bucket_name)

  @property
  def url_string(self):
    url_str = self.versionless_url_string
    if self.HasGeneration():
      url_str += '#%s' % self.generation
    return url_str

  @property
  def versionless_url_string(self):
    if self.IsProvider():
      return '%s://' % self.scheme
    elif self.IsBucket():
      return self.bucket_url_string
    return '%s://%s/%s' % (self.scheme, self.bucket_name, self.object_name)

  def __str__(self):
    return self.url_string

def GetSchemeFromUrlString(url_str):
  """Returns scheme component of a URL string."""

  end_scheme_idx = url_str.find('://')
  if end_scheme_idx == -1:
    # File is the default scheme.
    return 'file'
  else:
    return url_str[0:end_scheme_idx].lower()

def IsKnownUrlScheme(scheme_str):
  return scheme_str in ('file', 's3', 'gs')

def _GetPathFromUrlString(url_str):
  """Returns path component of a URL string."""

  end_scheme_idx = url_str.find('://')
  if end_scheme_idx == -1:
    return url_str
  else:
    return url_str[end_scheme_idx + 3:]

def ContainsWildcard(url_string):
  """Checks whether url_string contains a wildcard.

  Args:
    url_string: URL string to check.

  Returns:
    bool indicator.
  """
  return bool(WILDCARD_REGEX.search(url_string))

def GenerationFromUrlAndString(url, generation):
  """Decodes a generation from a StorageURL and a generation string.

  This is used to represent gs and s3 versioning.

  Args:
    url: StorageUrl representing the object.
    generation: Long or string representing the object's generation or
                version.

  Returns:
    Valid generation string for use in URLs.
  """
  if url.scheme == 's3' and generation:
    return text_util.DecodeLongAsString(generation)
  return generation

def HaveFileUrls(args_to_check):
  """Checks whether args_to_check contain any file URLs.

  Args:
    args_to_check: Command-line argument subset to check.

  Returns:
    True if args_to_check contains any file URLs.
  """
  for url_str in args_to_check:
    storage_url = StorageUrlFromString(url_str)
    if storage_url.IsFileUrl():
      return True
  return False

def HaveProviderUrls(args_to_check):
  """Checks whether args_to_check contains any provider URLs (like 'gs://').

  Args:
    args_to_check: Command-line argument subset to check.

  Returns:
    True if args_to_check contains any provider URLs.
  """
  for url_str in args_to_check:
    storage_url = StorageUrlFromString(url_str)
    if storage_url.IsCloudUrl() and storage_url.IsProvider():
      return True
  return False

def IsCloudSubdirPlaceholder(url, blr=None):
  """Determines if a StorageUrl is a cloud subdir placeholder.

  This function is needed because GUI tools (like the GCS cloud console) allow
  users to create empty "folders" by creating a placeholder object; and parts
  of gsutil need to treat those placeholder objects specially. For example,
  gsutil rsync needs to avoid downloading those objects because they can cause
  conflicts (see comments in rsync command for details).

  We currently detect two cases:
    - Cloud objects whose name ends with '_$folder$'
    - Cloud objects whose name ends with '/'

  Args:
    url: (gslib.storage_url.StorageUrl) The URL to be checked.
    blr: (gslib.BucketListingRef or None) The blr to check, or None if not
        available. If `blr` is None, size won't be checked.

  Returns:
    (bool) True if the URL is a cloud subdir placeholder, otherwise False.
  """
  if not url.IsCloudUrl():
    return False
  url_str = url.url_string
  if url_str.endswith('_$folder$'):
    return True
  if blr and blr.IsObject():
    size = blr.root_object.size
  else:
    size = 0
  return size == 0 and url_str.endswith('/')

def IsFileUrlString(url_str):
  """Returns whether a string is a file URL."""

  return GetSchemeFromUrlString(url_str) == 'file'

def StorageUrlFromString(url_str):
  """Static factory function for creating a StorageUrl from a string."""

  scheme = GetSchemeFromUrlString(url_str)

  if not IsKnownUrlScheme(scheme):
    raise InvalidUrlError('Unrecognized scheme "%s"' % scheme)
  if scheme == 'file':
    path = _GetPathFromUrlString(url_str)
    is_stream = (path == '-')
    is_fifo = False
    try:
      is_fifo = stat.S_ISFIFO(os.stat(path).st_mode)
    except OSError:
      pass
    return _FileUrl(url_str, is_stream=is_stream, is_fifo=is_fifo)
  return _CloudUrl(url_str)

def StripOneSlash(url_str):
  if url_str and url_str.endswith('/'):
    return url_str[:-1]
  return url_str

def UrlsAreForSingleProvider(url_args):
  """Tests whether the URLs are all for a single provider.

  Args:
    url_args: (Iterable[str]) Collection of strings to check.

  Returns:
    True if all URLs are for single provider; False if `url_args` was empty (as
    this would not result in a single unique provider) or URLs targeted multiple
    unique providers.
  """
  provider = None
  url = None
  for url_str in url_args:
    url = StorageUrlFromString(url_str)
    if not provider:
      provider = url.scheme
    elif url.scheme != provider:
      return False
  return provider is not None

def UrlsAreMixOfBucketsAndObjects(urls):
  """Tests whether the URLs are a mix of buckets and objects.

  Args:
    url_args: (Iterable[gslib.storage_url.StorageUrl]) Collection of URLs to
    check.

  Returns:
    True if URLs are a mix of buckets and objects. False if URLs are all buckets
    or all objects. None if invalid Cloud URLs are included.
  """
  if all(url.IsCloudUrl() for url in urls):
    are_buckets = list(map(lambda x: x.IsBucket(), urls))
    return any(are_buckets) and not all(are_buckets)

def RaiseErrorIfUrlsAreMixOfBucketsAndObjects(urls, recursion_requested):
  """Raises error if mix of buckets and objects adjusted for recursion."""
  if UrlsAreMixOfBucketsAndObjects(urls) and not recursion_requested:
    raise CommandException('Cannot operate on a mix of buckets and objects.')


import dash_core_components as dcc
import dash_bootstrap_components as dbc
import dash_html_components as html
from dash.dependencies import Input, Output

from datetime import datetime
import pandas as pd

from app import app
from components import range_slider as RangeSlider, default_card
from helpers import time_helper

df_clean = None

def layout(data):
    global df_clean
    df_clean = data

    return html.Div(children=[
        dbc.Alert("Overzicht totale omzet per product", color="info",
                  style={'text-align': 'center'}),
        dbc.Row([
            dbc.Col(
                html.Div(
                    dcc.Dropdown(id='product-select',
                                 placeholder="Op welk product wil je zoeken?",
                                 value='3852',
                                 options=[{'label': product_pair[1],
                                           'value': product_pair[0]} for
                                          product_pair in
                                          df_clean[['product_number',
                                                    'Artikel']].drop_duplicates().values.tolist()]),
                ), md=9),
            dbc.Col(
                html.Div([
                    dcc.Dropdown(id="product-rev-type", placeholder="Selecteer graph type", value="line",
                                 options=[{'label': "Lijndiagram", 'value': 'line'},
                                          {'label': "Staafdiagram", 'value': 'bar'}],
                                 style={'width': '15em', 'display': 'inline-block'}),
                ]), md=3),
        ]),
        dcc.DatePickerRange(id='product-rev-daterange',
                                        display_format='D-M-Y',
                                        start_date_placeholder_text="Vanaf",
                                        end_date_placeholder_text="Tot periode",
                                        initial_visible_month=datetime.today(),
                                        style={'display': 'inline-block',
                                               'margin-right': '1em', 'margin-top': '8px', 'margin-bottom': '8px'},
                                        clearable=True),
        default_card.showCard(
            dcc.Loading(id='loading-icon',
                        children=[dcc.Graph(id="revenue-product-graph",
                                            figure={'data': [{'x': df_clean.date, 'y': [420],
                                                              'type': 'bar',
                                                              'name': "Placeholder",
                                                              'hovertemplate': 'Product: %{x}, ' + '
Totale omzet: €%{y:,.2f}'}
                                                    ]})]
        ))
    ])

def get_product_rev_df(input_value, start_date, end_date):
    global df_clean

    product_rev_df = pd.DataFrame(
        df_clean.loc[df_clean['product_number'] == input_value]['omzet']
        .groupby(df_clean['date'].dt.date)
        .sum()
    )

    if start_date is not None and end_date is not None:
        product_rev_df = product_rev_df.loc[datetime.strptime(start_date, '%Y-%m-%d').date():datetime.strptime(end_date,
                                                                                '%Y-%m-%d').date()]

    return product_rev_df

@app.callback(Output('revenue-product-graph', 'figure'),
              [Input('product-select', 'value'),
               Input('product-rev-daterange', 'start_date'),
               Input('product-rev-daterange', 'end_date'),
               Input('product-rev-type', 'value')])
def update_product_rev_fig(input_value, start_date, end_date, chart_type):
    product_rev_df = get_product_rev_df(input_value, start_date, end_date)

    layout = {'title': "Omzet per product"}
    return {
        'data': [{
            'x': product_rev_df.index,
            'y': product_rev_df['omzet'],
            'type': chart_type,
            'hovertemplate': 'Totale omzet: €%{y:,.2f}'
        }],
        'layout': layout
    }


"""
    Testing reliability of the random function

    We will make a thousand executions of the random function in the interval 1 to 10 to verify the probability that a certain number will come out

"""
#
# IMPORT SECTION
#
import random

from MyFunc_ForTeacher import *
from Colors_ForTeacher import *

#
# ---------- COURSE EXCERCISE ----------
#

if __name__ == "__main__":
    print(f"\n{FR_GREEN}---------- main ----------{NO_COLOR}\n")
    pause()

    list=list(range(1,11))
    print(list)
    pause()
    my_value = random.choice(list)
    print(f"my_value:  {my_value}")
    i=1
    #print("my_value: " + my_value)
    while my_value != 5:
        i += 1
        my_value = random.choice(list)
        print(f"attempt {i}, value:  {my_value}")

    print(frGREEN(f"\nattempt {i} , my_value:  {my_value}\n"))

    # ------------------------------------------------
    #          SHOW VARS CHARACTERISTICS
    #------------------------------------------------
    yesss=True
    while yesss:
        _msg = "Do you want to see attributes for a specific VAR ? (Y,N): "
        answer=Y_N_2(_msg)
        if answer in ['Y','N']: yesss = False

    if answer == 'Y':
        # add question for name of var.....
        _what_var = str(input("What VAR ? "))
        try:
            _what_var
            _my_Obj_name = eval(_what_var)
            print(f"\n{FR_GREEN}---------- INFO FOR OBJECT '{_my_Obj_name}' ----------{NO_COLOR}\n")
            pause()
            # my objects functions
            mostrar(_my_Obj_name)

        except NameError:
            print(f"\n\t{FR_RED}---- Var '{_what_var}' doesn't exits ðŸ™„ðŸ™„  ----")
            print(f"\n{FR_GREEN}--------------- That's all for today ðŸ‘Œ ---------------{NO_COLOR}\n")

    else:
        print(f"\n{FR_GREEN}---------- That's all for today ðŸ‘Œ ----------{NO_COLOR}\n")

else:
    # something wrong
    print(f"\n{FR_RED}---- upsssssssss something is wrong ðŸ˜¢ðŸ˜¢  ---{NO_COLOR}\n")
    pause()


# coding:utf-8

from PyQt5.QtCore import QThread, pyqtSignal
from PyQt5.QtGui import QPixmap, QImage

from my_functions.gaussian_blur import getBlurPixmap

class BlurCoverThread(QThread):
    """ 磨砂专辑封面线程 """
    blurDone = pyqtSignal(QPixmap)

    def __init__(self, parent=None):
        super().__init__(parent)
        # 设置磨砂标志位
        self.albumCoverPath = ''
        self.blurPixmap = None
        self.blurRadius = 6
        self.bluredPicMaxSize = (450, 450)

    def __blurAlbumCover(self):
        """ 得到磨砂后的pixmap """
        self.blurPixmap = getBlurPixmap(
            self.albumCoverPath, self.blurRadius, 0.8, self.bluredPicMaxSize)

    def run(self):
        """ 开始磨砂 """
        if self.albumCoverPath:
            self.__blurAlbumCover()
            self.blurDone.emit(self.blurPixmap)

    def setTargetCover(self, albumCoverPath, blurRadius=6, bluredPicMaxSize=(450, 450)):
        """ 设置磨砂的目标图片 """
        self.albumCoverPath = albumCoverPath
        self.blurRadius = blurRadius
        self.bluredPicMaxSize = bluredPicMaxSize


import calendar
import xlsxwriter

from testes_pablo.config import days, doctor
from testes_pablo.excel.format import text_tittle_style, tittles_style, period_style, data_title_rule, \
    merge_format_month_rule, merge_empty_line_rule, days_number_format_rule, days_number_bg_rule, image_tittle_style
from testes_pablo.excel.functions import collaborator_write

workbook = xlsxwriter.Workbook('hello.xlsx')
worksheet1 = workbook.add_worksheet()

worksheet1.set_landscape()
worksheet1.set_paper(9)
worksheet1.center_horizontally()

text_tittle = workbook.add_format(text_tittle_style)
titulos = workbook.add_format(tittles_style)
celula = workbook.add_format()
period = workbook.add_format(period_style)
# -
data_title = workbook.add_format(data_title_rule)
merge_format_month = workbook.add_format(merge_format_month_rule)
merge_empty_line = workbook.add_format(merge_empty_line_rule)
days_number_format = workbook.add_format(days_number_format_rule)
days_number_bg = workbook.add_format(days_number_bg_rule)

worksheet1.insert_image('A1', 'logos2.png', image_tittle_style)

worksheet1.merge_range('A1:A6', '')
worksheet1.merge_range('A7:A8', 'EQUIPE', titulos)
worksheet1.merge_range('B7:B8', 'HORÁRIO', titulos)
worksheet1.merge_range('B1:AG6', '')

worksheet1.set_column('A:A', 74)
worksheet1.set_column('B:B', 18.30)
worksheet1.set_column('C1:AG1', 4.4)

worksheet1.set_row(0, 12.62)
worksheet1.set_row(1, 12.62)
worksheet1.set_row(2, 12.62)
worksheet1.set_row(3, 12.62)
worksheet1.set_row(4, 12.62)
worksheet1.set_row(5, 12.62)
worksheet1.set_row(8, 15)

worksheet1.write_string('B1',
                        'ESCALA MÉDICA CENTRO CIRÚRGICO\n HOSPITAL ESTADUAL DE PIRENÓPOLIS ERNESTINA LOPES JAIME\n JULHO / 2019',
                        text_tittle)

year = 2019
month = 7

monthRange = calendar.monthrange(year, month)

row_number_day = 7
col_number_day = 2
week_day = monthRange[0]
i = 0
row_number = 6
col_number = 2
month_days = 1

while i < monthRange[1]:
    # Cria a coluna onde fica os dias(1,2,3..)
    worksheet1.write(row_number, col_number, month_days, days_number_format)

    # Cria a coluna onde fica os dias da semana(S,D,Q...)
    if week_day == 5 or week_day == 6:

        worksheet1.write_column(row_number_day, col_number_day, str(days[week_day]), days_number_bg)
        worksheet1.set_column(col_number_day, col_number_day, 3, days_number_bg)
    else:
        worksheet1.write_column(row_number_day, col_number_day, str(days[week_day]), days_number_format)
        worksheet1.set_column(col_number_day, col_number_day, 3, days_number_format)

    week_day = week_day + 1
    if week_day > 6:
        week_day = 0

    i += 1
    col_number_day += 1
    col_number += 1
    month_days += 1

a = collaborator_write(9, 0, doctor, worksheet1, period, data_title, 'Diurno')
b = a + 1
c = collaborator_write(b, 0, doctor, worksheet1, period, data_title, 'Noturno')

worksheet1.set_default_row(hide_unused_rows=True)
worksheet1.set_column('AM:XFD', None, None, {'hidden': True})

workbook.close()


import rclpy
from rclpy.node import Node

from std_msgs.msg import String
from me134_interfaces.msg import SongMsg

import mido
import pianoman.utils.midi_helper as midi_helper

import time

names = mido.get_input_names()

RATE = 200.0 # Hz
SONGS_DIR = "/home/robot134/songs/"

notes_to_songs = {tuple(['E5', 'E5', 'F5']) : ("Beethhoven_edited.mid", 45),
                  tuple(['E4', 'E4', 'F4']) : ("Beethhoven_short.mid", 45),
                  tuple(['C6', 'C6', 'C6']) : ("kanye_lower.mid", 140),
                  tuple(['G4', 'D5', 'E5']) : ("lalalandTheme_edited.mid", 30),
                  tuple(['C4', 'C4', 'D4']) : ("leanOnMe.mid", 30),
                  tuple(['C4', 'F4', 'A4']) : ("amazingGrace.mid", 45),
                  tuple(['E4', 'G4', 'G4']) : ("hallelujah.mid", 35),
                  tuple(['D4', 'D4', 'D4']) : ("hotlineBling.mid", 30),
                  tuple(['E4', 'F#4', 'A#4']) : ("dancingQueen.mid", 35),
                  tuple(['F4', 'G4', 'C4']) : ("rickRoll.mid", 10),
                  tuple(['C4', 'C5', 'A4']) : ("ballgame.mid", 45),
                  tuple(['B4', 'B4', 'D5']) : ("bonJovi.mid", 35)
                  }

class PlaySongNode(Node):

    def __init__(self):
        super().__init__('play_song_node')

        self.pub = self.create_publisher(SongMsg, '/song_cmd', 30)
        self.note_pub = self.create_publisher(String, '/note', 30)

        self.last_three_notes = []
        simon_mode = False

        # msg = SongMsg()
        # msg.song_name = SONGS_DIR + "/lalalandTheme_edited.mid"
        # msg.bpm = 30
        # msg.simon_mode = False
        # self.pub.publish(msg)
        # return

        with mido.open_input(names[1]) as inport:
            for msg in inport:
                print(msg)
                if msg.type == 'control_change' and msg.channel == 0 and msg.control == 48:
                    simon_mode = msg.value == 127
                    m = SongMsg()
                    m.song_name = ""
                    m.bpm = 0
                    m.simon_mode = simon_mode
                    self.pub.publish(m)
                if msg.type == 'note_off':
                    # else:
                        print("piano note played")
                        note_string = midi_helper._midi_value_to_note(msg.note)

                        if len(self.last_three_notes) == 3:
                            self.last_three_notes.pop(0)
                        self.last_three_notes.append(note_string)

                        if tuple(self.last_three_notes) in notes_to_songs:
                            song, bpm = notes_to_songs[tuple(self.last_three_notes)]
                            song_name = song[:song.find('.')]

                            filename = SONGS_DIR + song
                            msg = SongMsg()
                            msg.song_name = filename
                            msg.bpm = bpm
                            msg.simon_mode = simon_mode
                            self.pub.publish(msg)

                            print(f"Playing {song_name}")

                        s = String()
                        s.data = note_string
                        self.note_pub.publish(s)

def main(args=None):
    # intialize ROS node.
    rclpy.init(args=args)
    node = PlaySongNode()

    rclpy.spin(node)

    # Destroy the node explicitly
    node.destroy_node()
    rclpy.shutdown()

if __name__ == '__main__':
    main()


import pygame
import os
from network import Network
from player import Player

pygame.font.init()
pygame.mixer.init()

WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
YELLOW = (255, 255, 0)

WIDTH, HEIGHT = 900, 500
MAX_BULLETS = 3
FPS = 60
WIN = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("First Game!")

SPACESHIP_WIDTH, SPACESHIP_HEIGHT = 55, 40
SPACE = pygame.transform.scale(pygame.image.load(
        os.path.join('Assets', 'space.png')), (WIDTH, HEIGHT))

WIDTH, HEIGHT = 900, 500
BORDER = pygame.Rect(WIDTH//2 - 5, 0, 10, HEIGHT)

#BULLET_HIT_SOUND = pygame.mixer.Sound('Assets/Grenade+1.mp3')
#BULLET_FIRE_SOUND = pygame.mixer.Sound('Assets/Gun+Silencer.mp3')

HEALTH_FONT = pygame.font.SysFont('comicsans', 40)
WINNER_FONT = pygame.font.SysFont('comicsans', 100)

players=[Player(SPACESHIP_WIDTH,SPACESHIP_HEIGHT,'spaceship_yellow.png',90,10,[],1,100,300,0),Player(SPACESHIP_WIDTH,SPACESHIP_HEIGHT,'spaceship_red.png',270,10,[],2,700,300,1)]

def read_pos(str):
    str = str.split(",")
    return int(str[0]), int(str[1]) ,int(str[2]),int(str[3]), int(str[4])

def make_pos(tup):
    return str(tup[0]) + "," + str(tup[1]) + "," + str(tup[2]) + "," + str(tup[3]) + "," + str(tup[4])

def bullets_read(str):
    str=str.split(",")
    return str

def bullets_make(tup):
    str_ans=""
    for i in range(len(tup)):
        str_ans+=str(tup[i]) + ","
    return str_ans

def main():
    clock = pygame.time.Clock()
    run = True
    n=Network()
    player_number=n.getP()
    player1=players[int(player_number)]
    player2=players[int(not int(player_number))]
    while run:
        clock.tick(FPS)
        if int(player_number)==0:
            p2Pos = read_pos(n.send(make_pos((player_number,player1.x, player1.y,player1.health,player2.health))))
        else:
            p2Pos = read_pos(n.send(make_pos((player_number,player1.x, player1.y,player2.health,player1.health))))

        player2.x = p2Pos[1]
        player2.y = p2Pos[2]
        if int(player_number)==0:
            player1.health=min(player1.health,p2Pos[3])
            player2.health=min(player2.health,p2Pos[4])
        else:
            player1.health=min(player1.health,p2Pos[4])
            player2.health=min(player2.health,p2Pos[3])
        player2.update()
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                run = False
                pygame.quit()
                exit()

            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_LCTRL and len(player1.bullets) < MAX_BULLETS:
                    if(not int(player_number)):
                        bullet = pygame.Rect(
                            player1.x + player1.width, player1.y + player1.height//2 - 2, 10, 5)
                    else:
                        bullet = pygame.Rect(
                            player1.x, player1.y + player1.height//2 - 2, 10, 5)
                    player1.bullets.append(bullet)
                    #BULLET_FIRE_SOUND.play()

            if event.type == player1.HIT:
                player2.health-=1
                #BULLET_HIT_SOUND.play()

        winner_text = ""
        if player1.health <= 0:
            if(not int(player_number)):
                winner_text = "Player 1 Wins!"
            else:
                winner_text = "Player 2 Wins!"

        if player2.health <= 0:
            if(not int(player_number)):
                winner_text = "Player 1 Wins!"
            else:
                winner_text = "Player 2 Wins!"

        if winner_text != "":
            player1.draw_window(SPACE,WIN,player2,player_number)
            Player.draw_winner(WIN,winner_text)
            return 1

        keys_pressed = pygame.key.get_pressed()
        player1.handle_bullets(player2)
        player1.handle_movement(keys_pressed)
        player1.draw_window(SPACE,WIN,player2,player_number)

main()


"""
URL configuration for src project.

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/4.2/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  path('', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
"""
from django.urls import path

from catdog.views import catdog_view, save_catdog, send_image_to_email, pet_filter
from school.views import all_groups_view, all_students_of_the_group

urlpatterns = [
    path('', catdog_view,
         name='catdog'),
    path('save_catdog123456', save_catdog,
         name='save_catdog'),
    path('send_mail', send_image_to_email,
         name='send_mail'),
    path('pet_filter', pet_filter,
         name='pet_filter'),
]


# function that initiates the line plot figure

from bokeh.models import FactorRange
from bokeh.plotting import figure
from Plot_Line_Scatter_ColumnDataSource import Johansson_CDS, Krug_CDS, Mertins_CDS

# function call
[johansson_cds, johansson_subtype_tumor_tuple, jo_unique_gene_list] = Johansson_CDS()
[krug_cds, krug_subtype_tumor_tuple, kr_unique_gene_list] = Krug_CDS()
[mertins_cds, mertins_subtype_tumor_tuple, me_unique_gene_list] = Mertins_CDS()

# dictionary key name
subtype_tuple = 'subtype, tumor'
subtype = 'subtype'
protein_data = 'protein_data'
mRNA_data = 'mRNA_data'
gene = 'gene'

# figure size and other constants
LINE_PLOT_WIDTH = 750
LINE_PLOT_HEIGHT = 125

def Johansson_Line_Plot():
    """Initializing the line plot"""
    jo_plot_p = figure(x_range=FactorRange(*johansson_subtype_tumor_tuple), title='', x_axis_label='',
                       y_axis_label='protein z-score', width=LINE_PLOT_WIDTH, height=LINE_PLOT_HEIGHT, output_backend="webgl")
    jo_plot_m = figure(x_range=FactorRange(*johansson_subtype_tumor_tuple), title='', x_axis_label='',
                       y_axis_label='mRNA z-score', width=LINE_PLOT_WIDTH, height=LINE_PLOT_HEIGHT, output_backend="webgl")

    return jo_plot_p, jo_plot_m

def Krug_Line_Plot():
    """Initializing the line plot"""
    kr_plot_p = figure(x_range=FactorRange(*krug_subtype_tumor_tuple), title='', x_axis_label='',
                       y_axis_label='protein z-score', width=LINE_PLOT_WIDTH, height=LINE_PLOT_HEIGHT, output_backend="webgl")
    kr_plot_m = figure(x_range=FactorRange(*krug_subtype_tumor_tuple), title='', x_axis_label='',
                       y_axis_label='mRNA z-score', width=LINE_PLOT_WIDTH, height=LINE_PLOT_HEIGHT, output_backend="webgl")

    return kr_plot_p, kr_plot_m

def Mertins_Line_Plot():
    """Initializing the line plot"""
    me_plot_p = figure(x_range=FactorRange(*mertins_subtype_tumor_tuple), title='', x_axis_label='',
                       y_axis_label='protein z-score', width=LINE_PLOT_WIDTH, height=LINE_PLOT_HEIGHT, output_backend="webgl")
    me_plot_m = figure(x_range=FactorRange(*mertins_subtype_tumor_tuple), title='', x_axis_label='',
                       y_axis_label='mRNA z-score', width=LINE_PLOT_WIDTH, height=LINE_PLOT_HEIGHT, output_backend="webgl")

    return me_plot_p, me_plot_m


#!/usr/bin/env python3

import os
import json
import textwrap

def indent(s, length=4):
    return '\n'.join([(' ' * length) + l for l in s.splitlines()])

def dedent(s):
    return textwrap.dedent(s)

def get_status(status_file):
    # Make sure the status directory exists.
    os.makedirs(os.path.dirname(status_file), exist_ok=True)

    # Make sure we have our status file.
    if not os.path.isfile(status_file):
        with open(status_file, 'w') as f:
            f.write('{}')

    with open(status_file, 'r') as f:
        return json.load(f)

def get_paths(build_postfix, **state):
    src_path = state['source']
    base_src = '{}{}'.format(os.path.basename(src_path), build_postfix)
    logs_path = os.path.join(state['logs_dir'], base_src)
    build_path = os.path.join(state['builds_dir'], base_src)
    status_path = os.path.join(state['status_dir'], '{}.json'.format(base_src))

    return src_path, base_src, logs_path, build_path, status_path

def update_status(status_file, args):
    status = get_status(status_file)
    status.update(args)

    with open(status_file, 'w') as f:
        json.dump(status, f, indent=4, separators=(',', ': '), sort_keys=True)

    return status

def is_sequence(item):
    if isinstance(item, (str, bytes)):
        return False
    elif not hasattr(item, "strip") and hasattr(item, "__getitem__") or hasattr(item, "__iter__"):
        return True
    else:
        return False

def parse_args(dict_args, **state):
    args = []

    for k, v in dict_args.items():
        if v is not None:
            if is_sequence(v):
                args = args + ['{}={}'.format(k, val).format(**state) for val in v]
            elif v is not True:
                args.append('{}={}'.format(k, v).format(**state))
            else:
                args.append(k)

    return args