from django.contrib import admin
from django.urls import include, path
from restapp import views
from rest_framework_simplejwt import views as jwt_views

urlpatterns = [
    path('', views.QuickLinks.as_view(), name='QuickLinks'),
    path('api/token/', jwt_views.TokenObtainPairView.as_view(), name='token_obtain_pair'),
    path('api/token/refresh/', jwt_views.TokenRefreshView.as_view(), name='token_refresh'),
    path('api/token/verify/', jwt_views.TokenVerifyView.as_view(), name='token_verify'),
    path('admin/', admin.site.urls),
    path('auth/', include('rest_framework.urls'), name='auth'),
    path('students/', views.StudentsView.as_view(), name='students'),
    path('students/<str:student_name>/', views.StudentDetailView.as_view(), name='single-student'),
    path('allsubjects/', views.AllSubjectView.as_view(), name='allsubjects'),
    path('attendance/', views.AttendanceView.as_view(), name='attendance'),
    path('bookdistribution/', views.BookDistributionView.as_view(), name='bookdistribution'),
    path('class/', views.ClassView.as_view(), name='class'),
    path('classsubjects/', views.ClassSubjectsView.as_view(), name='classsubjects'),
    path('library/', views.LibraryView.as_view(), name='library'),
    path('registration/', views.RegisterUserView.as_view(), name='registration'),
    path('allregistrations', views.AllRegistrationsView.as_view(), name='allregistrations'),
    path('allregistrations/<str:username>', views.SingleRegistrationView.as_view(), name='singleuser'),
    path('teachers/', views.TeachersView.as_view(), name='teachers'),
    path('teachers/<str:teacher_name>/', views.SingleTeacherView.as_view(), name='single-teacher'),
    path('teachersubjects/', views.TeacherSubjectView.as_view(), name='teachersubjects'),
    path('profile/', views.ProfileView.as_view(), name='profile'),
    path('profile/<int:pk>/', views.IndividualProfileView.as_view(), name='SingleProfile'),
    path('uploads/', views.MyUploadsView.as_view(), name='uploads')
]


def mergeSort(inputArray):
    if len(inputArray) >1:

        midIndex = len(inputArray)//2
        left = inputArray[:midIndex]
        right = inputArray[midIndex:]

        mergeSort(left)
        mergeSort(right)

        i=j=k=0

        while i < len(left) and j < len(right):
            if left[i] < right[j] :
                inputArray[k] = left[i]
                i += 1
            else :
                inputArray[k] = right[j]
                j += 1
            k += 1

        while i < len(left):
            inputArray[k] = left[i]
            i += 1;
            k += 1;
        while j < len(right):
            inputArray[k] = right[i]
            j += 1
            k += 1

def printList(inputArray):
    for i in range(len(inputArray)):
        print(inputArray[i], end ="")
    print()

# Driver Code
if __name__ == '__main__':
    inputArray = [12,11,13,5,6,7]
    print("Input Array", end ="\n")
    printList(inputArray)
    mergeSort(inputArray)
    print("Sorted Array", end ="\n")
    printList(inputArray)


import pytest
from great_ai.external.async_lru import alru_cache

pytestmark = pytest.mark.asyncio

async def test_alru_cache_open(check_lru, loop):
    @alru_cache()
    async def coro(val):
        return val

    await coro(1)

    check_lru(coro, hits=0, misses=1, cache=1, tasks=0)

    with pytest.raises(RuntimeError):
        coro.open()

    close = coro.close()

    assert coro.closed

    with pytest.raises(RuntimeError):
        await coro()

    with pytest.raises(RuntimeError):
        coro.open()

    await close

    check_lru(coro, hits=0, misses=0, cache=0, tasks=0)

    coro.open()

    ret = await coro(1)

    assert ret == 1

    check_lru(coro, hits=0, misses=1, cache=1, tasks=0)


import json
from datetime import timedelta

from django.http import JsonResponse
from django.utils import timezone
from oauth2_provider.models import AccessToken
from django.views.decorators.csrf import csrf_exempt

from .models import Order, OrderDetails
from restaurant.models import Meal
from .serializers import OrderSerializer, OrderStatusSerializer

@csrf_exempt
def customer_add_order(request):
    """
        params:
        access_token
        restaurant_id
        address
        order_details (json format), example:
            [{"meal_id": 1, "quantity": 2}, {"meal_id": 2, "quantity": 3}]
        return:
            {"status", "success"}
    """

    if request.method == 'POST':
        access_token = AccessToken.objects.get(
            token=request.POST.get('access_token'),
            expires__gt = timezone.now()
        )

        customer = access_token.user.customer

        if Order.objects.filter(customer=customer).exclude(status=Order.DELIVERED):
            return JsonResponse({"status": "failed", "error": "Your last order must be completed"})

        if not request.POST['address']:
            return JsonResponse({"status": "failed", "error": "Address is required"})

        order_details = json.loads(request.POST["order_details"])

        order_total = 0

        for meal in order_details:
            if not Meal.objects.filter(id=meal["meal_id"], restairant_id=request.POST["restairant_id"]):
                return JsonResponse({"status": "failed", "error": "Meals must be in only one restaurant"})
            else:
                order_total = Meal.objects.get(id=meal["meal_id"]).price * meal["quantity"]

        if len(order_details) > 0:
            order = Order.objects.create(
                customer=customer,
                restairant_id=request.POST["restairant_id"],
                total=order_total,
                status=Order.COOKING,
                address=request.POST["address"]
            )

            for meal in order_details:
                OrderDetails.objects.create(
                    order = order,
                    meal_id = meal["meal_id"],
                    quantity = meal["quantity"],
                    sub_total = Meal.objects.get(id=meal["meal_id"]).price * meal["quantity"]
                )

            return JsonResponse({"status": "success"})

    return JsonResponse({})

