#!/usr/bin/env python3
# Copyright (c) 2014 The Caroline authors. All rights reserved.
# Use of this source file is governed by a MIT license that can be found in the
# LICENSE file.
# Author: Aleksandr Derbenev <alex@technoworks.ru>

import json
from optparse import OptionParser
import os
import shutil
import random
import math

import bpy

class Bounds(object):
  def __init__(self, camera):
    self.angle_x = camera.angle_x
    self.angle_y = camera.angle_y
    self.angle = camera.angle
    self.clip_near = camera.clip_start
    self.clip_far = camera.clip_end

def random_mesh_origin(angle_x, angle_y, clip_near, clip_far):
  """Create random origin point for mesh. Assume that object will be visible if
     it's origin is in the truncated pyramid."""
  # Get z coordinate first because x and y ranges depends from it.
  z = random.uniform(clip_near + 2, clip_far - 2)
  x = random.uniform(-math.tan(angle_x / 2) * z,
      math.tan(angle_x / 2) * z / 2)
  y = random.uniform(-math.tan(angle_y / 2) * z,
      math.tan(angle_y / 2) * z / 2)
  return [x, y, -z]

def random_mesh_rotation():
  """Generate random angles for initial mesh rotation."""
  return [random.random(), random.random(), random.random()];

def random_mesh_constructor():
  """Returs lambda for creating a random mesh with given origin point and
     rotation."""
  def dimension(max_size):
    """Return random value for dimension."""
    return random.uniform(max_size / 10, max_size)

  return random.choice((
      lambda origin, rotation, max_size:
       bpy.ops.mesh.primitive_cone_add(radius1 = dimension(max_size) / 2,
           radius2 = dimension(max_size) / 2, depth = dimension(max_size),
           end_fill_type='TRIFAN',
           location=origin, rotation=rotation),
      lambda origin, rotation, max_size:
       bpy.ops.mesh.primitive_cube_add(radius = dimension(max_size) / 2,
           location = origin, rotation = rotation),
      lambda origin, rotation, max_size:
       bpy.ops.mesh.primitive_cylinder_add(radius = dimension(max_size) / 2,
           depth = dimension(max_size),
           location = origin, rotation = rotation),
      lambda origin, rotation, max_size:
       bpy.ops.mesh.primitive_ico_sphere_add(size = dimension(max_size) / 2,
           location = origin, rotation = rotation),
      lambda origin, rotation, max_size:
       bpy.ops.mesh.primitive_monkey_add(radius = dimension(max_size) / 2,
           location = origin, rotation = rotation),
      lambda origin, rotation, max_size:
       bpy.ops.mesh.primitive_plane_add(radius = dimension(max_size) / 2,
           location = origin, rotation = rotation),
      lambda origin, rotation, max_size:
       bpy.ops.mesh.primitive_torus_add(
           major_radius = random.uniform(max_size / 4, max_size) / 2,
           minor_radius = dimension(max_size / 5) / 2,
           location = origin, rotation = rotation),
      lambda origin, rotation, max_size:
       bpy.ops.mesh.primitive_uv_sphere_add(size = dimension(max_size) / 2,
           location = origin, rotation = rotation)
    ))

def override_context(options):
  """Copy bpy.context and replace some values by provided in dictionary."""
  context = bpy.context.copy()
  for key in options.keys():
    context[key] = options[key]
  return context

def parse_options():
  """Configure and run command line arguments parser."""
  parser = OptionParser()
  parser.add_option('-f', '--fixtures', dest = 'count', type = 'int',
      default = 1, action = 'store',
      help = 'Number of test fixtures to generate.')
  parser.add_option('-m', '--meshes', dest = 'meshes', type = 'int',
      default = 1, action = 'store',
      help = 'Maximum number of meshes in the scene.')
  parser.add_option('-o', '--output', dest = 'output', type = 'string',
      default = 'fixture', action = 'store',
      help = 'Name of the output directory. You can use %n for fixture number.'),
  parser.add_option('-d', '--distance', dest = 'distance', type = 'float',
      default = 0.08, action = 'store',
      help = 'Distantion between cameras in meters.')
  (options, args) = parser.parse_args()
  if options.count < 1:
    parser.error('Count of fixtures must be positive integer number.')
  if options.meshes < 1:
    parser.error('Maximum count of meshes must be positive integer number.')
  if options.count > 1 and '%n' not in options.output:
    options.output += '.%n'
  if options.distance <= 0:
    parser.error('Distance must be greater that 0.')
  options.output = options.output.replace('%n', '{number}')
  return (options, args);

def get_camera():
  camera = None
  for cam in bpy.data.cameras:
    if cam.name in bpy.context.scene.objects.keys():
      camera = cam
      break
  camera_object = bpy.data.objects[camera.name]
  return (camera, camera_object)

def cleanup_scene():
  """Cleanup current scene"""
  for item in bpy.data.meshes:
    if item.name in bpy.context.scene.objects.keys():
      bpy.context.scene.objects.unlink(bpy.data.objects[item.name])

def generate_mesh(bounds):
  """Count location and rotation for mesh, get and call constructor."""
  origin = random_mesh_origin(bounds.angle_x, bounds.angle_y,
      bounds.clip_near, bounds.clip_far)
  rotation = random_mesh_rotation()
  max_size = - origin[2] * math.tan(bounds.angle / 2)
  random_mesh_constructor()(origin=origin, rotation=rotation,
      max_size=max_size)

def generate_meshes(count, bounds):
  """Generate meshes on the scene."""
  for i in range(count):
    generate_mesh(bounds = bounds)

def setup_light(bounds):
  """Find and set lamp to the appropriate location."""
  lamp = bpy.data.lamps[0]
  if not lamp:
    lamp = bpy.data.lamps.new(name='lamp', type='SUN')
  lamp_object = bpy.data.objects[lamp.name]
  if lamp.name not in bpy.context.scene.objects:
    bpy.context.scene.objects.link(lamp_object)

  lamp_location = [
      0.0,
      math.tan(bounds.angle) * bounds.clip_far,
      -(bounds.clip_far - bounds.clip_near) / 2
    ]
  lamp.type = 'SUN'
  lamp_object.location = lamp_location
  lamp_object.rotation_mode = 'XYZ'
  lamp_object.rotation_euler = [0, - math.pi / 2, 0]

def prepare_dir(name):
  """Remove fixture directory if it exists. Create new one."""
  if os.path.exists(name):
    shutil.rmtree(name)

  os.mkdir(name)

def save_models(name):
  """Save each mesh to the Standford ply file. Return scene dictionary for
     config."""
  scene = {}
  for mesh in bpy.data.meshes:
    if mesh.name in bpy.context.scene.objects.keys():
      mesh_ply = mesh.name + '.ply'
      bpy.ops.export_mesh.ply(override_context({'selected_objects': mesh}),
          filepath=os.path.join(name, mesh_ply), check_existing=False,
          use_mesh_modifiers=False, use_normals=False, use_uv_coords=False,
          use_colors=False)
      scene[mesh.name] = mesh_ply
  return scene

def render_frames(name, distance, camera, camera_object, bounds):
  """Setup camera and render two frames."""
  cameras = []
  for i, location in enumerate([
    [-distance / 2, 0, 0],
    [distance / 2, 0, 0]
  ]):
    render = bpy.context.scene.render
    width = render.resolution_x
    height = render.resolution_y
    cam_name = 'camera_' + str(i)
    render.filepath = os.path.join(name, cam_name + '.png')
    camera_object.location = location
    camera_object.rotation_mode = 'XYZ'
    camera_object.rotation_euler = [0, 0, 0]
    bpy.ops.render.render(animation=False, write_still=True)
    cam = {
      'focus': camera.lens / 1000.0,
      'pixel_size': camera.sensor_width / width / 1000.0,
      'width': width,
      'height': height,
      'position': camera_object.location[:],
      'rotation': camera_object.rotation_euler[:],
      'type': 'image',
      'source': camera.name + '.png'
    }
    cameras.append(cam)
  return cameras

def save_config(name, config):
  """Generate config.json for given fixture."""
  config_file = open(os.path.join(name, 'config.json'), 'w')
  json.dump(config, config_file, skipkeys=True, ensure_ascii=False,
      allow_nan=False, indent=2, sort_keys=True)
  config_file.write('\n')

def save_fixture(name, distance, camera, camera_object, bounds):
  prepare_dir(name = name)

  config = {}
  config['scene'] = save_models(name = name)

  config['cameras'] = render_frames(name = name, distance = distance,
      camera = camera, camera_object = camera_object, bounds = bounds)

  save_config(name = name, config = config)

def generate_fixture(name, meshes, distance):
  """Generate and save a fixture."""

  name = os.path.normpath(name)

  (camera, camera_object) = get_camera()
  bounds = Bounds(camera)

  cleanup_scene()

  generate_meshes(count = meshes, bounds = bounds)
  setup_light(bounds = bounds)

  save_fixture(name = name, distance = distance, camera=camera,
      camera_object=camera_object, bounds=bounds)

def generate_fixtures(count, output, meshes, distance):
  """Generate all fixtures."""
  for i in range(count):
    generate_fixture(name = output.format(number = i),
        meshes = random.randrange(meshes) + 1, distance = distance)

def main():
  """Entry point."""
  (options, args) = parse_options()
  generate_fixtures(count = options.count, output = options.output,
      meshes = options.meshes, distance = options.distance)

if __name__ == '__main__':
  main()


from flask import Flask, render_template, Markup
import pandas as pd

path = 'F:/task4/'
data = pd.read_json(f'{path}movie-sessions-full.json', encoding = 'UTF-8')
data = data.values.tolist()

app = Flask('server')

@app.route('/')
def homepage():
    full_temp = ""
    for _3d, cinema_name, distance, film_name, image, price, rating, startTime in data:
        full_temp += f"""

{film_name}

{cinema_name}: {rating} баллов

Расстояние от девушки: {distance} км

    				"""
        full_temp += "
Снято в 3D!
" if _3d else ""
        full_temp += f"""
Время начала: {startTime}

Цена: {price}

            """

    full_temp = Markup(full_temp)

    return render_template('index.html', elements = full_temp)

app.run(host = '0.0.0.0')


"""
 Show how to use a sprite backed by a graphic.

 Sample Python/Pygame Programs
 Simpson College Computer Science
 http://programarcadegames.com/
 http://simpson.edu/computer-science/

 Explanation video: http://youtu.be/vRB_983kUMc
"""

import pygame

# Define some colors
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
GREEN = (0, 255, 0)
RED = (255, 0, 0)
BLUE = (0, 0, 255)
BROWN = (255, 64, 0)
SILVER = (192, 192, 192)

def christmas_tree_ball(screen, x = 0, y = 0, size=5):
    pygame.draw.circle(screen, SILVER, (x, y), size)

def christmas_tree(screen, x=0, y=0):
    pygame.draw.rect(screen, BROWN, (40 + x, 30 + y, 20, 100))
    pygame.draw.polygon(screen, GREEN, [(0 + x, 110 + y), (100 + x, 110 + y), (50 + x, 50 + y)])
    pygame.draw.polygon(screen, GREEN, [(10 + x, 80 + y), (90 + x, 80 + y), (50 + x, 30 + y)])
    pygame.draw.polygon(screen, GREEN, [(20 + x, 50 + y), (80 + x, 50 + y), (50 + x, 0 + y)])
    christmas_tree_ball(screen, 30 + x, 70 + y)
    christmas_tree_ball(screen, 50 + x, 60 + y)
    christmas_tree_ball(screen, 58 + x, 25 + y)
    christmas_tree_ball(screen, 40 + x, 100 + y)
    christmas_tree_ball(screen, 80 + x, 75 + y)

def dog(screen, x=0, y=0):
    # The dogs body
    pygame.draw.rect(screen, BROWN, (30 + x, 20 + y, 70, 30))
    # The dogs head
    pygame.draw.rect(screen, BROWN, (10 + x, 10 + y, 20, 20))
    # The dogs legs
    pygame.draw.rect(screen, BROWN, (40 + x, 50 + y, 10, 30))
    pygame.draw.rect(screen, BROWN, (80 + x, 50 + y, 10, 30))
    # The dogs tail
    pygame.draw.polygon(screen, BROWN, [(100 + x, 20 + y), (100 + x, 25 + y), (130 + x, 5 + y), (130 + x, 0 + y)])
    # The dogs ears
    pygame.draw.polygon(screen, BROWN, [(17 + x, 10 + y), (27 + x, 10 + y), (22 + x, 0 + y)])
    # The dogs snout
    pygame.draw.rect(screen, BROWN, (0 + x, 20 + y, 15, 7))
    # The dogs eyes
    pygame.draw.circle(screen, BLACK, (22 + x, 15 + y), 5)
    pygame.draw.circle(screen, BLUE, (21 + x, 16 + y), 3)

