#!/usr/bin/env python
import rospy
import numpy as np
from sensor_msgs.msg import Image
import cv2
from cv_bridge import CvBridge, CvBridgeError
from std_msgs.msg import Float32
from carla_msgs.msg import CarlaEgoVehicleStatus
from lane_detector import detect
#---------
# Task: Complete pid_control() function which computes 'steering_command' using PID control.
#---------
role_name = 'brandons_ride'
image_topic_name = "/carla/{}/rgb_front/image".format(role_name)
vehicle_status_topic_name = "/carla/{}/vehicle_status".format(role_name)
frame = None
bridge = CvBridge()
def image_callback(ros_image):
    global frame
    frame = bridge.imgmsg_to_cv2(ros_image, "bgr8")

FREQ = 20   #Hz (it's not a period)
dt = 1/float(FREQ)
prev_CTE = 0

current_speed = 0
prev_speed_error = 0
desired_speed = 55
def vehicle_status_callback(cmd):
    print("in lane follower callback")
    global current_speed
    current_speed = cmd.velocity

def speed_control():
	global prev_speed_error
	kp = 0.0078
	kd = 0.006
	speed_error = desired_speed-current_speed
	throttle_command = -(kp*speed_error + kd*(speed_error-prev_speed_error)/dt)
	prev_speed_error = speed_error
	return throttle_command

prev_CTEs = [0]
window_len = 5

def pid_control():
    global prev_CTE
    if frame is None:
        return
    frame_copy = np.copy(frame)
    CTE, cnt_left, cnt_right = detect(frame_copy)   #calls lane_detector.detect

    prev_CTEs.append(CTE)
    if len(prev_CTEs) > window_len:
        del prev_CTEs[0]

    cur_len = len(prev_CTEs)

    avg_CTE = sum(prev_CTEs)/float(cur_len)

    # working things out on paper will convince you that the following formula
    #   is true

    cur_deriv = (prev_CTEs[-1]-prev_CTEs[0])/cur_len

    kp = 0.0011 # proportional control, a gain that scales with the error
                 # Moves the car toward the reference point (center of lane)
    kd = 0.000 # derivative control, job is to decrease oscillation (steers car away from reference line)
                # Acts like a "brake" conteracts the correctional force, reduces overshoot by slowing
                # the correction factor as the target reference is approached

                # integral control, control is proportional to both error and duration of
                # error. Over time, if error accumulates, then correction increases over time
                # too.
    #---------
    steering_command = -(kp*CTE + kd*(CTE-prev_CTE)/dt)
    #steering_command = -(kp*avg_CTE + kd*cur_deriv)
    print("derivative: " + str(cur_deriv))
    #---------
    prev_CTE = CTE
    #print("Steering command: ", steering_command)
    print("CTE: ", CTE)
    return steering_command

if __name__ == '__main__':
    try:
        rospy.Subscriber(image_topic_name, Image, image_callback)
        rospy.Subscriber(vehicle_status_topic_name, CarlaEgoVehicleStatus, vehicle_status_callback)
        pub_steer = rospy.Publisher('/carla/{}/cv_steer'.format(role_name), Float32, queue_size=1)
        pub_throttle = rospy.Publisher('/carla/{}/throttle_control'.format(role_name), Float32, queue_size=1)
        rospy.init_node('lane_follower', anonymous=False)
        rate = rospy.Rate(FREQ)
        while not rospy.is_shutdown():
            steering_command = pid_control()
            # take care of steering
            speed_command = speed_control()
            # publish stuff
            pub_throttle.publish(speed_command) # TODO: throttle vs speed
            pub_steer.publish(steering_command)
            rate.sleep()

    except rospy.ROSInterruptException:
        pass


from pymongo import *
from tkinter import *
from tkinter.ttk import *
class view:
    def __init__(self):
        self.root=Tk()
        self.t1=Treeview(self.root,columns=("eid","name","Age","Post","salary"))
        self.t1.heading("eid", text="Employee_Id")
        self.t1.heading("name",text="Employee_Name")
        self.t1.heading("Age",text="Age")
        self.t1.heading("Post",text="Post")
        self.t1.heading("salary",text="Salary")
        self.t1["show"]="headings"
        myclient = MongoClient("mongodb://localhost:27017/")
        mydb = myclient["employee"]
        mycol = mydb["employee_data"]
        result=mycol.find({})
        i=0
        for row in result:
            self.t1.insert("",index=i,value=[row["eid"],row["name"],row["Age"],row["Post"],row["salary"]])
            i=i+1
        self.t1.pack()
        self.root.mainloop()


n = int(input())
given_A = list(map(int, input().split()))
A = []
for kabuka in given_A:
    if len(A) > 0 and kabuka == A[-1]:
        continue
    else:
        A.append(kabuka)

# 株価が全て同じ時のコーナーケース
if len(A) == 1:
    print(1000)
    exit()

money = 1000
stock = 0
n = len(A)
for i in range(len(A)):
    if i == 0:
        if A[i] < A[i + 1]:
            stock = money // A[i]
            money = money % A[i]
    elif i == n - 1:
        if A[i - 1] < A[i]:
            money += stock*A[i]
            stock = 0
    else:
        if (A[i - 1] < A[i]) & (A[i] > A[i + 1]):
            money += stock*A[i]
            stock = 0
        elif (A[i - 1] > A[i]) & (A[i] < A[i + 1]):
            stock = money // A[i]
            money = money % A[i]
print(money)


from django.db.models import Sum
from django.views.generic import ListView
from .models import StateStats

class ViewCoveredRegions(ListView):
    model = StateStats
    template_name = 'index.html'

    def get_context_data(self, *, object_list=None, **kwargs):
        context = super(ViewCoveredRegions, self).get_context_data(**kwargs)

        stats_list = StateStats.objects.all()
        stats_data = []

        total_rigid_waste = StateStats.objects.aggregate(rigid_waste=Sum('rigid'))['rigid_waste']
        total_flexible_waste = StateStats.objects.aggregate(flexible_waste=Sum('flexible'))['flexible_waste']
        total_mlp_waste = StateStats.objects.aggregate(mlp_waste=Sum('mlp'))['mlp_waste']

        for state_details in stats_list:
            total_waste = StateStats.total_waste(state_details)
            if total_waste > 2000:
                color = '#0E2433'
                recovery_rank = 1
            elif 1500 < total_waste <= 2000:
                color = '#296D9E'
                recovery_rank = 2
            else:
                color = '#45B6FE'
                recovery_rank = 3

            stats_data.append({
                "state_code": state_details.state_code,
                "state_name": state_details.state_name,
                "rigid": state_details.rigid,
                "flexible": state_details.flexible,
                "mlp": state_details.mlp,
                "total_waste": total_waste,
                "color": color,
                "recovery_rank": recovery_rank
            })

        # print(stats_list)
        context['stats_data'] = stats_data
        context['total_rigid_waste'] = total_rigid_waste
        context['total_flexible_waste'] = total_flexible_waste
        context['total_mlp_waste'] = total_mlp_waste
        return context


from beartype.typing import (
    Any,
    Callable,
    Union,
)
from jax import lax
from jax.experimental import host_callback
from jaxtyping import Float  # noqa: TCH002
from tqdm.auto import tqdm

from gpjax.typing import Array  # noqa: TCH001

def progress_bar(num_iters: int, log_rate: int) -> Callable:
    r"""Progress bar decorator for the body function of a `jax.lax.scan`.

    Example:
    ```python
        >>> import jax.numpy as jnp
        >>> import jax
        >>>
        >>> carry = jnp.array(0.0)
        >>> iteration_numbers = jnp.arange(100)

        >>> @progress_bar(num_iters=iteration_numbers.shape[0], log_rate=10)
        >>> def body_func(carry, x):
        ...    return carry, x
        >>>
        >>> carry, _ = jax.lax.scan(body_func, carry, iteration_numbers)
    ```

    Adapted from this [excellent blog post](https://www.jeremiecoullon.com/2021/01/29/jax_progress_bar/).

    Might be nice in future to directly create a general purpose `verbose scan`
    inplace of a for a jax.lax.scan, that takes the same arguments as a jax.lax.scan,
    but prints a progress bar.
    """
    tqdm_bars = {}
    remainder = num_iters % log_rate

    """Define a tqdm progress bar."""
    tqdm_bars[0] = tqdm(range(num_iters))
    tqdm_bars[0].set_description("Compiling...", refresh=True)

    def _update_tqdm(args: Any, transform: Any) -> None:
        r"""Update the tqdm progress bar with the latest objective value."""
        value, iter_num = args
        tqdm_bars[0].set_description("Running", refresh=False)
        tqdm_bars[0].update(iter_num)
        tqdm_bars[0].set_postfix({"Value": f"{value: .2f}"})

    def _close_tqdm(args: Any, transform: Any) -> None:
        r"""Close the tqdm progress bar."""
        tqdm_bars[0].close()

    def _callback(cond: bool, func: Callable, arg: Any) -> None:
        r"""Callback a function for a given argument if a condition is true."""
        dummy_result = 0

        def _do_callback(_) -> int:
            """Perform the callback."""
            return host_callback.id_tap(func, arg, result=dummy_result)

        def _not_callback(_) -> int:
            """Do nothing."""
            return dummy_result

        _ = lax.cond(cond, _do_callback, _not_callback, operand=None)

    def _update_progress_bar(value: Float[Array, "1"], iter_num: int) -> None:
        r"""Update the tqdm progress bar."""
        # Conditions for iteration number
        is_multiple: bool = (iter_num % log_rate == 0) & (
            iter_num != num_iters - remainder
        )
        is_remainder: bool = iter_num == num_iters - remainder
        is_last: bool = iter_num == num_iters - 1

        # Update progress bar, if multiple of log_rate
        _callback(is_multiple, _update_tqdm, (value, log_rate))

        # Update progress bar, if remainder
        _callback(is_remainder, _update_tqdm, (value, remainder))

        # Close progress bar, if last iteration
        _callback(is_last, _close_tqdm, None)

    def _progress_bar(body_fun: Callable) -> Callable:
        r"""Decorator that adds a progress bar to `body_fun` used in `jax.lax.scan`."""

        def wrapper_progress_bar(carry: Any, x: Union[tuple, int]) -> Any:
            # Get iteration number
            if type(x) is tuple:
                iter_num, *_ = x
            else:
                iter_num = x

            # Compute iteration step
            result = body_fun(carry, x)

            # Get value
            *_, value = result

            # Update progress bar
            _update_progress_bar(value, iter_num)

            return result

        return wrapper_progress_bar

    return _progress_bar

__all__ = [
    "progress_bar",
]


# -*- coding: utf-8 -*-
"""
    This file is used for create and inherit the core controllers
"""
import datetime
from datetime import timedelta
from odoo.http import request, Controller, route
from odoo import _, http
import logging
from odoo.exceptions import UserError
from odoo.addons.auth_signup.controllers.main import AuthSignupHome
from odoo.addons.mass_mailing.controllers.main import MassMailController

_logger = logging.getLogger(__name__)