def customer_get_latest_order(request):
    """
        params:
        access_token
        return:
            data witl all details about order
    """
    access_token = AccessToken.objects.get(
        token=request.GET.get('access_token'),
        expires__gt = timezone.now()
    )
    customer = access_token.user.customer

    order = OrderSerializer(
        Order.objects.filter(customer=customer).last()
    ).data

    return JsonResponse({ "last": order })

def customer_get_latest_order_status(request):
    """
        params:
        access_token
        return:
            data witl all details about order
    """
    access_token = AccessToken.objects.get(
        token=request.GET.get('access_token'),
        expires__gt = timezone.now()
    )
    customer = access_token.user.customer

    order_status = OrderStatusSerializer(
        Order.objects.filter(customer=customer).last()
    ).data

    return JsonResponse({ "last_order_status": order_status })

def order_notification(request, last_request_time):
    notification = Order.objects.filter(
        restaurant=request.user.restaurant,
        created_at__gt=last_request_time
    ).count()

    return JsonResponse({"notification": notification})

def driver_get_ready_orders(request):
    orders = OrderSerializer(
        Order.objects.filter(status = Order.READY, driver = None).order_by("-id"),
        many=True
    ).data

    return JsonResponse({
        "orders": orders
    })

@csrf_exempt
def driver_pick_order(request):
    """
        params:
        access_token
        order_id
        return:
            {"status", "success"}
    """

    if request.method == 'POST':
        access_token = AccessToken.objects.get(
            token=request.POST.get('access_token'),
            expires__gt = timezone.now()
        )

        driver = access_token.user.driver

        if Order.objects.filter(driver=driver, status=Order.ONTHEWAY):
            return JsonResponse({
                "status": "failed",
                "error": "Your outstanding order is not delivered yet"
            })

        try:
            order = Order.objects.get(
                id = request.POST["order_id"],
                driver = None,
                status = Order.STATUS
            )

            order.driver = driver
            order.status = Order.ONTHEWAY
            order.picked_at = timezone.now()
            order.save()

            return JsonResponse({ "status": "success" })
        except Order.DoesNotExist:
            return JsonResponse({
                "status": "failed",
                "error": "This order has been picked up by another"
            })

def driver_get_latest_order(request):
    access_token = AccessToken.objects.get(
        token=request.GET['access_token'],
        expires__gt = timezone.now()
    )

    driver = access_token.user.driver

    order = OrderSerializer(
        Order.objects.filter(driver=driver, status=Order.ONTHEWAY).last()
    ).data

    return JsonResponse({
        "order": order
    })

@csrf_exempt
def driver_complete_order(request):
    """
        params:
        access_token
        order_id
        return:
            {"status", "success"}
    """

    if request.method == 'POST':
        access_token = AccessToken.objects.get(
            token=request.POST.get('access_token'),
            expires__gt = timezone.now()
        )

        driver = access_token.user.driver

        order = Order.objects.get(
            id = request.POST["order_id"],
            driver = None,
        )

        order.status = Order.DELIVERED
        order.save()

        return JsonResponse({ "status": "success" })

def driver_get_revenue(request):
    access_token = AccessToken.objects.get(
        token=request.POST.get('access_token'),
        expires__gt = timezone.now()
    )

    driver = access_token.user.driver

    revenue = {}
    today = timezone.now()
    current_weekdays = [today + timedelta(days=i) for i in range(0 - today.weekday(), 7 - today.weekday())]

    for day in current_weekdays:
        orders = Order.objects.filter(
            driver = driver,
            status = Order.DELIVERED,
            created_at__year = day.year,
            created_at__month = day.month,
            created_at__day = day.day
        )

        revenue[day.strftime("%a")] = sum(order.total for order in orders)

    return JsonResponse({ "revenue": revenue })


import logging, traceback
logger = logging.getLogger(__name__)
logging.getLogger('packet').setLevel(logging.WARNING)

import socket
from time import time

import packet

class RemoteRawCamera:
    def __init__(self, address, port=10000):
        logger.info('connecting to {}:{}'.format(address, port))

        self._socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self._socket.connect((address, port))

    def read(self):
        images = packet.parse(self._receive)
        logger.debug('received {} images'.format(len(images)))

        if len(images) == 2:
            (color, cloud) = images
            depth_uv = None
        elif len(images) == 3:
            (color, cloud, depth_uv) = images
        else:
            logger.warn('unrecognized number of images from camera')
            raise RuntimeError('unrecognized number of images from camera')

        return (color, cloud, depth_uv)

    def _receive(self, n):
        buf = []

        while n > 0:
            data = self._socket.recv(min(n, 4096))
            n -= len(data)
            buf.append(data)

        logger.debug('received {:.3f} KiB'.format(sum(map(len, buf)) / 1000.0))

        if len(buf) == 1:
            return buf[0]
        else:
            return ''.join(buf)

    def close(self):
        self._socket.close()
        logger.info('disconnected')

if __name__ == '__main__':
    logging.basicConfig(level=logging.DEBUG, format='%(asctime)-15s %(filename)s:%(lineno)d %(levelname)s: %(message)s')
    logging.getLogger('OpenGL').setLevel(99)

    import sys, numpy, matplotlib.cm
    from PySide.QtGui import QApplication

    from ui.numpy_widget import NumpyWidget

    camera = RemoteRawCamera('localhost')

    app = QApplication(sys.argv)
    color_window = NumpyWidget()
    color_window.show()
    depth_window = NumpyWidget()
    depth_window.show()

    colormap = numpy.float32(matplotlib.cm.jet(numpy.arange(1001) / 1000.0))

    n = 0

    try:
        mark = time()
        while True:
            (color, cloud, _) = camera.read()

            color_window.update_frame(color)
            depth_window.update_frame(colormap[numpy.clip(cloud[:,:,2], 0, len(colormap) - 1).astype(numpy.int)])
            app.processEvents()

            n += 1

            if n % 30 == 0:
                # print some debug stats
                fps = 30 / (time() - mark)
                mark = time()
                logger.debug('{:.1f} fps'.format(fps))

    except KeyboardInterrupt:
        pass

    camera.close()