pygame.init()

# Set the width and height of the screen [width, height]
size = (700, 500)
screen = pygame.display.set_mode(size)

pygame.display.set_caption("My Game")

# Loop until the user clicks the close button.
done = False

# Used to manage how fast the screen updates
clock = pygame.time.Clock()

# Game Controller
# Current position
x_coord = 10
y_coord = 10

# Count the joysticks the computer has
joystick_count = pygame.joystick.get_count()
if joystick_count == 0:
    # No joysticks!
    print("Error, I didn't find any joysticks!")
else:
    # Use joystick #0 and initialise it.
    my_joystick = pygame.joystick.Joystick(0)
    my_joystick.init()

# -------- Main Program Loop -----------
while not done:
    # --- Main event loop
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            done = True

    # --- Game logic should go here
    pos = pygame.mouse.get_pos()
    mouse_x = pos[0]
    mouse_y = pos[1]

    button_clicked = pygame.MOUSEBUTTONDOWN

    # As long as there is a joystick:
    if joystick_count != 0:
        # This gets the position of the axis on the game controller.
        # It returns a number between -1.0 and +1.0
        horiz_axis_pos = my_joystick.get_axis(2)
        vert_axis_pos = my_joystick.get_axis(3)

        # Move x according to the axis. We multiply by 10 to speed up the movement.
        # Convert to an integer because we can't draw at pixel 3.5, just 3 or 4.
        if x_coord < 565 and x_coord > 0:
            x_coord = x_coord + int(horiz_axis_pos * 10)
        elif x_coord >=565 and horiz_axis_pos <= 0:
            x_coord = x_coord + int(horiz_axis_pos * 10)
        elif x_coord <= 0 and horiz_axis_pos >= 0:
            x_coord = x_coord + int(horiz_axis_pos * 10)
        if y_coord <= 420 and y_coord > 0:
            y_coord = y_coord + int(vert_axis_pos * 10)
        elif y_coord >= 420 and vert_axis_pos <= 0:
            y_coord = y_coord + int(vert_axis_pos * 10)
        elif y_coord <= 0 and vert_axis_pos >= 0:
            y_coord = y_coord + int(vert_axis_pos * 10)

    # --- Drawing code should go here

    # First, clear the screen to white. Don't put other drawing commands
    # above this, or they will be erased with this command.
    screen.fill(WHITE)
    christmas_tree(screen, mouse_x, mouse_y)
    dog(screen, x_coord, y_coord)

    # --- Go ahead and update the screen with what we've drawn.
    pygame.display.flip()

    # --- Limit to 60 frames per second
    clock.tick(60)

# Close the window and quit.
# If you forget this line, the program will 'hang'
# on exit if running from IDLE.
pygame.quit()


from django.urls import path
from django.views.generic.base import TemplateView

from . import views

urlpatterns = [
    path('counsellor/', views.counsellor_home, name='counsellor'),
    path('counsellor/update/', views.update, name='update'),
    path('recent/', views.recentChatroom, name='recent'),

    path('waiting_students/', views.available_chatroom, name='waiting_students'),

    path('studentCounselling/', views.studentCounselling, name='studentCounselling'),
    path('chatroom/<uuid:chatroom_id>/', views.Chat, name='chatroom'),
    path('chatroom_refresh/<uuid:chatroom_id>/', views.messagerefresh, name='chatroomrefresh'),

    path('student/', TemplateView.as_view(template_name='student.html'), name='student'),
]


import time
from queue import Empty, Full

import cv2
from imutils import resize

from pipert.core.message import Message
from pipert.core.message_handlers import RedisHandler
from pipert.core.message import message_decode, message_encode
from pipert.core.routine import Routine