class ClaricoExtended(http.Controller):

    @http.route(['/get_best_seller_data'], type='json', auth="public", website=True)
    def get_best_seller_data(self, **kwargs):
        website_id = request.website.id
        request.env.cr.execute("""SELECT PT.id, SUM(SO.product_uom_qty),PT.website_id
                                          FROM sale_order S
                                          JOIN sale_order_line SO ON (S.id = SO.order_id)
                                          JOIN product_product P ON (SO.product_id = P.id)
                                          JOIN product_template pt ON (P.product_tmpl_id = PT.id)
                                          WHERE S.state in ('sale','done')
                                          AND (S.date_order >= %s AND S.date_order <= %s)
                                          AND (PT.website_id IS NULL OR PT.website_id = %s)
                                          AND PT.active='t'
                                          AND PT.is_published='t'
                                          GROUP BY PT.id
                                          ORDER BY SUM(SO.product_uom_qty)
                                          DESC LIMIT %s
                                       """,
                               [datetime.datetime.today() - timedelta(30), datetime.datetime.today(), website_id, 12])
        table = request.env.cr.fetchall()
        products = []
        for record in table:
            if record[0]:
                pro_obj = request.env['product.template'].sudo().browse(record[0])
                if pro_obj.sale_ok == True and pro_obj.is_published == True:
                    products.append(pro_obj)
        if products:
            values = {
                'filter_data': products,
                'is_default': False,
            }
            response = http.Response(template="clarico_extended.common_dynamic_ept", qcontext=values)
            return response.render()

    @http.route(['/get_limited_edition_data'], type='json', auth="public", website=True)
    def get_limited_edition_data(self, **kwargs):
        products = request.env['product.template'].sudo().search(
            [('website_published', '=', True), ('sale_ok', '=', True), ('is_published', '=', True),
             ('is_limited_edition', '=', True)], order='id desc',
            limit=12)
        if products:
            values = {
                'filter_data': products,
                'is_default': False,
                'limited_edition': True if request.env.user._is_public() else False,
            }
            response = http.Response(template="clarico_extended.common_dynamic_ept", qcontext=values)
            return response.render()

    @http.route(['/news_item'], type='json', auth="public", website=True)
    def get_news_item(self, news_id=None):
        """
        This controller return the template for news
        :param news_id:
        :return: cannafr_news_popup_view template html
        """
        if news_id:
            news = request.env['cannafr.news'].search([['id', '=', news_id]])
            values = {
                'news': news,
            }
            response = http.Response(template="clarico_extended.cannafr_news_popup_view", qcontext=values)
            return response.render()

    @http.route(['/event_item'], type='json', auth="public", website=True)
    def get_event_item(self, event_id=None):
        """
        This controller return the template for events
        :param event_id:
        :return: cannafr_event_popup template html
        """
        if event_id:
            event = request.env['cannafr.events'].search([['id', '=', int(event_id)]])
            values = {
                'event': event,
            }
            response = http.Response(template="clarico_extended.cannafr_event_popup", qcontext=values)
            return response.render()

    @http.route(['/get_department_team'], type='json', auth="public", website=True)
    def get_department_team(self, department_id=None):
        """
        This controller return the template for teams
        :param department_id:
        :return: cannafr_team_popup_ept template html
        """
        if department_id:
            # is_video_data = request.env['cannafr.department'].search([['id', '=', int(department_id)]]).is_video_display
            dept_teams = request.env['cannafr.department'].search(
                [['id', '=', int(department_id)]]).team_line_ids.mapped('team_id').filtered('website_published')
            values = {
                'dept_teams': dept_teams
            }
            response = http.Response(template="clarico_extended.cannafr_team_popup_ept", qcontext=values)
            return response.render()

    @http.route(['/get_department_team_data'], type='json', auth="public", website=True)
    def get_department_team_data(self, team_id=None):
        """
        This controller return the template for Team details
        :param team_id:
        :return: cannafr_team_detail_popup_ept template html
        """
        if team_id:
            team = request.env['cannafr.team'].search([['id', '=', int(team_id)]])
            values = {
                'team': team,
            }
            response = http.Response(template="clarico_extended.cannafr_team_detail_popup_ept", qcontext=values)
            return response.render()

class UserCustomFields(AuthSignupHome):

    def do_signup(self, qcontext):
        """ Override the do_signup() from the auth_signup base model for adding lastname, date_of_birth, telephone field
            :param qcontext : represent all key values of signup response.
            :returns: object of super method of auth_signup model's base class.
        """
        values = {key: qcontext.get(key) for key in
                  ('login', 'name', 'last_name', 'date_of_birth', 'telephone', 'password')}
        if not values:
            raise UserError(_("The form was not properly filled in."))
        if values.get('password') != qcontext.get('confirm_password'):
            raise UserError(_("Passwords do not match; please retype them."))
        if values.get('name') == '':
            raise UserError(_("Name is necessary."))
        if values.get('last_name') == '':
            raise UserError(_("Last name is necessary."))
        if values.get('date_of_birth') == '':
            raise UserError(_("Date of Birth is necessary."))
        if values.get('login') == '':
            raise UserError(_("Email is necessary."))

        supported_langs = [lang['code'] for lang in request.env['res.lang'].sudo().search_read([], ['code'])]

        if request.lang in supported_langs:
            values['lang'] = request.lang

        Contacts = request.env['mail.mass_mailing.contact'].sudo()
        name, email = Contacts.get_name_email(values.get('login'))

        website_list_id = request.env['mail.mass_mailing.list'].sudo().search([('is_website_mailing', '=', True)], limit=1)
        if website_list_id:
            list_id = website_list_id
        else:
            list_id = request.env['mail.mass_mailing.list'].sudo().search([('name', '!=', '')],limit=1)

        contact_ids = Contacts.search([
            ('list_ids', 'in', [int(list_id)]),
            ('email', '=', email),
        ], limit=1)
        if not contact_ids:
            # inline add_to_list as we've already called half of it
            Contacts.create({'name': name, 'email': email, 'list_ids': [(6, 0, [int(list_id)])]})
        elif contact_ids.opt_out:
            contact_ids.opt_out = False
        # add email to session
        request.session['mass_mailing_email'] = email

        self._signup_with_values(qcontext.get('token'), values)
        request.env.cr.commit()

class CannaPartnership(http.Controller):

    @http.route(['/create_partnership_data'], type='json', auth="public", website=True, csrf=False)
    def create_partnership_data(self, **kwargs):
        """
            @desc: This method takes data from form and creates record in cn.partnership model.
            @args: **kwargs
            @return: returns to Home Page after form is submitted.
        """
        request.env['cn.partnership'].sudo().create({
            'name': kwargs.get('name', ''),
            'email': kwargs.get('email', ''),
            'description': kwargs.get('description', ''),
            'is_become_partner': kwargs.get('is_become_partner', ),
            'is_organize_event': kwargs.get('is_organize_event', ),
            'is_other': kwargs.get('is_other', )
        })

        return request.redirect("/")

# class CannaNewslaterSubscribe(MassMailController):


#importamos cmath para emplear la funcion log
from cmath import log
# Definicion de la funcion es_solucion, ingresando como parametros un arrary que contiene el dato y la cantidad, y el valor a devolver
def es_solucion(solucion, valor_devolver):
    #Inicializacion de total en 0
    total = 0
    #Se repite hasta que no existan elementos en solucion, almacenando cada elemento de solucion en la variable moneda
    for moneda in solucion:
        #total se forma a partir de redondear a dos decimales la suma del total mas el producto de los dos primeros elementos del vector
        #Se repite hasta que se acabe el vector solucion, insertando los valores que tiene inicialemnte y repitiendolo hasta completar el valor a devolver
        total = round(total + ( moneda[0] * moneda[1]), 2)
    #de tener todas las monedas a devolver emplea un condicional de igualdad que retorna true en caso de que el total sea igual al valor a devolver
    #en caso contrario retorna false
    if (total == valor_devolver):
        return True
    else:
        return False
 #Define la funcion que imprime un vector que almacena vectores donde se imprime el valor de la moneda y la cantidad de onedas
def cambio(conjunto_candidatos, valor_devolver):
    solucion = []
    #ordenamos el vector con la finalidad que en un inicio el algoritmo escoga las monedas de denominacion mas altas para que se use
    #La menor cantidad de monedas posible
    conjunto_candidatos.sort()
    #inicializa el restante igualando con el valor_devolver ingresado
    restante = valor_devolver
    #Realiza repeticiones mientras el vector conjunto_candidatos tenga datos, y es_solucion con los valores hasta ese entonces del vector solucion sea falso
    while conjunto_candidatos and not es_solucion(solucion, valor_devolver):
        #Saca datos del vector conjunto_candidatos
        dato = conjunto_candidatos.pop()
        #compara si el dato es menor o igual al valor restante
        if (dato <= restante):
        #la cantidad sale partir de la parte entera del cociente al realizar la divicion entre restante y dato respectivamente
            cantidad = restante // dato
            #se almacena el valor almacenado en dato y cantidad en el arreglo de vectores solucion
            solucion.append([dato, cantidad])
            #el restante es a partir de reedondear a dos decimales el restante menos el dato multiplicada por la cantidad
            restante = round(restante - (dato * cantidad), 2)
            complejidad = complejidad + 1
    #Si es_solucion da el valor de verdadero implica que existe una forma de devolver el valor, caso contrario  imprimie none
    if(es_solucion(solucion, valor_devolver)):
        #Calculo de complejidad
        complejidad=(2*len(solucion) + 1 + len(solucion)*log(len(solucion)))
        print("El valor de la complejidad del algoritmo es: ", complejidad)
        return solucion
    else:
        return None

monedas = [0.01, 0.05, 1, 0.25, 0.5, 0.1]
vuelto = cambio(monedas, 0.75)
print("La cantidad necesaria para devolver el vuelto es: ", vuelto)


from django.urls import path
from .views import *

urlpatterns = [
    path('', home, name='home'),
    path('about/', about, name='about'),
    path('contact/', contact, name='contact'),
    path('register/', user_register, name='register'),
    path('login/', user_login, name='login'),
    path('dashboard/', dashboard, name='dashboard'),
    path('new_post/', new_post, name='new_post'),
    path('update_post/<int:pk>/', update_post, name='update_post'),
    path('delete_post/<int:pk>/', delete_post, name='delete_post'),
    path('logout/', user_logout, name='logout'),
]


class LinkedList(object):
	def __init__(self):
		self.start_node = None
		self.end_node = None

		self.get_next = None
		self.set_next = None

		self.get_prev = None
		self.set_prev = None

		self.current_iter_id = 0
		self.iters = {}

	def register_next_fn(self, g, s):
		self.get_next = g
		self.set_next = s

	def register_prev_fn(self, g, s):
		self.get_prev = g
		self.set_prev = s

	def is_empty(self):
		if self.start_node is None:
			return True
		else:
			return False

	def get_start_node(self):
		return self.start_node

	def get_end_node(self):
		return self.end_node

	def append(self, node):
		self.set_next(node, None)

		if self.start_node is None:
			self.start_node = node
			self.set_prev(node, None)

		if self.end_node is not None:
			self.set_next(self.end_node, node)

		self.set_prev(node, self.end_node)
		self.end_node = node

	def remove(self, node):
		prev_node = self.get_prev(node)
		next_node = self.get_next(node)

		if next_node is not None:
			self.set_prev(next_node, prev_node)
		if prev_node is not None:
			self.set_next(prev_node, next_node)

		if self.start_node is node:
			self.start_node = next_node

		if self.end_node is node:
			self.end_node = prev_node

		update_itr = []
		for itr in self.iters.values():
			if itr is node:
				update_itr.append( (itr, self.get_next(node)))
		self.iters.update(update_itr)

	def iter(self):
		iter_id = self.current_iter_id
		self.current_iter_id += 1

		self.iters[iter_id] = self.start_node

		return LinkedListIter(self, iter_id)

	def iter_reset(self, iter_id):
		self.iters[iter_id] = self.start_node

	def iter_next(self, iter_id):
		if iter_id not in self.iters:
			return None
		node = self.iters[iter_id]
		if node is not None:
			self.iters[iter_id] = self.get_next(node)
		return node