# -*- coding: utf-8 -*-
"""
Created on Wed Feb 15 16:55:38 2023

@author: fitzgeraldj
"""
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns

# read the data from a CSV file
data = pd.read_csv('DepressionReadings.csv')

# convert the "date" column to a datetime object
data['date'] = pd.to_datetime(data['date'])
#data['day'] = pd.to_datetime(data['date'],format='%d/%m/%Y').dt.day
data['timestamp'] = pd.to_datetime(data['timestamp'], format= '%Y/%m/%d %H:%M')
data['day'] = data['timestamp'].dt.day
data['month'] = data['timestamp'].dt.month
data['ddmm'] = data['timestamp'].dt.strftime('%d%m')
#data['no'] = data.groupby('id').cumcount()+1
data.loc[:, 'no'] = data.groupby('id').cumcount() + 1
data.fillna(0, inplace=True)

#extract2225 = data.query("id == 'condition_22' or id == 'control_25'")
extract22 = data.query("id == 'condition_22'")
extract25 = data.query("id == 'control_25'")
#extract19.to_csv('C:/mtu/project/patient16-control28.csv', index=False)
#extract22.loc[:, 'no'] = extract22.groupby('id').cumcount() + 1
#extract25.loc[:, 'no'] = extract25.groupby('id').cumcount() + 1

daily_mean22 = extract22.groupby(['no','id'])['activity'].mean()
daily_mean25 = extract25.groupby(['no','id'])['activity'].mean()
daily_mean22 = daily_mean22.unstack()
daily_mean25 = daily_mean25.unstack()

plt.plot(daily_mean25.index, daily_mean25.values, label="Control 25")
plt.plot(daily_mean22.index, daily_mean22.values, label="Patient 22")

plt.xlabel('Minutes recorded per person')
plt.ylabel('Average activity rate')
plt.title('Daily average activity rate Patient 22 v Control 25')
plt.legend()
plt.show()
# =============================================================================

extract22 = data.query("id == 'condition_22'")
extract25 = data.query("id == 'control_25'")
Patient22 = extract22.groupby(['date'])['activity'].mean()
Control25 = extract25.groupby(['date'])['activity'].mean()

activ = [Patient22,Control25]
#print(activ22)
#boxPlot2522 = []

fig, ax = plt.subplots()

ax.boxplot(activ)

ax.set_xticklabels(['Patient','Control'])
ax.set_ylabel('daily average activity')
#ax.set_xlabel('Patient 22 v Control 25')
ax.set_title("Box plot of daily average activities Patient 22 v Control 25")
plt.show()
# =============================================================================
#Control 9 Pateient 20
extract09 = data.query("id == 'control_9'")
extract20 = data.query("id == 'condition_20'")

#extract09.loc[:, 'no'] = extract09.groupby('id').cumcount() + 1
#extract20.loc[:, 'no'] = extract20.groupby('id').cumcount() + 1

daily_mean09 = extract09.groupby(['no','id'])['activity'].mean()
daily_mean20 = extract20.groupby(['no','id'])['activity'].mean()

daily_mean09 = daily_mean09.unstack()
daily_mean20 = daily_mean20.unstack()

#print(daily_mean09)

plt.plot(daily_mean09.index, daily_mean09.values, label="Control 09")
plt.plot(daily_mean20.index, daily_mean20.values, label="Patient 20")

plt.xlabel('Minutes recorded per person')
plt.ylabel('Average activity rate')
plt.title('Daily average activity rate Patient 20 v Control 09')
plt.legend()
plt.show()

Patient20 = extract20.groupby(['date'])['activity'].mean()
Control09 = extract09.groupby(['date'])['activity'].mean()

active = [Patient20,Control09]

fig, ax = plt.subplots()

ax.boxplot(active)

ax.set_xticklabels(['Patient','Control'])
ax.set_ylabel('daily average activity')
#ax.set_xlabel('Patient 22 v Control 25')
ax.set_title("Box plot of daily average activities Patient 20 v Control 9")
plt.show()

act_mean = data['activity'].mean()        # Calculate the mean age
act_median = data['activity'].median()    # Calculate the median age
act_min = data['activity'].min()          # Calculate the minimum age
act_max = data['activity'].max()          # Calculate the maximum age
act_var = data['activity'].var()          # Calculate the variance of ages
act_std = data['activity'].std()          # Calculate the standard deviation of ages
act_count = data['activity'].count()      # Calculate the number of non-missing age values

print("Activity Stats:  MEAN: "+str(act_mean)," MEDIAN: "+str(act_median))
print("Activity Stats:  MIN: "+str(act_min)," MAX: "+str(act_max))
print("Activity Stats:  Variance: "+str(act_var)," Standard Deviation: "+str(act_std))
print("Activity Stats:  COUNT: "+str(act_count))

data['id2'] = data['id'].str[:5]
data['date'] = data['date'].astype(str)
#maskCondition = (data['id'] == 'condi')
#data['date_id'] = data['date'].astype(str) + '_' + data['id2'].astype(str)

newData = pd.pivot_table(data, values='activity', index='date', columns=(data['id2']=='condi'))

sns.heatmap(newData)


# encoding=utf-8
"""
@Time: 2019/7/5 17:57
@Author: liushuo
@File: get_object.py
@Desc:
@Software: PyCharm
"""

import boto3
from datetime import datetime

client = boto3.client('s3')
objs = client.list_objects(Bucket='l2c-web')
while 'index.html' in objs.keys():
    objs_contents = objs['Contents']
    for i in range(len(objs_contents)):
        filename = objs_contents[i]['Key']