class Listen2Stream(Routine):

    def __init__(self, stream_address, queue, fps=30., *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.stream_address = stream_address
        self.isFile = str(stream_address).endswith("mp4")
        self.stream = None
        # self.stream = cv2.VideoCapture(self.stream_address)
        self.queue = queue
        self.fps = fps
        self.updated_config = {}

    def begin_capture(self):
        self.stream = cv2.VideoCapture(self.stream_address)
        if self.isFile:
            self.fps = self.stream.get(cv2.CAP_PROP_FPS)
            self.stream.set(cv2.CAP_PROP_FRAME_WIDTH, 640)
            self.stream.set(cv2.CAP_PROP_FRAME_HEIGHT, 480)
        self.logger.info("Starting video capture on %s", self.stream_address)

    def change_stream(self):
        if self.stream_address == self.updated_config['stream_address']:
            return
        self.stream_address = self.updated_config['stream_address']
        self.fps = self.updated_config['FPS']
        self.isFile = str(self.stream_address).endswith("mp4")
        self.logger.info("Changing source stream address to %s",
                         self.updated_config['stream_address'])
        self.begin_capture()

    def grab_frame(self):
        grabbed, frame = self.stream.read()
        msg = Message(frame, self.stream_address)
        msg.record_entry(self.component_name, self.logger)
        return grabbed, msg

    def main_logic(self, *args, **kwargs):
        if self.updated_config:
            self.change_stream()
            self.updated_config = {}

        start = time.time()
        grabbed, msg = self.grab_frame()
        if grabbed:
            frame = msg.get_payload()
            frame = resize(frame, 640, 480)
            # if the stream is from a webcam, flip the frame
            if self.stream_address == 0:
                frame = cv2.flip(frame, 1)
            try:
                self.queue.get(block=False)
            except Empty:
                pass
            finally:
                msg.update_payload(frame)
                self.queue.put(msg)
                if self.isFile:
                    wait = time.time() - start
                    time.sleep(max(1 / self.fps - wait, 0))
                # self.queue.put(frame, block=False)
                time.sleep(0)
                return True

    def setup(self, *args, **kwargs):
        self.begin_capture()

    def cleanup(self, *args, **kwargs):
        self.stream.release()
        del self.stream

# TODO: add Error handling to connection
class Message2Redis(Routine):

    def __init__(self, out_key, url, queue, maxlen, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.out_key = out_key
        self.url = url
        self.queue = queue
        self.maxlen = maxlen
        self.msg_handler = None

    def main_logic(self, *args, **kwargs):
        try:
            msg = self.queue.get(block=False)
            msg.record_exit(self.component_name, self.logger)
            encoded_msg = message_encode(msg)
            self.msg_handler.send(encoded_msg, self.out_key)
            time.sleep(0)
            return True
        except Empty:
            time.sleep(0)  # yield the control of the thread
            return False

    def setup(self, *args, **kwargs):
        self.msg_handler = RedisHandler(self.url, self.maxlen)
        self.msg_handler.connect()

    def cleanup(self, *args, **kwargs):
        self.msg_handler.close()

class MessageFromRedis(Routine):

    def __init__(self, in_key, url, queue, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.in_key = in_key
        self.url = url
        self.queue = queue
        self.msg_handler = None
        self.flip = False
        self.negative = False

    def main_logic(self, *args, **kwargs):
        encoded_msg = self.msg_handler.receive(self.in_key)
        if encoded_msg:
            msg = message_decode(encoded_msg)
            msg.record_entry(self.component_name, self.logger)
            try:
                self.queue.put(msg, block=False)
                return True
            except Full:
                try:
                    self.queue.get(block=False)
                except Empty:
                    pass
                finally:
                    self.queue.put(msg, block=False)
                    return True
        else:
            time.sleep(0)
            return False

    def setup(self, *args, **kwargs):
        self.msg_handler = RedisHandler(self.url)
        self.msg_handler.connect()

    def cleanup(self, *args, **kwargs):
        self.msg_handler.close()

class DisplayCV2(Routine):
    def __init__(self, queue, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.queue = queue
        self.negative = False

    def main_logic(self, *args, **kwargs):
        try:
            msg = self.queue.get(block=False)
            frame = msg.get_payload()
            if self.negative:
                frame = 255 - frame
            cv2.imshow('Display', frame)
            cv2.waitKey(1)
        except Empty:
            time.sleep(0)

    def setup(self, *args, **kwargs):
        pass

    def cleanup(self, *args, **kwargs):
        cv2.destroyAllWindows()

class DisplayFlask(Routine):
    def __init__(self, in_key, queue, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.in_key = in_key
        self.queue = queue
        self.negative = False

    def main_logic(self, *args, **kwargs):
        try:
            frame = self.queue.get(block=False)
            if self.negative:
                frame = 255 - frame
            cv2.imshow('Display', frame)
            cv2.waitKey(1)
            return True
        except Empty:
            time.sleep(0)
            return False

    def setup(self, *args, **kwargs):
        pass

    def cleanup(self, *args, **kwargs):
        cv2.destroyAllWindows()


# topics = ["动态规划"]

from typing import List

class Solution:
    """
    0-1 背包(二维)
    """

    def findMaxForm(self, strs: List[str], m: int, n: int) -> int:
        # dp[i][j] 表示不超过 i 个 0 和 j 个 1 的最长子集
        dp: List[List[int]] = [[0] * (n + 1) for _ in range(m + 1)]

        for k in range(len(strs)):
            c0 = strs[k].count('0')
            c1 = strs[k].count('1')
            for i in range(m + 1)[::-1]:
                for j in range(n + 1)[::-1]:
                    if k == 0:
                        dp[i][j] = 0 if (c0 > i or c1 > j) else 1
                    elif i >= c0 and j >= c1:
                        dp[i][j] = max(dp[i][j], dp[i - c0][j - c1] + 1)

        return dp[m][n]


from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager
import time

driver = webdriver.Chrome(ChromeDriverManager().install())

try:
    # Oldal betöltése
    driver.get("https://witty-hill-0acfceb03.azurestaticapps.net/mutant_teams.html")
    time.sleep(2)

    # Függvény az elemek attributumainak és az elvárt, csoport szerinti attributumok összehasonlítására:

    def hero_team_finder(hero, teams):
        hero_element = driver.find_element_by_id(hero)
        assert hero_element.get_attribute('data-teams') == teams

    # Angel (aki mindegyik csoport tagja)
    hero_team_finder('angel', 'original force factor hellfire')

    # Beast (Aki original és factor)
    hero_team_finder('beast', 'original factor')

    # Cyclops
    hero_team_finder('cyclops', 'original force factor')

    # És a többi:
    hero_team_finder('emma-frost', 'hellfire')
    hero_team_finder('iceman', 'original factor')

    # És így tovább....

finally:
    driver.close()


from django.test import Client, TestCase
from django.urls import reverse

from http import HTTPStatus

class StaticViewsTests(TestCase):
    def setUp(self):
        self.guest_client = Client()
        self.url_template = {
            'about:author': 'about/author.html',
            'about:tech': 'about/tech.html'
        }

    def test_page_accessible(self):
        for adress in self.url_template.keys():
            with self.subTest(adress=adress):
                response = self.guest_client.get(reverse(adress))
                self.assertEqual(response.status_code, HTTPStatus.OK)

    def test_page_accessible(self):
        for adress, template in self.url_template.items():
            with self.subTest(adress=adress):
                response = self.guest_client.get(reverse(adress))
                self.assertTemplateUsed(response, template)


from nltk.parse.corenlp import CoreNLPDependencyParser, CoreNLPParser
from nltk.stem.wordnet import WordNetLemmatizer
import sqlite3,os
from sqlite3 import Error
import sjuman2_spate505 as part1

#--- Lambda function to return Noun and generate appropriate where clause for that root word
def returnNounReps(ner_tag,l):
	movie=""
	location=""
	person=""
	title=""
	tag=[ner_tag[i][1] for i in range(0,len(ner_tag)) if ner_tag[i][0]==l[0]]
	if len(tag)==0:
		tag='X'
	else:
		tag=tag[0]
	if tag=='PERSON':
		if person!="":
			person+=" and "
		person+=" lower(p.name) like '%" + str(l[0]).lower() + "%'"
	elif tag=='LOCATION':
		location=" lower(p.pob) like '%" + str(l[0]).lower() + "%'"
	elif tag=='NATIONALITY':
		place=nationality_mapping[l[0].upper()]
		location=" lower(p.pob) like '%" + str(place).lower() + "%'"
	elif tag=='TITLE':
		title=l2[0].lower()
	else:
		if movie!="":
			movie+=" and "
		movie+=" lower(m.name) like '%" + str(l[0]).lower() + "%'"
	return person,location,title,movie

#-- Generate the clauses to be used in the query
def getClause(parse,ner_tag):
	nationality_mapping={"ITALIAN": "ITALY", "GERMAN": "GERMANY", "FRENCH":"FRANCE", "BRITISH": "UK", "AMERICAN": "USA" }
	acts=['act','star']
	person=""
	location=""
	movie=""
	title=""
	title1=""
	direct='N'
	act='N'
	oscar='N'
	osc=""
	from_clause=""
	year=""
	born=""
	movie_mapping={'movie': 'film', 'film' : 'film', 'picture' : 'film'}
	for l in list(parse.triples()):
		# Handling the subject  and modifiers: Nouns associated with the VERB
		if 'nsubj' in l[1] or 'nmod' in l[1] or 'compound' in l[1]:
			if 'VB' in l[0][1]:
				lm=WordNetLemmatizer().lemmatize(l[0][0],'v')
				if lm=="win":
					oscar='Y'
				elif lm=='born':
					born='Y'
				elif lm in ['star','act']:
					act='Y'
				elif lm in ['direct']:
					direct='Y'
			elif 'NNP' in l[0][1]:
				per,loc,title,mov=returnNounReps(ner_tag,l[0])
				if person!="" and per!="":
					person+=" and "
				person+=per
				if loc!="" and person!="":
					person+=" and "
				person+=loc
				if movie!="" and mov!="":
					movie+=" and "
				movie+=mov
			if 'NNP' in l[2][1]:
				per,loc, title, mov=returnNounReps(ner_tag,l[2])
				if person!="" and per!="":
					person+=" and "
				person+=per
				if loc!="" and person!="":
					person+=" and "
				person+=loc
				if movie!="" and mov!="":
					movie+=" and "
				movie+=mov
			if 'NN' in l[0][1]:
				tag=[ner_tag[i][1] for i in range(0,len(ner_tag)) if ner_tag[i][0].lower()==l[0][0].lower()]
				if len(tag)==0:
					tag='X'
				else:
					tag=tag[0]
				if tag=='TITLE':

					if l[0][0].lower() in ['actor','actress','act']:
						act='Y'
					if l[0][0].lower() in ['director','directors']:
						direct='Y'
		# Handling adjectives: finding category for oscars
		if 'amod' in l[1] or ('nsubj' in l[1] and 'JJ' in l[2][1]) or ('dobj' in l[1]):
			if 'best' in l[2][0].lower():
				oscar='Y'
				word=l[0][0].lower()
				if word in ['movie','picture','cinema']:
					word="film"
				title1="best%" + word
			if 'dobj' in l[1] and 'best' in title1:
				title1+="%" +l[2][0].lower()

		# Handling case: by-direct and with-act
		if 'case' in l[1]:

			if l[2][1]=='IN':
				if l[2][0].lower()=='with':
					act='Y'
				if l[2][0].lower()=='by':
					direct='Y'
			if l[2][1]=='CD' or l[0][1]=='CD':
				if l[2][1]=='CD':
					d=l[2][0]
				else:
					d=l[0][0]
				if born=='Y':
					if person!="":
						person+=" and "
					person+=" p.dob like '" + d + "%'"
				if oscar=='Y':

					if osc!="":
						osc+=" and "
					osc+=" o.year=" + d
				else:
					if movie!="":
						movie+=" and "
					movie+=" m.year=" + d

	if title1!="":
		if osc!="":
			osc+=" and "
		osc+=" lower(o.type) like '%" + title1 + "%'"
	from_clause=""
	if person!="":
		from_clause+=" person p "
	if movie!="":
		from_clause+=", movie m "
	if oscar=='Y':
		from_clause+=", oscar o "
	if act=='Y':
		from_clause+=", actor a "
	if direct=='Y':
		from_clause+=", director d "

	return from_clause,person,movie,location,oscar,osc,born

# generate the query + base conditions
def generate_query(dep_parse,ner_tag, parse):
	from_clause,person,movie,location,oscar,osc,born=getClause(dep_parse,ner_tag)
	select_clause=""
	if 'SBAR' not in parse:
		select_clause="Select case when count(*)>=1 then 'Yes' else 'No' end "
	# Setting base conditions for where clause

	wh_query=person + movie + osc + location
	if person!="":
		#wh_query=person
		if 'actor' in from_clause:
			wh_query+=" and p.id=a.actor_id"
		elif 'director' in from_clause:
			wh_query+= " and p.id=d.director_id"

	if 'oscar' in from_clause and 'movie' in from_clause:
		wh_query+=" and m.id=o.movie_id "

	if 'oscar' in from_clause and 'person' in from_clause:
		wh_query+=" o.person_id=p.id  and " + osc

	if 'movie' in from_clause and 'actor' in from_clause:
		wh_query+=" a.movie_id=m.id"

	query=select_clause + " from " + from_clause[1:] + " where " + wh_query
	print(query)
	return query

qstn="Which album by Swift was released in 2012?"
parser = CoreNLPDependencyParser()

depparse = next(parser.raw_parse(qstn))
for l in list(depparse.triples()):
	print(l)
ner_tagger = CoreNLPParser(url='http://localhost:9000', tagtype='ner')
ner_tag=ner_tagger.tag(qstn.split())
generate_query(depparse,ner_tag,'S')


from xml.etree.ElementTree import Element
from .. import TReqz

class reqif_attribute_definition(TReqz.reqif_identifiable):

    def __init__(self, content: Element = None, id_dict=None):
        self.default_value: TReqz.reqif_attribute_value = None  # element, optional
        self.type: TReqz.reqif_datatype_definition = None  # local_ref, required
        self.is_editable: str = None  # attribute, optional
        super(reqif_attribute_definition, self).__init__(content, id_dict)
        self.name:str = "ATTRIBUTE-DEFINITION"

    def decode(self, content: Element, id_dict: TReqz.reqif_id_dict = None):
        super().decode(content, id_dict)

        self.is_editable = TReqz.reqif_utils.unescapeAttribute(content.get("IS-EDITABLE"))

    def encode(self):
        elem = super().encode()
        elem.tag = self.name
        TReqz.xml_utils.setElementAttribute(
            elem, "IS-EDITABLE", TReqz.reqif_utils.escapeAttribute(self.is_editable))
        return elem


import sys
sys.path.append('../')

from schmactions import schmactions

import astropy.units as u
import pickle

import matplotlib.pyplot as plt
from scipy.stats import sigmaclip
import numpy as np

import matplotlib as mpl
from matplotlib import rc
rc('font', **{'family': 'serif', 'serif': ['Computer Modern']})
rc('text', usetex=True)
mpl.rcParams['text.latex.preamble'] = [r'\usepackage{amsmath} \usepackage{bm}']

textwidth = 7.10000594991
columnwidth = 3.35224200913

tb_c = ['#4e79a7', '#f28e2b', '#e15759', '#76b7b2', '#59a14f',
        '#edc948', '#b07aa1', '#ff9da7', '#9c755f', '#bab0ac']

xmin = 0
xmax = 1000

y0min = 20
y0max = 40
y1min = -1800
y1max = -1000
y2min = 10
y2max = 30

histmin = 15
histmax = 30

histmin_thin = 0
histmax_thin = 5

def sclip(a, s=4):
    _, low0, high0 = sigmaclip(a[:,0], low=s, high=s)
    _, low1, high1 = sigmaclip(a[:,1], low=s, high=s)
    _, low2, high2 = sigmaclip(a[:,2], low=s, high=s)
    a0bool = np.logical_and(a[:,0] > low0, a[:,0] < high0)
    a1bool = np.logical_and(a[:,1] > low1, a[:,1] < high1)
    a2bool = np.logical_and(a[:,2] > low2, a[:,2] < high2)
    k0 = np.where(a0bool)[0]
    k1 = np.where(a1bool)[0]
    k2 = np.where(a2bool)[0]
    return k0, k1, k2

zout = pickle.load(open('zout.p', 'rb'))
xout = pickle.load(open('xout.p', 'rb'))
res = pickle.load(open('true_res.p', 'rb'))
J0, J1, J2 = res['actions'].to_value(u.kpc*u.km/u.s)

zout_thin = pickle.load(open('zout_thin.p', 'rb'))
xout_thin = pickle.load(open('xout_thin.p', 'rb'))
res_thin = pickle.load(open('true_res_thin.p', 'rb'))
J0_thin, J1_thin, J2_thin = res_thin['actions'].to_value(u.kpc*u.km/u.s)

init_pos = [8, 0, 0] * u.kpc
init_vel = [0, -190, 50] * u.km/u.s
init_vel_thin = [0, -190, 10] * u.km/u.s

s = schmactions(init_pos, init_vel)
sthin = schmactions(init_pos, init_vel_thin)

zact = s.extract_actions(zout)
xact = s.extract_actions(xout)

ztime = s.extract_time(zout)
xtime = s.extract_time(xout)

zact_thin = sthin.extract_actions(zout_thin)
ztime_thin = sthin.extract_time(zout_thin)

fig, ax = plt.subplots(2, 3, figsize=(textwidth, 4), sharex=True)

for x,t,a in zip(ax, (ztime, xtime), (zact, xact)):
    # get keys corresponding to 4 sigmaclip
    k0, k1, k2 = sclip(a)
    x[0].plot(t[k0], a[:,0][k0], c=tb_c[0])
    x[1].plot(t[k1], a[:,1][k1], c=tb_c[0])
    x[2].plot(t[k2], a[:,2][k2], c=tb_c[0])

    x[0].plot(t, np.full(len(t), J0), c=tb_c[0], ls='dashed')
    x[1].plot(t, np.full(len(t), J1), c=tb_c[0], ls='dashed')
    x[2].plot(t, np.full(len(t), J2), c=tb_c[0], ls='dashed')

    # set limits on plots
    x[0].set_ylim(y0min, y0max)
    x[1].set_ylim(y1min, y1max)
    x[2].set_ylim(y2min, y2max)
    for xx in x:
        xx.set_xlim(xmin, xmax)

for x in ax[1]:
    x.set_xlabel(r'$t\,[\,\text{Myr}\,]$')
    x.set_xticks(np.arange(0,1000,100), minor=True)

for x in ax[:,0]:
    x.set_ylabel(r'$J_{R,\text{obs}}\,[\,\text{kpc}\,\text{km}/\text{s}\,]$')
for x in ax[:,1]:
    x.set_ylabel(r'$J_{\phi,\text{obs}}\,[\,\text{kpc}\,\text{km}/\text{s}\,]$')
for x in ax[:,2]:
    x.set_ylabel(r'$J_{z,\text{obs}}\,[\,\text{kpc}\,\text{km}/\text{s}\,]$')

ax[0][1].set_title(r'$z\,\text{offset}=100\,\text{pc}$')
ax[1][1].set_title(r'$x\,\text{offset}=100\,\text{pc}$')

fig.tight_layout()
plt.savefig('schmactions_one_orbit.pdf')
plt.close()

fig, ax = plt.subplots(2,1, figsize=(columnwidth,6.5))

k0, k1, k2 = sclip(zact)
dJzJz = 0.5*(np.percentile(zact[:,2][k2], 95) - np.percentile(zact[:,2][k2], 5))

ax[0].hist(zact[:,2][k2], bins=np.linspace(histmin, histmax, 60),
        edgecolor='k', fc='none', histtype='stepfilled')
ax[0].arrow(J2, 60, dJzJz, 0, head_width=1, head_length=0.4, length_includes_head=True, color='k')
ax[0].text(J2+dJzJz/3.5, 61, r'$\Delta J_z$', color='k')

ax[0].axvline(x=J2, color='k', ls='dashed', lw=1)
ax[0].set_ylabel(r'$\text{count}$')
ax[0].text(14.5, 75, r'\text{thick-disk orbit}', color='k')

k0t, k1t, k2t = sclip(zact_thin)
dJzJz_thin = 0.5*(np.percentile(zact_thin[:,2][k2t], 95) - np.percentile(zact_thin[:,2][k2t], 5))

ax[1].hist(zact_thin[:,2][k2t], bins=np.linspace(histmin_thin, histmax_thin, 60),
        edgecolor='k', fc='none', histtype='stepfilled')
ax[1].arrow(J2_thin, 60, dJzJz_thin, 0, head_width=1, head_length=0.15, length_includes_head=True, color='k')
ax[1].text(J2_thin+dJzJz_thin/3.5, 61.5, r'$\Delta J_z$', color='k')

ax[1].axvline(x=J2_thin, color='k', ls='dashed', lw=1)
ax[1].set_ylabel(r'$\text{count}$')
ax[1].text(1.3, 100, r'\text{thin-disk orbit}', color='k')

ax[1].set_xlabel(r'$J_{z,\text{obs}}\,[\,\text{kpc}\,\text{km}/\text{s}\,]$')

fig.tight_layout()
plt.savefig('schmactions_Jz_hist.pdf')


import pandas as pd
import sqlite3
from pandas import DataFrame

n_conn = sqlite3.connect('northwind_small.sqlite3')
n_curs = n_conn.cursor()

# What are the ten most expensive items (per unit price) in the database?
query = """
SELECT ProductName, UnitPrice
FROM Product
ORDER BY UnitPrice DESC
LIMIT 10
"""
n_curs.execute(query)
print(n_curs.fetchall())

# What is the average age of an employee at the time of their hiring? (Hint: a
# lot of arithmetic works with dates.)

query = """
SELECT AVG(HireDate-BirthDate)
FROM Employee
"""
n_curs.execute(query)
print(n_curs.fetchall())

# answer: 37.22

# (*Stretch*) How does the average age of employee at hire vary by city?
query = """SELECT City, AVG(HireDate-BirthDate)
FROM Employee
GROUP BY City
"""
n_curs.execute(query)
print(n_curs.fetchall())

# What are the ten most expensive items (per unit price)
# in the database *and* their suppliers?
query = """
SELECT ProductName, UnitPrice, CompanyName
FROM Product as p
JOIN Supplier as s
ON p.SupplierID = s.ID
ORDER BY UnitPrice DESC
LIMIT 10
"""
n_curs.execute(query)
print(n_curs.fetchall())

# What is the largest category (by number of unique products in it)?
query = """
SELECT CategoryName, COUNT(CategoryName)
FROM Category as c
JOIN Product as p
ON c.ID=p.CategoryID
GROUP BY CategoryName
ORDER by COUNT(CategoryName) DESC
"""
n_curs.execute(query)
print(n_curs.fetchall())

# largest category is Confections 13

# (*Stretch*) Who's the employee with the most territories? Use `TerritoryId`
# (not name, region, or other fields) as the unique identifier for territories.
# EMPLOYEE ID 7

query = """
SELECT EmployeeId, TerritoryId, COUNT(DISTINCT TerritoryId)
FROM EmployeeTerritory
GROUP BY EmployeeId
ORDER BY COUNT(DISTINCT TerritoryId) DESC
"""
n_curs.execute(query)
print(n_curs.fetchall())


##############################################################################
#
# Copyright (c) 2004 Zope Corporation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL).  A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE.
#
##############################################################################
"""Principal Information Interfaces

$Id$
"""
from zope.i18n import MessageIDFactory
from zope.interface import Interface
from zope.schema import TextLine

_ = MessageIDFactory('messageboard')

class IPrincipalInformation(Interface):
    """This interface additional information about a principal."""

    email = TextLine(
        title=_("E-mail"),
        description=_("E-mail Address"),
        default=u"",
        required=False)

    ircNickname = TextLine(
        title=_("IRC Nickname"),
        description=_("IRC Nickname"),
        default=u"",
        required=False)


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import pandas as pd
from plotnine import ggplot, aes, geom_point, labs
from ._themes import theme_std

def scatter_pseudotime(adata, y, size = 1.5, alpha = 1, color = 'black'):
    """Plots a scatter plot of pseudotime vs one or multiple variables

    Parameters
    --------------
    adata: AnnData
        The AnnData object being used for the analysis. Must be previously
        evaluated by `tl.pseudotime`.
    y: str or list
        If type(y) == str, y must be a variable annotated in adata.obs and
        will be used as the y-axis. If type(y) == list, then multiple variables
        will be plotted using a shared y-axis but different point colors.
    size: float
        Controls the point size of the plot.
    alpha: float
        A value between 0 and 1. Controls point transparency.
    color: str
        A supported color name. Controls the point color if type(y)==str.
        Ignored otherwise.

    Returns
    -------------
    A plotnine scatter plot of pseudotime.
    """
    if type(y) == str:
        #-- Get data
        if y in adata.obs.columns:
            plot_df = pd.DataFrame({'x': adata.obs['pseudotime'], 'y': adata.obs[y]})
        elif y in adata.var_names:
            plot_df = pd.DataFrame({'x': adata.obs['pseudotime'], 'y': adata[:,y].X.flatten()})

        #-- Make plot
        if color in adata.obs.columns:
            time_scatter = (ggplot(plot_df, aes(x = 'x', y = 'y'))
              + geom_point(aes(color = color), size = size, alpha = alpha)
              + labs(x = 'Pseudotime', y = y)
              + theme_std)
        else:
            time_scatter = (ggplot(plot_df, aes(x = 'x', y = 'y'))
              + geom_point(size = size, alpha = alpha, color = color)
              + labs(x = 'Pseudotime', y = y)
              + theme_std)

    else:
        #-- Make multiple color plot
        plt_vars = y
        plt_vars.append('pseudotime')
        sannot = adata.obs.copy()[plt_vars]
        sannot['id'] = range(sannot.shape[0])

        plot_df = pd.melt(sannot, id_vars = ['id', 'pseudotime'],
                            var_name = 'signature', value_name = 'score')

        time_scatter = (ggplot(plot_df, aes('pseudotime', 'score'))
         + geom_point(aes(color = 'signature'), alpha = alpha, size = size)
         + theme_std)

    return time_scatter


"""Tests for cement.ext.ext_argparse."""

import sys
import re
from argparse import ArgumentError
from cement.ext.ext_argparse import ArgparseArgumentHandler
from cement.ext.ext_argparse import ArgparseController, expose
from cement.ext.ext_argparse import _clean_label, _clean_func
from cement.utils import test
from cement.utils.misc import rando
from cement.core.exc import InterfaceError, FrameworkError

APP = rando()[:12]

if (sys.version_info[0] > 3 and sys.version_info[1] >= 4):
    ARGPARSE_SUPPORTS_DEFAULTS = True
else:
    ARGPARSE_SUPPORTS_DEFAULTS = False

class Base(ArgparseController):

    class Meta:
        label = 'base'
        arguments = [
            (['--foo'], dict(dest='foo')),
        ]

    @expose(hide=True, help="this help doesn't get seen")
    def default(self):
        return "Inside Base.default"

    @expose()
    def cmd1(self):
        return "Inside Base.cmd1"

    @expose()
    def command_with_dashes(self):
        return "Inside Base.command_with_dashes"

class Second(ArgparseController):

    class Meta:
        label = 'second'
        stacked_on = 'base'
        stacked_type = 'embedded'
        arguments = [
            (['--foo2'], dict(dest='foo2')),
        ]

    @expose(
        arguments=[
            (['--cmd2-foo'],
             dict(help='cmd2 sub-command only options', dest='cmd2_foo')),
        ]
    )
    def cmd2(self):
        if self.app.pargs.cmd2_foo:
            return "Inside Second.cmd2 : Foo > %s" % self.app.pargs.cmd2_foo
        else:
            return "Inside Second.cmd2"

class Third(ArgparseController):

    class Meta:
        label = 'third'
        stacked_on = 'base'
        stacked_type = 'nested'
        arguments = [
            (['--foo3'], dict(dest='foo3')),
        ]

    @expose(hide=True)
    def default(self):
        return "Inside Third.default"

    @expose()
    def cmd3(self):
        return "Inside Third.cmd3"

class Fourth(ArgparseController):

    class Meta:
        label = 'fourth'
        stacked_on = 'third'
        stacked_type = 'embedded'
        hide = True
        help = "this help doesn't get seen cause we're hiding"
        arguments = [
            (['--foo4'], dict(dest='foo4')),
        ]

    @expose()
    def cmd4(self):
        return "Inside Fourth.cmd4"

class Fifth(ArgparseController):

    class Meta:
        label = 'fifth'
        stacked_on = 'third'
        stacked_type = 'nested'
        hide = True
        help = "this help isn't seen... i'm hiding"
        arguments = [
            (['--foo5'], dict(dest='foo5')),
        ]

    @expose(hide=True)
    def default(self):
        return "Inside Fifth.default"

    @expose()
    def cmd5(self):
        return "Inside Fifth.cmd5"

class Sixth(ArgparseController):

    class Meta:
        label = 'sixth'
        stacked_on = 'fifth'
        stacked_type = 'nested'
        arguments = [
            (['--foo6'], dict(dest='foo6')),
        ]

    @expose(hide=True)
    def default(self):
        return "Inside Sixth.default"

    @expose()
    def cmd6(self):
        return "Inside Sixth.cmd6"

class Seventh(ArgparseController):

    class Meta:
        label = 'seventh'
        stacked_on = 'fourth'
        stacked_type = 'embedded'
        arguments = [
            (['--foo7'], dict(dest='foo7')),
        ]

    @expose()
    def cmd7(self):
        return "Inside Seventh.cmd7"

class Unstacked(ArgparseController):

    class Meta:
        label = 'unstacked'
        stacked_on = None
        arguments = [
            (['--foo6'], dict(dest='foo6')),
        ]

class BadStackType(ArgparseController):

    class Meta:
        label = 'bad_stack_type'
        stacked_on = 'base'
        stacked_type = 'bogus_stacked_type'
        arguments = [
            (['--foo6'], dict(dest='foo6')),
        ]

class DuplicateArguments(ArgparseController):

    class Meta:
        label = 'duplicate_arguments'
        arguments = [
            (['--foo'], dict(dest='foo')),
        ]

class ControllerCommandDuplicateArguments(ArgparseController):

    class Meta:
        label = 'controller_command_duplicate_arguments'

    @expose(
        arguments=[
            (['--foo'], dict(dest='foo')),
            (['--foo'], dict(dest='foo')),
        ]
    )
    def sub_command(self):
        pass

class AlternativeDefault(ArgparseController):

    class Meta:
        label = 'alternative_default'
        default_func = 'alternative_default'
        stacked_on = 'base'
        stacked_type = 'nested'

    @expose(hide=True)
    def alternative_default(self):
        return "Inside AlternativeDefault.alternative_default"

class BadAlternativeDefault(ArgparseController):

    class Meta:
        label = 'bad_alternative_default'
        default_func = 'bogus_default'
        stacked_on = 'base'
        stacked_type = 'nested'

class Aliases(ArgparseController):

    class Meta:
        label = 'aliases'
        aliases = ['aliases-controller', 'ac']
        stacked_on = 'base'
        stacked_type = 'nested'

    @expose(aliases=['aliases-cmd-1', 'ac1'])
    def aliases_cmd1(self):
        return "Inside Aliases.aliases_cmd1"

class ArgparseExtTestCase(test.CementExtTestCase):

    def setUp(self):
        super(ArgparseExtTestCase, self).setUp()
        self.app = self.make_app(APP,
                                 argument_handler=ArgparseArgumentHandler,
                                 handlers=[
                                     Sixth,
                                     Base,
                                     Second,
                                     Third,
                                     Fourth,
                                     Fifth,
                                     Seventh,
                                 ],
                                 )

    def test_clean_label(self):
        self.eq(_clean_label('some_cmd_name'), 'some-cmd-name')

    def test_clean_func(self):
        self.eq(_clean_func('some-cmd-name'), 'some_cmd_name')

    def test_base_default(self):
        if not ARGPARSE_SUPPORTS_DEFAULTS:
            raise test.SkipTest(
                'Argparse does not support default commands in Python < 3.4'
            )

        with self.app as app:
            res = app.run()
            self.eq(res, "Inside Base.default")

    def test_base_cmd1(self):
        with self.app as app:
            app._meta.argv = ['cmd1']
            res = app.run()
            self.eq(res, "Inside Base.cmd1")

    def test_base_command_with_dashes(self):
        with self.app as app:
            app._meta.argv = ['command-with-dashes']
            res = app.run()
            self.eq(res, "Inside Base.command_with_dashes")

    def test_controller_commands(self):
        with self.app as app:
            app._meta.argv = ['cmd2']
            res = app.run()
            self.eq(res, "Inside Second.cmd2")
        self.tearDown()

        self.setUp()
        with self.app as app:
            app._meta.argv = ['third', 'cmd3']
            res = app.run()
            self.eq(res, "Inside Third.cmd3")
        self.tearDown()

        self.setUp()
        with self.app as app:
            app._meta.argv = ['third', 'cmd4']
            res = app.run()
            self.eq(res, "Inside Fourth.cmd4")
        self.tearDown()

        self.setUp()
        with self.app as app:
            app._meta.argv = ['third', 'fifth', 'cmd5']
            res = app.run()
            self.eq(res, "Inside Fifth.cmd5")
        self.tearDown()

        self.setUp()
        with self.app as app:
            app._meta.argv = ['third', 'fifth', 'sixth', 'cmd6']
            res = app.run()
            self.eq(res, "Inside Sixth.cmd6")
        self.tearDown()

        self.setUp()
        with self.app as app:
            app._meta.argv = ['third', 'cmd7']
            res = app.run()
            self.eq(res, "Inside Seventh.cmd7")
        self.tearDown()

    def test_base_cmd1_parsing(self):
        with self.app as app:
            app._meta.argv = ['--foo=bar', 'cmd1']
            res = app.run()
            self.eq(res, "Inside Base.cmd1")
            self.eq(app.pargs.foo, 'bar')

    def test_second_cmd2(self):
        with self.app as app:
            app._meta.argv = ['--foo=bar', '--foo2=bar2', 'cmd2']
            res = app.run()
            self.eq(res, "Inside Second.cmd2")
            self.eq(app.pargs.foo, 'bar')
            self.eq(app.pargs.foo2, 'bar2')

    def test_third_cmd3(self):
        with self.app as app:
            app._meta.argv = [
                '--foo=bar', '--foo2=bar2',
                'third', '--foo3=bar3', '--foo4=bar4', '--foo7=bar7', 'cmd3',
            ]
            res = app.run()
            self.eq(res, "Inside Third.cmd3")
            self.eq(app.pargs.foo, 'bar')
            self.eq(app.pargs.foo2, 'bar2')
            self.eq(app.pargs.foo3, 'bar3')
            self.eq(app.pargs.foo4, 'bar4')
            self.eq(app.pargs.foo7, 'bar7')

    def test_fifth_cmd5(self):
        with self.app as app:
            app._meta.argv = [
                '--foo=bar', '--foo2=bar2',
                'third', '--foo3=bar3', '--foo4=bar4',
                'fifth', '--foo5=bar5', 'cmd5'
            ]
            res = app.run()
            self.eq(res, "Inside Fifth.cmd5")
            self.eq(app.pargs.foo, 'bar')
            self.eq(app.pargs.foo2, 'bar2')
            self.eq(app.pargs.foo3, 'bar3')
            self.eq(app.pargs.foo4, 'bar4')
            self.eq(app.pargs.foo5, 'bar5')

    def test_sixth_cmd6(self):
        with self.app as app:
            app._meta.argv = [
                '--foo=bar', '--foo2=bar2',
                'third', '--foo3=bar3', '--foo4=bar4',
                'fifth', '--foo5=bar5', 'sixth', '--foo6=bar6', 'cmd6',
            ]
            res = app.run()
            self.eq(res, "Inside Sixth.cmd6")
            self.eq(app.pargs.foo, 'bar')
            self.eq(app.pargs.foo2, 'bar2')
            self.eq(app.pargs.foo3, 'bar3')
            self.eq(app.pargs.foo4, 'bar4')
            self.eq(app.pargs.foo5, 'bar5')
            self.eq(app.pargs.foo6, 'bar6')

    def test_seventh_cmd7(self):
        with self.app as app:
            app._meta.argv = [
                '--foo=bar', '--foo2=bar2',
                'third', '--foo3=bar3', '--foo4=bar4', '--foo7=bar7', 'cmd7',
            ]
            res = app.run()
            self.eq(res, "Inside Seventh.cmd7")
            self.eq(app.pargs.foo, 'bar')
            self.eq(app.pargs.foo2, 'bar2')
            self.eq(app.pargs.foo3, 'bar3')
            self.eq(app.pargs.foo4, 'bar4')
            self.eq(app.pargs.foo7, 'bar7')

    def test_collect(self):
        with self.app as app:
            args = app.controller._collect_arguments()
            cmds = app.controller._collect_commands()
            args2, cmds2 = app.controller._collect()
            self.eq((args, cmds), (args2, cmds2))

    def test_controller_embedded_on_base(self):
        self.app._meta.argv = ['cmd2']
        with self.app as app:
            res = app.run()
            self.eq(res, "Inside Second.cmd2")

    def test_controller_command_arguments(self):
        self.app._meta.argv = ['cmd2', '--cmd2-foo=bar2']
        with self.app as app:
            res = app.run()
            self.eq(res, "Inside Second.cmd2 : Foo > bar2")

    def test_controller_default_nested_on_base(self):
        if not ARGPARSE_SUPPORTS_DEFAULTS:
            raise test.SkipTest(
                'Argparse does not support default commands in Python < 3.4'
            )

        self.app._meta.argv = ['third']
        with self.app as app:
            res = app.run()
            self.eq(res, "Inside Third.default")

    def test_controller_command_nested_on_base(self):
        self.app._meta.argv = ['third', 'cmd3']
        with self.app as app:
            res = app.run()
            self.eq(res, "Inside Third.cmd3")

    def test_controller_doubled_embedded(self):
        self.app._meta.argv = ['third', 'cmd4']
        with self.app as app:
            res = app.run()
            self.eq(res, "Inside Fourth.cmd4")

    def test_controller_default_double_nested(self):
        if not ARGPARSE_SUPPORTS_DEFAULTS:
            raise test.SkipTest(
                'Argparse does not support default commands in Python < 3.4'
            )
        self.app._meta.argv = ['third', 'fifth']
        with self.app as app:
            res = app.run()
            self.eq(res, "Inside Fifth.default")

    def test_controller_command_double_nested(self):
        self.app._meta.argv = ['third', 'fifth', 'cmd5']
        with self.app as app:
            res = app.run()
            self.eq(res, "Inside Fifth.cmd5")

    def test_alternative_default(self):
        if not ARGPARSE_SUPPORTS_DEFAULTS:
            raise test.SkipTest(
                'Argparse does not support default commands in Python < 3.4'
            )

        self.reset_backend()
        self.app = self.make_app(APP,
                                 argv=['alternative_default'],
                                 argument_handler=ArgparseArgumentHandler,
                                 handlers=[
                                     Base,
                                     AlternativeDefault,
                                 ],
                                 )
        with self.app as app:
            res = app.run()
            self.eq(res,
                    "Inside AlternativeDefault.alternative_default")

    @test.raises(FrameworkError)
    def test_bad_alternative_default_command(self):
        if not ARGPARSE_SUPPORTS_DEFAULTS:
            raise test.SkipTest(
                'Argparse does not support default commands in Python < 3.4'
            )

        self.reset_backend()
        self.app = self.make_app(APP,
                                 argv=['bad_alternative_default'],
                                 argument_handler=ArgparseArgumentHandler,
                                 handlers=[
                                     Base,
                                     BadAlternativeDefault,
                                 ],
                                 )
        try:
            with self.app as app:
                res = app.run()

        except FrameworkError as e:
            res = re.match("(.*)does not exist(.*)bogus_default(.*)",
                           e.__str__())
            self.ok(res)
            raise

    @test.raises(InterfaceError)
    def test_invalid_stacked_on(self):
        self.reset_backend()
        try:
            self.app = self.make_app(APP,
                                     argument_handler=ArgparseArgumentHandler,
                                     handlers=[
                                         Base,
                                         Unstacked,
                                     ],
                                     )
            with self.app as app:
                app.run()
        except InterfaceError as e:
            self.ok(re.match("(.*)is not stacked anywhere!(.*)", e.msg))
            raise

    @test.raises(InterfaceError)
    def test_invalid_stacked_type(self):
        self.reset_backend()
        try:
            self.app = self.make_app(APP,
                                     argument_handler=ArgparseArgumentHandler,
                                     handlers=[
                                         Base,
                                         BadStackType,
                                     ],
                                     )
            with self.app as app:
                app.run()
        except InterfaceError as e:
            self.ok(re.match("(.*)has an unknown stacked type(.*)", e.msg))
            raise

    @test.raises(ArgumentError)
    def test_duplicate_arguments(self):
        self.reset_backend()
        try:
            self.app = self.make_app(APP,
                                     argument_handler=ArgparseArgumentHandler,
                                     handlers=[
                                         Base,
                                         DuplicateArguments,
                                     ],
                                     )
            with self.app as app:
                app.run()
        except ArgumentError as e:
            self.ok(re.match("(.*)conflicting option string(.*)",
                             e.__str__()))
            raise

    @test.raises(ArgumentError)
    def test_controller_command_duplicate_arguments(self):
        self.reset_backend()
        try:
            self.app = self.make_app(APP,
                                     argument_handler=ArgparseArgumentHandler,
                                     handlers=[
                                         Base,
                                         ControllerCommandDuplicateArguments,
                                     ],
                                     )
            with self.app as app:
                app.run()
        except ArgumentError as e:
            self.ok(re.match("(.*)conflicting option string(.*)",
                             e.__str__()))
            raise

    def test_aliases(self):
        if sys.version_info[0] < 3:
            raise test.SkipTest(
                'Argparse does not support aliases in Python < 3'
            )
        self.reset_backend()

        self.app = self.make_app(APP,
                                 argument_handler=ArgparseArgumentHandler,
                                 handlers=[
                                     Base,
                                     Aliases,
                                 ],
                                 )
        with self.app as app:
            app._meta.argv = ['aliases', 'aliases-cmd1']
            res = app.run()
            self.eq(res, "Inside Aliases.aliases_cmd1")

            app._meta.argv = ['aliases', 'aliases-cmd-1']
            app._setup_arg_handler()
            res = app.run()
            self.eq(res, "Inside Aliases.aliases_cmd1")

            app._meta.argv = ['aliases-controller', 'aliases-cmd1']
            app._setup_arg_handler()
            res = app.run()
            self.eq(res, "Inside Aliases.aliases_cmd1")

            app._meta.argv = ['ac', 'ac1']
            app._setup_arg_handler()
            res = app.run()
            self.eq(res, "Inside Aliases.aliases_cmd1")

    def test_unknown_arguments(self):
        self.reset_backend()

        class MyArgumentHandler(ArgparseArgumentHandler):
            class Meta:
                label = 'my_argument_handler'
                ignore_unknown_arguments = True
        self.app = self.make_app(APP,
                                 argument_handler=MyArgumentHandler,
                                 )
        with self.app as app:
            app._meta.argv = ['-l', 'some-other-argument']
            app.run()
            res = '-l' in app.args.unknown_args
            self.ok(res)
            res = 'some-other-argument' in app.args.unknown_args
            self.ok(res)


# -*- coding: utf-8 -*-
"""
Created on Sun Sep 29 00:26:54 2019

@author: RUDRAJIT
"""
from PIL import Image

img=Image.open('test2.png')
rgb_im=img.convert('RGB')#convert image to rgb value
r,g,b=rgb_im.getpixel((101,1))#row column
print(r,g,b)


'''
    Ensemble method: phương pháp kết hợp
    class: sklearn.ensemble.ExtraTreeClassifier
    class: sklearn.ensemble.RandomForestClassifier
'''

from sklearn.ensemble import RandomForestClassifier
from sklearn.ensemble import ExtraTreesClassifier

# [height, weight,shoe_size]
X = [[181, 80, 44], [177, 70, 43], [160, 60, 38], [154, 54, 37], [166, 65, 40],
     [190, 90, 47], [175, 64, 39],
     [177, 70, 40], [159, 55, 37], [171, 75, 42], [181, 85, 43]]

# với mỗi bộ X ở trên gán nhãn cho Y

Y = ['male', 'male', 'female', 'female', 'male', 'male', 'female', 'female',
     'female', 'male', 'male']

clf = RandomForestClassifier(n_estimators=2)

clf = clf.fit(X,Y)

prection = clf.predict([[190, 70, 43]])

print(prection)

clf2 = ExtraTreesClassifier(n_estimators=2)

clf2 = clf2.fit(X,Y)

prection2 = clf2.predict([[190, 70, 43]])

print(prection2)

Month 1 - Data Analysis/Week 1 - Learn Python/LearnSimpleCode/sklearn/ensemble.py


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Apr 30 11:49:22 2017

@author: gibraanrahman

Script to cluster t-SNE data for tumor 170410 from DBSCAN identified
clusters and perform histogram analysis on clusters 1 and 5.
"""

import pandas as pd
import numpy as np
import math
import matplotlib.pyplot as plt
from matplotlib.pylab import savefig
from matplotlib.colors import ListedColormap

def cluster_map():
    """Map 6 clusters and noise to colors on t-SNE map."""
    data = pd.read_csv('170410_Tumor/1000it_tseed1_comp_clusterlab.csv')
    data['Color'] = range(data.shape[0])

    cmap = ListedColormap(['black', 'orange', 'blue',
                           'green', 'red', 'purple', 'grey'], 'indexed')

    plt.scatter(data['X0'], data['X1'], c=cmap(data['cluster']), s=15)
    plt.xlabel('t-SNE X1')
    plt.ylabel('t-SNE X2')

stain_data = pd.read_csv('170410_Tumor/woPI_comp_lgcl.csv')
stain_data = stain_data[stain_data['FSC-A'] > 50000]

drops = ['Alexa Fluor 700-A_Comp', 'FSC-A', 'SSC-A']
stain_data = stain_data.drop(drops, axis=1)

stain_data.index = range(stain_data.shape[0])
stain_data.columns = ['CD31', 'CD45', 'HER2', 'CD309']

# CD309 placed next to CD31 for comparison w/in cluster 5
CD309 = list(stain_data['CD309'])
CD45 = list(stain_data['CD45'])
stain_data['CD45'] = CD309
stain_data['CD309'] = CD45
stain_data.columns = ['CD31', 'CD309', 'HER2', 'CD45']
print(stain_data.head())

tsne_data = pd.read_csv('170410_Tumor/1000it_tseed1_comp_clusterlab.csv')
clust1 = tsne_data['cluster'] == 1
clust5 = tsne_data['cluster'] == 5

# Don't think these are necessary
tsne_data1 = tsne_data[clust1]
tsne_data5 = tsne_data[clust5]

# Stain intensities for clusters 1 & 5
stain_data1 = stain_data[clust1]
stain_data5 = stain_data[clust5]

binwidth = 0.1

# Histogram analysis of cluster 1
plt.figure(num=5, figsize=(15,4))
for i, col in enumerate(stain_data.columns):
    plt.subplot(1, 4, i+1)
    plt.xlim([-1, 5])
    plt.ylim([0, 0.12])
    # Weight intensities as fraction of cluster
    weights = np.ones_like(stain_data5[col])/len(stain_data5[col])
    num_bins = np.arange(stain_data5[col].min(),
                         stain_data5[col].max() + binwidth,
                         binwidth)
    plt.hist(stain_data5[col],
             bins=num_bins,
             weights=weights,
             color='purple')
    plt.xlabel(col)
    if col == 'CD31':   # Plot y-axis on left-most subplot
        plt.ylabel('Fraction of Cluster')

savefig('170410_Tumor/Plots/Clust5')

# Histogram analysis of cluster 5
plt.figure(num=1, figsize=(15,4))
for i, col in enumerate(stain_data.columns):
    plt.subplot(1, 4, i+1)
    plt.xlim([-1, 5])
    plt.ylim([0, 0.12])
    # Weight intensities as fraction of cluster
    weights = np.ones_like(stain_data1[col])/len(stain_data1[col])
    num_bins = np.arange(stain_data1[col].min(),
                         stain_data1[col].max() + binwidth,
                         binwidth)
    plt.hist(stain_data1[col],
             bins = num_bins,
             weights=weights,
             color='orange')
    plt.xlabel(col)
    if col == 'CD31':   # Plot y-axis on left-most subplot
        plt.ylabel('Fraction of Cluster')

savefig('170410_Tumor/Plots/Clust1')


from django.urls import reverse_lazy
from rest_framework import status
from rest_framework.test import APITestCase

from .factory import (
    ActorFactory,
    CastFactory,
    CinemaAwardFactory,
    CinemaAwardMovieFactory,
    MovieFactory,
    UserFactory,
)

# factory data

def get_new_cinema_award_instance(i=1):
    cinema_award = CinemaAwardFactory(name=f'cinema-award-{i}')
    movie1 = get_new_movie_instance(i=i * 10 + 1)['movie']
    movie2 = get_new_movie_instance(i=i * 10 + 2)['movie']

    movie_award1 = CinemaAwardMovieFactory(
        cinema_award=cinema_award, movie=movie1, rank=1
    )
    movie_award2 = CinemaAwardMovieFactory(
        cinema_award=cinema_award, movie=movie2, rank=1
    )

    return {
        'cinema_award': cinema_award,
        'rank': [movie_award1, movie_award2],
    }

def get_new_cinema_award_data(i=1):
    data = get_new_cinema_award_instance(i=i)

    return {
        'id': data['cinema_award'].id,
        'name': data['cinema_award'].name,
        'rank': [
            {
                'movie_id': v.movie.id,
                'movie_name': v.movie.name,
                'rank': v.rank,
            }
            for v in data['rank']
        ],
    }

def get_new_movie_instance(i=1):
    movie = MovieFactory(name=f'movie-{i}')
    actor1 = ActorFactory(name=f'actor-{i}-1')
    actor2 = ActorFactory(name=f'actor-{i}-2')

    casting_actor_1 = CastFactory(
        movie=movie, actor=actor1, character_name=f'character-name-{i}-1'
    )
    casting_actor_2 = CastFactory(
        movie=movie, actor=actor2, character_name=f'character-name-{i}-2'
    )

    return {'movie': movie, 'casting': [casting_actor_1, casting_actor_2]}

def get_new_movie_data(i=1):
    data = get_new_movie_instance(i=i)

    return {
        'id': data['movie'].id,
        'name': data['movie'].name,
        'casting': [
            {
                'actor_id': v.actor.id,
                'actor_name': v.actor.name,
                'character_name': v.character_name,
            }
            for v in data['casting']
        ],
    }

# test

class CinemaAPITestCase(APITestCase):
    URL_PREFIX_NAME = 'api:cinema'
    factory_class = MovieFactory

    @classmethod
    def setUpTestData(cls):
        cls.user = UserFactory()

    def test_get_list(self):
        data = get_new_cinema_award_data()

        self.client.force_authenticate(self.user)
        response = self.client.get(
            reverse_lazy(f'{self.URL_PREFIX_NAME}-list')
        )
        self.assertEqual(response.status_code, status.HTTP_200_OK)

        result = response.json()['results'][0]
        assert result['name'] == data['name']
        assert result['rank'] == data['rank']

    def test_get_detail(self):
        data = get_new_cinema_award_data(i=1)

        self.client.force_authenticate(self.user)
        response = self.client.get(
            reverse_lazy(
                f'{self.URL_PREFIX_NAME}-detail', kwargs={'pk': data['id']}
            )
        )
        self.assertEqual(response.status_code, status.HTTP_200_OK)

        result = response.json()
        assert result['name'] == data['name']
        assert result['rank'] == data['rank']

    def test_get_cinema_movies_list(self):
        data = get_new_cinema_award_data(i=1)

        self.client.force_authenticate(self.user)
        response = self.client.get(
            reverse_lazy(f'{self.URL_PREFIX_NAME}-movies')
        )
        self.assertEqual(response.status_code, status.HTTP_200_OK)

        result = response.json()
        assert result[0]['name'] == data['name']
        assert result[0]['rank'] == data['rank']

    def test_get_cinema_awards_by_movie(self):
        cinema1 = get_new_cinema_award_data(i=1)
        cinema2 = get_new_cinema_award_data(i=2)

        new_movie = CinemaAwardMovieFactory(
            cinema_award_id=cinema2['id'],
            movie_id=cinema1['rank'][0]['movie_id'],
            rank=3,
        )

        cinema2['rank'].append(
            {
                'movie_id': new_movie.movie.id,
                'movie_name': new_movie.movie.name,
                'rank': new_movie.rank,
            }
        )

        self.client.force_authenticate(self.user)
        response = self.client.get(
            reverse_lazy(
                f'{self.URL_PREFIX_NAME}-movies', kwargs={'movie_pk': 1}
            )
        )
        self.assertEqual(response.status_code, status.HTTP_200_OK)

        result = response.json()

        data = [cinema1, cinema2]

        assert len(data) == len(result)

        for i in range(len(result)):
            assert result[i]['name'] == data[i]['name']
            assert result[i]['rank'] == data[i]['rank']

    def test_put_cinema_awards_by_movie(self):
        cinema1 = get_new_cinema_award_data(i=1)

        self.client.force_authenticate(self.user)
        response = self.client.put(
            reverse_lazy(
                f'{self.URL_PREFIX_NAME}-movies',
                kwargs={'movie_pk': cinema1['id']},
            )
        )
        self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT)


"""
Tests scikit-imputer converter.
"""
import unittest
import numpy as np
from sklearn.preprocessing import Imputer
from onnxmltools.convert.sklearn.ImputerConverter import ImputerConverter
from onnxmltools.convert.sklearn.convert import convert
from onnxmltools.convert.common.ConvertContext import ConvertContext
from onnxmltools.convert.common.model_util import make_tensor_value_info
from onnxmltools.proto import onnx_proto

class TestSklearnImputerConverter(unittest.TestCase):

    def test_model_imputer(self):
        model = Imputer(missing_values='NaN', strategy='mean', axis=0)
        model.fit([[1, 2], [np.nan, 3], [7, 6]])
        model_onnx = convert(model, 'scikit-learn imputer', [('features', 'int32', 2)])
        self.assertTrue(model_onnx is not None)

    def test_imputer_int_inputs(self):
        model = Imputer(missing_values='NaN', strategy='mean', axis=0)
        model.fit([[1, 2], [np.nan, 3], [7, 6]])

        context = ConvertContext()
        node = ImputerConverter.convert(context, model,
            [make_tensor_value_info('features', onnx_proto.TensorProto.INT32, [2])])
        self.assertTrue(node is not None)

        # should contain two nodes
        self.assertEqual(len(node), 2)
        # last node should contain the Imputer
        outputs = node[-1].outputs
        self.assertEqual(len(outputs), 1)
        self.assertEqual(outputs[0].type.tensor_type.shape.dim[-1].dim_value, 2)

    def test_imputer_float_inputs(self):
        model = Imputer(missing_values='NaN', strategy='mean', axis=0)
        model.fit([[1, 2], [np.nan, 3], [7, 6]])

        context = ConvertContext()
        node = ImputerConverter.convert(context, model,
            [make_tensor_value_info('features', onnx_proto.TensorProto.FLOAT, [2])])
        self.assertTrue(node is not None)

        # should contain two nodes
        self.assertEqual(len(node), 1)

        # last node should contain the Imputer
        outputs = node[-1].outputs
        self.assertEqual(len(outputs), 1)
        self.assertEqual(outputs[0].type.tensor_type.shape.dim[-1].dim_value, 2)


from django.urls import path
from wms import views, services, prints
from interfacing import views as interface_view

urlpatterns = []

# Common
urlpatterns += [
    path('list_of_pharmaceutical_suppliers/', services.ListOfPharmaceuticalSuppliers.as_view()),
    path('list_of_product_combo/', services.ListOfProducts.as_view()),
    path('list_of_logistic_flew_combo/', services.ListOfLogisticFlewTypes.as_view()),
    path('list_of_from_store_authorized_combo/', services.ListOfFromStoreAuthorized.as_view()),
    path('list_of_to_store_authorized_combo/', services.ListOfFromStoreAuthorized.as_view()),
    path('list_of_emplacement_combo/', services.ListOfEmplacements.as_view()),
    path('list_of_product_status_combo/', services.ListOfProductStatus.as_view()),
    path('workload_statistics/', services.WorkloadStatistics.as_view()),
    path('upload_invoice_scan/', views.upload_invoice_scan),

]

# Purchase
urlpatterns += [
    path('list_of_pharmaceutical_purchases_details/', services.ListOfPurchaseDetails.as_view()),
    path('list_of_pharmaceutical_purchases_details_tempo/', services.ListOfPurchaseDetailsTempo.as_view()),
    path('list_of_pharmaceutical_purchases/', services.ListOfPurchase.as_view()),
    path('pharmaceutical_purchases_transactions/', views.pharmaceutical_purchase_transactions),
    path('pharmaceutical_purchases_history/', views.pharmaceutical_purchase_history),
    path('print_pharmaceutical_purchase_receipt/', prints.print_pharmaceutical_purchase_receipt),
    path('upload_purchase_receipt_scan/', views.upload_purchase_receipt_scan),
]

# Purchase confirmation
urlpatterns += [
    path('pharmaceutical_purchase_confirmation/', views.pharmaceutical_purchase_confirmation),
    path('list_of_temporary_executors_for_pharmaceutical_purchase/',
         services.ListOfTemporaryExecutorsForPharmaceuticalPurchase.as_view()),
]

# Invoices management
urlpatterns += [
    path('pharmaceutical_invoices_view/', views.pharmaceutical_invoices),
    path('pharmaceutical_invoices_history/', services.HistoryOfPharmaceuticalInvoices.as_view()),
    path('list_of_pharmaceutical_invoices_combo/', services.ListOfPharmaceuticalInvoices.as_view()),

]

# Inventory reports
urlpatterns += [
    path('inventory_by_emplacement_view', views.inventory_by_emplacement),
    path('inventory_by_emplacement', services.InventoryByEmplacement.as_view()),
    path('export_inventory_by_emplacement', services.ExportInventoryByEmplacement.as_view()),
]

# Transfer
urlpatterns += [
    path('list_of_transfer_details/', services.ListOfTransferDetails.as_view()),
    path('list_of_transfer_details_tempo/', services.ListOfTransferDetailsTempo.as_view()),
    path('list_of_transfer/', services.ListOfTransfer.as_view()),
    path('transfer_transactions/', views.transfer_transactions),
    path('inventory_for_transfer/', services.ListOfAvailableProductsForTransfer.as_view()),
    path('transfer_history/', views.transfer_history),
    path('print_transfer_order/', prints.print_transfer_order)
]

# Transfer confirmation
urlpatterns += [
    path('warehouse_transfer_confirmation/', views.warehouse_transfer_confirmation),
    path('list_of_temporary_executors/', services.ListOfTemporaryExecutorsForTransfer.as_view()),

]

# External Transfer
urlpatterns += [
    path('list_of_external_transfer_details/', services.ListOfExternalTransferDetails.as_view()),
    path('list_of_external_transfer_details_tempo/', services.ListOfExternalTransferDetailsTempo.as_view()),
    path('list_of_external_transfer/', services.ListOfExternalTransfer.as_view()),
    path('external_transfer_transactions/', views.external_transfer_transactions),
    path('external_transfer_history/', views.external_transfer_history),
    path('print_external_transfer_order/', prints.print_external_transfer_order)
]

# External Transfer confirmation, shipping and reception
urlpatterns += [
    path('external_transfer_confirmation/', views.external_transfer_confirmation),
    path('external_transfer_shipping/', views.external_transfer_shipping),
    path('external_transfer_reception/', views.external_transfer_reception),
    path('list_of_temporary_executors_for_external_transfer/',
         services.ListOfTemporaryExecutorsForExternalTransfer.as_view()),
    path('export_external_transfer_data/', services.ExportExternalTransferData.as_view()),
    path('upload_external_transfer/', interface_view.upload_external_transfer),
]


#!/usr/bin/env python
"""Sub-sample sequence from a FASTA, FASTQ or SFF file.

This tool is a short Python script which requires Biopython 1.62 or later
for SFF file support. If you use this tool in scientific work leading to a
publication, please cite the Biopython application note:

Cock et al 2009. Biopython: freely available Python tools for computational
molecular biology and bioinformatics. Bioinformatics 25(11) 1422-3.
http://dx.doi.org/10.1093/bioinformatics/btp163 pmid:19304878.

This script is copyright 2010-2013 by Peter Cock, The James Hutton Institute
(formerly the Scottish Crop Research Institute, SCRI), UK. All rights reserved.
See accompanying text file for licence details (MIT license).

This is version 0.1.0 of the script, use -v or --version to get the version.
"""
import os
import sys

def stop_err(msg, err=1):
    sys.stderr.write(msg.rstrip() + "\n")
    sys.exit(err)

if "-v" in sys.argv or "--version" in sys.argv:
    print("v0.1.0")
    sys.exit(0)

#Parse Command Line
if len(sys.argv) < 5:
    stop_err("Requires at least four arguments: seq_format, in_file, out_file, mode, ...")
seq_format, in_file, out_file, mode = sys.argv[1:5]
if in_file != "/dev/stdin" and not os.path.isfile(in_file):
    stop_err("Missing input file %r" % in_file)

if mode == "everyNth":
    if len(sys.argv) != 6:
        stop_err("If using everyNth, just need argument N (integer, at least 2)")
    try:
        N = int(sys.argv[5])
    except:
        stop_err("Bad N argument %r" % sys.argv[5])
    if N < 2:
        stop_err("Bad N argument %r" % sys.argv[5])
    if (N % 10) == 1:
        sys.stderr.write("Sampling every %ist sequence\n" % N)
    elif (N % 10) == 2:
        sys.stderr.write("Sampling every %ind sequence\n" % N)
    elif (N % 10) == 3:
        sys.stderr.write("Sampling every %ird sequence\n" % N)
    else:
        sys.stderr.write("Sampling every %ith sequence\n" % N)
    def sampler(iterator):
        global N
        count = 0
        for record in iterator:
            count += 1
            if count % N == 1:
                yield record
elif mode == "percentage":
    if len(sys.argv) != 6:
        stop_err("If using percentage, just need percentage argument (float, range 0 to 100)")
    try:
        percent = float(sys.argv[5]) / 100.0
    except:
        stop_err("Bad percent argument %r" % sys.argv[5])
    if percent <= 0.0 or 1.0 <= percent:
        stop_err("Bad percent argument %r" % sys.argv[5])
    sys.stderr.write("Sampling %0.3f%% of sequences\n" % (100.0 * percent))
    def sampler(iterator):
        global percent
        count = 0
        taken = 0
        for record in iterator:
            count += 1
            if percent * count > taken:
                taken += 1
                yield record
else:
    stop_err("Unsupported mode %r" % mode)

def raw_fasta_iterator(handle):
    """Yields raw FASTA records as multi-line strings."""
    while True:
        line = handle.readline()
        if line == "":
            return # Premature end of file, or just empty?
        if line[0] == ">":
            break

    no_id_warned = False
    while True:
        if line[0] != ">":
            raise ValueError(
                "Records in Fasta files should start with '>' character")
        try:
            id = line[1:].split(None, 1)[0]
        except IndexError:
            if not no_id_warned:
                sys.stderr.write("WARNING - Malformed FASTA entry with no identifier\n")
        no_id_warned = True
        id = None
        lines = [line]
        line = handle.readline()
        while True:
            if not line:
                break
            if line[0] == ">":
                break
            lines.append(line)
            line = handle.readline()
        yield "".join(lines)
        if not line:
            return # StopIteration

def fasta_filter(in_file, out_file, iterator_filter):
    count = 0
    #Galaxy now requires Python 2.5+ so can use with statements,
    with open(in_file) as in_handle:
        with open(out_file, "w") as pos_handle:
            for record in iterator_filter(raw_fasta_iterator(in_handle)):
                count += 1
                pos_handle.write(record)
    return count

try:
    from galaxy_utils.sequence.fastq import fastqReader, fastqWriter
    def fastq_filter(in_file, out_file, iterator_filter):
        count = 0
        #from galaxy_utils.sequence.fastq import fastqReader, fastqWriter
        reader = fastqReader(open(in_file, "rU"))
        writer = fastqWriter(open(out_file, "w"))
        for record in iterator_filter(reader):
            count += 1
            writer.write(record)
        writer.close()
        reader.close()
        return count
except ImportError:
    from Bio.SeqIO.QualityIO import FastqGeneralIterator
    def fastq_filter(in_file, out_file, iterator_filter):
        count = 0
        with open(in_file) as in_handle:
            with open(out_file, "w") as pos_handle:
                for title, seq, qual in iterator_filter(FastqGeneralIterator(in_handle)):
                    count += 1
                    pos_handle.write("@%s\n%s\n+\n%s\n" % (title, seq, qual))
        return count

def sff_filter(in_file, out_file, iterator_filter):
    count = 0
    try:
        from Bio.SeqIO.SffIO import SffIterator, SffWriter
    except ImportError:
        stop_err("SFF filtering requires Biopython 1.54 or later")
    try:
        from Bio.SeqIO.SffIO import ReadRocheXmlManifest
    except ImportError:
        #Prior to Biopython 1.56 this was a private function
        from Bio.SeqIO.SffIO import _sff_read_roche_index_xml as ReadRocheXmlManifest
    with open(in_file, "rb") as in_handle:
        try:
            manifest = ReadRocheXmlManifest(in_handle)
        except ValueError:
            manifest = None
        in_handle.seek(0)
        with open(out_file, "wb") as out_handle:
            writer = SffWriter(out_handle, xml=manifest)
            in_handle.seek(0) #start again after getting manifest
            count = writer.write_file(iterator_filter(SffIterator(in_handle)))
            #count = writer.write_file(SffIterator(in_handle))
    return count

if seq_format.lower()=="sff":
    count = sff_filter(in_file, out_file, sampler)
elif seq_format.lower()=="fasta":
    count = fasta_filter(in_file, out_file, sampler)
elif seq_format.lower().startswith("fastq"):
    count = fastq_filter(in_file, out_file, sampler)
else:
    stop_err("Unsupported file type %r" % seq_format)

sys.stderr.write("Sampled %i records\n" % count)


import datetime
import io
import time
from fractions import Fraction

import gpiozero
import picamera
from PIL import Image, ImageStat

def get_average_brightness(image):
    image = image.copy().convert("L")
    return ImageStat.Stat(image).mean[0]

def capture(shutter_speed, iso=800, exposure_mode="off"):
    stream = io.BytesIO()
    camera = picamera.PiCamera(resolution=(1024, 768), framerate=Fraction(1, 6), sensor_mode=3)
    camera.shutter_speed = shutter_speed
    camera.iso = iso
    camera.exposure_mode = exposure_mode

    camera.start_preview()
    time.sleep(1)
    camera.capture(stream, format="png")
    stream.seek(0)
    camera.close()

    return stream

filename = datetime.datetime.now().strftime(r"still_%Y%m%d_%H%M%S.png")

shutter_speed = 500_000
max_shutter_speed = 6_000_000
min_shutter_speed = 1_000

wanted_brightness = 128

led17 = gpiozero.LED(17)
led17.on()
time.sleep(1)

best_image = None
best_brightness = None
best_brightness_delta = 256

print(datetime.datetime.now().isoformat(timespec="seconds"), "START")

for x in range(5):
    stream = capture(shutter_speed)
    image = Image.open(stream)
    brightness = get_average_brightness(image)
    brightness_delta = abs(wanted_brightness-brightness)
    factor = wanted_brightness/brightness
    new_shutter_speed = int(shutter_speed*factor)

    print(
        datetime.datetime.now().isoformat(timespec="seconds"),
        f"seq={x}",
        f"ss=[{shutter_speed:,} => {new_shutter_speed:,}]",
        f"brightness=[{brightness:,.2f}*{factor:,.2f} ~= {wanted_brightness}]"
    )

    if brightness_delta < best_brightness_delta:
        best_image = image
        best_brightness = brightness
        best_brightness_delta = brightness_delta

    if shutter_speed == max_shutter_speed:
        print(datetime.datetime.now().isoformat(timespec="seconds"), "BREAK max shutter speed")
        break
    elif shutter_speed == min_shutter_speed:
        print(datetime.datetime.now().isoformat(timespec="seconds"), "BREAK min shutter speed")
        break
    else:
        shutter_speed = max(min(new_shutter_speed, max_shutter_speed), min_shutter_speed)

print(datetime.datetime.now().isoformat(timespec="seconds"), f"Best brightness: {best_brightness:,.2f}", f"Saving {filename}")
best_image.save(filename)

led17.off()

print(datetime.datetime.now().isoformat(timespec="seconds"), "STOP")


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

import functools

from neutron_lib import exceptions as n_exc
from oslo_log import helpers as log_helpers
from oslo_log import log as logging
from oslo_utils import excutils

from vmware_nsx._i18n import _
from vmware_nsx.services.lbaas import base_mgr
from vmware_nsx.services.lbaas import lb_common
from vmware_nsx.services.lbaas import lb_const
from vmware_nsx.services.lbaas.nsx_v3.implementation import lb_utils
from vmware_nsxlib.v3 import exceptions as nsxlib_exc
from vmware_nsxlib.v3 import load_balancer as nsxlib_lb
from vmware_nsxlib.v3 import utils

LOG = logging.getLogger(__name__)

class EdgePoolManagerFromDict(base_mgr.NsxpLoadbalancerBaseManager):
    def _get_pool_kwargs(self, name=None, tags=None, algorithm=None,
                         description=None):
        kwargs = {
            'snat_translation': {'type': "LBSnatAutoMap"}}
        if name:
            kwargs['name'] = name
        if tags:
            kwargs['tags'] = tags
        if algorithm:
            kwargs['algorithm'] = algorithm
        if description:
            kwargs['description'] = description
        return kwargs

    def _get_pool_tags(self, context, pool):
        return lb_utils.get_tags(self.core_plugin, pool['id'],
                                 lb_const.LB_POOL_TYPE, pool['tenant_id'],
                                 context.project_name)

    def _remove_persistence(self, pool, vs_data):
        sp = pool.get('session_persistence')
        lb_client = self.core_plugin.nsxpolicy.load_balancer
        pp_client = None
        if not sp:
            LOG.debug("No session persistence info for pool %s", pool['id'])
        elif sp['type'] == lb_const.LB_SESSION_PERSISTENCE_HTTP_COOKIE:
            pp_client = lb_client.lb_cookie_persistence_profile
        elif sp['type'] == lb_const.LB_SESSION_PERSISTENCE_APP_COOKIE:
            pp_client = lb_client.lb_cookie_persistence_profile
        else:
            pp_client = lb_client.lb_source_ip_persistence_profile

        persistence_profile_id = vs_data.get('persistence_profile_id')
        if persistence_profile_id:
            pp_client.delete(persistence_profile_id)

    def _process_vs_update(self, context, pool, pool_id, listener, completor):
        vs_client = self.core_plugin.nsxpolicy.load_balancer.virtual_server
        try:
            # Process pool persistence profile and
            # create/update/delete profile for virtual server
            vs_data = vs_client.get(listener['id'])
            if pool and pool_id:
                (persistence_profile_id,
                 post_process_func) = self._setup_session_persistence(
                    pool, self._get_pool_tags(context, pool),
                    listener, vs_data)
            else:
                post_process_func = functools.partial(
                    self._remove_persistence, pool, vs_data)
                persistence_profile_id = None
        except nsxlib_exc.ManagerError:
            with excutils.save_and_reraise_exception():
                completor(success=False)
                LOG.error("Failed to configure session persistence "
                          "profile for pool %(pool_id)s",
                          {'pool_id': pool['id']})
        try:
            # Update persistence profile and pool on virtual server
            vs_client.update(
                listener['id'],
                pool_id=pool_id,
                lb_persistence_profile_id=persistence_profile_id)

            LOG.debug("Updated NSX virtual server %(vs_id)s with "
                      "pool %(pool_id)s and persistence profile %(prof)s",
                      {'vs_id': listener['id'], 'pool_id': pool['id'],
                       'prof': persistence_profile_id})
            if post_process_func:
                post_process_func()
        except nsxlib_exc.ManagerError:
            with excutils.save_and_reraise_exception():
                completor(success=False)
                LOG.error('Failed to attach pool %s to virtual '
                          'server %s', pool['id'], listener['id'])

    def _build_persistence_profile_tags(self, pool_tags, listener):
        tags = pool_tags[:]
        # With octavia loadbalancer name might not be among data passed
        # down to the driver
        lb_data = listener.get('loadbalancer')
        if lb_data:
            tags.append({
                'scope': 'os-lbaas-lb-name',
                'tag': lb_data['name'][:utils.MAX_TAG_LEN]})
        tags.append({
            'scope': 'os-lbaas-lb-id',
            'tag': listener['loadbalancer_id']})
        tags.append({
            'scope': 'os-lbaas-listener-id',
            'tag': listener['id']})
        return tags

    def _setup_session_persistence(self, pool, pool_tags, listener, vs_data):
        sp = pool.get('session_persistence')
        pers_type = None
        cookie_name = None
        cookie_mode = None
        lb_client = self.core_plugin.nsxpolicy.load_balancer
        pp_client = None
        if not sp:
            LOG.debug("No session persistence info for pool %s", pool['id'])
        elif sp['type'] == lb_const.LB_SESSION_PERSISTENCE_HTTP_COOKIE:
            pp_client = lb_client.lb_cookie_persistence_profile
            pers_type = nsxlib_lb.PersistenceProfileTypes.COOKIE
            cookie_name = sp.get('cookie_name')
            if not cookie_name:
                cookie_name = lb_const.SESSION_PERSISTENCE_DEFAULT_COOKIE_NAME
            cookie_mode = "INSERT"
        elif sp['type'] == lb_const.LB_SESSION_PERSISTENCE_APP_COOKIE:
            pp_client = lb_client.lb_cookie_persistence_profile
            pers_type = nsxlib_lb.PersistenceProfileTypes.COOKIE
            # In this case cookie name is mandatory
            cookie_name = sp['cookie_name']
            cookie_mode = "REWRITE"
        else:
            pp_client = lb_client.lb_source_ip_persistence_profile
            pers_type = nsxlib_lb.PersistenceProfileTypes.SOURCE_IP

        if pers_type:
            # There is a profile to create or update
            pp_kwargs = {
                'persistence_profile_id': pool['id'],
                'name': "persistence_%s" % utils.get_name_and_uuid(
                    pool['name'] or 'pool', pool['id'], maxlen=235),
                'tags': self._build_persistence_profile_tags(
                    pool_tags, listener)
            }
            if cookie_name:
                pp_kwargs['cookie_name'] = cookie_name
                pp_kwargs['cookie_mode'] = cookie_mode

        persistence_profile_id = vs_data.get('persistence_profile_id')
        if persistence_profile_id:
            # NOTE: removal of the persistence profile must be executed
            # after the virtual server has been updated
            if pers_type:
                # Update existing profile
                LOG.debug("Updating persistence profile %(profile_id)s for "
                          "listener %(listener_id)s with pool %(pool_id)s",
                          {'profile_id': persistence_profile_id,
                           'listener_id': listener['id'],
                           'pool_id': pool['id']})
                pp_client.update(persistence_profile_id, **pp_kwargs)
                return persistence_profile_id, None
            else:
                # Prepare removal of persistence profile
                return (None, functools.partial(self._remove_persistence,
                                                vs_data))
        elif pers_type:
            # Create persistence profile
            pp_id = pp_client.create_or_overwrite(**pp_kwargs)
            LOG.debug("Created persistence profile %(profile_id)s for "
                      "listener %(listener_id)s with pool %(pool_id)s",
                      {'profile_id': pp_id,
                       'listener_id': listener['id'],
                       'pool_id': pool['id']})
            return pp_id, None
        return None, None

    @log_helpers.log_method_call
    def create(self, context, pool, completor):
        pool_client = self.core_plugin.nsxpolicy.load_balancer.lb_pool

        pool_name = utils.get_name_and_uuid(pool['name'] or 'pool', pool['id'])
        tags = self._get_pool_tags(context, pool)

        description = pool.get('description')
        lb_algorithm = lb_const.LB_POOL_ALGORITHM_MAP.get(pool['lb_algorithm'])
        # NOTE(salv-orlando): Guard against accidental compat breakages
        try:
            listener = pool['listener'] or pool['listeners'][0]
        except IndexError:
            # If listeners is an empty list we hit this exception
            listener = None
        # Perform additional validation for session persistence before
        # creating resources in the backend
        lb_common.validate_session_persistence(pool, listener, completor)
        try:
            kwargs = self._get_pool_kwargs(
                pool_name, tags, lb_algorithm, description)
            pool_client.create_or_overwrite(lb_pool_id=pool['id'], **kwargs)
        except nsxlib_exc.ManagerError:
            completor(success=False)
            msg = (_('Failed to create pool on NSX backend: %(pool)s') %
                   {'pool': pool['id']})
            raise n_exc.BadRequest(resource='lbaas-pool', msg=msg)

        # The pool object can be created with either --listener or
        # --loadbalancer option. If listener is present, the virtual server
        # will be updated with the pool. Otherwise, just return. The binding
        # will be added later when the pool is associated with layer7 rule.
        # FIXME(salv-orlando): This two-step process can leave a zombie pool on
        # NSX if the VS update operation fails
        if listener:
            self._process_vs_update(context, pool, pool['id'], listener,
                                    completor)
        completor(success=True)

    @log_helpers.log_method_call
    def update(self, context, old_pool, new_pool, completor):
        pool_client = self.core_plugin.nsxpolicy.load_balancer.lb_pool

        pool_name = None
        tags = None
        lb_algorithm = None
        description = None
        if new_pool['name'] != old_pool['name']:
            pool_name = utils.get_name_and_uuid(new_pool['name'] or 'pool',
                                                new_pool['id'])
            tags = self._get_pool_tags(context, new_pool)
        if new_pool['lb_algorithm'] != old_pool['lb_algorithm']:
            lb_algorithm = lb_const.LB_POOL_ALGORITHM_MAP.get(
                new_pool['lb_algorithm'])
        if new_pool.get('description') != old_pool.get('description'):
            description = new_pool['description']
        # NOTE(salv-orlando): Guard against accidental compat breakages
        try:
            listener = new_pool['listener'] or new_pool['listeners'][0]
        except IndexError:
            # If listeners is an empty list we hit this exception
            listener = None
            # Perform additional validation for session persistence before
            # operating on resources in the backend
        lb_common.validate_session_persistence(new_pool, listener, completor,
                                               old_pool=old_pool)

        try:
            kwargs = self._get_pool_kwargs(pool_name, tags, lb_algorithm,
                                           description)
            pool_client.update(lb_pool_id=new_pool['id'], **kwargs)
            if (listener and new_pool['session_persistence'] !=
                old_pool['session_persistence']):
                self._process_vs_update(context, new_pool, new_pool['id'],
                                        listener, completor)
            completor(success=True)
        except Exception as e:
            with excutils.save_and_reraise_exception():
                completor(success=False)
                LOG.error('Failed to update pool %(pool)s with '
                          'error %(error)s',
                          {'pool': old_pool['id'], 'error': e})

    @log_helpers.log_method_call
    def delete(self, context, pool, completor):
        pool_client = self.core_plugin.nsxpolicy.load_balancer.lb_pool

        # NOTE(salv-orlando): Guard against accidental compat breakages
        try:
            listener = pool['listener'] or pool['listeners'][0]
        except IndexError:
            # If listeners is an empty list we hit this exception
            listener = None
        if listener:
            try:
                self._process_vs_update(
                    context, pool, None, listener, completor)
            except Exception as e:
                LOG.error('Disassociation of listener %(lsn)s from pool '
                          '%(pool)s failed with error %(err)s',
                          {'lsn': listener['id'],
                           'pool': pool['id'],
                           'err': e})
        try:
            pool_client.delete(pool['id'])
        except nsxlib_exc.ResourceNotFound:
            pass
        except nsxlib_exc.ManagerError:
            completor(success=False)
            msg = (_('Failed to delete lb pool from nsx: %(pool)s') %
                   {'pool': pool['id']})
            raise n_exc.BadRequest(resource='lbaas-pool', msg=msg)

        completor(success=True)

    @log_helpers.log_method_call
    def delete_cascade(self, context, pool, completor):
        self.delete(context, pool, completor)


import random
import discord
from discord.ext import commands

from .inputs import cl, cf, chill, cfe, ur
from .utils import COLOR

class Coffee(commands.Cog):
    def __init__(self, client):
        self.client = client

    @commands.command(aliases=['ask_out'])
    async def wannagrabacoffee(self, ctx, *, member: discord.Member):
        '''Wanna ask someone out on coffee'''
        embed = discord.Embed(
            title=f'{member}, Someone wants to grab a coffee with you...*wink *wink',
            color=COLOR.DEFAULT)
        embed.add_field(name='This happened....', value=f'{random.choice(cf)}')
        embed.set_footer(text='not actually')
        await ctx.send(embed=embed)

    @commands.command(aliases=['brew'])
    async def coffee(self, ctx):
        '''A lovely coffee command (sip, sip)'''
        op = f'{random.choice(cfe)}'
        embed = discord.Embed(title='Coffee',
                              description=op,
                              color=COLOR.DEFAULT)
        embed.set_footer(
            text=f'Caffeiene Level-{random.choice(cl)}.{random.choice(chill)}')
        embed.set_image(url=random.choice(ur))
        await ctx.send(embed=embed)

def setup(client):
    client.add_cog(Coffee(client))