class LinkedListIter(object):
	def __init__(self, ll, iter_id):
		self.ll = ll
		self.iter_id = iter_id

	def __iter__(self):
		return self

	def __next__(self):
		node = self.ll.iter_next(self.iter_id)
		if node:
			return node
		else:
			raise StopIteration


import sys
import pymongo

class jsonFormat():
    def __init__(self):
        self.MongoDB = pymongo.MongoClient("mongodb://Data:Password@IP:Port/DbName?authMechanism=SCRAM-SHA-1").Dbname

    def send(self,rec):
        self.MongoDB.IntraNoPortConnection.insert(rec)

j = jsonFormat()

filename = sys.argv[1]
if filename:
    filehandle = open(filename)
    line = filehandle.readline().strip()
    while(line):
        rec = dict()
        tempList = line.split('|')
        rec['sip'] = tempList[0]
        rec['dip'] = tempList[1]
        rec['startTime'] = int(tempList[2])
        rec['durationTime'] = int(tempList[3])
        j.send(rec)
        line = filehandle.readline().strip()
else:
    exit(0)


def hebing(l1,l2):
    result = []
    while l1 and l2:
    # 1. 取出l1 l2的元素
        key1 = l1[0]
        key2 = l2[0]
    # 2. 比较两个元素的大小  将小的元素放入结果列表
    # 3. 从刚才放入小的列表中再取出一个元素进行比较
        if key1<key2:
            result.append(l1.pop(0))
        else:
            result.append(l2.pop(0))
    # 4. 重复2-3
    # 5. 当l1或l2有一个为空的时候，结束比较 将l1或l2的剩余元素直接放到结果列表
    return result+l1+l2

def guibing(l):
    if len(l)<2:
        return l
    # 1.将列表拆分，一分为二
    mid = len(l)//2
    # 2.将左右的小列表进行归并排序
    left = guibing(l[:mid])
    right = guibing(l[mid:])
    # 3.返回合并的之后的列表
    return hebing(left, right)
    # 4.当列表长度小于2的时候 递归收敛

if __name__ == '__main__':
    # l1 = [1, 3, 5, 7, 9]
    # l2 = [2, 4, 6, 8, 10]
    # l = hebing(l1, l2)
    # print(l)
    import random
    l = list(range(10))
    random.shuffle(l)
    print(l)
    # l = [223,332,332,134,456]
    l = guibing(l)
    print(l)


import sys
import os
import json
import numpy as np
import pandas as pd

class Model:
    def __init__(self, inputPath):
        '''
        load dnn model with Keras
        '''
        self.modelPath = inputPath

        if os.path.exists("/".join([self.modelPath, "checkpoints"])):
            self.modelPath = "/".join([self.modelPath, "checkpoints"])
        # load config file
        configFile = self.modelPath+"/net_config.json"
        if not os.path.exists(configFile):
            sys.exit("could not find config file {}, cannot load DNN".format(configFile))

        with open(configFile) as f:
            self.config = f.read()
        self.config = json.loads(self.config)

        # load trained model
        checkpointPath = self.modelPath+"/trained_model.h5py"
        if not os.path.exists(checkpointPath):
            sys.exit("could not find trained model {}".format(checkpointPath))

        print("\nloading DNN model from {}\n".format(self.modelPath))
        try:
            from keras.models import load_model
            self.model = load_model(checkpointPath)
        except:
            from tensorflow.keras.models import load_model
            self.model = load_model(checkpointPath)

        self.model.summary()

    def setVariables(self):
        '''
        read list of variables used for DNN evaluation
        read norm table with mean and std.dev values for all of theses variables
        '''
        # load variable normalization
        normFile = self.modelPath+"/variable_norm.csv"
        if not os.path.exists(normFile):
            sys.exit("could not find file with variable norms {}".format(normFile))

        self.variable_norms = pd.read_csv(normFile, index_col=0)
        print("\nvariable norms:")
        print(self.variable_norms)
        self.variables = list(self.variable_norms.index.values)

    def findBest(self, entry):
        '''
        evaluate DNN for all entries given

        output: index, value of best combination
        '''
        matrix = entry[self.variables].values
        idx = 0
        for _, row in self.variable_norms.iterrows():
            matrix[:,idx]-=row["mu"]
            matrix[:,idx]/=row["std"]
            idx+=1
        predictions = self.model.predict(matrix)
        bestIndex = np.argmax(predictions[:,0])
        return bestIndex, predictions[bestIndex][0]

    def evaluate(self, entry):
        '''
        evaluate dnn with inputs
        inputs are either ndarray of events already cut to the dnn input variables
        or dataframe with correct input variable column names

        output: dnn predictions, max value of prediction vectors
        '''
        if not type(entry) == np.ndarray:
            matrix = entry[self.variables].values
        else:
            matrix = entry

        # norm variables
        idx=0
        for _, row in self.variable_norms.iterrows():
            matrix[:,idx]-=row["mu"]
            matrix[:,idx]/=row["std"]
            idx+=1

        # predict
        predictions = self.model.predict(matrix)

        # get maximum index
        maxIndex = np.argmax(predictions, axis = 1)
        return predictions, maxIndex


from midiutil import MIDIFile
import random

notes = 96
count = time = track = channel = 0
duration = 1
volume = 127
tempo = 120

MyMIDI = MIDIFile(1)
MyMIDI2 = MIDIFile(2)

MyMIDI.addTrackName(track,time,"Drum Track")
MyMIDI2.addTrackName(track,time,"Rhythm Track")

MyMIDI.addTempo(track,time,tempo)
MyMIDI2.addTempo(track,time,tempo)

def fib_nr(n):
    num1 = 0
    num2 = 1
    term = 0
    for i in range(n):
        num1 = num2
        num2 = term
        term = num1 + num2
    return term

nterms = 16
f = []
print_f = []

for i in range(0,nterms):
    f.append(fib_nr(i)%16) #mod 16 to keep from going out of range of number of kick drum patterns
    print_f.append(fib_nr(i))

print("Fibonacci #'s:\n", print_f)
print("Fibonacci #'s with % 16:\n", f, "\n")
i=36
beats =(
    [i,i,i,i],
    [i,i,i,0],
    [i,i,0,i],
    [i,i,0,0],
    [i,0,i,i],
    [i,0,i,0],
    [i,0,0,i],
    [i,0,0,0],
    [0,i,i,i],
    [0,i,i,0],
    [0,i,0,i],
    [0,i,0,0],
    [0,0,i,i],
    [0,0,i,0],
    [0,0,0,i],
    [0,0,0,0],
)

metal_r=[24,26,27,29,31,32,35,36]
metal_r2 =[36,38,39] #43,45,46,48,50,51,54,55
scale = [50, 53, 57, 62, 65, 69]
vel = [63,63,64,63]

melody1 = []
#set melody1
for i in (range(0, 16)):
    m = random.choice(metal_r2)
    melody1.append(m)

#with .25, the kicks are 1/16th notes. 16 kick notes in one bar ( 4 notes)
def write_kick_with_rhythm():
    kick_note = 36
    time = 0
    count = 0

    for i in range(0,int(notes)):
        n = beats[f[count%16]]

        if i < 16:
            print("Beat ", f[i], n)
        xx = random.choice (metal_r2)

        for idx in (n):
            MyMIDI.addNote(track,channel,idx,time,duration,volume)

            if i < notes*(1/3) or i >= notes*(2/3):
                if count%4 == 2:
                    MyMIDI2.addNote(track,channel,metal_r2[count%3],time,duration,64)
                if idx!= 0:
                    MyMIDI2.addNote(track,channel,metal_r[count%3],time,duration,63)
                time+=.25
            if i >=notes*(1/3) and i < notes*(2/3):
                if idx != 0:
                    MyMIDI2.addNote(track,channel,melody1[count%16],time,.25,vel[count%3])
                    MyMIDI2.addNote(track,channel,melody1[count%16],time+.50,.25,vel[count%3])
                else:
                    MyMIDI2.addNote(track,channel,metal_r[count%3],time,duration,63)
                time+=.25
        count+=1
def write_snare():
    snare_note = 38
    time = 2
    count = 0

    for i in range(0,int(notes/4)):
        MyMIDI.addNote(track,channel,snare_note,time,duration,volume)
        time+=4
def write_ride():
    time = 0
    ride_note = 46

    for i in range(0,notes):
        MyMIDI.addNote(track,channel,ride_note,time,duration,volume)
        time+=1

write_kick_with_rhythm()
write_snare()
write_ride()

binfile = open("drums.mid",'wb')
binfile2 = open("rhythm.mid",'wb')

MyMIDI.writeFile(binfile)
MyMIDI2.writeFile(binfile2)

binfile.close()
binfile2.close()


'''
executavel no arquivo (testExp.py)
função teste
'''

def exp(strExp):

    contExp01 = contExp02 = 0

    for i in range(len(strExp)):
        if strExp[i] == '(':
            contExp01 += 1
        elif strExp[i] == ')':
            contExp02 += 1

    if contExp01 == contExp02:
        return 0
    else:
        return 1

'''
string = input('>>>Digite a expressão: ')

print('-+'*20)
if exp(string) == 0:
    print('>>>Parâmetros aceitos.')
else:
    print('>>>A sintaxe da sua expressão possui erros.')
'''


#! /usr/bin/env python
"""
This script is made to give you your age in leap years, months, days,
hours, minutes or even in seconds. This all depends on what option that
you choose that you would like to see. Keep in mind that if you choose
seconds or minutes that you do get older every second, so the moment you
see your result you could very much be seconds older or even a minute
older!! Just keep that in mind.

Parameter age: the age of the user
Parameter choice: the option picked to see the user's age in a specific
 format of their choosing.
"""

def age_teller(age, choice):

	if choice.lower() == "leap year":
		result = str(int(age) / 4)
		print("Congrats, you are "+ result + " leap years old!!")
	elif choice.lower() == "months":
		result = str(int(age) * 12)
		print("Wow, you are "+ result + " months old!!")
	elif choice.lower() == "days":
		result = str(int(age) * 365)
		print("Interesting, you are or over "+ result + " days old!!")
	elif choice.lower() == "minutes":
		result = str(int(age) * (365 * 24 * 60))
		print("Look at that, you are or over "+ result + " minutes old!!")
	elif choice.lower() == "seconds":
		result = str(int(age) * (365 * 24 * 60 * 60))
		print("Look at that, you are or over "+ result + " seconds old!!")
	else:
		if choice.lower() == "year" or choice.lower() == "years":
			print("You already know your age in years, dummy!")
		else:
			print("You did not make a good choice, goodbye!")

your_age = input("Enter your age: ")
print("Enter how you want to see your age (seconds, days, leap year, etc.)")
choice = input("==> ")
age_teller(your_age, choice)


#import matplotlib.pyplot as plt
import numpy as np
import pickle
import cv2
import random
import pandas as pd
from sklearn.metrics import classification_report
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import LabelEncoder
from keras.preprocessing.image import ImageDataGenerator
from keras.models import model_from_json, Model
from keras.layers import Dense, Activation, Conv2D, Input
from keras.layers.normalization import BatchNormalization
from keras.layers.convolutional import MaxPooling2D
from keras.layers.core import Flatten
from keras.utils import np_utils
from keras import optimizers
from keras.callbacks import ModelCheckpoint, CSVLogger
from keras.initializers import glorot_normal

# some declared variables