# print(response)


from django.urls import path

from .views import (EmployeesList, EmployeesListBonuses,
                    ProjectsList, addEmployee, bonuses, deleteBonus,
                    employeeBonusEdit, employeeDetail, index,
                    project_period, updateBonuses, updateTariff)

app_name = 'staff'

urlpatterns = [
    path('', index, name='index'),

    path('projects/', ProjectsList.as_view(), name='projects_list'),
    path('projects/<int:pk>/month/',
         project_period, name='project_detail'),
    path('projects_date/<int:id>/editTarrif/',
         updateTariff, name="project_tarrif"),
    path('projects_date/<int:pk>/<str:action>/employees/',
         bonuses, name='bonuses'),
    path('projects_date/<int:pk>/addEmployee/',
         addEmployee, name='add_employee'),

    path('projects_date/<int:pk>/updatebonuses/',
         updateBonuses, name='update_bonus'),
    path('projects_date/<int:pk>/deletebonuses/',
         deleteBonus, name='delete_bonus'),

    path('employees/', EmployeesList.as_view(), name='employee_list'),
    path('employees/<int:pk>/', employeeDetail, name='employee_detail'),
    path('employeesBonus/edit/<int:pk>/',
         employeeBonusEdit, name='employee_bonus_edit'),
    path('employeesBonusTotal/', EmployeesListBonuses.as_view(),
         name='employees_bonuses'),
]


import numpy as np
primes = np.empty(10001, dtype=int)
ind = 2
p = 0
while p <= 10000:
    if 0 in ind % primes[:p]:
        ind += 1
        continue
    primes[p] = ind
    p += 1
    ind += 1
print(primes[-1])


#Joy Arendse-Gorvalla
def Pairs (s): #creating a function that will determine number of pairs in a sentence
    if len(s) == 1 or len(s) == 0:
        return 0
    if s[0] == s[1]:
        return 1 + Pairs(s [2:])
    else:
        return 0 + Pairs(s[1:])

message = input ("Enter a message:\n") #ask user to enter a message
print ("Number of pairs:",Pairs(message)) #displays number of pairs in that message


from django.db import models
from model_utils.models import TimeStampedModel

from ksatria_muslim.children.models import Child

class Package(TimeStampedModel):
    title = models.CharField(max_length=255, unique=True)
    price = models.PositiveIntegerField()

    length = models.PositiveIntegerField()  # length on minutes

    def __str__(self):
        return self.title

class ChildPackage(TimeStampedModel):
    package = models.ForeignKey(Package, on_delete=models.CASCADE, related_name="children")
    child = models.ForeignKey(Child, on_delete=models.CASCADE, related_name="purchased_packages")
    is_exhausted = models.BooleanField(default=False)

    def __str__(self):
        return f"{self.child_id} - {self.package_id}"

    @property
    def remaining(self):
        # total usage in seconds, and package length in minutes
        usages = self.usages.all()
        if not usages:
            return self.package.length

        usage_duration = sum([usage.duration for usage in usages]) / 60
        return self.package.length - usage_duration

class PackageUsage(TimeStampedModel):
    child_package = models.ForeignKey(ChildPackage, on_delete=models.CASCADE, related_name="usages")
    started_at = models.DateTimeField(null=True, blank=True)
    finished_at = models.DateTimeField(null=True, blank=True)

    @property
    def duration(self):
        if not self.finished_at:
            return 0
        return (self.finished_at - self.started_at).total_seconds()

    def __str__(self):
        return f"{self.duration} - {self.child_package_id}"


#!/usr/bin/python
import roslib
import rospy
import actionlib

from math import pi
from cirp_vision.msg import CirpDetectedPieces
from iri_wam_generic_pickorplace.msg import PickOrPlaceAction, PickOrPlaceGoal

LEFT = 0
MIDDLE = 1
RIGHT = 2
HELD = 3
LAST_D = 4
LAST_L = 5

class EnvironmentError(Exception):
    pass

class Environment:

    REST_POINT = [0.22, 0.000, 0.06]
    RIGHT_CTN_POINT = [0.087, 0.531, -0.07] # REAL
    LEFT_CTN_POINT = [0.126, -0.490, -0.07] # REAL
    # LEFT_CTN_POINT = [-0.125, -0.65, -0.2] # SIMULATION
    # RIGHT_CTN_POINT = [-0.125, 0.65, -0.2] # SIMULATION

    def __init__(self):
        rospy.init_node("environment")
        self._th1 = rospy.get_param("~/th1", default=-0.2)
        self._th2 = rospy.get_param("~/th2", default=0.2)
        self._on_table = None
        self._holding = None
        self._last_r = None
        self._last_l = None
        rospy.Subscriber("pieces", CirpDetectedPieces, self._detected_cb)

    def _detected_cb(self, data):
        if not self._on_table:
            rospy.loginfo("First CirpDetectedPieces message received")
        on_table = [None, None, None]
        for color, point in zip(data.colors, data.positions):
            if point.y < self._th1:
                position = LEFT
            elif point.y < self._th2:
                position = MIDDLE
            else:
                position = RIGHT
            if on_table[position] is not None:
                rospy.logwarn("More than one piece in position " + str(position))
            else:
                on_table[position] = (color, [point.x, point.y, point.z])
        self._on_table = on_table

    def _pick(self, location):
        if self._on_table and self._on_table[location] is not None and self._holding is None:
            color = self._on_table[location][0]
            position = self._on_table[location][1]
            action_client = actionlib.SimpleActionClient("pick_or_place",
                    PickOrPlaceAction)
            rospy.loginfo("Waiting for action server...")
            action_client.wait_for_server()
            goal = PickOrPlaceGoal()
            goal.ini_point = position[0:2] + [position[2]+0.1]
            goal.grasp_point = position # REAL
            # goal.grasp_point = position[0:2] + [position[2]-0.005] # SIMULATION
            goal.end_point = Environment.REST_POINT
            goal.ini_EF_rpy = [pi, 0, pi]
            goal.end_EF_rpy = [pi, 0, pi]
            goal.pick = True
            goal.execute = True
            action_client.send_goal(goal)
            rospy.loginfo("Executing pick action...")
            action_client.wait_for_result(rospy.Duration(60.0))
            result = action_client.get_result()
            if result.successful:
                self._holding = color
        return self.get_current_state()

    def _put(self, where):
        if self._holding is not None:
            color = self._holding
            action_client = actionlib.SimpleActionClient("pick_or_place",
                    PickOrPlaceAction)
            rospy.loginfo("Waiting for action server...")
            action_client.wait_for_server()
            goal = PickOrPlaceGoal()
            if where == LEFT:
                goal.ini_point = list(Environment.LEFT_CTN_POINT)
                goal.grasp_point = Environment.LEFT_CTN_POINT
            else:
                goal.ini_point = list(Environment.RIGHT_CTN_POINT)
                goal.grasp_point = Environment.RIGHT_CTN_POINT
            # goal.ini_point[-1] += 0.2
            goal.end_point = Environment.REST_POINT
            goal.ini_EF_rpy = [pi, 0, pi]
            goal.end_EF_rpy = [pi, 0, pi]
            goal.pick = False
            goal.execute = True
            action_client.send_goal(goal)
            rospy.loginfo("Executing put action...")
            action_client.wait_for_result(rospy.Duration(60.0))
            result = action_client.get_result()
            if result.successful:
                self._holding = None
                if where == LEFT:
                    self._last_l = color
                else:
                    self._last_r = color
        return self.get_current_state()

    def execute_action(self, action):
        if action == "pickL":
            return self._pick(LEFT)
        elif action == "pickM":
            return self._pick(MIDDLE)
        elif action == "pickR":
            return self._pick(RIGHT)
        elif action == "putL":
            return self._put(LEFT)
        elif action == "putR":
            return self._put(RIGHT)
        else:
            raise EnvironmentError("Unknown action: " + action)

    def get_current_state(self):
        if not self._on_table:
            rospy.logwarn("There is no data about the pieces on the table yet")
            on_table = [None, None, None]
        else:
            # in Python3, explicit conversion to list is required
            on_table = map(lambda t: t[0] if t else None, self._on_table)
        state = on_table + [self._holding, self._last_l, self._last_r]
        return state

if __name__ == "__main__":
    env = Environment()
    rospy.sleep(rospy.Duration(1.0))
    # env.execute_action("pickM")
    # env.execute_action("putL")
    # env.execute_action("pickL")
    # env.execute_action("putR")
    # env.execute_action("pickR")
    # env.execute_action("putR")
    quit = False
    while not quit:
        cmd = int(raw_input("Select command: (1) query_state; "
            "(2) pickL; (3) pickM; (4) pickR; (5) putL; (6) putR; (7) exit: "))
        if cmd == 1:
            print(env.get_current_state())
        elif cmd == 2:
            print(env.execute_action("pickL"))
        elif cmd == 3:
            print(env.execute_action("pickM"))
        elif cmd == 4:
            print(env.execute_action("pickR"))
        elif cmd == 5:
            print(env.execute_action("putL"))
        elif cmd == 6:
            print(env.execute_action("putR"))
        elif cmd == 7:
            print("Shutting down...")
            quit = True
        else:
            rospy.logerr("Unknown cmd: " + str(cmd))


# -*- coding: utf-8 -*-
# encoding: utf-8

import os
import time
import ast
import copy
import json

from multi_web import MultiWEB