randomSeed = 42
networkInitialize = glorot_normal()
inputDataShape = (224, 224, 3)
epoch = 50
BatchSize = 32
outputClasses = 2
random.seed(randomSeed)
learningRate = 0.0001

# Function to convert the the data from binray to decimal
def decimalDecoding(inputdata):
    decoded_data = []
    for i in range(inputdata.shape[0]):
        decoded_data.append(np.argmax(inputdata[i]))
    return np.array(decoded_data)

pickle_file = open('E:\\data\\BUE\\Year 3\\Semster one\\GP\\Nour\\Main\\Nour.pkl', 'rb') # read the binary data in the pickle file
[normalizedDatax, imageLabels] = pickle.load(pickle_file)
pickle_file.close() # close the pickle file

label_encoder = LabelEncoder()
label_encoder.fit(imageLabels)
encoded_label = label_encoder.transform(imageLabels)
dataY = np_utils.to_categorical(encoded_label)

# split data into train and test with ratio 90,10 respectively
(trainX, testX, trainY, testY) = train_test_split(normalizedDatax, dataY, test_size=0.10, random_state=42)
# split tarninig into valdiation and training with ratio 10, 90 respectively
trainX, valX, trainY, valY = train_test_split(trainX, trainY, test_size=0.1, random_state=42)

training = False
if training:

    InputImages = Input(shape=(224, 224, 3))
    x1 = Conv2D(32, (3, 3), strides=(1, 1), kernel_initializer=networkInitialize, padding='same')(InputImages)
    x1 = BatchNormalization()(x1)
    x1 = Activation('relu')(x1)
    x1 = MaxPooling2D(pool_size = (2, 2))(x1)
    x2 = Conv2D(64, (3, 3), strides=(1, 1), kernel_initializer=networkInitialize,  padding='same')(x1)
    x2 = BatchNormalization()(x2)
    x2 = Activation('relu')(x2)
    x2 = MaxPooling2D(pool_size=(2, 2))(x2)
    x3 = Conv2D(64, (3, 3), strides=(1, 1), kernel_initializer=networkInitialize,  padding='same')(x2)
    x3 = BatchNormalization()(x3)
    x3 = Activation('relu')(x3)
    x3 = MaxPooling2D(pool_size=(2, 2))(x3)
    x4 = Conv2D(128, (3, 3), strides=(1, 1), kernel_initializer=networkInitialize,  padding='same')(x3)
    x4 = BatchNormalization()(x4)
    x4 = Activation('relu')(x4)
    x4 = MaxPooling2D(pool_size=(2, 2))(x4)
    x5 = Conv2D(128, (3, 3), strides=(1, 1), kernel_initializer=networkInitialize,  padding='same')(x4)
    x5 = BatchNormalization()(x5)
    x5 = Activation('relu')(x5)
    x5 = MaxPooling2D(pool_size=(2, 2))(x5)
    x6 = Conv2D(256, (3, 3), strides=(1, 1), kernel_initializer=networkInitialize,  padding='same')(x5)
    x6 = BatchNormalization()(x6)
    x6 = Activation('relu')(x6)
    x6 = MaxPooling2D(pool_size=(2, 2))(x6)
    x7 = Conv2D(256, (3, 3), strides=(1, 1), kernel_initializer=networkInitialize,  padding='same')(x6)
    x7 = BatchNormalization()(x7)
    x7 = Activation('relu')(x7)
    x7 = MaxPooling2D(pool_size=(2, 2))(x7)
    x8 = Flatten()(x7)
    x9 = Dense(500,  activation='relu')(x8)
    outputs = Dense(2,  activation='sigmoid')(x9)

    model = Model(inputs=InputImages, outputs=outputs)

    stochastic_gradient_descent_optimizer = optimizers.SGD(lr=learningRate, decay=1e-6, momentum=0.9, nesterov=True)
    # compile the model
    model.compile(loss='categorical_crossentropy', optimizer='Adam', metrics=['accuracy'])
    print(model.summary())

    model.fit(trainX, trainY, validation_data=(valX, valY), epochs=epoch, batch_size=BatchSize)

    # serialize model to JSON
    model_json = model.to_json()
    with open('model_'+str(epoch)+'.json', "w") as json_file:
        json_file.write(model_json)

    # serialize weights to HDF5
    model.save_weights('model_'+str(epoch)+'.h5')


#!/usr/bin/python3
import argparse
import time
import sys
import datetime
import json
from influxdb import InfluxDBClient
from influxdb.exceptions import InfluxDBClientError, InfluxDBServerError
import logging

from gpiozero import LightSensor
from w1thermsensor import W1ThermSensor
from time import sleep

measurement = "fridge"
fridge_light_on = True

def send_data_to_influx(store, row):
    try:
        store.write_points(row, time_precision='s')
    except ConnectionError as e:
        logging.warning("Failed to connect to Influx host {}:{} - {}".format(dbhost, port, e))
    except InfluxDBClientError as e:
        if e.code == 404:
            logging.error("Database '{}' not found.".format(dbname))
        else:
            logging.error("Write InfluxDB client failed {}@{}:{} - {}".format(dbname,dbhost, port, e))
    except InfluxDBServerError as e:
            logging.error("Write InfluxDB server failed {}@{}:{} - {}".format(dbname,dbhost, port, e))

def light_on():
	global fridge_light_on
	fridge_light_on = True
	read_therm()

def light_off():
	global fridge_light_on
	fridge_light_on = False
	read_therm()

def read_therm():
	readings = {}
	readings["light"] = fridge_light_on
	for sensor in W1ThermSensor.get_available_sensors():
		readings["temp_"+sensor.id] = sensor.get_temperature()

	row = [ { "measurement":measurement,
				"tags": {},
				"time": int(time.time()),
				"fields":readings
			}
		]
	logging.debug(json.dumps(row))
	send_data_to_influx(store, row)
# Allow setting of basic config at commandline.

parser = argparse.ArgumentParser(description='Generating report cards for STAC-M3 Streaming™')
parser.add_argument('--dbhost', dest='dbhost', required=False, default="babbage.local",
                    help="The IP or resolvable hostname of the influx data base")
parser.add_argument('--dbport', dest='port', required=False, default=8086,
                    help="The port number for the influx data base")
parser.add_argument("--user", dest='user', required=False, default="fridgemon",
                    help="the influx username")
parser.add_argument("--pass", dest='pw', required=False, default="fridgemon",
                    help="the influx password")
parser.add_argument("--dbname", dest='dbname', required=False, default="fridgemon",
                    help="the influx database that will be used.")
args = parser.parse_args()

dbhost = args.dbhost
port   = args.port
user   = args.user
pw     = args.pw
dbname = args.dbname

# Create the InfluxDB client object
store = InfluxDBClient(dbhost, port, user, pw, dbname)

ldr = LightSensor(23, queue_len=1)
ldr.when_light = light_on
ldr.when_dark = light_off

while True:
	read_therm()
	sleep(5)


"""create locations table

Revision ID: 468946541a57
Revises: 26e3340ce799
Create Date: 2013-11-03 23:24:23.069426

"""
from alembic import op
import sqlalchemy as sa

revision = '468946541a57'
down_revision = '26e3340ce799'

def upgrade():
    op.create_table(
        'locations',
        sa.Column('id', sa.Integer, primary_key=True),
        sa.Column('created', sa.DateTime(timezone=True)),
        sa.Column('city', sa.Unicode(75), nullable=False),
        sa.Column('country_code', sa.Unicode(3), nullable=False)
    )

def downgrade():
    op.drop_table('locations')


from os import system
from sys import platform
from random import randint
from time import sleep

if platform == 'win32': clear_string = 'cls'
if platform in ('darwin', 'linux'): clear_string = 'clear'

class chararray:
    def __init__(self,tuple,state=None):
        self.height = tuple[0]
        self.width = tuple[1]
        if state is None:
            self.lst = []
            for _ in range(self.height):
                row = []
                for _ in range(self.width):
                    row.append('_')
                self.lst.append(row)
        else:
            self.lst = state

    def __getitem__(self,index):
        return self.lst[index]

    def refresh(self):
        for row in range(self.height):
            for column in range(self.width):
                self.lst[row][column] = '_'

    def __repr__(self):
        return self.lst.__repr__()

    def copyboard(self):
        return_lst = []

        for lst in self.lst:
            copied_list = lst.copy()
            return_lst.append(copied_list)

        return chararray((self.height,self.width),return_lst)

#win condition determines if the most recent placement won the game
#i is the y coord, read from top, j is the x coord, read from left
def win_condition(i,j,board, current_player):
    #test if the current cell is viable to look at
    def test(_i,_j):
        #if out of bounds
        if _i < 0 or _i >= board.board_height or _j < 0 or _j >= board.board_width:
            return False

        #if empty
        value = board.board_matrix[_i][_j]
        if value == '_':
            return False

        #if opposite marker
        if (value == '#' and current_player == -1) or (value == 'O' and current_player == 1):
            return False

        return True

    #possible suroundings
    surrounding = [(i-1,j-1),(i,j-1),(i+1,j-1),(i+1,j),(i+1,j+1),(i,j+1),(i-1,j+1)]
    #test viable locations
    to_check=[]
    for item in surrounding:
        if test(item[0],item[1]):
            to_check.append(item)

    #test viables for connect four
    for item in to_check:
        delta_i = i-item[0]
        delta_j = j-item[1]
        #if the opposite direction is also viable
        if (i+delta_i,j+delta_j) in to_check:
            if test(i+2*delta_i,j+2*delta_j) or test(i-2*delta_i,j-2*delta_j):
                #inside win!
                return True
        else:
            if test(i-2*delta_i,j-2*delta_j) and test(i-3*delta_i,j-3*delta_j):
                #ray win
                return True

    return False

class Board:
    def __init__(self, board_height=6, board_width=7, board_state=None, whosmove=1):
        if board_state is None:
            self.board_matrix = chararray((board_height,board_width))
            self.board_matrix.refresh()

        else:
            self.board_matrix = board_state

        self.board_width = board_width
        self.board_height = board_height
        self.whosmove = whosmove

    def __bool__(self): return self.board_matrix[self.board_height-1] == ['_' for i in range(self.board_width)]

    def __repr__(self):
        board_labels = '|'
        divider = '|'
        for i in range(self.board_width):
            board_labels += ' ' + str(i+1) + ' '
            divider += '---'
        board_labels += '|'
        divider += '|'

        board_string = ''
        for index, row in enumerate(self.board_matrix):
            board_string += '|'
            for item in row:
                board_string += ' ' + item + ' '

            if index == self.board_height-1:
                board_string += '|'
            else:
                board_string += '| \n'

        return board_string + '\n' + divider + '\n' + board_labels + '\n' + divider

    def update(self, column):
        column -= 1
        #dropping piece down...
        for i in range(self.board_height):
            position = self.board_height - 1 - i
            if self.board_matrix[position][column] == '_':
                if self.whosmove == 1: self.board_matrix[position][column] = '#'
                if self.whosmove == -1: self.board_matrix[position][column] = 'O'

                win = win_condition(position, column, self, self.whosmove)
                self.whosmove *= -1
                if win: return 'win'
                elif '_' not in self.board_matrix[0]: return 'draw'

                return 'continue'

        raise Exception

    def best_move(self, max_depth, verbose=False):
        def board_evaluation(board): return 0

        class Node:
            def __init__(self,data, depth = 0,parent = None, children = None, move_from_parent=None):
                self.data = data #board state
                self.eval = None #board eval
                self.depth = depth
                self.parent = parent
                self.move_from_parent = move_from_parent # the move taken to arrive at the node from it's parent
                if children is None: self.children = []
                else: self.children = children

        #game tree class
        class Tree():
            def __init__(self,root, whosmoveroot):
                self.root = root
                self.whosmoveroot = whosmoveroot

            def make(self,max_depth,verbose):
                def help(node,max_depth,verbose):
                    for column in range(node.data.board_width):
                        if node.data.board_matrix[0][column] == '_':
                            new_board = Board(board_state=node.data.board_matrix.copyboard(), whosmove=node.data.whosmove)
                            update = new_board.update(column+1)
                            new_node = Node(data=new_board,move_from_parent=column+1, depth=node.depth+1)
                            node.children.append(new_node)

                            if update == 'win' : new_node.eval = float('inf') * self.whosmoveroot * (1 - 2*(node.depth % 2))
                            elif update == 'draw': new_node.eval = 0
                            #if at the bottom of the tree, evaluate the board
                            elif new_node.depth == max_depth: new_node.eval = board_evaluation(new_node.data.board_matrix)
                            else: help(new_node, max_depth, verbose)

                help(self.root, max_depth, verbose)

            def score(self, verbose):
                def help(node, verbose):
                    if node.eval is not None: return node.eval

                    if self.whosmoveroot*(2*(node.depth % 2)-1) == 1:
                        minscore = float('inf')
                        for child in node.children:
                            node.eval = help(child,verbose)
                            if node.eval < minscore:
                                minscore = node.eval
                            if child.depth <= 2 and verbose:
                                print(child.data)
                                print('eval:',child.eval, 'move from parent:', child.move_from_parent, 'depth:', child.depth)
                        node.eval = minscore
                        return minscore

                    else:
                        maxscore = -float('inf')
                        for child in node.children:
                            node.eval = help(child,verbose)
                            if node.eval > maxscore:
                                maxscore = node.eval
                            if child.depth <=2 and verbose:
                                print(child.data)
                                print('eval:',child.eval, 'move from parent:', child.move_from_parent, 'depth:', child.depth)
                        node.eval = maxscore
                        return maxscore

                return help(self.root, verbose)

            def best(self):
                if self.whosmoveroot == 1:
                    best_moves = []
                    maxscore = -float('inf')
                    for child in self.root.children:
                        if child.eval > maxscore:
                            maxscore = child.eval
                            best_moves = [child.move_from_parent]
                        elif child.eval == maxscore:
                            best_moves.append(child.move_from_parent)

                    return best_moves[randint(0, len(best_moves)-1)]

                elif self.whosmoveroot == -1:
                    minscore = float('inf')
                    best_moves = []
                    for child in self.root.children:
                        if child.eval < minscore:
                            minscore = child.eval
                            best_moves = [child.move_from_parent]
                        elif child.eval == minscore:
                            best_moves.append(child.move_from_parent)

                    return best_moves[randint(0,len(best_moves)-1)]

        return_tree = Tree(root=Node(data=self), whosmoveroot = self.whosmove)

        return_tree.make(max_depth, verbose)
        return_tree.score(verbose)
        return_val = return_tree.best()
        return return_val

#takes type input_type, set of accepted responses, and a error message return_string if right type but non-considered value, func always accepts quit, Quit, q, Q
def player_input(input_type, accepted, return_string):
    given = input()
    while True:
        try:
            if str(given) in ('Quit','quit','q','Q'):
                print('Game Quit.')
                break
            if input_type(given) in accepted:
                given = input_type(given)
                return given
            else:
                given = input_type(given)
                print(return_string)
                given = input()
        except:
            if input_type == int: print('Not an integer! Please try again.')
            if input_type == str: print('Not an string! Please try again.')
            given = input()

def player_text_input(forbidden_string_lst = None): # takes users text input and returns it as long as it is not in a list of forbidden strings
    if forbidden_string_lst is None: forbidden_string_lst = []
    given = input()
    while True:
        if str(given) in ('Quit','quit','q','Q'):
                print('Game Quit.')
                break
        if given in forbidden_string_lst:
            print('You can\'t use that name! Choose another.')
            given = input()
        if len(given) > 50:
            print('The entered name is too long. Try entering a name less than 50 characters.')
            given = input()
        if len(given) == 0:
            print('The entered name is too short. Try entering a name that is atleast 1 character long.')
            given = input()
        if len(given) > 0 and len(given) <= 50 and given not in ('Quit','quit','q','Q') and given not in forbidden_string_lst:
            return given

class Player:
    def __init__(self, name, alias, computer=False):
        self.name = name
        self.alias = alias
        self.computer = computer #boolean if whether or not the player is the computer

class Game:
    def __init__(self, player1, player2):
        self.board=Board()
        self.player1 = player1
        self.player2 = player2
        self.current_player = self.player1
        self.moves = 0

    def start(self):
        print(self.board)
        result = 'continue'

        while True: #gameloop
            if not self.current_player.computer:
                print('{}\'s turn'.format(self.current_player.name))
                while True:
                    chosen_position = player_input(int, (1,2,3,4,5,6,7), 'Please enter integer 1 - 7.')
                    if chosen_position is None: return [0,0] # if user quits out here, they do not want to play again.
                    else:
                        result = self.board.update(chosen_position)
                        if result != 'illegal': break
                        print('That position is filled. Choose another location.')

            if self.current_player.computer:
                print('Computer\'s turn')
                chosen_position = self.board.best_move(max_depth=6) #give the computer what turn it is
                result = self.board.update(chosen_position)

            system(clear_string)
            print(self.board)
            if result in ('win', 'draw'):
                system(clear_string)
                print(self.board)
                if result == 'win':
                    print('{} wins!\n'.format(self.current_player.name))
                elif result == 'draw':
                    print('It\'s a draw!\n')
                return_lst = [0,0]
                if result == 'win': return_lst[self.current_player.alias-1] = 1
                elif result == 'draw': return_lst = [0.5,0.5]
                return return_lst

            if self.current_player.alias == 1: self.current_player = self.player2
            elif self.current_player.alias == 2: self.current_player = self.player1

class Session:
    def __init__(self):
        self.rivalries_dict = {}

    def start(self):
        system(clear_string)
        print('-----Welcome to Connect 4-----\n')
        sleep(0.5)

        play_again=True
        while play_again:

            print('Enter player names. Enter \'Computer\' for either Player 1 or Player 2 to play the computer.\n')

            sleep(0.5)

            print('What would you like Player 1\'s name to be?')
            name_1 = player_text_input()
            if name_1 is None: return False # if user quits out here, they do not want to play again.
            elif name_1 == 'Computer': self.player1 = Player(name='Computer', alias=1, computer=True)
            else: self.player1 = Player(name=name_1, alias = 1)

            print('What would you like Player 2\'s name to be?')
            name_2 = player_text_input([self.player1.name])
            if name_2 is None: return False # if user quits out here, they do not want to play again.
            elif name_2 == 'Computer': self.player2 = Player(name='Computer', alias=2, computer=True)
            else: self.player2 = Player(name=name_2, alias = 2)

            try:
                self.rivalries_dict[(name_1.lower(), name_2.lower())][0]
                self.rivalries_dict[(name_2.lower(), name_1.lower())][0]
            except KeyError:
                self.rivalries_dict[(name_1.lower(), name_2.lower())] = [0,0]
                self.rivalries_dict[(name_2.lower(), name_1.lower())] = [0,0]
            system(clear_string)

            print('Enter \'Quit\' at anytime to exit the game.\n')
            system(clear_string)
            game_result = Game(player1 = self.player1, player2 = self.player2).start()

            self.rivalries_dict[(name_1.lower(), name_2.lower())][0] += game_result[0]
            self.rivalries_dict[(name_1.lower(), name_2.lower())][1] += game_result[1]

            name1score = self.rivalries_dict[(name_1.lower(), name_2.lower())][0] + self.rivalries_dict[(name_2.lower(), name_1.lower())][1]
            name2score = self.rivalries_dict[(name_2.lower(), name_1.lower())][0] + self.rivalries_dict[(name_1.lower(), name_2.lower())][1]
            if name1score == 1: s1 = ''
            else: s1 = 's'
            if name2score == 1: s2 = ''
            else: s2 = 's'
            if name1score + name2score != 0: print('The running total is {} point{} for {} and {} point{} for {}.\n'.format(name1score,s1,name_1,name2score,s2,name_2))

            print('Would you like to play again?')
            play_again = player_input(str, ('yes', 'Yes', 'y', 'no', 'No', 'n'), 'Please enter \'Yes\' or \'No\'')
            if play_again in ('no', 'No', 'n') or play_again is None: play_again = False
            if play_again in ('yes', 'Yes', 'y'): play_again = True

if __name__ == '__main__': Session().start()


from torch.utils.data import DataLoader, Dataset, Sampler
from pathlib import Path
from collections import defaultdict
import json
import random
from multiprocessing import Pool
import h5py
import pickle
import math
from tqdm import tqdm
import torch
import numpy as np

from torch.utils.data.distributed import DistributedSampler

import transformers
from transformers import T5TokenizerFast, BartTokenizer
from tokenization import VLT5TokenizerFast

from qa_answer_table import AnswerTable

project_dir = Path(__file__).resolve().parent.parent  # VLT5
workspace_dir = project_dir.parent
dataset_dir = workspace_dir.joinpath('datasets/').resolve()
coco_dir = dataset_dir.joinpath('COCO')
vg_dir = dataset_dir.joinpath('VG')
coco_img_dir = coco_dir.joinpath('images/')
coco_feature_dir = coco_dir.joinpath('features')
gqa_dir = dataset_dir.joinpath('GQA')