########################################################################
class LightAPI(MultiWEB):
    """
    Light API for MultiWEB
    """

    #----------------------------------------------------------------------
    def __init__(self, *args, **kwargs):
        """
        Init MapsWEB constructor
        """
        MultiWEB.__init__(self, *args, **kwargs)
        """
        create map name 'api'
        """
        # invariable name for api
        self.invariable_name += ['api']
        self.api2maps = {
            'api': {
                "request": self.request_api,
                "content": 'api',
                "timestamp": 0,
                "multi": False
            }
        }
        self.maps.update(self.api2maps)
        """
        API schema dict
            'api key name':{
                    'obj': self.api_module_name,
                    'args': { # need args
                        'arg_name': [type1,type2] #types list in priotity
                    },
                    'opts': {} #optional args - type as 'args'
                }
            # int input for bool data type
        """
        self.api_args_keys = ["args"]
        self.api_opts_keys = ["opts"]
        self.api_schema = {
            "help": {
                "obj": self.api_help,
                "opts": {
                    "name": str,
                    },
                },
            "test": {
                "obj": self.api_test,
                "args": {
                    "data": [
                        int,
                        float,
                        unicode,
                        ],
                    },
                },
            "sources": {
                "obj": self.api_sources,
                "opts": {
                    "index": int,
                    "enable": bool,
                    },
                },
            "formats": {
                "obj": self.api_formats,
                "opts": {
                    "name": str,
                    "enable": bool,
                    },
                },
            "maps": {
                "obj": self.api_maps,
                "opts": {
                    "name": str,
                    "del": bool,
                    },
                },
            "serialize": {
                "obj": self.api_serialize,
                "opts": {
                    "name": str,
                    "replace": bool,
                    },
                },
            "timeout": {
                "obj": self.api_timeout,
                "args": {
                    "sec": int,
                    },
                "opts": {
                    "name": str,
                    },
                },
            }

    def api_help(self, **kwargs):
        """
        default api method:
            def method_name(self, **kwargs)
                return dict{} or tuple(result,content_type)
        """
        # find help for key 'name'
        if kwargs.has_key('name'):
            if self.api_schema.has_key(kwargs['name']):
                all_api_schema = {kwargs['name']: self.api_schema[kwargs['name']]}
            else:
                all_api_schema = {}
        else:
            all_api_schema = self.api_schema
        # gen help dict
        schema_help = {}
        for key in all_api_schema:
            schema_help[key] = {}
            for subkey in self.api_args_keys + self.api_opts_keys:
                if self.api_schema[key].has_key(subkey):
                    schema_help[key][subkey] = {}
                    args = self.api_schema[key][subkey]
                    for arg in args:
                        types = args[arg]
                        if not isinstance(types, list): types = [types]
                        schema_help[key][subkey][arg] = [my.__name__ for my in types]
        return {
            "api_keys": schema_help,
        }

    def api_test(self, **kwargs):
        return {
            "data_type": type(kwargs["data"]).__name__,
            "data_value": kwargs["data"],
        }

    def api_sources(self, **kwargs):
        if kwargs.has_key('index'):
            index = kwargs['index']
            if index + 1 <= len(self.serial_src):
                src_out = [self.serial_src[index]]
            else:
                return {
                    'result': False,
                    'error': 'Index too large',
                }
        else:
            src_out = self.serial_src
        # test to found
        if len(src_out) == 0:
            return {
                "result": False,
                "error": "Sources not found",
            }
        else:
            # enable
            if kwargs.has_key('enable'):
                for src in src_out:
                    src['enable'] = kwargs['enable']
            #query to list
            out = copy.deepcopy(src_out)
            for src in out:
                if src.has_key('query'):
                    if not isinstance(src['query'], list):
                        src['query'] = src['query'].split('\n')
        return {
            "sources": out,
        }

    def api_formats(self, **kwargs):
        # find format for key 'name'
        if kwargs.has_key('name'):
            if self.serial_formats.has_key(kwargs['name']):
                if kwargs.has_key('enable'):
                    self.serial_formats[kwargs['name']]['enable'] = kwargs['enable']
                all_formats = {kwargs['name']: self.serial_formats[kwargs['name']]}
            else:
                all_formats = {}
        else:
            all_formats = self.serial_formats
        # create out
        out = {
            "formats": {},
        }
        for key in all_formats:
            out['formats'][key] = all_formats[key]['enable']
        return out

    def api_maps(self, **kwargs):
        out = {}
        # find map for key 'name'
        if kwargs.has_key('name'):
            if self.maps.has_key(kwargs['name']):
                all_maps = {kwargs['name']: self.maps[kwargs['name']]}
            else:
                all_maps = {}
        else:
            all_maps = self.maps
        # gen maps dict
        maps_out = {}
        for key in all_maps:
            if key not in self.invariable_name:
                # time
                if self.maps[key]['timestamp'] != 0:
                    data_time = time.ctime(int(self.maps[key]['timestamp']))
                else:
                    data_time = 'unlimited'
                # request & map data
                map_cont = self.maps[key]['content']
                map_format = self.maps[key]['format']
                metadata = self.serial_formats[map_format]['metadata'](map_cont)
                maps_out[key] = {
                    'format': map_format,
                    'metadata': metadata,
                    'multi': int(self.maps[key]['multi']),
                    'datatime': data_time,
                }
        # test to found
        if maps_out == {}:
            return {
                "result": False,
                "error": "Maps not found",
            }
        else:
            out['maps'] = maps_out
        # delete
        if kwargs.has_key('del') and kwargs.has_key('name'):
            if kwargs['del']:
                del(self.maps[kwargs['name']])
                out['delete'] = True
        return out

    def api_serialize(self, **kwargs):
        if kwargs.has_key('replace'):
            replace = kwargs['replace']
        else:
            replace = True
        if kwargs.has_key('name'):
            map_name = kwargs['name']
            if self.maps.has_key(map_name) and not replace:
                return {
                    "serialize": map_name,
                    "error": "replace is not allow",
                    "result": False,
                }
            else:
                map_ = self.serializer(map_name)
                if map_ and map_name not in self.invariable_name:
                    self.maps[map_name] = map_
                    return {
                        "serialize": map_name,
                        "result": True,
                    }
                else:
                    return {
                        "serialize": map_name,
                        "error": "Map is not found",
                        "result": False,
                    }
        else:
            self.full_serializer(replace=replace)
            return {
                "serialize": "full",
                "result": True,
            }

    def api_timeout(self, **kwargs):
        # find map for key 'name'
        if kwargs.has_key('name'):
            if self.maps.has_key(kwargs['name']):
                all_map_nam = [kwargs['name']]
            else:
                all_map_nam = []
        else:
            all_map_nam = [my for my in self.maps]
        # cleant map for timeout
        clean_map_nam = []
        cur_time = time.time()
        for map_name in all_map_nam:
            map_time = self.maps[map_name]['timestamp']
            if cur_time - map_time > kwargs['sec'] and map_time != 0:
                del(self.maps[map_name])
                clean_map_nam.append(map_name)
        return {
            'clean': clean_map_nam,
        }

    def metadata4mapnik(self, map_cont):
        return {}

    def request_api(self, env, data):
        # find query string value
        query_string = env['QUERY_STRING'].split('&')
        query_method = query_string.pop(0)
        query_args = {}
        for sval in query_string:
            sval_div = sval.split('=')
            if len(sval_div) == 2:
                query_args[sval_div[0]] = sval_div[-1]

        # validization
        valid = True
        if self.api_schema.has_key(query_method):
            for subkey in self.api_args_keys + self.api_opts_keys:
                if self.api_schema[query_method].has_key(subkey):
                    need = self.api_schema[query_method][subkey]
                else:
                    need = {}
                for arg in need:
                    if query_args.has_key(arg):
                        arg_data = query_args[arg]
                        if isinstance(need[arg], list):
                            arg_types = need[arg]
                        else:
                            arg_types = [need[arg]]
                        for arg_type in arg_types:
                            valid = False
                            try:
                                if arg_type is bool:
                                    query_args[arg] = arg_type(int(arg_data))
                                else:
                                    query_args[arg] = arg_type(arg_data)
                            except:
                                pass
                            else:
                                valid = True
                                break
                        if not valid:
                            err = "Argument '{0}' for API Key '{1}' wrong type".format(
                                arg,
                                query_method
                            )
                            break
                    elif subkey in self.api_args_keys:
                        valid = False
                        err = "Argument '{0}' for API Key '{1}' not found".format(
                            arg,
                            query_method
                        )
                        break
        elif query_method == '':
            query_method = 'help'
        else:
            valid = False
            err = "API Key '{}' not found".format(query_method)

        # run api method
        if valid:
            out = self.api_schema[query_method]["obj"](**query_args)
        else:
            out = {
                "error": err,
                "result": False,
            }

        # init reslt and content type
        if isinstance(out, tuple):
            result, content_type = out
        elif isinstance(out, dict):
            content_type = 'application/json'
            if not out.has_key('result'):
                out['result'] = True
            result = b'{}'.format(json.dumps(out))
        else:
            out = {
                "error": "Not valid output for API Method {}".format(query_method),
                "result": False,
            }
            content_type = 'application/json'
            result = b'{}'.format(json.dumps(out))

        out_req = (content_type, result)
        return out_req