class GQAFineTuneDataset(Dataset):
    def __init__(self, split='train,valid', raw_dataset=None, rank=-1, topk=-1, verbose=True, args=None, mode='train'):
        super().__init__()

        self.raw_dataset = raw_dataset
        self.topk = topk
        self.verbose = verbose
        self.args = args

        self.mode = mode

        # Loading datasets to data
        self.sources = split.split(',')
        if self.verbose:
            print('Data sources: ', self.sources)

        if 't5' in self.args.backbone:
            if self.args.use_vision:
                self.tokenizer = VLT5TokenizerFast.from_pretrained(
                    args.backbone,
                    # max_length=self.args.max_text_length,
                    do_lower_case=self.args.do_lower_case)
            else:
                self.tokenizer = T5TokenizerFast.from_pretrained(
                    args.backbone,
                    # max_length=self.args.max_text_length,
                    do_lower_case=self.args.do_lower_case)
        elif 'bart' in self.args.backbone:
            self.tokenizer = BartTokenizer.from_pretrained(
                args.backbone,
                # max_length=self.args.max_text_length,
                do_lower_case=self.args.do_lower_case)

            additional_special_tokens = [f'<extra_id_{i}>' for i in range(100-1, -1, -1)] + \
                    [f'<vis_extra_id_{i}>' for i in range(100-1, -1, -1)]
            special_tokens_dict = {'additional_special_tokens': additional_special_tokens}
            num_added_toks = self.tokenizer.add_special_tokens(special_tokens_dict)

        self.img_ids_to_source = {}
        data_info_dicts = []
        for source in self.sources:
            data_info_path = dataset_dir.joinpath(f'GQA/{source}.json')
            with open(data_info_path) as f:
                _data_info_dicts = json.load(f)
                # source_img_ids.append([d['img_id'] for d in _data_info_dicts])
                for _d in _data_info_dicts:
                    self.img_ids_to_source[_d['img_id']] = source
                    _d['source'] = source

                data_info_dicts.extend(_data_info_dicts)
            if self.verbose:
                print(f"Loaded {len(_data_info_dicts)} data from", source)

        data = data_info_dicts

        self.n_gpus = torch.cuda.device_count()

        self.rank = rank

        if self.topk > 0:
            data = data[:self.topk]
            if self.verbose:
                print(f"Use only {self.topk} data")

        self.data = data

        if self.verbose:
            print("# all sentences:", len(self.data))

        self.n_boxes = args.n_boxes

        self.source_to_featname = {
            'train': 'others',
            'valid': 'others',
            'submit': 'others',

            'testdev': 'testdev'
        }

        self.featname_to_h5 = {
            'others': vg_dir.joinpath('features/vg_gqa_obj36.h5'),
            'testdev': gqa_dir.joinpath('features/gqa_testdev_obj36.h5'),
        }

    def __len__(self):
        return len(self.data)

    def __getitem__(self, idx):

        out_dict = {}
        out_dict['args'] = self.args

        datum = self.data[idx]
        # uid = datum['uid']
        # out_dict['uid'] = uid
        # out_dict['uid'] = uid

        ###### Image ######
        if self.args.use_vision:
            img_id = datum['img_id']
            out_dict['img_id'] = img_id

            source = self.img_ids_to_source[img_id]

            featname = self.source_to_featname[source]

            # f = self.source_to_h5[source]
            f = self.featname_to_h5[featname]

            if isinstance(f, Path):
                # path = self.data_source_to_h5_path[source]
                f = h5py.File(f, 'r')
                # self.split_to_h5_features[split_i] = f
                # self.source_to_h5[source] = f
                self.featname_to_h5[featname] = f

            feats = np.zeros(shape=(self.n_boxes, 2048), dtype=np.float32)
            f[f'{img_id}/features'].read_direct(feats)
            feats = torch.from_numpy(feats)
            out_dict['vis_feats'] = feats

            # Normalize the boxes (to 0 ~ 1)
            img_h = f[f'{img_id}/img_h'][()]
            img_w = f[f'{img_id}/img_w'][()]
            boxes = f[f'{img_id}/boxes'][()]  # (x1, y1, x2, y2)
            boxes[:, (0, 2)] /= img_w
            boxes[:, (1, 3)] /= img_h
            np.testing.assert_array_less(boxes, 1+1e-5)
            # np.testing.assert_array_less(boxes, 1+5e-2)
            np.testing.assert_array_less(-boxes, 0+1e-5)
            boxes = torch.from_numpy(boxes)

            boxes.clamp_(min=0.0, max=1.0)

            out_dict['boxes'] = boxes

        ###### Text #####
        # caption = datum['caption']
        sent = datum['sent']

        input_ids = self.tokenizer.encode(f'gqa: {sent}', max_length=20, truncation=True)
        question_id = datum['question_id']
        out_dict['question_id'] = question_id

        out_dict['sent'] = sent
        out_dict['input_ids'] = torch.LongTensor(input_ids)
        out_dict['input_length'] = len(input_ids)

        if 'label' in datum:
            label = datum['label']
            out_dict['label'] = label

            # https://github.com/airsplay/lxmert/blob/master/src/pretrain/lxmert_pretrain.py#L191
            answers = []
            scores = []
            for a, s in label.items():
                answers.append(a)
                scores.append(s)

            score_sum = sum(scores)

            if score_sum == 0:
                answer = ''
                score = 0.
            else:
                prob = [score / score_sum for score in scores]
                choice = np.random.multinomial(1, prob).argmax()
                answer = answers[choice]
                score = scores[choice]
                assert len(answer) > 0, (sent, label, choice, answer)

            out_dict['answer'] = answer
            out_dict['score'] = score
            out_dict['all_answers'] = answers

            if sum(scores) > 0:
                best_answers = []
                best_score = max(scores)
                for a, s in label.items():
                    if s == best_score and s > 0:
                        best_answers.append(a)
                out_dict['best_answers_tokenized'] = [self.tokenizer.encode(a) for a in best_answers]
            else:
                out_dict['best_answers_tokenized'] = [[]]

            target_ids = self.tokenizer.encode(answer)

            out_dict['target_ids'] = torch.LongTensor(target_ids)
            out_dict['target_length'] = len(target_ids)

        return out_dict

    def collate_fn(self, batch):
        batch_entry = {}

        args = batch[0]['args']

        B = len(batch)

        S_W_L = max(entry['input_length'] for entry in batch)
        input_ids = torch.ones(B, S_W_L, dtype=torch.long) * self.tokenizer.pad_token_id

        if args.use_vision:
            V_L = len(batch[0]['boxes'])
            feat_dim = batch[0]['vis_feats'].shape[-1]

            boxes = torch.zeros(B, V_L, 4, dtype=torch.float)
            vis_feats = torch.zeros(B, V_L, feat_dim, dtype=torch.float)

        if 'target' in batch[0]:
            # targets = []
            targets = torch.zeros(B, len(batch[0]['target']), dtype=torch.float)
        if 'target_ids' in batch[0]:
            T_W_L = max(entry['target_length'] for entry in batch)
            target_ids = torch.ones(B, T_W_L, dtype=torch.long) * self.tokenizer.pad_token_id

        sentences = []
        question_ids = []
        answers = []
        all_answers = []
        all_answers_tokenized = []
        best_answers_tokenized = []
        img_ids = []
        img_paths = []
        labels = []
        scores = []

        for i, entry in enumerate(batch):
            input_ids[i, :entry['input_length']] = entry['input_ids']

            if args.use_vision:
                boxes[i] += entry['boxes']
                vis_feats[i] += entry['vis_feats']
                # img_ids.append(entry['img_id'])
                # img_paths.append(entry['img_path'])

            if 'target_ids' in entry:
                target_ids[i, :entry['target_length']] = entry['target_ids']

            if 'target' in entry:
                targets[i] += entry['target']
                # targets.append(entry['target'])

            sentences.append(entry['sent'])
            question_ids.append(entry['question_id'])
            if 'answer' in entry:
                answers.append(entry['answer'])
            if 'all_answers' in entry:
                all_answers.append(entry['all_answers'])
            if 'all_answers_tokenized' in entry:
                all_answers_tokenized.append(entry['all_answers_tokenized'])
            if 'best_answers_tokenized' in entry:
                best_answers_tokenized.append(entry['best_answers_tokenized'])
            if 'score' in entry:
                scores.append(entry['score'])

            if 'label' in entry:
                labels.append(entry['label'])

        batch_entry['input_ids'] = input_ids
        if 'target_ids' in batch[0]:
            word_mask = target_ids != self.tokenizer.pad_token_id
            target_ids[~word_mask] = -100
            batch_entry['target_ids'] = target_ids
        if 'target' in batch[0]:
            # targets = torch.stack(targets, dim=0)
            batch_entry['targets'] = targets

        if args.use_vision:
            batch_entry['boxes'] = boxes
            batch_entry['vis_feats'] = vis_feats
            # batch_entry['img_id'] = img_ids
            # batch_entry['img_paths'] = img_paths

        batch_entry['sent'] = sentences
        batch_entry['question_ids'] = question_ids
        batch_entry['answers'] = answers
        batch_entry['all_answers'] = all_answers
        batch_entry['all_answers_tokenized'] = all_answers_tokenized
        batch_entry['best_answers_tokenized'] = best_answers_tokenized
        batch_entry['scores'] = torch.FloatTensor(scores)
        batch_entry['labels'] = labels

        batch_entry['task'] = 'gqa'

        return batch_entry

def get_loader(args, split='train', mode='train',
               batch_size=32, workers=4, distributed=False, gpu=0,
               topk=-1, verbose=None):

    if verbose is None:
        verbose = (gpu == 0)

    _dset = GQADataset(split, verbose)

    dataset = GQAFineTuneDataset(
        split,
        raw_dataset=_dset,
        rank=gpu,
        topk=topk,
        verbose=verbose,
        args=args,
        mode=mode)

    if distributed:
        sampler = DistributedSampler(dataset)
    else:
        sampler = None
    if mode == 'train':
        loader = DataLoader(
            dataset, batch_size=batch_size, shuffle=(sampler is None),
            num_workers=workers, pin_memory=True, sampler=sampler,
            collate_fn=dataset.collate_fn)
    else:
        loader = DataLoader(
            dataset,
            batch_size=batch_size,
            num_workers=workers, pin_memory=True,
            sampler=sampler,
            shuffle=None if (sampler is not None) else False,
            collate_fn=dataset.collate_fn,
            drop_last=False)

    loader.evaluator = GQAEvaluator(_dset)
    loader.task = 'gqa'

    return loader

class GQADataset:
    """
    A GQA data example in json file:
    {
        "img_id": "2375429",
        "label": {
            "pipe": 1.0
        },
        "question_id": "07333408",
        "sent": "What is on the white wall?"
    }
    """

    def __init__(self, splits: str, verbose=True):
        self.name = splits
        self.splits = splits.split(',')

        # Loading datasets to data
        self.data = []
        for split in self.splits:
            self.data.extend(json.load(open(gqa_dir.joinpath("%s.json" % split))))
        if verbose:
            print("Load %d data from split(s) %s." %
                  (len(self.data), self.name))

        # List to dict (for evaluation and others)
        self.id2datum = {
            datum['question_id']: datum
            for datum in self.data
        }

        # Answers
        self.ans2label = json.load(open(gqa_dir.joinpath("trainval_ans2label.json")))
        self.label2ans = json.load(open(gqa_dir.joinpath("trainval_label2ans.json")))
        assert len(self.ans2label) == len(self.label2ans)
        for ans, label in self.ans2label.items():
            assert self.label2ans[label] == ans

    @property
    def num_answers(self):
        return len(self.ans2label)

    def __len__(self):
        return len(self.data)

class GQAEvaluator:
    def __init__(self, dataset: GQADataset):
        self.dataset = dataset

    def evaluate(self, quesid2ans: dict):
        score = 0.
        for quesid, ans in quesid2ans.items():
            datum = self.dataset.id2datum[quesid]
            label = datum['label']
            if ans in label:
                score += label[ans]
        return score / len(quesid2ans)

    def dump_result(self, quesid2ans: dict, path):
        """
        Dump the result to a GQA-challenge submittable json file.
        GQA json file submission requirement:
            results = [result]
            result = {
                "questionId": str,      # Note: it's a actually an int number but the server requires an str.
                "prediction": str
            }
        :param quesid2ans: A dict mapping question id to its predicted answer.
        :param path: The file path to save the json file.
        :return:
        """
        with open(path, 'w') as f:
            result = []
            for ques_id, ans in quesid2ans.items():
                result.append({
                    'questionId': ques_id,
                    'prediction': ans
                })
            json.dump(result, f, indent=4, sort_keys=True)


"""
Source: https://github.com/deepmind/dm_control/tree/main/dm_control/mjcf
"""

from dm_control import mjcf

arena = mjcf.RootElement(model="ssl_env")
arena.worldbody.add('geom', name='ground', type='plane', size=[10, 10, 1])

robot = mjcf.from_path('../robotics/onshape/mjmodel.xml')
robot.set_attributes(model=f"robot")

print(robot)
arena.attach(robot)

with open("ssl_bot.xml", "w") as f:
    f.write(arena.to_xml_string())