import unittest
from src.nlp_model.utils import load_reviews, extract_texts_and_labels
from src.nlp_model.train import train_model
from sklearn.metrics import precision_score, recall_score

class TestModelMetrics(unittest.TestCase):
    def setUp(self):
        reviews = load_reviews('./data/review_100_samples.json')
        texts, labels = extract_texts_and_labels(reviews)

        model, data_val, labels_val = train_model(texts, labels)
        self.y_pred = model.predict(data_val)
        self.y_true = labels_val

    def test_precision_score_should_be_above_threshold(self):
        p = precision_score(self.y_true, self.y_pred)

        self.assertGreaterEqual(p, 0.5)

    def test_recall_score_should_be_above_threshold(self):
        r = recall_score(self.y_true, self.y_pred)

        self.assertGreaterEqual(r, 0.5)


import requests

lausanne_lat = 46.520
lausanne_long = 6.620

API_URL = "https://api.sunrise-sunset.org/json"

parameters = {
    "lat": lausanne_lat,
    "lng": lausanne_long,
    "formatted": 0
}

response = requests.get(url=API_URL, params=parameters, timeout=5)
response.raise_for_status()
data = response.json()
sunrise =  data["results"]["sunrise"]
sunset = data["results"]["sunset"]

print(f"Sunrise: {sunrise.split('T')[1].split('+')[0]} / Sunset: {sunset.split('T')[1].split('+')[0]}")


znamespace
SpriteKind
Enemy2 = SpriteKind.create()

def on_a_pressed():
    if steve.vy == 0:
        steve.vy = -200
controller.A.on_event(ControllerButtonEvent.PRESSED, on_a_pressed)

def on_overlap_tile(sprite, location):
    info.change_life_by(-1)
scene.on_overlap_tile(SpriteKind.player,
    assets.tile("""
        lava
    """),
    on_overlap_tile)

def on_overlap_tile2(sprite, location):
    global steve, myEnemy2, myEnemy1
    tiles.set_tilemap(tilemap("""
        level3
    """))
    scene.set_background_color(9)
    steve = sprites.create(assets.image("""
        steve
    """), SpriteKind.player)
    steve.ay = 500
    controller.move_sprite(steve, 150, 0)
    scene.camera_follow_sprite(steve)
    mouse_button.destroy()
    info.set_life(3)
    myEnemy2 = sprites.create(assets.image("""
        grim reeper
    """), SpriteKind.enemy)
    tiles.place_on_random_tile(myEnemy2, assets.tile("""
        test
    """))
    myEnemy2.follow(steve, 20)
    info.set_score(0)
    myEnemy1 = sprites.create(assets.image("""
        duck
    """), SpriteKind.Enemy2)
    myEnemy1.follow(steve, 30)
    tiles.place_on_random_tile(myEnemy1, assets.tile("""
        duck1
    """))
scene.on_overlap_tile(SpriteKind.player,
    assets.tile("""
        play2
    """),
    on_overlap_tile2)

def on_overlap_tile3(sprite, location):
    if controller.A.is_pressed():
        steve.vy = -150
scene.on_overlap_tile(SpriteKind.player,
    assets.tile("""
        under water
    """),
    on_overlap_tile3)

def on_overlap_tile4(sprite, location):
    global steve, myEnemy2, myEnemy1
    scene.set_background_color(9)
    tiles.set_tilemap(tilemap("""
        level1
    """))
    steve = sprites.create(assets.image("""
        steve
    """), SpriteKind.player)
    steve.ay = 500
    controller.move_sprite(steve, 150, 0)
    scene.camera_follow_sprite(steve)
    mouse_button.destroy()
    info.set_life(3)
    myEnemy2 = sprites.create(assets.image("""
        grim reeper
    """), SpriteKind.enemy)
    tiles.place_on_random_tile(myEnemy2, assets.tile("""
        test
    """))
    myEnemy2.follow(steve, 20)
    info.set_score(0)
    myEnemy1 = sprites.create(assets.image("""
        duck
    """), SpriteKind.Enemy2)
    myEnemy1.follow(steve, 30)
    tiles.place_on_random_tile(myEnemy1, assets.tile("""
        duck1
    """))
scene.on_overlap_tile(SpriteKind.player,
    assets.tile("""
        play
    """),
    on_overlap_tile4)

def on_menu_pressed():
    global mouse_button
    tiles.set_tilemap(tilemap("""
        main menu
    """))
    scene.set_background_color(13)
    mouse_button = sprites.create(assets.image("""
        mouse button
    """), SpriteKind.player)
    controller.move_sprite(mouse_button)
    steve.destroy()
controller.menu.on_event(ControllerButtonEvent.PRESSED, on_menu_pressed)

def on_life_zero():
    global picture
    steve.destroy()
    picture = sprites.create(assets.image("""
        picture
    """), SpriteKind.projectile)
    assets.image("""
        picture
    """).fill(info.score())
    info.start_countdown(0)
info.on_life_zero(on_life_zero)

def on_overlap_tile5(sprite, location):
    global steve, myEnemy2, myEnemy1
    scene.set_background_color(9)
    tiles.set_tilemap(tilemap("""
        level7
    """))
    steve = sprites.create(assets.image("""
        steve
    """), SpriteKind.player)
    steve.ay = 500
    controller.move_sprite(steve, 150, 0)
    scene.camera_follow_sprite(steve)
    mouse_button.destroy()
    info.set_life(3)
    myEnemy2 = sprites.create(assets.image("""
        grim reeper
    """), SpriteKind.enemy)
    tiles.place_on_random_tile(myEnemy2, assets.tile("""
        test
    """))
    myEnemy2.follow(steve, 20)
    info.set_score(0)
    myEnemy1 = sprites.create(assets.image("""
        duck
    """), SpriteKind.Enemy2)
    myEnemy1.follow(steve, 30)
    tiles.place_on_random_tile(myEnemy1, assets.tile("""
        duck1
    """))
scene.on_overlap_tile(SpriteKind.player,
    assets.tile("""
        p
    """),
    on_overlap_tile5)

def on_on_overlap(sprite, otherSprite):
    info.change_score_by(1)
    myEnemy1.destroy()
sprites.on_overlap(SpriteKind.player, SpriteKind.Enemy2, on_on_overlap)

def on_overlap_tile6(sprite, location):
    tiles.set_tilemap(tilemap("""
        level0
    """))
    scene.set_background_color(4)
scene.on_overlap_tile(SpriteKind.player,
    assets.tile("""
        nether portll
    """),
    on_overlap_tile6)

def on_on_overlap2(sprite, otherSprite):
    info.change_life_by(-1)
    myEnemy2.destroy()
sprites.on_overlap(SpriteKind.player, SpriteKind.enemy, on_on_overlap2)

picture: Sprite = None
myEnemy1: Sprite = None
myEnemy2: Sprite = None
steve: Sprite = None
mouse_button: Sprite = None
tiles.set_tilemap(tilemap("""
    main menu
"""))
scene.set_background_color(13)
mouse_button = sprites.create(assets.image("""
    mouse button
"""), SpriteKind.player)
controller.move_sprite(mouse_button)
scene.camera_follow_sprite(mouse_button)


from jax import numpy as jnp

from tensorflow_probability.substrates import jax as tfp_jax
from tensorflow_probability.substrates import numpy as tfp_np
tfd_np = tfp_jax.distributions
tfb_np = tfp_jax.bijectors

class ClippingBijector(tfb_np.Bijector):
  '''
  dummy clipping bijector that just restricts the values of the input in the reversed direction
  keeping the forward direction unchanged and making the ILDJ 0.0 regardless.

  This is necessary because bounding bijectors using Sigmoid or Softplus are undefined at the extremes.
  '''
  def __init__(self, clip_value_min=None, clip_value_max=None, clip_epsilon=4e-6, validate_args=False, name="clipping_bijector"):
      super().__init__(
          validate_args=validate_args,
          forward_min_event_ndims=0,
          name=name)

      self._clip_value_min = clip_value_min + clip_epsilon if clip_value_min is not None else jnp.finfo(jnp.float32).min
      self._clip_value_max = clip_value_max - clip_epsilon if clip_value_max is not None else jnp.finfo(jnp.float32).max

  def _forward(self, x):
      return x

  def _inverse(self, y):
      return jnp.clip(y, self._clip_value_min, self._clip_value_max)

  def _inverse_log_det_jacobian(self, y):
      # Return 0.0 for the ILDJ
      return jnp.zeros_like(y)

  def _forward_log_det_jacobian(self, x):
      # Return 0.0 for the FLDJ
      return jnp.zeros_like(x)

def make_bounding_bijector_np(lower_bound=None, upper_bound=None):
  if lower_bound is not None and upper_bound is not None:
    scale = upper_bound - lower_bound
    shift = lower_bound
    return tfb_np.Chain([
      ClippingBijector(clip_value_min=lower_bound, clip_value_max=upper_bound),
      tfb_np.Shift(shift=shift),
      tfb_np.Scale(scale=scale),
      tfb_np.Sigmoid()
    ])
  elif lower_bound is not None:
    return tfb_np.Chain([
      ClippingBijector(clip_value_min=lower_bound),
      tfb_np.Shift(shift=lower_bound),
      tfb_np.Softplus()
    ])
  elif upper_bound is not None:
    return tfb_np.Chain([
      ClippingBijector(clip_value_max=upper_bound),
      tfb_np.Shift(shift=upper_bound),
      tfb_np.Scale(scale=-1),
      tfb_np.Softplus()
    ])
  else:
    return tfb_np.Identity()

def make_standardization_bijector_np(mean, std):
  return tfb_np.Chain([tfb_np.Shift(shift=mean),
                    tfb_np.Scale(scale=std)])

def make_bounding_and_standardization_bijector_np(variable_metadata):
  mean, std, lower_bound, upper_bound = map(lambda x: getattr(variable_metadata, x), ['mean', 'std', 'lower_bound', 'upper_bound'])
  return tfb_np.Chain([make_bounding_bijector_np(lower_bound, upper_bound),
                    make_standardization_bijector_np(mean, std)])