from numpy import *
arr1 = array([1,2,3,9,7,6])
arr2 = array([3,5,6,8,9,1])
# arr1 = arr1 + 5 # add value to each element of array
# print("Adding 5 to each element of Array:", arr1)
# arr3 = arr1 + arr2
# print("Addition of 2 Arrays:", arr3)
# print("Sin of Array:", sin(arr3))
# print("Cos of Array:", cos(arr3))
# print("Square root of Array:",(sqrt(arr3)))
# sum(arr1), min(arr1), max(arr1), average(arr1), sort(arr1), unique(arr1)
# print(mean(arr1))
# print(median(arr1))
# print(concatenate([arr1,arr2]))
# arr3 = arr1 # address of both Arrays are same
# print(id(arr1),id(arr3))
# arr4 = arr1.view() #any change in Arr1 will reflect in Arr4
arr5 = arr1.copy() # change in Arr1 will not reflect in Arr5
arr1[1] = 7
#print(id(arr5))
print(arr1,arr5)


import types

import numpy as np
import pandas as pd
from scipy import stats

from universal import tools

class AssetFilter(object):
    def __init__(self, window=None, threshold=0.3):
        self.window = window
        self.threshold = threshold

    def _filter(self, R):
        # sh[col] = tools.sharpe(total_ret.div(total_weights, axis=0), alpha=0.000001)
        # to_remove = set(sh.index[sh - full_sharpe > 0.00001])

        SAMPLES = 50
        np.random.seed(42)
        sh = []
        for _ in range(SAMPLES):
            # get bootstrap sample
            R_sample = R.sample(n=len(R), replace=True)
            sh.append(
                {col: tools.sharpe(R_sample[col], alpha=0.00001) for col in R_sample}
            )
        sh = pd.DataFrame(sh)

        sh_diff = sh.subtract(sh["full"], 0)
        cdf = stats.norm.cdf(
            0.0, loc=sh_diff.mean(), scale=0.01 + sh_diff.std() / np.sqrt(len(sh_diff))
        )
        to_remove = sh_diff.columns[cdf < self.threshold]
        to_remove = to_remove.drop("full", errors="ignore")

        print(list(to_remove))
        return to_remove

    def fit(self, R, B):
        # convert it to log returns
        R_log = np.log(R)

        if self.window:
            R_log = R_log.iloc[-self.window :]

        # find sharpe ratio without assets
        RR = {"full": R_log.sum(1)}
        for col in R.columns:
            total_ret = R_log.drop(col, 1).sum(1)
            # total_weights = B.drop(col, 1).sum(1) + 1e-10
            RR[col] = total_ret

        to_remove = self._filter(pd.DataFrame(RR))

        # print(to_remove)
        return to_remove

def filter_result(S, algo, asset_filter=None, result=None):
    """Filter assets for algo by their past-performance."""
    result = result or algo.run(S)
    asset_filter = asset_filter or AssetFilter()

    # monkey-patch algo's step
    step_fun = algo.step

    def step(self, x, last_b, history):
        # find assets to remove -asset_r is already weighted
        R = result.asset_r.loc[: x.name]
        B = result.B.loc[: x.name]
        cols = asset_filter.fit(R, B)

        # get weights with removed assets
        w = step_fun(x.drop(cols), last_b.drop(cols), history.drop(cols, 1))

        # put back assets with zero weights
        w = w.reindex(last_b.index).fillna(0.0)
        return w

    algo.step = types.MethodType(step, algo)

    # run algo with filtered assets
    new_result = algo.run(S)

    # put back old step method
    algo.step = types.MethodType(step_fun, algo)
    return new_result, result


#!/usr/bin/env python
from FileLoader import *
import sys
import pdb
import numpy as np
imgsDir=FileLoader(sys.argv[1])
imgsDir.filterByExt('.jpg')
with open ('imageFiles.txt','w') as f:
    f.write("\n".join(imgsDir.getFilePaths()))

label = list()
for path in imgsDir.getFilePaths():
    tmp=path.split('/')
    tmp1 = tmp[-1].split('_')
    label.append(tmp1[0]+' '+tmp1[1])

with open ('imageLabels.txt','w') as g:
    g.write("\n".join(label))


from .models import Review, Song, Cluster
from django.contrib.auth.models import User
from sklearn.cluster import KMeans
from scipy.sparse import dok_matrix, csr_matrix
import numpy as np

def update_clusters(is_new_user):
    num_reviews = Review.objects.count()
    update_step = 10
    if num_reviews % update_step == 0 or is_new_user:
        # Create a sparse matrix from user reviews
        all_users = User.objects.only("username")
        all_reviewed_song_ids = set(map(lambda x: x.song.id, Review.objects.only("song")))
        num_users = len(list(all_users))
        ratings_m = dok_matrix((num_users, max(all_reviewed_song_ids)+1), dtype=np.float32)

        for i in range(num_users): # each user corresponds to a row, in the order of all_authors
            user_reviews = Review.objects.filter(author=all_users[i])
            for user_review in user_reviews:
                ratings_m[i,user_review.song.id] = user_review.rating

        # Perform kmeans clustering
        k = int(num_users / 10) + 2
        kmeans = KMeans(n_clusters=k)
        clustering = kmeans.fit(ratings_m.tocsr())

        # Update clusters
        Cluster.objects.all().delete()
        new_clusters = {i: Cluster(name=i) for i in range(k)}
        for cluster in new_clusters.values(): # clusters need to be saved before referring to users
            cluster.save()
        for i,cluster_label in enumerate(clustering.labels_):
            new_clusters[cluster_label].users.add(User.objects.get(username=all_users[i].username))


kacsayi = int(input("kaç sayı toplayacağız "))
def toplanacakSayılar(i):
    int(input("please give me the numbers you want me to sum= "))

for kac in range (kacsayi):
    a= toplanacakSayılar(kac)

sum = 0
sum = sum + a


from django.shortcuts import render
from django.views.generic import View, RedirectView
from .forms import SearchForm
from .api_interations import search_recipe, get_recipe
from .models import Recipe, Ingredient
from django.contrib.auth.mixins import LoginRequiredMixin
# Create your views here.

class SearchRecipes(View):
    template_name = 'main/search.html'

    def get(self,request, *args, **kwargs): ## request.method==GET
        return render(request, self.template_name, {'form': SearchForm()})

    def post(self, request, *args, **kwargs): ## request.method==POST
        form = SearchForm(request.POST)
        if form.valid(self):
            data = search_recipe(form.cleaned_data['text'])
        else:
            data=None
        return render(request, self.template_name, {'form': form, 'recipe_list': data})

class FetchDataToDB(LoginRequiredMixin,RedirectView):
    pattern_name = 'search'

    def get_redirect_url(self, *args, **kwargs):
        id = self.kwargs['id']
        data = get_recipe(id)
        print(data.keys)
        r = Recipe.objects.create(
            spoon_id=data['id'],
            ingredients=data['extendedIngredients'],
            title= data['title'],
            ready_minutes = data['readyInMinutes'],
            servings = data['servings'],
            image = data['image'],
            summary = data['summary'],
            instructions = data['instructions']
        )

        self.request.user.profile.common_recipes.add(r)  ## r.profile_set.add(self.request.user.profile)
        return super().get_redirect_url()


import requests
from bs4 import BeautifulSoup

def main():
	url = "https://almacendecaballos.com/"
	cabecera = {'User-Agent':'Firefox'}
	peticion = requests.get(url=url,headers=cabecera)
	soup = BeautifulSoup(peticion.text,'html5lib')
	for v in soup.find_all('meta'):
		if v.get('name') == 'generator':
			version = v.get('content')
	print(version)

if __name__ == '__main__':
	try:
		main()
	except KeyboardInterrupt:
		print("Saliendo")
		exit()


import os
from scipy.io.wavfile import write as write_wav
from IPython.display import Audio
os.environ["CUDA_VISIBLE_DEVICES"] = "0"
os.environ["SUNO_USE_SMALL_MODELS"] = "1"
os.environ["SUNO_OFFLOAD_CPU"] = "0"

import nltk  # we'll use this to split into sentences
from bark.generation import (
    generate_text_semantic,
    preload_models,
)
from bark import generate_audio, SAMPLE_RATE
import numpy as np
import torch
# torch.cuda.reset_peak_memory_stats()
preload_models()
import whisper

model = whisper.load_model("base")
result = model.transcribe("output_audio.wav")
print(result["text"])
text_prompt = result["text"]
text_prompt.replace("\n", " ").strip()
# We split longer text into sentences using nltk and generate the sentences one by one.
sentences = nltk.sent_tokenize(text_prompt)

SPEAKER = "v2/en_speaker_6"
silence = np.zeros(int(0.25 * SAMPLE_RATE))  # quarter second of silence

pieces = []
for sentence in sentences:
    audio_array = generate_audio(sentence, history_prompt=SPEAKER)
    pieces += [audio_array, silence.copy()]
concatenated_audio = np.concatenate(pieces)

# save audio to disk
output_wav_path = "whisper_and_bark_test1.wav"
write_wav(output_wav_path, SAMPLE_RATE, concatenated_audio)


from question_model import Question
from quiz_brain import QuizBrain
from random import shuffle
import requests

def CreateQuestionBank(n_questions = 10, difficulty = 'Medium'):
	url = "https://opentdb.com/api.php?amount="+n_questions+"&category=9&difficulty="+difficulty.lower()+"&type=boolean"
	source = requests.get(url).json()
	print(source)
	question_bank = []
	for qdict in source["results"]:
		question_bank.append(Question(qdict["question"], qdict["correct_answer"]))
	return question_bank

if __name__ == "__main__":
	# Get quiz questions based on user inputs
	number_of_questions = input("How many questions would you like? ")
	difficulty = input("Select your level of difficulty ('Easy','Medium','Hard'): ")

	quiz = QuizBrain(CreateQuestionBank(number_of_questions, difficulty))
	while quiz.still_has_questions():
		quiz.next_question()

	print(f"Your final score is {quiz.score}/{quiz.question_number}")


"""程序说明"""
# -*-  coding: utf-8 -*-
# Author: cao wang
# Datetime : 2020
# software: PyCharm
# 收获:
import  os
import schedule
import time

def rate():
    start_time = time.time()
    print("开始运行中------------------------------")
    index = 1
    path = r"F:\360下载\doc(第二次）".strip("\u202a")
    doc_and_docx_list = os.listdir(path)
    frequence = []
    for i in doc_and_docx_list:
        # print(i.split(".")[1])
        if i.split(".")[1] == "docx":
            frequence.append(i)
            index += 1
    print("docx文档一共： ", index)
    return start_time,index

def calculation():
    print(schedule.every(1).minutes.do(rate))
    schedule.run_pending()
calculation()

def print_():
    """测试使用函数"""
    start_time = time.time()
    time.sleep(5)
    end_time = time.time()
    return start_time,end_time

中国裁判文书网/selenium路线/数据清洗模块/文书由doc转为docx/转换速度.py


import torch
import torchaudio
from datasets import load_dataset, load_metric
from transformers import Wav2Vec2ForCTC, Wav2Vec2Processor
import re

test_dataset = load_dataset("common_voice", "zh-HK", split="test")
cer = load_metric("cer")

processor = Wav2Vec2Processor.from_pretrained("CAiRE/wav2vec2-large-xlsr-53-cantonese")
model = Wav2Vec2ForCTC.from_pretrained("CAiRE/wav2vec2-large-xlsr-53-cantonese")
model.to("cuda")

chars_to_ignore_regex = '[\,\?\.\!\-\;\:\"\“\%\‘\'\”\�]'

# Preprocessing the datasets.
# We need to read the aduio files as arrays
def speech_file_to_array_fn(batch):
  batch["sentence"] = re.sub(chars_to_ignore_regex, '', batch["sentence"]).lower()
  speech_array, sampling_rate = torchaudio.load(batch["path"])
  resampler = torchaudio.transforms.Resample(sampling_rate, 16_000)
  batch["speech"] = resampler(speech_array).squeeze().numpy()
  return batch

test_dataset = test_dataset.map(speech_file_to_array_fn)

# Preprocessing the datasets.
# We need to read the aduio files as arrays
def evaluate(batch):
  inputs = processor(batch["speech"], sampling_rate=16_000, return_tensors="pt", padding=True)

  with torch.no_grad():
    logits = model(inputs.input_values.to("cuda"), attention_mask=inputs.attention_mask.to("cuda")).logits

  pred_ids = torch.argmax(logits, dim=-1)
  batch["pred_strings"] = processor.batch_decode(pred_ids)
  return batch

result = test_dataset.map(evaluate, batched=True, batch_size=8)

print("CER: {:2f}".format(100 * cer.compute(predictions=result["pred_strings"], references=result["sentence"])))


cont = 0
otimo = 0
total_idd = 0
bom = 0
for i in range (1,16):
    for n in range (1,16):
        i = int(input('Qual a sua idade? '))
        n = int(input('Qual nota você dá para esse filme? \n 3 - ótimo \n 2 - bom \n 1 - regular: '))
        total_idd +=i
        if n ==3:
            otimo +=1
            media_idd = total_idd / otimo

        if n ==1:
            cont+=1

        if n ==2:
            bom+=1
            total_bom = (bom*100) / 15
    print (f'A média da idade das pessoas que votaram ótimo é: {media_idd:.2f} anos')
    print (f'A quantidade de pessoas que responderam regular foi: {cont}')
    print (f'A porcentagem de pessoas que responderam bom foi de {total_bom:.2f}%')


from django.shortcuts import render
from django.http import HttpResponse
from . import dbmanager
# Create your views here.

def home(request):
    return render(request,"homepage2.html")
global nxt
nxt=1
val_share=""
val_curfew=""

def add(request):
    addr=request.POST["addr"]
    Type=request.POST["type"]
    students=request.POST["students"]
    times=request.POST["times"]
    rent=request.POST["rent"]
    nego1=request.POST["nego1"]
    deposit=request.POST["deposit"]
    nego2=request.POST["nego2"]

    data=[addr,Type,rent,nego1,deposit,nego2,students,times]

    res=addr+Type+students+times+rent+nego1+deposit+nego2
    dbmanager.updateDB("calc_primaryform", data)

    #columns=['id', 'name', 'address', 'type_of_lease', 'rent', 'nego1', 'deposit', 'nego2', 'type_of_students', 'restrictions']
    columns=dbmanager.column("calc_subform_amenities")
    columns=columns[:-1]
    val_shares=Type
    val_curfew=times
    #lobal nxt
    nxt=len(columns)
    final=[]
    for index,val in enumerate(columns):
        label="try"+str(index)
        #print(val,type(val))
        try:
            val.index("is")
            final.append((val[2:],0,label))
            #final.append(0)
        except:
            pass
        try:
            val.index("no")
            final.append((val[2:],1,label))
            #final.append(1)
        except:
            pass

    #for val in final:
        #print(val)

    #nxt=len(final)
    print("form1",len(final),nxt)
            #print(val,"error")
    return render(request,"result2.html",{"valve":final})
    #num1=http

def sub(request):
    outs=[]
    columns=dbmanager.column("calc_subform_amenities")
    columns=columns[:-1]
    nxt=len(columns)
    print("now in subform amenities@@@@@@@@@@@@@@@@@@@@@")

    for x in columns:
        print(x)

    labels=[]
    print(nxt)

    for x in range(0,nxt):
        label="try"+str(x)

        labels.append(label)
        #print(label,labels)

        print(label)
        labels.append(label)
        temp=request.GET.get(label)
        print(temp)
        outs.append(temp)

    print(outs)

    dbmanager.updateDB("calc_subform_amenities", outs)
    """
    send to database
    """
    columns=dbmanager.column("calc_subform_restrictions")

    final=[]

    for index,x in enumerate(columns):
        s="try"+str(index)
        final.append((x,s))
    final=final[:-1]
    print("@@@@@@@@@@@@@@@@@@@@@@",columns)
    print(final)
    return render(request,"result3.html",{"valve":final})

def mul(request):
    outs=[]
    columns=dbmanager.column("calc_subform_restrictions")
    columns=columns[:-1]
    nxt=len(columns)
    print(nxt)
    print("now in subform restrictions@@@@@@@@@@@@@@@@@@@@@")

    for x in columns:
        print(x)

    labels=[]

    for x in range(0,nxt):
        label="try"+str(x)

        labels.append(label)
        #print(label,labels)

        print(label)
        labels.append(label)
        temp=request.GET.get(label)
        print(temp)
        outs.append(temp)

    print(outs)

    dbmanager.updateDB("calc_subform_restrictions", outs)
    """
    send to sharing or thankyou
    """

    return render(request,"result.html")

"""
def mul(request):
    outs=[]
    columns=dbmanager.column("calc_subform_restrictions")
    columns=columns[:-1]
    print(columns)
    nxt=len(columns)

    for x in columns:
        print(x)
    labels=[]
    print(nxt)
    for x in range(0,nxt):
        label="try"+str(x)

        labels.append(label)
        #print(label,labels)

        print(label)

        temp=request.GET.get(label)
        #print(temp)
        outs.append(temp)
    print(columns)
    print(outs)

    #send to database

    columns=dbmanager.column("calc_subform_curfew")
    final=[]
    for x,y in zip(columns,labels):

        final.append((x,y))

    return render(request,"result.html")
"""


unit = float(input("Choose a storage unit to convert from:"
                   "\n1 - Byte\n2 - Kilobyte\n3 - Megabyte\n4 - Gigabyte\n5 - Terabyte\n"))
qty = float(input("Enter the storage amount: "))
conversion = float(input("Choose a storage unit to convert to:"
                         "\n1 - Byte\n2 - Kilobyte\n3 - Megabyte\n4 - Gigabyte\n5 - Terabyte\n"))
sub = unit - conversion

level = 1024

if unit == conversion or sub == 0:
    print("You're trying to convert into the same unit.")
else:
    if sub > 0:
        result = qty * (level ** sub)
        print(f"Your input '{qty, unit}' has been converted into '{result, conversion}'")
    elif sub < 0:
        result = qty / (level ** -sub)
        print(f"Your input '{qty, unit}' has been converted into '{result, conversion}'")


@app.route('/prestitiUtente')
def prestito():
    codiceFiscale = request.args['utente']
    biblioteca = request.args['biblio']
    with psycopg2.connect(database='X') as conn:
        with conn.cursor() as cur:
            cur.execute
            (
                """SELECT idRisorsa, dataInizio, durata
                   FROM Prestito
                   WHERE idUtente = %s AND idBiblioteca = %s""",
                   (codiceFiscale,biblioteca)
            )
        lista = cur.fetchall()
    conn.close()

    if not lista:
        return render_template('/nessunPrestito.html')
    else:
        return render_template('view.html',listaPrestiti=lista,cUtente=codiceFiscale,idbiblio=biblioteca)


import cv2 as cv
import os
# from detection_test.draw_pose_box import draw_axis
from dt_apriltags import Detector
from calibration.calibrate import get_params

display_ip = os.environ.get('DISP')
print(display_ip)

params = get_params()
camera_parameters = ( params[0,0], params[1,1], params[0,2], params[1,2] )
print('params', params)

at_detector = Detector(families='tag36h11',
                       nthreads=1,
                       quad_decimate=1.0,
                       quad_sigma=0.0,
                       refine_edges=1,
                       decode_sharpening=0.25,
                       debug=0)
rtsp_stream = "rtsp://" + display_ip + ":8554/cam"
print(rtsp_stream)
cap = cv.VideoCapture(rtsp_stream)
if not cap.isOpened():
    print("Cannot open camera")
    exit()
while True:
    # Capture frame-by-frame
    ret, frame = cap.read()
    # if frame is read correctly ret is True
    if not ret:
        print("Can't receive frame (stream end?). Exiting ...")
        break
    # Our operations on the frame come here
    gray = cv.cvtColor(frame, cv.COLOR_BGR2GRAY)
    tags = at_detector.detect(gray, estimate_tag_pose=True, camera_params=camera_parameters, tag_size=0.2)

    for tag in tags:
        for idx in range(len(tag.corners)):
            cv.line(frame, tuple(tag.corners[idx-1, :].astype(int)), tuple(tag.corners[idx, :].astype(int)), (0, 255, 0))
        # uncomment for draw test
        # draw_axis(frame, tag.pose_R, tag.pose_t, params)

    # Display the resulting frame
    cv.imshow('frame', frame)
    if cv.waitKey(1) == ord('q'):
        break

# When everything done, release the capture
cap.release()
cv.destroyAllWindows()


from wget import download

class downloader:
    # Create a downloadfile method
    # Accepting the url and the file storage location
    # Set the location to an empty string by default.
    def downloadFile(self, url, dest=""):
         # Download file and with a custom progress bar
        download(url, out = dest)

dataset_dir = "A:\\xR-EgoPose\\data\\Dataset\\"
train_dir = dataset_dir + "TrainSet\\"
test_dir = dataset_dir + "TestSet\\"
val_dir = dataset_dir + "ValSet\\"

fileDef_val = list([("male_008_a_a", 'i')])

fileDef_test = list([("female_004_a_a", 'i'),
                   ("female_008_a_a", 'i'),
                   ("female_010_a_a", 'i'),
                   ("female_012_a_a", 'f'),
                   ("female_012_f_s", 'a'),
                   ("male_001_a_a", 'i'),
                   ("male_002_a_a", 'j'),
                   ("male_004_f_s", 'a'),
                   ("male_006_a_a", 'i'),
                   ("male_007_f_s", 'a'),
                   ("male_010_a_a", 'i'),
                   ("male_014_f_s", 'a')])

fileDef_train = list([("female_001_a_a", 'i'),
                   ("female_002_a_a", 'j'),
                   ("female_002_f_s", 'a'),
                   ("female_003_a_a", 'f'),
                   ("female_005_a_a", 'i'),
                   ("female_006_a_a", 'i'),
                   ("female_007_a_a", 'h'),
                   ("female_009_a_a", 'i'),
                   ("female_011_a_a", 'f'),
                   ("female_014_a_a", 'f'),
                   ("female_015_a_a", 'j'),
                   ("male_003_f_s", 'a'),
                   ("male_004_a_a", 'i'),
                   ("male_005_a_a", 'j'),
                   ("male_006_f_s", 'a'),
                   ("male_007_a_a", 'i'),
                   ("male_008_f_s", 'a'),
                   ("male_009_a_a", 'h'),
                   ("male_010_f_s", 'a'),
                   ("male_011_f_s", 'a'),
                   ("male_014_a_a", 'i')])

def process(fileDef_list, dest_str):
    downloadObj = downloader()

    for _, fileDef_tup in enumerate(fileDef_list):
        prefix, maxIndex = fileDef_tup

        index_list = []
        alpha = 'a'
        for _ in range(0,26):
            index_list.append(alpha)
            if alpha == maxIndex:
                break
            alpha = chr(ord(alpha)+1)

        for _, index in enumerate(index_list):
            url="https://github.com/facebookresearch/xR-EgoPose/releases/download/v1.0/{}.tar.gz.parta{}".format(prefix, index)
            print("Downloading: " + url)
            downloadObj.downloadFile(url, dest_str)

#process(fileDef_test, test_dir)
#process(fileDef_train, train_dir)
process(fileDef_val, val_dir)