import torch
import segmentation_models_pytorch as smp

DECODERS = [
    'DeepLabV3',
    'DeepLabV3Plus',
    'FPN',
    'Linknet',
    'MAnet',
    'PAN',
    'PSPNet',
    'Unet',
    'UnetPlusPlus',
]
ENCODERS = list(smp.encoders.encoders.keys())

def define_model(
        decoder_name,
        encoder_name,
        num_classes=1,
        activation=None,
        encoder_weights='imagenet',
):
    """
    Define segmentation model using segmentation-models-pytorch,
    see 'https://github.com/qubvel/segmentation_models.pytorch'.

    Args:
        decoder_name (str): Name of architecture to use.
        encoder_name (str): Name of encoder to use.
        num_class (int): Number of classes to classify. Defaults to 1.
        activation (str, optional): Name of activation function, apply to last layer.
            Defaults to None,
        encoder_weights (str, optional): Pretrained model weights for encoder.
            Defaults to pretrained on "imagenet" dataset.
    """
    assert decoder_name in DECODERS, "Decoder name not supported"
    assert encoder_name in ENCODERS, "Encoder name not supported"

    decoder = getattr(smp, decoder_name)

    model = decoder(
        encoder_name,
        encoder_weights=encoder_weights,
        classes=num_classes,
        activation=activation
    )

    return model


from nonebot import on_command
from nonebot.typing import Bot, Event
import os
from pathlib import Path
from utils.eve import get_data
import xmltodict,json,requests
from utils.utils_img import compress_image, aio_download_pics
eve = on_command('eve')
@eve.handle()
async def _(bot: Bot, event: Event, state: dict):
	help_doc='/eve 物品名 星域名(可选) 查询价格\n/minerals查询吉他市场基础矿物的收购最高价\nquicklook 订单查询(未实装)'
	msg = str(event.message).strip().split(' ')
	if msg == ['']:
		await eve.finish(help_doc)
	elif len(msg) == 1:
		data=get_data(msg[0])
	elif len(msg) == 2:
		data=get_data(msg[0],msg[1])
	if data[0] == -1:
		await eve.finish("未知星域")
	elif data[0] == -2:
		await eve.finish("未查询到物品")
	buy=data[0]['buy']
	sell=data[0]['sell']
	if data[2]=="":
		data[2]="all"
	await eve.send(f"正在查询星域{data[2]}中的{data[1]}")
	msg0=f"需求量:{buy['volume']}\n"
	msg0+=f"最高价:{buy['max']} 最低价:{buy['min']}\n"
	msg0+=f"出售总量:{sell['volume']}\n"
	msg0+=f"最高价:{sell['max']} 最低价:{sell['min']}\n"
	await eve.finish(msg0)
#--------矿物价格
minerals= on_command('minerals')
@minerals.handle()
async def _(bot: Bot, event: Event, state: dict):
	try:
		text=requests.get('https://www.ceve-market.org/api/evemon').text
		data=xmltodict.parse(text,encoding='utf-8')["minerals"]["mineral"]
	except:
		await minerals.finish('发生了奇怪的错误,请用/report向管理汇报')
	msg0='以下是基础矿物吉他收购价格\n'
	for d in data:
		msg0+="{0:10}\t{1:<10}\n".format(d['name'].strip(),d['price'].strip(),'　')
	await minerals.finish(msg0)
#--------订单信息
quicklook=on_command('quicklook')
@quicklook.handle()
async def _(bot: Bot, event: Event, state: dict):
	msg = str(event.message).strip().split(' ')
	if msg == ['']:
		await quicklook.finish('/quicklook sell/buy 物品名 星域名来查询订单信息')
	pass
#-------安全地图
safemap=on_command('safemap')
async def _(bot: Bot, event: Event, state: dict):
	safemap_url='https://www.ceve-market.org/dumps/safemap/last.png'
	await safemap.finish('[CQ:image,file=file:///{compress_image(await aio_download_pics(safemap_url))}]')


# Importa PI
from math import pi

# "Banco de dados"
class Registro(object):
    def __init__(self):
        self.pontos = list()
        self.circulos = list()

    def registrar(self, ponto=None, circulo=None):
        if isinstance(circulo, Circulo):
            self.circulos.append([circulo.centro, circulo.raio])
        if isinstance(ponto, Ponto):
            self.pontos.append([ponto.x, ponto.y])

    def get_registros_pontos(self):
        return self.pontos

    def get_registros_circulos(self):
        return self.circulos

    def del_registro_circulos(self, index):
        self.circulos.pop(index)

# Class Ponto
class Ponto(object):
    def __init__(self, x: float, y: float, registro):
        self.x = float()
        self.y = float()
        if self.se_ponto(x, y, registro):
            self.x = x
            self.y = y
            registro.registrar(ponto=self)

    def se_ponto(self, x, y, registro):
        registros = registro.get_registros_pontos()
        ponto = [x, y]
        for reg in registros:
            if ponto == reg:
                return False
        return True

    def get_ponto(self):
        return (self.x, self.y)

# Class DiatanciaPontos
class DistanciaPontos(object):
    def __init__(self, p1: Ponto, p2: Ponto):
        self.ponto1 = p1
        self.ponto2 = p2

    def get_distancia_ponto(self):
        dx = abs(self.ponto2.x - self.ponto1.x)
        dy = abs(self.ponto2.y - self.ponto1.y)
        return pow(pow(dx, 2) + pow(dy, 2), (1/2))

# Class Círculo
class Circulo(object):
    def __init__(self, centro: Ponto, ponto: Ponto, registro: Registro):
        self.centro_class = centro
        self.ponto_class = ponto
        self.centro = [centro.x, centro.y]
        self.ponto = [ponto.x, ponto.y]
        self.raio = DistanciaPontos(centro, ponto).get_distancia_ponto()
        if self.se_circulo(self.centro, self.raio, registro):
            registro.registrar(circulo=self)
        else:
            self.centro = None
            self.ponto = None
            self.raio = None

    def se_circulo(self, centro, raio, registro):
        registros = registro.get_registros_circulos()
        circulo = [centro, raio]
        for reg in registros:
            if circulo == reg:
                return False
        return True

    def destruir_circulo(self, registro):
        for index, reg in enumerate(registro.get_registros_circulos()):
            if [self.centro, self.raio] == reg:
                registro.del_registro_circulos(index)

    def get_area(self):
        return round(pi * pow(self.raio, 2))

    def __lt__(self, other):
        distancia = DistanciaPontos(self.centro_class, other).get_distancia_ponto()
        if self.raio == distancia:
            return True
        else:
            return False

    def __sub__(self, other):
        distancia = DistanciaPontos(self.centro_class, other).get_distancia_ponto()
        if distancia < self.raio:
            return True
        else:
            return False

# Cria "Banco de dados" (registro)
registro = Registro()
# Cria Pontos
ponto1 = Ponto(0, 0, registro)
ponto2 = Ponto(0, 5, registro)
ponto3 = Ponto(5, 0, registro)

# 1/2) Cria Círculos / Verifica Círculos
circulo1 = Circulo(ponto1, ponto2, registro)
circulo2 = Circulo(ponto2, ponto1, registro)

# 3) Deleta Círculos
circulo2.destruir_circulo(registro)

# 4) Area do Círculo
circulo1.get_area()

# 5) Pertence ao Círculo
circulo1 < ponto1

# 6) Interno ao Círculo
circulo1 - ponto1

estruturas-de-dados/03-tipos-abstratos-de-dados/Tipos Abstratos de Dados - Ponto.py


from random import randint

def poly_hash(P, p, x):
	h = 0
	for i in reversed(range(len(P))):
		h = (h * x + ord(P[i])) % p
	return h

def precompute_hashes(T, len_p, p, x):
	len_t = len(T)
	n = len_t - len_p + 1

	hashes = [None] * n
	s = T[len(T) - len_p:]
	hashes[-1] = poly_hash(s, p, x)
	y = 1
	for i in range(len_p):
		y = (y * x) % p

	for i in reversed(range(n - 1)):
		hashes[i] = (x * hashes[i + 1] + ord(T[i]) - y * ord(T[i + len_p])) % p
	return hashes

def rabin_karp(T, P):
	p = 7 + 10**12
	x = randint(1, p - 1)
	result = []
	p_hash = poly_hash(P, p, x)
	hashes = precompute_hashes(T, len(P), p, x)
	for i in range(len(T) - len(P) + 1):
		h = hashes[i]
		if p_hash != h:
			continue
		if T[i:i + len(P)] == P:
			result.append(i)
	return result

def main():
	P = input()
	T = input()
	# T = 'testTesttesT'
	# P = 'Test'
	print(*rabin_karp(T, P))

if __name__ == '__main__':
	main()


import wget
import requests
import os
import hashlib
import tarfile

def has_new_ver(ver_url, ver_fname):
    "用于检查是否有新版本，有则返回True，否则返回False"
    # 如果本地没有版本文件，则有新版本
    if not os.path.exists(ver_fname):
        return True

    # 如果本地和远程版本文件不一样，则有新版本
    with open(ver_fname) as fobj:
        local_ver = fobj.read()
    r = requests.get(ver_url)
    if local_ver != r.text:
        return True

    # 如果上述条件都不满足，则没有新版本
    return False

def check_file(md5url, fname):
    "用于检查文件是否损坏，未损坏返回True，否则返回False"
    # 计算本地文件的md5值
    m = hashlib.md5()
    with open(fname, 'rb') as fobj:
        while 1:
            data = fobj.read(4096)
            if not data:
                break
            m.update(data)

    # 取出网上md5值，进行比较
    r = requests.get(md5url)
    if m.hexdigest() == r.text.strip():  # 去除网上md5文件尾部\n
        return True

    # 如果本地和远程的md5值不一样，返回False
    return False

def deploy(app_fname, deploy_dir, dest):
    "用于部署程序到应用服务器"
    # 解压文件到目标
    tar = tarfile.open(app_fname)
    tar.extractall(path=deploy_dir)
    tar.close()

    # 拼接出解压目录的绝对路径
    app_dir = os.path.basename(app_fname)
    app_dir = app_dir.replace('.tar.gz', '')
    app_dir = os.path.join(deploy_dir, app_dir)

    # 创建快捷方式，如果快捷方式已存在，先删除它
    if os.path.exists(dest):
        os.remove(dest)

    os.symlink(app_dir, dest)

if __name__ == '__main__':
    # 检查是否有新版本，没有新版本退出
    ver_url = 'http://192.168.81.135/deploy/live_ver'
    ver_fname = '/var/www/deploy/live_ver'
    if not has_new_ver(ver_url, ver_fname):
        print('未发现新版本。')
        exit(1)

    # 下载新版本
    r = requests.get(ver_url)
    pkg_url = 'http://192.168.81.135/deploy/pkgs/myweb-%s.tar.gz' % r.text
    app_fname = '/var/www/download/myweb-%s.tar.gz' % r.text
    wget.download(pkg_url, app_fname)

    # 检查新版本程序文件是否损坏，如损坏则删除它并退出
    md5url = pkg_url + '.md5'
    if not check_file(md5url, app_fname):
        print('文件已损坏。')
        os.remove(app_fname)
        exit(2)

    # 部署软件
    deploy_dir = '/var/www/deploy'
    dest = '/var/www/html/nsd1912'
    deploy(app_fname, deploy_dir, dest)

    # 更新本地版本live_ver文件
    if os.path.exists(ver_fname):
        os.remove(ver_fname)
    wget.download(ver_url, ver_fname)


#!/usr/bin/env python
# -*- coding: utf-8 -*-

# ROS与视觉系统联合调试代码
# 第三版
# 使用service连接visual端；使用action连接web端
# 434 135 749
# i1dC80

import rospy, sys, math, roslib, actionlib
import moveit_commander
import numpy as np
from copy import deepcopy
from std_msgs.msg import Bool
from moveit_commander import MoveGroupCommander, PlanningSceneInterface
from moveit_msgs.msg import PlanningScene, ObjectColor
from geometry_msgs.msg import Pose, PoseStamped, Twist
from sensor_msgs.msg import JointState
from tf.transformations import euler_from_quaternion, quaternion_from_euler
from abb_irb1200_planning.msg import AbbGraspAction, AbbGraspFeedback, AbbGraspResult
from abb_irb1200_planning.srv import *

NODE_NAME = "abb_real_demo"
ARM_GROUP = "manipulator"
HOME_POSE = "home"
ALL_ZERO_POSE = "all-zero"
TOPIC_NAME = "cmd_vel"
REFERENCE_FRAME = "base_link"
ON_OFF_SIGNAL_TOPIC = "end_effector"
END_EFFECTOR_LINK = "link_6"
VISUAL_TOPIC_TYPE = Twist

HEIGHT_OF_ROBOT = 0.81
HEIGHT_OF_END_EFFECTOR = 0.17
GAP_TO_ITEM = 0.10

GET_DATA_SIGNAL = 1

class MoveItCartesianDemo:
    def __init__(self):
        # 初始化move_group的API
        moveit_commander.roscpp_initialize(sys.argv)

        # 初始化ROS节点
        rospy.init_node(NODE_NAME, anonymous=True)
        self.pub = rospy.Publisher(ON_OFF_SIGNAL_TOPIC, Bool, queue_size=2)
        self.rate = rospy.Rate(2)

        # 是否需要使用笛卡尔运动规划
        self.cartesian = rospy.get_param('~cartesian', True)

        # 初始化需要使用move group控制的机械臂中的self.arm group
        self.arm = MoveGroupCommander(ARM_GROUP)
        # 设置目标位置所使用的参考坐标系
        reference_frame = 'base_link'
        self.arm.set_pose_reference_frame(REFERENCE_FRAME)
        # 获取终端link的名称
        end_effector_link = 'link_6'
        # 当运动规划失败后，允许重新规划
        self.arm.allow_replanning(True)

        # 设置位置（单位：米）和姿态（单位：弧度）的允许误差
        self.arm.set_goal_position_tolerance(0.01)
        self.arm.set_goal_orientation_tolerance(0.1)

        # 环境建模
        scene = PlanningSceneInterface()
        self.scene_pub = rospy.Publisher('planning_scene', PlanningScene, queue_size=5)
        self.colors = dict()
        rospy.sleep(1)

        # 场景物体设置
        table_id = 'table'
        scene.remove_world_object(table_id)
        self.table_ground = 0.592 - 0.148
        table_size = [0.5, 1.5, 0.04]
        table_pose = PoseStamped()
        table_pose.header.frame_id = REFERENCE_FRAME
        table_pose.pose.position.x = 0.6
        table_pose.pose.position.y = - 0.5
        table_pose.pose.position.z = self.table_ground - table_size[2] / 2.0
        table_pose.pose.orientation.w = 1.0
        scene.add_box(table_id, table_pose, table_size)

        self.setColor(table_id, 0, 0.8, 0, 1.0)
        self.sendColors()

        # rospy.loginfo(self.arm.get_current_pose(END_EFFECTOR_LINK).pose)

        # # 控制机械臂先回到初始化位置
        # self.arm.set_named_target(ALL_ZERO_POSE)
        # self.arm.go()
        # # rospy.sleep(1)
        # rospy.loginfo("已到达准备点")
        # rospy.spin()

        # 控制机械臂先回到初始化位置
        self.arm.set_named_target(HOME_POSE)
        self.arm.go()
        # rospy.sleep(1)
        rospy.loginfo("已到达准备点")

        # rospy.spin()

        # 第二段运动：移动到停泊点
        anchor_pose = [0, 0.597, -0.665, 0, 1.636, 0]
        self.arm.set_joint_value_target(anchor_pose)
        self.arm.go()
        rospy.loginfo("已移动到停泊点")
        start_pose = self.arm.get_current_pose(END_EFFECTOR_LINK).pose

        # 提前规划：停泊点位置
        self.anchor_pose = self.arm.get_current_pose(END_EFFECTOR_LINK).pose
        self.anchor_pose.position.x = 0.7
        self.anchor_pose.position.y = 0
        self.anchor_pose.position.z = 0.764   # self.table_ground + 0.10 + HEIGHT_OF_END_EFFECTOR
        self.anchor_pose.orientation.x = 0
        self.anchor_pose.orientation.y = 0.707
        self.anchor_pose.orientation.z = 0
        self.anchor_pose.orientation.w = 0.707

        # 用于确定停泊点的关节角情况
        # waypoints = []
        # waypoints.append(start_pose)
        # waypoints.append(self.anchor_pose)
        # traj, fraction = self.cartesian_plan(self.arm, waypoints)
        # self.arm.set_start_state_to_current_state()
        # if fraction == 1.0:
        #     self.arm.execute(traj)
        #     rospy.loginfo("已到达吸取点")
        # else:
        #     rospy.spin()

        # def callback(data):
        #     rospy.loginfo(data)
        # rospy.Subscriber('joint_states', JointState, callback)

        # rospy.spin()

        # 提前规划:中间点位置
        self.middle_pose = deepcopy(start_pose)
        self.middle_pose.position.x = 0
        self.middle_pose.position.y = 0.7
        self.middle_pose.position.z = self.anchor_pose.position.z
        self.middle_pose.orientation.x = -0.5
        self.middle_pose.orientation.y = 0.5
        self.middle_pose.orientation.z = 0.5
        self.middle_pose.orientation.w = 0.5

        # 提前规划:下料点位置
        self.place_pose = deepcopy(start_pose)
        self.place_pose.position.x = 0
        self.place_pose.position.y = 0.7
        self.place_pose.position.z = 0.05 + HEIGHT_OF_END_EFFECTOR - 0.14
        self.place_pose.orientation.x = -0.5
        self.place_pose.orientation.y = 0.5
        self.place_pose.orientation.z = 0.5
        self.place_pose.orientation.w = 0.5

        # 用于确定下料点的关节角情况
        # waypoints = []
        # waypoints.append(start_pose)
        # waypoints.append(self.place_pose)
        # traj, fraction = self.cartesian_plan(self.arm, waypoints)
        # self.arm.set_start_state_to_current_state()
        # if fraction == 1.0:
        #     self.arm.execute(traj)
        #     rospy.loginfo("已到达吸取点")
        # else:
        #     rospy.spin()

        # def callback(data):
        #     rospy.loginfo(data)
        # rospy.Subscriber('joint_states', JointState, callback)

        # rospy.spin()

        # 提前规划：释放点位置
        self.release_pose = deepcopy(start_pose)
        self.release_pose.position.x = 0.7
        self.release_pose.position.y = 0
        self.release_pose.position.z = 0.704   # self.table_ground + 0.10 + HEIGHT_OF_END_EFFECTOR
        self.release_pose.orientation.x = 0
        self.release_pose.orientation.y = 0.707
        self.release_pose.orientation.z = 0
        self.release_pose.orientation.w = 0.707

        while not rospy.is_shutdown():
            # 开启web端action通讯，等待讯号
            self.server = actionlib.SimpleActionServer('abb_grasp', AbbGraspAction, self.abb_execute, False)
            self.server.start()
            rospy.spin()

        # 关闭并退出moveit
        moveit_commander.roscpp_shutdown()
        moveit_commander.os._exit(0)

    # action callback function
    def abb_execute(self, goal):
        # 统计参数，与action有关
        self.num = 0    # 计算本轮循环中的件数
        self.schedule_percent = AbbGraspFeedback()    # 统计进度百分比
        self.schedule_result = AbbGraspResult()    # 统计完成进度数量
        self.goal = goal    # 设定目标值
        self.item_id = 0    # 初始化计件id值

        rate = rospy.Rate(25)
        rospy.loginfo("Get message from web socket and action!")

        while self.num <= self.goal.grasp_id:
            self.num += 1

            # service 方法 - 接收视觉处理后的数据
            rospy.wait_for_service('abb_visual')
            rospy.loginfo("Start to get coorporation data from visual PC...")
            try:
                rospy.loginfo("Service client Start.")
                abb_get_visual_data = rospy.ServiceProxy('abb_visual', AbbPose)
                res_coordinate = abb_get_visual_data(GET_DATA_SIGNAL)
                rospy.loginfo(res_coordinate)
                if (res_coordinate.item_id - self.item_id):
                    # self.arm.set_start_state_to_current_state()
                    # 执行函数
                    self.callback(res_coordinate)
                    self.item_id = res_coordinate.item_id
            except rospy.ServiceException as e:
                rospy.loginfo("Service call failed: %s"%e)

        self.server.set_succeeded(self.schedule_result)
        rospy.loginfo(self.schedule_result)
        rospy.loginfo("------------Finished------------")

    # 获取视觉处理的坐标位置后的执行函数
    def callback(self, data):
        # 设置机械臂工作空间中的目标位姿，位置使用x,y,z坐标描述
        # 姿态使用四元数描述，基于base_link坐标系

        rospy.loginfo("目标点位置：\n")
        rospy.loginfo(data)

        ##################### 即时规划 ######################
        # 获取当前位姿数据为停泊点位姿
        anchor_pose = self.arm.get_current_pose(END_EFFECTOR_LINK).pose
        anchor_pose.orientation.x = 0
        anchor_pose.orientation.y = 0.707
        anchor_pose.orientation.z = 0
        anchor_pose.orientation.w = 0.707
        self.anchor_pose = anchor_pose

        # 初始化路点列表
        waypoints = []
        # 将初始位姿加入路点列表
        if self.cartesian:
            waypoints.append(anchor_pose)
        # 初始化路点数据
        wpose = deepcopy(anchor_pose)
        # wpose.orientation.x = 0
        # wpose.orientation.y = 0.707
        # wpose.orientation.z = 0
        # wpose.orientation.w = 0.707

        # 第三段路径：停泊点=》吸取点
        rospy.loginfo("规划：从停泊点至吸取点")
        wpose.position.x = data.position_x
        wpose.position.y = data.position_y
        #------------------- !!!注意!!! -------------------#
        # if data.orientation_x:
        #     wpose.position.z = 0.699 # data.position_z  # 0.714
        # else:
        #     wpose.position.z = 0.692 # data.position_z  # 0.714
        wpose.position.z = data.position_z
        #------------------- !!!修改!!! -------------------#
        rad_x = data.orientation_w
        rad_y = 1.5708
        rad_z = 0
        list_orientation = quaternion_from_euler(rad_x, rad_y, rad_z)
        wpose.orientation.x = list_orientation[0]
        wpose.orientation.y = list_orientation[1]
        wpose.orientation.z = list_orientation[2]
        wpose.orientation.w = list_orientation[3]
        #------------------- !!!修改!!! -------------------#
        if self.cartesian:
            # 气泵控制，气阀操作，吸盘抓取
            on_off_signal = 1
            self.pub.publish(on_off_signal)
            rospy.loginfo("Open the gas valve.")
            self.rate.sleep()

            waypoints.append(wpose)

        traj, fraction = self.cartesian_plan(self.arm, waypoints)
        self.arm.set_start_state_to_current_state()
        if fraction == 1.0:
            wait_time = data.time / 1000
            rospy.sleep(wait_time)
            self.arm.set_start_state_to_current_state()
            self.arm.execute(traj)
            rospy.loginfo("已到达吸取点")
        else:
            rospy.loginfo("Anchor_to_Grasp_Path Planning failed with only " + str(fraction) + "success after " + str(100) + " attempts.")

        # def callback(data):
        #     rospy.loginfo(data)
        # rospy.Subscriber('joint_states', JointState, callback)

        # rospy.spin()

        # # 第3.5段路径：吸取点 =》 反弹点
        # self.arm.shift_pose_target(2, 0.05, END_EFFECTOR_LINK)
        # self.arm.go()
        # rospy.sleep(1)

        # 第四段路径：反弹点 =》 停泊点
        rospy.loginfo("规划：从吸取点返回停泊点")
        # grasp_pose = self.arm.get_current_pose(END_EFFECTOR_LINK).pose
        # waypoints = []
        # waypoints.append(grasp_pose)
        # waypoints.append(anchor_pose)
        # traj, fraction = self.cartesian_plan(self.arm, waypoints)
        # self.arm.set_start_state_to_current_state()
        # if fraction == 1.0:
        #     self.arm.execute(traj)
        #     rospy.loginfo("已返回停泊点")
        # else:
        #     rospy.loginfo("Grasp_to_Anchor_Path Planning failed with only " + str(fraction) + "success after " + str(100) + " attempts.")
        anchor_pose = [0, 0.597, -0.665, 0, 1.636, 0]  # 停泊点 [0, 0.597, -0.665, 0, 1.636, 0]
        self.arm.set_joint_value_target(anchor_pose)
        self.arm.go()
        rospy.loginfo("已移动到停泊点")
        ###################### 即时规划结束 ####################

        # rospy.spin()

        # anchor_pose = [0, 0.597, -0.665, 0, 1.636, 0]  # 停泊点 [0, 0.597, -0.665, 0, 1.636, 0]
        # self.arm.set_joint_value_target(anchor_pose)
        # self.arm.go()
        # rospy.loginfo("已移动到停泊点")

        # rospy.spin()

        ####################### 提前规划 ######################
        if data.orientation_x:   # ox != 0, trangle
            middle_pose = [1.571, 0.597, -0.665, 0, 1.636, 0]
            place_pose = [1.571, 1.297, -0.270, -0.003, 0.544, 0.003]
        else:                   # ox == 0, circle
            middle_pose = [2.285, 0.597, -0.665, 0, 1.636, 0]
            place_pose = [2.285, 1.471, -0.687, -0.002, 0.788, 0.715]
        # 停泊点 =》 下料点
        # self.anchor_point_to_middle_point(True)
        # middle_pose = [1.571, 0.597, -0.665, 0, 1.636, 0]
        self.arm.set_joint_value_target(middle_pose)
        self.arm.go()
        rospy.loginfo("已移动到中间点")

        # 测试，下料点定点使用
        # rospy.spin()
        # middle_point = self.arm.get_current_pose(END_EFFECTOR_LINK).pose
        # waypoints = []
        # waypoints.append(middle_point)
        # waypoints.append(self.place_pose)
        # traj, fraction = self.cartesian_plan(self.arm, waypoints)
        # self.arm.set_start_state_to_current_state()
        # if fraction == 1.0:
        #     self.arm.execute(traj)
        #     rospy.loginfo("已到达吸取点")
        # else:
        #     rospy.spin()
        # def callback(data):
        #     rospy.loginfo(data)
        # rospy.Subscriber('joint_states', JointState, callback)
        # rospy.spin()

        # self.middle_point_to_place_point(True)
        # place_pose = [1.571, 1.297, -0.270, -0.003, 0.544, 0.003]
        self.arm.set_joint_value_target(place_pose)
        self.arm.go()
        rospy.loginfo("已到达下料点")

        # rospy.sleep(1)

        # rospy.spin()

        # 气阀操作，吸盘释放
        on_off_signal = 0
        self.pub.publish(on_off_signal)
        rospy.loginfo("Close the gas valve.")
        self.rate.sleep()
        rospy.sleep(1)

        # 下料点 =》 停泊点
        # self.middle_point_to_place_point(False)
        # middle_pose = [1.571, 0.597, -0.665, 0, 1.636, 0]
        self.arm.set_joint_value_target(middle_pose)
        self.arm.go()
        rospy.loginfo("已返回中间点")
        # self.anchor_point_to_middle_point(False)
        anchor_pose = [0, 0.597, -0.665, 0, 1.636, 0]
        self.arm.set_joint_value_target(anchor_pose)
        self.arm.go()
        rospy.loginfo("已返回停泊点")
        rospy.sleep(1)

        # rospy.spin()

        # 停泊点 =》 下料点
        # self.anchor_point_to_middle_point(True)
        # middle_pose = [1.571, 0.597, -0.665, 0, 1.636, 0]
        self.arm.set_joint_value_target(middle_pose)
        self.arm.go()
        rospy.loginfo("已移动到中间点")
        # self.middle_point_to_place_point(True)

        # place_pose = [1.571, 1.297, -0.270, -0.003, 0.544, 0.003]
        self.arm.set_joint_value_target(place_pose)
        self.arm.go()
        rospy.loginfo("已返回下料点")

        rospy.sleep(1)

        # 气阀操作,吸盘吸取
        on_off_signal = 1
        self.pub.publish(on_off_signal)
        rospy.loginfo("Open the gas valve.")
        self.rate.sleep()
        rospy.sleep(1)

        # 下料点 =》 停泊点
        # self.middle_point_to_place_point(False)
        # middle_pose = [1.571, 0.597, -0.665, 0, 1.636, 0]
        self.arm.set_joint_value_target(middle_pose)
        self.arm.go()
        rospy.loginfo("已返回中间点")
        # self.anchor_point_to_middle_point(False)
        anchor_pose = [0, 0.597, -0.665, 0, 1.636, 0]
        self.arm.set_joint_value_target(anchor_pose)
        self.arm.go()
        rospy.loginfo("已返回停泊点")

        # rospy.spin()

        # 停泊点 =》 释放点
        self.anchor_point_to_release_point(True)
        rospy.loginfo("已到达释放点")

        # 气阀操作，吸盘释放
        on_off_signal = 0
        self.pub.publish(on_off_signal)
        rospy.loginfo("Close the gas valve.")
        self.rate.sleep()

        # 释放点 =》 停泊点
        self.anchor_point_to_release_point(False)
        rospy.loginfo("已返回停泊点")
        ####################### 提前规划结束 ######################

        self.schedule_percent.percent_complete = self.num / float(self.goal.grasp_id)
        self.server.publish_feedback(self.schedule_percent)
        self.schedule_result.total_grasped = self.num
        rospy.loginfo("Schedule: %0.2f %%", self.schedule_percent.percent_complete * 100)
        rospy.loginfo("Total Grasped: %d ", int(self.schedule_result.total_grasped))
        rospy.loginfo("------------- End: Wait For Next Grasp -----------")

    def cartesian_plan(self, arm_object, point_list):
        fraction = 0.0       # 路径规划覆盖率
        maxtries = 100        # 最大尝试规划次数
        attempts = 0        # 已经尝试规划次数

        # 设置机械臂当前的状态为运动初始状态
        arm_object.set_start_state_to_current_state()

        # 尝试规划一条笛卡尔空间下的路径，依次通过所有路点
        while fraction < 1.0 and attempts < maxtries:
            (traj, fraction) = arm_object.compute_cartesian_path(
                    point_list,     # 路点列表
                    0.01,        # 终端步进值
                    0.0,        # 跳跃阈值
                    True        # 避障规划
                )

            attempts += 1

            # 打印运动规划进程
            if attempts % 10 == 0:
                rospy.loginfo("Still trying after " +  str(attempts) + " attempts...")

        return traj, fraction

    def anchor_point_to_middle_point(self, dirc):
        # 提前规划运动：
        # dirc = true: 从停泊点到下料点
        # dirc = false: 从下料点到停泊点
        waypoints = []
        if dirc:
            start_pose = self.arm.get_current_pose(END_EFFECTOR_LINK).pose
            waypoints.append(start_pose)
        # waypoints.append(self.anchor_pose)
        wpose = deepcopy(self.anchor_pose)

        # 平面圆弧转动
        rospy.loginfo("进入多边形迫近圆形插补方法规划")
        i = 1
        while wpose.position.x > 0:
            # cos_5 = 0.99619
            # sin_5 = 0.08716
            # rad_5 = 5.0 / 180.0 * math.pi
            cos_1 = 0.99985
            sin_1 = 0.01745
            rad_1 = 1.0 / 180.0 * math.pi
            wpose.position.x = wpose.position.x * cos_1 - np.sign(self.place_pose.position.y) * wpose.position.y * sin_1
            wpose.position.y = np.sign(self.place_pose.position.y) * wpose.position.x * sin_1 + wpose.position.y * cos_1
            # wpose.position.z += delta_z    # z轴取消插补
            rad_x = - np.sign(self.place_pose.position.y) * rad_1 * i
            rad_y = 1.5708
            rad_z = 0
            list_orientation = quaternion_from_euler(rad_x, rad_y, rad_z)
            wpose.orientation.x = list_orientation[0]
            wpose.orientation.y = list_orientation[1]
            wpose.orientation.z = list_orientation[2]
            wpose.orientation.w = list_orientation[3]
            i += 1

            if self.cartesian:
                waypoints.append(deepcopy(wpose))
            else:
                self.arm.set_pose_target(wpose)
                self.arm.go()
        # waypoints.append(self.middle_pose)

        if not dirc:
            start_pose = self.arm.get_current_pose(END_EFFECTOR_LINK).pose
            waypoints.append(start_pose)
            waypoints.reverse()

        traj, fraction = self.cartesian_plan(self.arm, waypoints)
        # f = open("plan_of_cartisen_demo.txt", "w")
        # f.write(str(traj))
        # f.close()
        if fraction == 1.0:
            self.arm.set_start_state_to_current_state()
            self.arm.execute(traj)
            rospy.loginfo("停泊点和中间点间运动已执行")
        else:
            rospy.loginfo("Anchor_to_Place_Path Planning failed with only " + str(fraction) + "success after " + str(100) + " attempts.")

    def middle_point_to_place_point(self, dirc):
        # 提前规划运动：
        # dirc = true: 从中间点到下料点
        # dirc = false: 从下料点到中间点
        waypoints = []
        if dirc:
            start_pose = self.arm.get_current_pose(END_EFFECTOR_LINK).pose
            waypoints.append(start_pose)
            waypoints.append(self.place_pose)
        else:
            start_pose = self.arm.get_current_pose(END_EFFECTOR_LINK).pose
            waypoints.append(start_pose)
            waypoints.append(self.middle_pose)

        traj, fraction = self.cartesian_plan(self.arm, waypoints)
        if fraction == 1.0:
            self.arm.set_start_state_to_current_state()
            self.arm.execute(traj)
            # def callback(data):
            #     rospy.loginfo(data)
            # rospy.Subscriber('joint_states', JointState, callback)
            # rospy.spin()
            rospy.loginfo("中间点和下料点间运动已执行")
        else:
            rospy.loginfo("Anchor_to_Place_Path Planning failed with only " + str(fraction) + "success after " + str(100) + " attempts.")

    def anchor_point_to_release_point(self, dirc):
        # 提前规划运动：
        # dirc = true: 从停泊点到释放点
        # dirc = false: 从释放点到停泊点
        waypoints = []
        waypoints.append(self.anchor_pose)
        waypoints.append(self.release_pose)
        if not dirc:
            waypoints.reverse()

        traj, fraction = self.cartesian_plan(self.arm, waypoints)
        if fraction == 1.0:
            self.arm.set_start_state_to_current_state()
            self.arm.execute(traj)
            rospy.loginfo("停泊点和释放点间运动已执行")
        else:
            rospy.loginfo("Anchor_to_Release_Path Planning failed with only " + str(fraction) + "success after " + str(100) + " attempts.")

    def B_spline(self, degree, l, coeff, knot, dense, points):
        '''
        degree: 阶数
        l: l = n - k = point_num - k + 1
        coeff: 控制点坐标,list
        knot: 节点组,list
        dense: 分辨率，每段点数
        points: 轨迹点坐标,list
        '''
        u = 0
        point_num = 0
        i = degree
        while i <= l + degree:
            if knot[i+1] > knot[i]:
                for p in range(dense):
                    u = knot[i] + p * (knot[i + 1] - knot[i]) / dense
                    points[point_num] = self.deboor(degree, coeff, knot, u, i, l)
                    point_num += 1
            i += 1
        # return points # 可能不需要返回值

    def deboor(self, degree, coeff, knot, u, i, l):
        '''
        degree: 阶数
        coeff: 控制点坐标,list
        knot: 节点组,list
        u 和 i: 主要是传参
        '''
        coeffa = [None] * (degree + 1)
        j = i - degree
        while j <= i:
            coeffa[j] = coeff[j]
            j += 1

        k = 1
        while k <= degree:
            j = i

            while j >= i - degree + k:
                t1 = (knot[j + degree - k + 1] - u) / (knot[j + degree - l + 1] - knot[j])
                t2 = 1.0 - t1
                coeffa[j] = t1 * coeffa[j - 1] + t2 * coeffa[j]
                j -= 1

            k += 1
        return coeffa[i]

    def middle_ctrl_point(self, start_pose, target_pose):
        middle_point_X = abs(start_pose.position.x - target_pose.linear.x) / 2
        middle_point_Y = abs(start_pose.position.y - target_pose.linear.y) / 2
        theta = math.atan(middle_point_Y / middle_point_X)
        cos_theta = math.cos(theta)
        sin_theta = math.sin(theta)
        print(middle_point_X, middle_point_Y)
        print(theta, cos_theta, sin_theta)
        middle_ctrl_point_X = start_pose.position.x * cos_theta
        middle_ctrl_point_Y = start_pose.position.x * sin_theta
        return middle_ctrl_point_X, middle_ctrl_point_Y

    def setColor(self, name, r, g, b, a=0.9):
        color = ObjectColor()
        color.id = name
        color.color.r = r
        color.color.g = g
        color.color.b = b
        color.color.a = a
        self.colors[name] = color

    def sendColors(self):
        p = PlanningScene()
        p.is_diff = True
        for color in self.colors.values():
            p.object_colors.append(color)
        self.scene_pub.publish(p)

if __name__ == "__main__":
    try:
        MoveItCartesianDemo()
    except rospy.ROSInterruptException:
        pass


import pygame
from pygame import Color, font

pygame.font.init()

BACKGROUND_COLOR = Color(30, 30, 30)
GAME_FONT = font.SysFont("Arial", 20, bold=True)
SCREEN_CAPTION = "Happy This Is the Last Assignment"
SCREEN_ICON = r'../misc/pokeball.png'
LINE_COLOR = Color(255, 255, 255)
CIRCLE_COLOR = Color(128, 216, 255)
TEXT_COLOR = Color(222, 22, 22)
BUTTON_COLOR = Color(255, 255, 255)


from __future__ import print_function

import math
import os

import carla
from srunner.challenge.autoagents.autonomous_agent import Track
from srunner.challenge.envs.scene_layout_sensors import SceneLayoutReader, ObjectFinder
from srunner.challenge.envs.sensor_interface import CallBack, CANBusSensor, HDMapReader
from srunner.scenariomanager.carla_data_provider import CarlaDataProvider

MAX_ALLOWED_RADIUS_SENSOR = 5.0

class SensorConfigurationInvalid(Exception):

    """Base class for other exceptions"""

    def __init__(self, message):
        print(message)
        super(SensorConfigurationInvalid, self).__init__()

class AgentWrapper(object):

    """
    Wrapper for autonomous agents required for tracking and checking of used sensors
    """

    _agent = None
    _sensors_list = []
    _challenge_mode = False

    def __init__(self, agent, challenge_mode):
        """
        Set the autonomous agent
        """
        self._agent = agent
        self._challenge_mode = challenge_mode

    def __call__(self):
        """
        Pass the call directly to the agent
        """
        return self._agent()

    def setup_sensors(self, vehicle, debug_mode=False):
        """
        Create the sensors defined by the user and attach them to the ego-vehicle
        :param vehicle: ego vehicle
        :return:
        """
        bp_library = CarlaDataProvider.get_world().get_blueprint_library()
        for sensor_spec in self._agent.sensors():
            # These are the pseudosensors (not spawned)
            if sensor_spec['type'].startswith('sensor.scene_layout'):
                # Static sensor that gives you the entire information from the world (Just runs once)
                sensor = SceneLayoutReader(CarlaDataProvider.get_world())
            elif sensor_spec['type'].startswith('sensor.object_finder'):
                # This sensor returns the position of the dynamic objects in the scene.
                sensor = ObjectFinder(CarlaDataProvider.get_world(), sensor_spec['reading_frequency'])
            elif sensor_spec['type'].startswith('sensor.can_bus'):
                # The speedometer pseudo sensor is created directly here
                sensor = CANBusSensor(vehicle, sensor_spec['reading_frequency'])
            elif sensor_spec['type'].startswith('sensor.hd_map'):
                # The HDMap pseudo sensor is created directly here
                sensor = HDMapReader(vehicle, sensor_spec['reading_frequency'])
            # These are the sensors spawned on the carla world
            else:
                bp = bp_library.find(str(sensor_spec['type']))
                if sensor_spec['type'].startswith('sensor.camera'):
                    bp.set_attribute('image_size_x', str(sensor_spec['width']))
                    bp.set_attribute('image_size_y', str(sensor_spec['height']))
                    bp.set_attribute('fov', str(sensor_spec['fov']))
                    sensor_location = carla.Location(x=sensor_spec['x'], y=sensor_spec['y'],
                                                     z=sensor_spec['z'])
                    sensor_rotation = carla.Rotation(pitch=sensor_spec['pitch'],
                                                     roll=sensor_spec['roll'],
                                                     yaw=sensor_spec['yaw'])
                elif sensor_spec['type'].startswith('sensor.lidar'):
                    bp.set_attribute('range', str(sensor_spec['range']))
                    bp.set_attribute('rotation_frequency', str(sensor_spec['rotation_frequency']))
                    bp.set_attribute('channels', str(sensor_spec['channels']))
                    bp.set_attribute('upper_fov', str(sensor_spec['upper_fov']))
                    bp.set_attribute('lower_fov', str(sensor_spec['lower_fov']))
                    bp.set_attribute('points_per_second', str(sensor_spec['points_per_second']))
                    sensor_location = carla.Location(x=sensor_spec['x'], y=sensor_spec['y'],
                                                     z=sensor_spec['z'])
                    sensor_rotation = carla.Rotation(pitch=sensor_spec['pitch'],
                                                     roll=sensor_spec['roll'],
                                                     yaw=sensor_spec['yaw'])
                elif sensor_spec['type'].startswith('sensor.other.gnss'):
                    sensor_location = carla.Location(x=sensor_spec['x'], y=sensor_spec['y'],
                                                     z=sensor_spec['z'])
                    sensor_rotation = carla.Rotation()

                # create sensor
                sensor_transform = carla.Transform(sensor_location, sensor_rotation)
                sensor = CarlaDataProvider.get_world().spawn_actor(bp, sensor_transform, vehicle)
            # setup callback
            sensor.listen(CallBack(sensor_spec['id'], sensor, self._agent.sensor_interface))
            self._sensors_list.append(sensor)

        self._validate_sensor_configuration()

        while not self._agent.all_sensors_ready():
            if debug_mode:
                print(" waiting for one data reading from sensors...")
            CarlaDataProvider.perform_carla_tick()

    def _validate_sensor_configuration(self):
        """
        Ensure that the sensor configuration is valid, in case the challenge mode is used
        Returns true on valid configuration, false otherwise
        """

        if not self._challenge_mode:
            return

        phase_codename = os.getenv('CHALLENGE_PHASE_CODENAME', 'dev_track_3')
        track = int(phase_codename.split("_")[2])
        phase = phase_codename.split("_")[0]

        if phase != 'debug' and Track(track) != self._agent.track:
            raise SensorConfigurationInvalid("You are submitting to the wrong track [{}]!".format(Track(track)))

        for sensor in self._agent.sensors():
            if self._agent.track == Track.ALL_SENSORS:
                if sensor['type'].startswith('sensor.scene_layout') or sensor['type'].startswith(
                        'sensor.object_finder') or sensor['type'].startswith('sensor.hd_map'):
                    raise SensorConfigurationInvalid("Illegal sensor used for Track [{}]!".format(self._agent.track))

            elif self._agent.track == Track.CAMERAS:
                if not (sensor['type'].startswith('sensor.camera.rgb') or sensor['type'].startswith(
                        'sensor.other.gnss') or sensor['type'].startswith('sensor.can_bus')):
                    raise SensorConfigurationInvalid("Illegal sensor used for Track [{}]!".format(self._agent.track))

            elif self._agent.track == Track.ALL_SENSORS_HDMAP_WAYPOINTS:
                if (sensor['type'].startswith('sensor.scene_layout') or
                        sensor['type'].startswith('sensor.object_finder')):
                    raise SensorConfigurationInvalid("Illegal sensor used for Track [{}]!".format(self._agent.track))
            else:
                if not (sensor['type'].startswith('sensor.scene_layout') or sensor['type'].startswith(
                        'sensor.object_finder') or sensor['type'].startswith('sensor.other.gnss')
                        or sensor['type'].startswith('sensor.can_bus')):
                    raise SensorConfigurationInvalid("Illegal sensor used for Track [{}]!".format(self._agent.track))

            # let's check the extrinsics of the sensor
            if 'x' in sensor and 'y' in sensor and 'z' in sensor:
                if math.sqrt(sensor['x']**2 + sensor['y']**2 + sensor['z']**2) > MAX_ALLOWED_RADIUS_SENSOR:
                    raise SensorConfigurationInvalid(
                        "Illegal sensor extrinsics used for Track [{}]!".format(self._agent.track))

    def cleanup(self):
        """
        Remove and destroy all sensors
        """
        for i, _ in enumerate(self._sensors_list):
            if self._sensors_list[i] is not None:
                self._sensors_list[i].stop()
                self._sensors_list[i].destroy()
                self._sensors_list[i] = None
        self._sensors_list = []


import asyncio
import asyncpgsa
from sqlalchemy import (
    MetaData, Table, Column, ForeignKey,
    Integer, String, Date, Boolean
)

meta = MetaData()

users = Table(              # Table of users Data
    'users', meta,
    Column('id', Integer, primary_key=True),
    Column('login', String(64), nullable=False),
    Column('token', String(32), nullable=False)
)

members = Table(            # Table of chat's members Data
    'members', meta,
    Column('chat_id', Integer,
        ForeignKey('chats.id',  ondelete='CASCADE')),
    Column('user_id', Integer,
        ForeignKey('users.id',  ondelete='CASCADE')),
    Column('permit', Boolean) #
)

chats = Table(              # Table of chats Data
    'chats', meta,
    Column('id', Integer, primary_key=True),
    Column('name', String(128), nullable=False),
    Column('isOpen', Boolean, nullable=False),
    Column('owner_id', Integer,
        ForeignKey('users.id', ondelete='CASCADE'))
)

messages = Table(           # Table of messages Data
    'messages', meta,
    Column('id', Integer, primary_key=True),
    Column('text', String(256), nullable=False),
    Column('isEdited', Boolean, nullable=False),
    Column('owner_id', Integer,
        ForeignKey('users.id', ondelete='CASCADE')),
    Column('chat_id', Integer,
        ForeignKey('chats.id', ondelete='CASCADE'))
)

async def init_pg(app):
    "At start application "
    conf = app['config']['database_uri']
    app['db'] = await asyncpgsa.create_pool(dsn=conf)

async def close_pg(app):
    " At close application "
    await app['db'].close()


import scipy.misc
import numpy as np
import torchvision.transforms as transforms
from PIL import Image
import torch
from torch.utils.data import Dataset
import glob

class SegmentationTransform(object):
    def __init__(self, train_trainsforms=True, num_classes=3):
        self.train_trainsforms = train_trainsforms
        self.to_tensor = transforms.ToTensor()
        if train_trainsforms:
            self.resize = transforms.Resize(size=(286, 286))
        else:
            self.resize = transforms.Resize(size=(256, 256))
        self.num_classes = num_classes

    def __call__(self, image, segmentation):

        if self.train_trainsforms:
            image = self.resize(transforms.transforms.ToPILImage()(image))
            segmentation = self.resize(transforms.transforms.ToPILImage()(segmentation))

            # mirroring
            if np.random.random() < 0.5:
                image = image.transpose(Image.FLIP_LEFT_RIGHT)
                segmentation = segmentation.transpose(Image.FLIP_LEFT_RIGHT)

            # random crop
            x_offset = np.random.randint(0, 21)
            y_offset = np.random.randint(0, 21)

            image = image.crop((x_offset, y_offset, x_offset + 256, y_offset + 256))
            segmentation = segmentation.crop((x_offset, y_offset, x_offset + 256, y_offset + 256))

        else:
            image = self.resize(transforms.transforms.ToPILImage()(image))
            segmentation = self.resize(transforms.transforms.ToPILImage()(segmentation))

        image_tensor, segmentation_tensor = self.to_tensor(image), self.to_tensor(segmentation)
        image_tensor = transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))(image_tensor)
        segmentation_tensor = transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))(segmentation_tensor)

        return image_tensor, segmentation_tensor

class SegmentationDataset(Dataset):
    def __init__(self, path_to_datafolder='./datasets/facades/train/', transforms=None):
        if transforms:
            self.transforms = transforms
        else:
            self.transforms = None

        self.mixed_images_filenames = sorted(glob.glob('{}*.jpg'.format(path_to_datafolder)))

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

    def __getitem__(self, idx):
        mixed_image = scipy.misc.imread(self.mixed_images_filenames[idx])
        size = mixed_image.shape[0]
        image        = mixed_image[:, :size]
        segmentation = mixed_image[:, size:]

        if self.transforms:
            image, segmentation = self.transforms(image, segmentation)
        return image, segmentation


# -*- coding: utf-8 -*-
"""
Created on Wed Aug  7 10:11:23 2019

@author: Victor Zuanazzi
"""

class Rental:
    def __init__(self, start_date, vehicle):
        """Class to keep the state of the rental"""
        self.start_date = start_date
        self.vehicle = vehicle
        self.returned = False

class Inventory:
    """Class to keep the inventory"""
    def __init__(self):

        self.transport_types = {'bike', 'car', 'motorbike', 'boat'}
        self.price = {'bike': 1, 'car': 100, 'motorbike': 10, 'boat': 1000}
        self._total = {'bike': 10, 'car': 10, 'motorbike': 10, 'boat': 10}
        self.num_available = self._total.copy()
        self.rentals= {}
        self.all_rents_in_history = 0

    def list_of_vehicles(self):
        """returns the list of vehicles"""
        return self.transport_types

    def give_info(self, vehicle):
        """give the information regarding one specific transport type.
        This logic does not scale for an arbitrary number of information.
        inptu:
            vehicle: string, one of the transport_types
        return: int tuple, (price, num_available)"""
        return self.price[vehicle], self.num_available[vehicle]

    def rent_a_vehicle(self, vehicle, start_date):
        """process the rent of a vehicle.
        input:
            vehicle: string, one of the transport_types
            start_date: int, a number between 1 and 365 making the day of the
                year. (that is only done to simplify the logic)
        output:
            bool, False if the rent is not possible.
            integer, protoco_number
        """

        if self.num_available[vehicle] == 0:
            print(f"There is no {vehicle} of this type left")
            return False

        self.num_available[vehicle] -= 1
        self.all_rents_in_history +=1
        protocol_number = self.all_rents_in_history

        self.rentals[protocol_number] = Rental(int(start_date), vehicle)

        return protocol_number

    def pay_rental(self, protocol_number, end_date):
        """defines the amount to be paid and process the return of the vehicle.
        input:
            protocol_number: int (or numeric string), containing the protocol
                number of the rental
            end_date: int, the return date, assumed to be higher than the start
                date. Number between 0 and 356."""

        protocol_number = int(protocol_number)
        end_date = int(end_date)

        if protocol_number not in self.rentals:
            print("This protocol number does not exist")
            return False

        if self.rentals[protocol_number].returned:
            print("This vehicle was already returned")
            return False
        else:
            self.rentals[protocol_number].returned = True

        vehicle = self.rentals[protocol_number].vehicle
        start_date = self.rentals[protocol_number].start_date

        to_pay = (end_date - start_date) *  self.price[vehicle]

        self.num_available[vehicle] += 1
        return to_pay

def main():

    inventory = Inventory()

    actions = {"help",
               "list of all vehicles",
               "info about specific vehicle",
               "rent a vehicle",
               "pay rental costs",
               "exit"}

    act_help = {"help": "provides information about all options",
               "list of all vehicles": "returns the list of vehicles",
               "info about specific vehicle": "gives the information of a specific transport type",
               "rent a vehicle": "rent a vehicle of choosing",
               "pay rental costs": "pays for the rental of the vehicle",
               "exit": "terminates the program"}

    while True:
        action = input(f"Select one action: {actions} \n")

        if action not in actions:
            print("The input does is not a supported action.")
            continue

        if action == "help":
            print("You have the following options:")
            for key in act_help:
                print(f"\t {key}: {act_help[key]}")

        if action == 'list of all vehicles':
            print(f"{inventory.list_of_vehicles()}")
            continue

        if action == 'info about specific vehicle':
            vehicle = input("Which vehicle do you want to know more about? \n")
            info = inventory.give_info(vehicle)
            print(f"{vehicle}: \n\t price: {info[0]}, \n\t available units: {info[1]}")
            continue

        if action == "rent a vehicle":
            vehicle = input(f"Which vehicle do you want to rent? {inventory.list_of_vehicles()}\n")
            start_date = input("When Would you like to rent it? " +
                               "Please, give a number between 0 and 365" +
                               " correspondent to the day of the year. \n")
            protocol_number = inventory.rent_a_vehicle(vehicle, start_date)
            if protocol_number > 0:
                print(f"You successfuly rented the {vehicle} at {start_date}")
                print(f"Your protocol number is: {protocol_number}. " +
                      "You will need this number in order to return the vehicle.")

        if action == "pay rental costs":
            protocol_number = input(f"Please provide your protocol number. \n")
            end_date = input(f"Please, provide the date the rent ends. \n" +
                             "Please, give a number between 0 and 365" +
                             " correspondent to the day of the year. \n")

            to_pay = inventory.pay_rental(protocol_number, end_date)

            if to_pay > 0:
                print(f"Your rental bill is of EUR {to_pay}.")

        if action == "exit":
            print("This session will be terminated")
            break

if __name__ == '__main__':
    main()


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

from tools.common import now, sndErr
from tools.first import err, snd, BASE_DIR
from tools.DC import DC, well, toWell  # , profiles

# from appSchedule.models import Hours

import json
import zlib, base64
from datetime import datetime
import os
import sqlite3 as sqldb
import time
from contextlib import suppress
import threading
from cgi import log

# *** *** ***

@sndErr
def createDB(dba, *addPath):
    cat = 'createDB'
    dbAlias = tableName(dba)
    # if dbAlias not in profiles:
        # err(f'''Invalid dbAlias: "{dbAlias or '-empty-'}"''', cat=cat)
        # return

    path = os.path.join(BASE_DIR, 'DB', *addPath)
    os.makedirs(path, exist_ok=True)
    dbFile = os.path.join(path, f'{dbAlias}.rsf')

    con = sqldb.connect(database=dbFile, timeout=10.0)
    con.create_collation("casei", sqlite_collation_casei)
    con.create_function("sqLike", 2, sqlite_function_sqLike)

    sql = """CREATE TABLE "LIFE" (
"id" integer NOT NULL PRIMARY KEY AUTOINCREMENT,
"unid" char(32) NOT NULL,
"xfld" text NOT NULL,
"xmdf" timestamp NULL);

CREATE INDEX "LIFE_unid" ON "LIFE" ("unid");
CREATE INDEX "LIFE_xmdf" ON "LIFE" ("xmdf");
"""
    cur = con.cursor()

    for s in sql.split(';\n'):
        s and cur.execute(s)

    with suppress(Exception):
        cur.close()
        con.commit()
        con.close()

    snd(f'Created database "{dbFile}"', cat=cat)
    return True

# *** *** ***

def tableName(dbAlias):
    return dbAlias.replace('.', '/').upper()

def sqlite_collation_casei(x, y):
    _x = x.lower()
    _y = y.lower()
    return 0 if _x == _y else -1 if _x < _y else 1

def sqlite_function_sqLike(s, patt):
    # TODO: process wildcards
    # return fnmatch.fnmatch(s, patt.replace('%', '*').replace('_', '?'))

    _patt = patt.lower().replace('%', '')
    _s = s.lower()
    if patt[0] == '%' and patt[-1] == '%':
        return _patt in _s
    elif patt[0] == '%':
        return _s.endswith(_patt)
    elif patt[-1] == '%':
        return _s.startswith(_patt)
    else:
        return _s == _patt

# *** *** ***

def hasDB(dbAlias):
    dbFile = os.path.join(BASE_DIR, 'DB', f'{tableName(dbAlias).upper()}.rsf')
    return os.path.isfile(dbFile) and os.stat(dbFile).st_size

# *** *** ***

def connectToSrv(dba):
    dbAlias = tableName(dba)
    # if dbAlias not in profiles:
        # err(f'''Invalid dbAlias: "{dbAlias or '-empty-'}"''', cat='connectToSrv')
        # return

    dbFile = os.path.join(BASE_DIR, 'DB', f'{dbAlias}.rsf')

    if os.path.isfile(dbFile) and os.stat(dbFile).st_size:
        if lockupConnect(dbAlias):
            con = sqldb.connect(database=dbFile, timeout=10.0)
            con.create_collation("casei", sqlite_collation_casei)
            con.create_function("sqLike", 2, sqlite_function_sqLike)
            return con
        else:
            err(f'SQLITE: DB "{dbFile}" is locked', cat='connectToSrv')
            return
    else:
        a = 1 / 0
        err(f'SQLITE: DB "{dbFile}" not found', cat='connectToSrv')

# *** *** ***

lockedCon = {}

def lockupConnect(dbAlias):
    if dbAlias not in lockedCon:
        lockedCon[dbAlias] = threading.Lock()
        lockedCon[dbAlias].acquire()
        return True

    for n in range(100):
        try:
            if dbAlias not in lockedCon or lockedCon[dbAlias].acquire(False):
                return True
        except:
            return True
        time.sleep(0.1)

def unlockCon(con, dbAlias):
    with suppress(Exception):
        con.close()
    try:
        lockedCon[tableName(dbAlias)].release()
        del lockedCon[tableName(dbAlias)]
    except:
        pass

def unlockAll():
    global lockedCon
    for l in lockedCon.items():
        l.release()
    lockedCon = {}

# *** *** ***

def docFromDB(dcUK):
    """
    возвращает документ по unid. unid - текстовый hex
    если unid пустой возвращает по знчению ключей
    """

    if not dcUK.unid:
        keys = {k.partition('_')[2]: v for k, v in dcUK.items() if k.startswith('KEY_')}
        if keys:
            for doc in allFromDB(dcUK.dbAlias):
                if dcUK.viewKey and dcUK.viewKey != doc.key:
                    continue
                if all(doc[k] == v for k, v in keys.items()):
                    dcUK.doc = DC(doc)
                    return True
        return

    # ***

    try:
        unid = dcUK.unid.replace('-', '')
        con = connectToSrv(dcUK.dbAlias)
        if not con:
            return

        if dcUK.xmdf:
            xmdf = f"xmdf='{dcUK.xmdf}'"
        else:
            xmdf = 'xmdf IS NULL'

        sql = f"SELECT xfld FROM LIFE WHERE (unid='{unid}') AND ({xmdf});"

        cur = con.cursor()
        cursor = cur.execute(sql)
        if not cursor:
            cur and cur.close()
            unlockCon(con, dcUK.dbAlias)
            return

        xfld = None
        for row in cursor:
            xfld = row[0] or '{}'

        cur.close()
        unlockCon(con, dcUK.dbAlias)

        if not xfld:
            return

        fields = json.loads(xfld)
        if 'ROOT' in fields:
            root, _, styles = fields['ROOT'].partition('_¤_')
            fields['ROOT'] = zlib.decompress(base64.b64decode(root)).decode()
            styles = styles and zlib.decompress(base64.b64decode(styles)).decode()
            styles = (styles + ('_¤_' * 9)).split('_¤_')
            for i in range(9):
                if styles[i]:
                    fields[f'ROOT_STYLES_{(i+1)*1000}'] = styles[i]
        dcUK.doc = DC(fields)
        return True

    except Exception as ex:
        err(f'dbAlias={dcUK.dbAlias}&unid={unid}\n{ex}', cat='Book.py.docFromDB')

# *** *** ***

def docSaveDB(dcUK):
    '''
    dcUK.doc - документ, который нужно записать
    oldDoc - запись в базе с существующим документом, котрую нужно перевести в истоию.
    '''
    old = DC({'dbAlias': dcUK.dbAlias, 'unid': dcUK.unid})
    oldDoc = docFromDB(old)
    unid = dcUK.unid.replace('-', '')
    con = connectToSrv(dcUK.dbAlias)
    if not con:
        return

    if oldDoc:  # есть такой, - переводим в историю
        dcUK.doc.MODIFIED = now('-')
        dcUK.doc.MODIFIER = dcUK.userName
        sql = [f"UPDATE LIFE SET xmdf='{datetime.now()}' WHERE (unid='{unid}') AND (xmdf IS NULL);"]
    else:
        sql = []
        dcUK.doc.CREATED = now('-')
        dcUK.doc.CREATOR = dcUK.userName

    # сохраняем новый док(или новую версию)
    if dcUK.doc.root:
        r = dcUK.doc.root

        s = ''
        for i in range(1000, 9001, 1000):
            s += dcUK.doc[f'ROOT_STYLES_{i}'] + '_¤_'

        fs = len(r) + len(s)
        r = zlib.compress(r.encode(), 9)
        r = str(base64.b64encode(r), 'ascii')
        s = zlib.compress(s.encode(), 9)
        s = str(base64.b64encode(s), 'ascii')

        dcUK.doc.root = f'{r}_¤_{s}'

        le64 = len(r) + len(s)
        le = f'fullsize:{fs} => zip => b64:{le64}'
        proc = int(100 * (fs - le64) / (fs or le64))
        dcUK.doc.pageSize = le
        snd(f'{le} (doc {dcUK.doc.docNo} in "{dcUK.dbAlias}") press:{proc}%', cat='ROOT-size')

    xfi = json.dumps(dcUK.doc._KV_, ensure_ascii=False)
    sql.append(f"INSERT INTO LIFE (unid, xfld, xmdf) VALUES ('{unid}', '{xfi}', NULL);")

    cur = con.cursor()

    for s in sql:
        try:
            cur.execute(s)
        except Exception as ex:
            err(f'can not execute SQL statement. Exception: {ex}, SQL: {s}', cat='docSaveDB')
            with suppress(Exception):
                cur and cur.close()
                con.rollback()
                unlockCon(con, dcUK.dbAlias)
            return

    try:
        cur.close()
        con.commit()
        unlockCon(con, dcUK.dbAlias)
        return True
    except Exception as ex:
        unlockCon(con, dcUK.dbAlias)
        err(f'{ex}', cat='docSaveDB-commit')

# *** *** ***

# @sndErr
def allFromDB(dbAlias, dir_=None):
    """
    возвращает все документы из таблицы
    """

    con = connectToSrv(dbAlias)
    if not con:
        return []

    sql = 'SELECT xfld FROM LIFE WHERE (xmdf IS NULL);'

    cur = con.cursor()
    cursor = cur.execute(sql) or []

    docs = []
    for row in cursor:
        fields = json.loads(row[0])
        if dir_ and dir_ != 'ALL' and fields.get('DIR') != dir_:
            continue

        if 'ROOT' in fields:
            root, _, styles = fields['ROOT'].partition('_¤_')
            try:
                fields['ROOT'] = zlib.decompress(base64.b64decode(root)).decode()
            except Exception as ex:
                err(f'{ex}', cat='ROO-decompress')
                fields['ROOT'] = '{"boxIndex": 100}'
            try:
                fields['ROOT_STYLES'] = styles and zlib.decompress(base64.b64decode(styles)).decode()
                styles = styles and zlib.decompress(base64.b64decode(styles)).decode()
                styles = (styles + ('_¤_' * 9)).split('_¤_')
                for i in range(9):
                    if styles[i]:
                        fields[f'ROOT_STYLES_{(i+1)*1000}'] = styles[i]
            except Exception as ex:
                err(f'{ex}', cat='ROOT_STYLES-decompress')
                fields['ROOT_STYLES'] = ''

        docs.append(DC(fields))

    cur.close()
    unlockCon(con, dbAlias)

    return docs

# *** *** ***

def setDocNo(dbAlias):
    table = 'appAll_docno'
    docNoAlias = 'docno'
    con = connectToSrv(docNoAlias)
    if not con:
        return

    try:
        sql = f"SELECT docno FROM {table} WHERE dbalias='{dbAlias}';"
        cur = con.cursor()
        cursor = cur.execute(sql)
        n = 0
        if cursor:
            for row in cursor:
                n = row[0]
        else:
            unlockCon(con, docNoAlias)
            err(f'for {dbAlias} cur.execute == None', cat='setDocNo')
            return

        if n:
            sql = f"UPDATE {table} SET docno={n+1} WHERE dbalias='{dbAlias}';"
        else:
            sql = f"INSERT INTO {table} (dbalias, docno) VALUES ('{dbAlias}', 1);"

        cur.execute(sql)
        cur.close()
        con.commit()
        unlockCon(con, docNoAlias)
        return str(n + 1)

    except Exception as ex:
        err(f'{ex}', cat='setDocNo')
        unlockCon(con, docNoAlias)

# *** *** ***

def fff(doc, fn='FILES'):  # fields for files
    return [ k for k, v in doc.items()
                if k.startswith(fn) and ('_' in k) and v.count('|') == 5
        ]

def filines(doc, fn='FILES'):
        return [f'{doc.F(k)}|{k}'.split('|') for k in fff(doc, fn)]

# *** *** **

def histFromDB(dcUK):
    """
    возвращает все времена переведов в историю
    """

    con = connectToSrv(dcUK.dbAlias)
    if not con:
        return []
    unid = dcUK.unid.replace('-', '')

    sql = f"SELECT xmdf, xfld FROM LIFE WHERE (unid == '{unid}') AND (xmdf IS NOT NULL);"
#    sql = f"SELECT xmdf, xfld, unid FROM LIFE WHERE (xmdf IS NOT NULL);"

    cur = con.cursor()
    cursor = cur.execute(sql) or []

    hist = []

    for row in cursor:
        xfld = row[1] or '{}'

        fields = json.loads(xfld)
        ls = fields.get('MODIFIER', fields.get('CREATOR', '')).partition(' ')
        mdf = f'{ls[0]} {ls[2] and ls[2][0]}'
        s1, _, size2 = fields.get('PAGESIZE', '').rpartition(':')
        size1 = s1.partition(':')[2].partition(' ')[0]
        hist.append(f"{row[0]} ({mdf}, size:{size1}->{size2}) {fields.get('NOTES', '')}")

    cur.close()
    unlockCon(con, dcUK.dbAlias)

    hist = sorted(hist)
    for i, h in enumerate(hist):
        hist[i] = f'{i+1:03}__{h}'

    return json.dumps(hist)

"""
def docsByCats(key, dcUK, param):
    '''
    param - dict
    cat: {},

    '''
    docs = well('docsByCats', key) or {}
    if docs:
        return docs

    ls = allFromDB(dcUK.dbAlias, dcUK.dir_) or []

    self.subCats = {}
    for d in ls:
        self.DBC['Все|'].append(d)
        for cat, fName in self.dcVP.cats.items():
            if fName and type(fName) == str:
                if fName[0] == '=': # formula
                    fi = eval(fName[1:])
                    print('*******', fi)
                else:
                    fi = d.F(fName)
                if fi:
                    if fi == True:
                        fi = ''
                    k = f'{cat}|{fi}'
                    if k in self.DBC:
                        self.DBC[k].append(d)
                    else:
                        self.DBC[k] = [d]
                    if cat not in self.subCats:
                        self.subCats[cat] = []
                    if fi and fi not in self.subCats[cat]:
                        self.subCats[cat].append(fi)

    for c in self.DBC:
        if sort == 'docNo':
            self.DBC[c] = sorted(self.DBC[c], key=lambda d: d.F(sort).rjust(6), reverse=reverse)
        else:
            self.DBC[c] = sorted(self.DBC[c], key=lambda d: d.F(sort), reverse=reverse)
    toWell(True, keyWell)

    return self.DBC.get(c_s, [])

"""

'''
dbLocks = {} # { dbAlias: [threading.Lock(), threading.get_ident()] }

def dbWait(dba):
    iniTime = time()
    while dba in dbLocks and dbLocks[dba][1] and dbLocks[dba][1] != threading.get_ident():
        sleep(0.1 + 0.05 * random())
#         print('dbWait %r, thread_id = %r, time = %r' % (dba, dbLocks[dba][1], time() - iniTime))
        if time() - iniTime > 60:
            return False
    return True

def dbIsLocked(dba):
    return dbLocks.get(dba, [0, 0])[1]

'''

if __name__ == '__main__':
    createDB('rf.qq/ogg')


import json

def eval_content(content):
    for item in content:
        if isinstance(content[item], dict):
            content[item] = eval_content(content[item])
        elif isinstance(content[item], list):
            temp_list =[];
            for element in content[item]:
                temp_list.append("Get the value for " + element.replace("//","->"))
            content[item]=temp_list
        else:
            content[item] = "get the value of this"
    return content

def parse_content(content):
    json_contents = json.loads(content)

    mapped_data = eval_content(json_contents["mappings"])
    print(mapped_data)

try:
    f= open('payload_briefbox_test.json')
except FileNotFoundError:
    print('File doesn\'t exit')
except Exception:
    print('Undefined variable...')
else:
    content=f.read()
    parse_content(content)
finally:
    print("Closing the file")
    try:
        f.close()
    except NameError:
        print("No need to close the file...")


#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time       : 2020-05-10
# @Author     : Joey Jiang
# @File       : base8_8_1.py
# @SOftware   : Visual Studio Code
# @Description: python外部源文件处理（二）

from selenium import webdriver
import time
from openpyxl import load_workbook

class SeleniumPython:
    def __init__(self):
        self.wb=load_workbook("selenium.xlsx")
        self.sheet=self.wb["Sheet1"]
    def go_to_baidu(self):
        driver=webdriver.Chrome()
        driver.get("https://www.baidu.com/")
        driver.find_element_by_id("kw").send_keys(self.sheet["A2"].value)
        driver.find_element_by_id("su").click()
        time.sleep(3)
        driver.quit()
SeleniumPython().go_to_baidu()


"""
Generating Figure 3
"""
import os

import matplotlib
import matplotlib.pyplot as plt
import matplotlib.transforms as mtransforms
import pandas as pd
import seaborn as sns
from loguru import logger
from statannotations.Annotator import Annotator

from src.utils import plot_interpolated_ecdf, scatbar

logger.info('Import OK')

# =================Set paths=================
input_folder = 'results/3_homogenate_SR/'
output_folder = 'results/figures/'

if not os.path.exists(output_folder):
    os.makedirs(output_folder)

# =======Set default plotting parameters=======
cm = 1/2.54
font = {'family': 'arial',
        'weight': 'normal',
        'size': 8,
        }
matplotlib.rc('font', **font)
plt.rcParams['svg.fonttype'] = 'none'
plt.rcParams['axes.titlesize'] = 8
plt.rcParams['figure.dpi'] = 300

palette = {
    '9': '#345995',
    '159': '#345995',
    '28': '#345995',
    '13': '#F03A47',
    '55': '#F03A47',
    '246': '#F03A47',
    'BSA': '#A9A9A9',
    'AD Mix': '#A9A9A9',
    'CRL': '#345995',
    'AD': '#F03A47',
    'BSA': '#A9A9A9',
    'high': '#F03A47',
    'low': '#F03A47',
}

# =================Organise data=================
for_plotting = pd.read_csv(f'{input_folder}for_plotting.csv')

proportions = pd.read_csv(f'{input_folder}proportions.csv')
proportions.drop([col for col in proportions.columns if 'Unnamed' in col], axis=1, inplace=True)
proportions['sample'] = proportions['sample'].astype(str)
proportion = {category: df.dropna(how='all', axis=1)
               for category, df in proportions.groupby('category')}

fil_proportion = pd.read_csv(f'{input_folder}fil_proportions.csv')
fil_proportion.drop(
    [col for col in fil_proportion.columns if 'Unnamed' in col], axis=1, inplace=True)
fil_proportion['sample'] = fil_proportion['sample'].astype(str)
fil_proportion = {category: df.dropna(how='all', axis=1)
                for category, df in fil_proportion.groupby('category')}

for_plotting_mean = pd.read_csv(f'{input_folder}for_plotting_mean.csv')

fitted_ecdfs = pd.read_csv(f'{input_folder}fitted_ecdfs.csv')
fitted_ecdfs.drop([col for col in fitted_ecdfs.columns if 'Unnamed' in col], axis=1, inplace=True)
fitted_ecdfs['sample'] = fitted_ecdfs['sample'].astype(str)
fitted_ecdfs = {category: df.dropna(how='all', axis=1)
                for category, df in fitted_ecdfs.groupby('category')}

for_plotting_fil_mean = pd.read_csv(f'{input_folder}for_plotting_fil_mean.csv')
p1byp2_for_plotting = pd.read_csv(
    f'{input_folder}p1byp2_for_plotting_all.csv')
p1byp2_for_plotting.drop(
    [col for col in p1byp2_for_plotting.columns if 'Unnamed' in col], axis=1, inplace=True)
p1byp2_for_plotting['sample'] = p1byp2_for_plotting['sample'].astype(str)
p1byp2_for_plotting = {category: df.dropna(how='all', axis=1) for category, df in p1byp2_for_plotting.groupby('category')}

# =================Plot figure=================

fig = plt.figure(figsize=(12.1 * cm, 4 * 6.1 * cm))
gs1 = fig.add_gridspec( nrows=8, ncols=4, wspace=0.95, hspace=1.5)
axA1 = fig.add_subplot(gs1[0:1, 0:1])
axA2 = fig.add_subplot(gs1[0:1, 1:2])
axA3 = fig.add_subplot(gs1[1:2, 0:1])
axA4 = fig.add_subplot(gs1[1:2, 1:2])
axA5 = fig.add_subplot(gs1[0:1, 2:3])
axA6 = fig.add_subplot(gs1[1:2, 2:3])
axA7 = fig.add_subplot(gs1[0:1, 3:4])
axA8 = fig.add_subplot(gs1[1:2, 3:4])

axB1 = fig.add_subplot(gs1[2:4, 0:1])
axB2 = fig.add_subplot(gs1[2:4, 1:2])
axB3 = fig.add_subplot(gs1[2:4, 2:3])
axB4 = fig.add_subplot(gs1[2:4, 3:4])

axC1 = fig.add_subplot(gs1[4:6, 0:2])
axC2 = fig.add_subplot(gs1[4:6, 2:4])

axD1 = fig.add_subplot(gs1[6:8, 0:1])
axD2 = fig.add_subplot(gs1[6:8, 1:2])
axD3 = fig.add_subplot(gs1[6:8, 2:3])
axD4 = fig.add_subplot(gs1[6:8, 3:4])

for ax, label in zip([axA1, axA5, axB1, axC1, axD1], ['A', 'B', 'C', 'D', 'E']):
    # label physical distance to the left and up:
    trans = mtransforms.ScaledTranslation(-30/72, -3/72, fig.dpi_scale_trans)
    ax.text(0.0, 1.0, label, transform=ax.transAxes + trans,
            fontsize=12, va='bottom', fontweight='bold')

# --------Panel A--------
axA1.axis('off')
axA2.axis('off')
axA3.axis('off')
axA4.axis('off')
axA5.axis('off')
axA6.axis('off')
axA7.axis('off')
axA8.axis('off')

# --------Panel B--------
scatbar(
    dataframe=for_plotting_mean, xcol='disease_state', ycol='smoothed_length', ax=axB1, xorder=['AD', 'CRL'],
    dotpalette=palette, barpalette=palette,
    pairs=[('AD', 'CRL')],
    )
axB1.set(title='Length', ylabel='Mean length [nm]', xlabel='')

scatbar(
    dataframe=for_plotting_mean, xcol='disease_state', ycol='scaled_perimeter', ax=axB2, xorder=['AD', 'CRL'],
    dotpalette=palette, barpalette=palette,
    pairs=[('AD', 'CRL')],
)
axB2.set(title='Perimeter', ylabel='Mean perimeter [nm]', xlabel='')

scatbar(
    dataframe=for_plotting_mean, xcol='disease_state', ycol='scaled_area', ax=axB3, xorder=['AD', 'CRL'],
    dotpalette=palette, barpalette=palette,
    pairs=[('AD', 'CRL')],
)
axB3.set(title='Area', ylabel='Mean area [x 10$^3$ nm$^2$]', xlabel='')

scatbar(
    dataframe=for_plotting_mean, xcol='disease_state', ycol='eccentricity', ax=axB4, xorder=['AD', 'CRL'],
    dotpalette=palette, barpalette=palette,
    pairs=[('AD', 'CRL')],
)
axB4.set(title='Eccentricity', ylabel='Mean eccentricity', xlabel='')

# --------Panel C--------

plot_interpolated_ecdf(
    fitted_ecdfs['smoothed_length'], ycol='smoothed_length', huecol='sample', palette=palette, ax=axC1, orientation='h')

plot_interpolated_ecdf(fitted_ecdfs['eccentricity'], ycol='eccentricity', huecol='sample', palette=palette, ax=axC2, orientation='h')

# --------Panel D--------

scatbar(
    dataframe=proportion['smoothed_length'], xcol='disease_state', ycol='high', ax=axD1, xorder=['AD', 'CRL'],
    dotpalette=palette, barpalette=palette,
    pairs=[('AD', 'CRL')],
)
axD1.set(title='Length\n(>250 nm)', ylabel='Long [%]', xlabel='')

scatbar(
    dataframe=proportion['scaled_perimeter'], xcol='disease_state', ycol='high', ax=axD2, xorder=['AD', 'CRL'],
    dotpalette=palette, barpalette=palette,
    pairs=[('AD', 'CRL')],
)
axD2.set(title='Perimeter\n(>550 nm)', ylabel='Long perimeter [%]', xlabel='')

scatbar(
    dataframe=proportion['scaled_area'], xcol='disease_state', ycol='high', ax=axD3, xorder=['AD', 'CRL'],
    dotpalette=palette, barpalette=palette,
    pairs=[('AD', 'CRL')],
)
axD3.set(title='Area\n(>15x10$^3$nm$^2$)', ylabel='Large [%]', xlabel='')

scatbar(
    dataframe=proportion['eccentricity'], xcol='disease_state', ycol='high', ax=axD4, xorder=['AD', 'CRL'],
    dotpalette=palette, barpalette=palette,
    pairs=[('AD', 'CRL')],
)
axD4.set(title='Eccentricity\n(>0.9)', ylabel='Fibrils [%]', xlabel='')

handles, labels = axC1.get_legend_handles_labels()
by_label = dict(zip(labels, handles))
simple_legend = {'AD': by_label['13'],
                 'CRL': by_label['9']}
for label, ax in zip(['Length [nm]', 'Eccentricity'], [axC1, axC2]):
    ax.legend(simple_legend.values(), simple_legend.keys(), frameon=False)
    ax.set_xlabel(label)
    ax.set_ylabel('Proportion')

for ax in fig.axes:
    ax.spines[['right', 'top']].set_visible(False)

#plt.tight_layout()
plt.savefig(f'{output_folder}Figure3_homogenate_SR.svg')
plt.show()


import subprocess as sp

x = [1e-1]
y = [1e-1]
z = [1,0]
for xIdx in x:
    for yIdx in y:
        for zIdx in z:
            sp.call("python NASVDPP.py --dataset yelp-91 --pretrain " + str(zIdx) + " --verbose 1 --batch_" "choice user --epochs 500 \
            --weight_size 10 --embed_size 10 --data_alpha 0 --regs [1e-1,1e-0,1e-1,1e-7,1e-2,1e-3] --alpha 0.5 --train_loss 0 \
            --beta 0 --num_neg 4 --lr 0.1 --activation 0 --algorithm 0", shell=True)

            # + " + str(zIdx) + "," + str(yIdx) + "," + str(xIdx)" +
            # 1r 0.03


#######################################
# --- Taille des points d'intérêts ---#
#######################################
# size = 2
# 4 : cellule au mètre
# 3 : cellule à la rue
# 2 : cellule au quartier
# 1 : cellule à la ville
# 0 : cellule à la région
# -1 : cellule au pays

######################################
# --- Nb de POI à vérifier par ID ---#
######################################
# nbPOI = 3
# 3: Vérification des 3 POI les plus fréquentés en terme de temps de présence.

################################
# --- Définition des heures ---#
################################
# Détection des POI -nuit, travail et weekend- durant les heures suivantes:
# night_start, night_end = 22, 6
# De 22h00 à 6h00
# work_start, work_end = 9, 16
# De 9h00 à 16h00
# weekend_start, weekend_end = 10, 18

import pandas as pd
import numpy as np

def main(df_anon, df_original, nb_orig_lines):
    #Global variables
    score = 0
    size = 2
    values = ['NIGHT', 'NIGHT','WORK', 'WEEKEND']
    df_orig = df_original.copy()
    df_anon = df_anon.copy()

    if(len(df_anon)!=0):

        df_orig['DateTime']= df_orig['DateTime'].astype('datetime64[ns]')
        df_orig['ID']= df_orig['ID'].astype('string')
        df_orig['lat']= df_orig['lat'].astype('float64')
        df_orig['lon']= df_orig['lon'].astype('float64')

        df_anon['DateTime']= df_anon['DateTime'].astype('datetime64[ns]')
        df_anon['ID']= df_anon['ID'].astype('string')
        df_anon['lat']= df_anon['lat'].astype('float64')
        df_anon['lon']= df_anon['lon'].astype('float64')
        #df_anon['ID']=df_orig['ID']
        df_anon['ID']= df_orig.loc[df_anon.index.intersection(df_orig.index),'ID']

        #Pre-treatment of original dataframe
        df_orig['lat']=df_orig['lat'].round(size)
        df_orig['lon']=df_orig['lon'].round(size)
        df_orig['Hour'] = df_orig.loc[:,'DateTime'].dt.hour
        df_orig['Day'] = df_orig.loc[:,'DateTime'].dt.day
        df_orig['Month'] = df_orig.loc[:,'DateTime'].dt.month
        df_orig['Week'] = df_orig.loc[:,'DateTime'].dt.isocalendar().week
        df_orig['DayOfTheWeek'] = df_orig.loc[:,'DateTime'].dt.dayofweek
        df_orig.sort_values(by=['ID', 'DateTime'], inplace=True)
        df_orig.reset_index(drop=True, inplace=True)
        df_orig['DatetimeIndex'] = np.select(conditions(df_orig), values, 'RegularTime')
        df_orig['time_spent']=0

        df_orig['Index_of_POI'] = df_orig['ID'] + '-' + df_orig['Day'].astype('string') + '-' + df_orig['Week'].astype('string') + '-' + df_orig['lat'].astype('string') + '-' + df_orig['lon'].astype('string') + '-' + df_orig['DatetimeIndex'].astype('string')
        df_orig['Index_of_POI_shifted_backward'] = df_orig['Index_of_POI'].shift(-1)
        df_orig['Index_of_POI_shifted_forward'] = df_orig['Index_of_POI'].shift(+1)
        df_orig.loc[0,'Index_of_POI_shifted_forward']='0'
        df_orig.loc[len(df_orig)-1,'Index_of_POI_shifted_backward']='0'
        df_orig['start_time'] = df_orig.loc[~(df_orig['Index_of_POI']==df_orig['Index_of_POI_shifted_forward']), 'DateTime']
        df_orig.fillna(method="ffill", inplace=True)
        df_orig['time_spent'] = (df_orig['DateTime'] - df_orig['start_time'])

        #Getting the POI
        df_orig2 = df_orig.loc[~(df_orig['Index_of_POI_shifted_backward']==df_orig['Index_of_POI']),['ID', 'lat', 'lon', 'Week', 'DatetimeIndex', 'time_spent']].groupby(by=['ID', 'lat', 'lon', 'Week', 'DatetimeIndex']).sum().reset_index()
        df_orig2 = df_orig2.sort_values(by=['ID', 'Week', 'time_spent',  'DatetimeIndex'], ascending=[True, True, False, False]).reset_index(drop=True)
        df_orig2 = df_orig2.groupby(by=['ID', 'Week', 'DatetimeIndex']).head(1).reset_index(drop=True)

        #Pre-treatment of anonymized dataframe

        df_anon['lat']=df_anon['lat'].round(size)
        df_anon['lon']=df_anon['lon'].round(size)
        df_anon['Hour'] = df_anon.loc[:,'DateTime'].dt.hour
        df_anon['Day'] = df_anon.loc[:,'DateTime'].dt.day
        df_anon['Month'] = df_anon.loc[:,'DateTime'].dt.month
        df_anon['Week'] = df_anon.loc[:,'DateTime'].dt.isocalendar().week
        df_anon['DayOfTheWeek'] = df_anon.loc[:,'DateTime'].dt.dayofweek
        df_anon.sort_values(by=['ID', 'DateTime'], inplace=True)
        df_anon.reset_index(drop=True, inplace=True)
        df_anon['DatetimeIndex'] = np.select(conditions(df_anon), values, 'RegularTime')
        df_anon['time_spent']=0

        df_anon['Index_of_POI'] = df_anon['ID'] + '-' + df_anon['Day'].astype('string') + '-' + df_anon['Week'].astype('string') + '-' + df_anon['lat'].astype('string') + '-' + df_anon['lon'].astype('string') + '-' + df_anon['DatetimeIndex'].astype('string')
        df_anon['Index_of_POI_shifted_backward'] = df_anon['Index_of_POI'].shift(-1)
        df_anon['Index_of_POI_shifted_forward'] = df_anon['Index_of_POI'].shift(+1)
        df_anon.loc[0,'Index_of_POI_shifted_forward']='0'
        df_anon.loc[len(df_anon)-1,'Index_of_POI_shifted_backward']='0'
        df_anon['start_time'] = df_anon.loc[~(df_anon['Index_of_POI']==df_anon['Index_of_POI_shifted_forward']), 'DateTime']
        df_anon.fillna(method="ffill", inplace=True)
        df_anon['time_spent'] = (df_anon['DateTime'] - df_anon['start_time'])

        df_anon2 = df_anon.loc[~(df_anon['Index_of_POI_shifted_backward']==df_anon['Index_of_POI']),['ID', 'lat', 'lon', 'Week', 'DatetimeIndex', 'time_spent']].groupby(by=['ID', 'lat', 'lon', 'Week', 'DatetimeIndex']).sum().reset_index()
        df_anon2 = df_anon2.sort_values(by=['ID', 'Week', 'time_spent',  'DatetimeIndex'], ascending=[True, True, False, False]).reset_index(drop=True)

        #Comparing the time spent in POI between original and anonymized dataset
        df_orig2 = df_orig2.loc[~(df_orig2.DatetimeIndex =='RegularTime')]
        left_join_df = pd.merge(df_orig2, df_anon2, on=['ID','lat','lon','Week','DatetimeIndex'], how='left')

        left_join_df['time_spent_y'] = left_join_df['time_spent_y'].fillna(pd.Timedelta(seconds=0))
        left_join_df['diff_time_spent'] = abs( left_join_df['time_spent_y'].dt.total_seconds() - left_join_df['time_spent_x'].dt.total_seconds() )
        left_join_df['time_spent_x'] = left_join_df['time_spent_x'].dt.total_seconds()

        #Calculating the scrore
        score = 1- (left_join_df['diff_time_spent'].sum()/left_join_df['time_spent_x'].sum())
    return score

def conditions(df):
    return [
        (df['DayOfTheWeek'] < 4) & (df['Hour']>=22) & (df['Hour']<=23),
        (df['DayOfTheWeek'] < 4) & (df['Hour']>=0) & (df['Hour']<=6),
        (df['DayOfTheWeek'] < 4) & (df['Hour']>=9) & (df['Hour']<=17),
        (df['DayOfTheWeek'] >= 4) & (df['Hour']>=10) & (df['Hour']<=18)
    ]


from collections import defaultdict
"""
    0th: brute force BFS
    Time    O(N^N)
    Space   O(N)
    LTE
"""

class Solution(object):
    def numBusesToDestination(self, routes, S, T):
        """
        :type routes: List[List[int]]
        :type S: int
        :type T: int
        :rtype: int
        """
        if S == T:
            return 0
        connections = {}
        for route in routes:
            for stop in route:
                if stop not in connections:
                    connections[stop] = set(route)
                else:
                    for s in route:
                        connections[stop].add(s)
        q = [(S, 0)]
        seen = set([S])
        while len(q) > 0:
            node, steps = q.pop(0)
            # if node in seen:
            #     continue
            # seen.add(node)
            if node == T:
                return steps
            if node in connections:
                children = connections[node]
                for child in children:
                    if child not in seen:
                        seen.add(node)
                        q.append((child, steps + 1))
        return -1

s = Solution()

a = [[1, 2, 7], [3, 6, 7]]
b = 1
c = 6
print(s.numBusesToDestination(a, b, c))

a = [[7, 12], [4, 5, 15], [6], [15, 19], [9, 12, 13]]
b = 15
c = 12
print(s.numBusesToDestination(a, b, c))

print("----")

"""
    1st: optimized BFS
    - when we put nodes into the BFS queue, dont consider the current route for further exploration
    - we can use 2 hashtables to achieve that

    e.g.
    [[1,2,7],[3,6,7]]

    ht1 stores the relationshp of { routeId: stops }
    ht1 = {
        0: {1, 2, 7},
        1: {3, 6, 7}
    }

    ht2 stores the relationshp of { stopId: related routeIds }
    ht2 = {
        1: [0],
        2: [0],
        3: [1],
        6: [1],
        7: [0, 1]
    }

    Time    O(RS + RS^2) ???
    Space   O(N)
    1920 ms, faster than 9.62%
"""

class Solution(object):
    def numBusesToDestination(self, routes, S, T):
        if S == T:
            return 0

        # routeId: stops = { rid1: [stop1, stop2, stop3...], id2: [...], ... }
        routeSet = {}
        # stopId: related routeIds = { sid1: { rid1, rid2, rid3,...}, sid2: { rid1, rid2,..}... }
        connections = defaultdict(list)
        for i in range(len(routes)):
            route = routes[i]
            routeSet[i] = set(route)
            for stop in route:
                connections[stop].append(i)
        # BFS
        q = [(S, -1, 0)]
        seen = set()
        while len(q) > 0:
            node, curRoute, steps = q.pop(0)
            if node in seen:
                continue
            seen.add(node)
            if node == T:
                return steps
            # look for the related routes
            if node in connections:
                for rr in connections[node]:
                    if rr == curRoute:
                        continue
                    # put every bus stop into the queue from every related route
                    for stop in routeSet[rr]:
                        q.append((stop, rr, steps + 1))
        return -1

s = Solution()

a = [[1, 2, 7], [3, 6, 7]]
b = 1
c = 6
print(s.numBusesToDestination(a, b, c))

a = [[7, 12], [4, 5, 15], [6], [15, 19], [9, 12, 13]]
b = 15
c = 12
print(s.numBusesToDestination(a, b, c))

print("-----")

"""
    2nd: another BFS approach
    - instead of BFS through the bus stops, we BFS through the bus routes

    Time    O(RRS + RR) ???
    Space   O(N)
    2816 ms, faster than 5.02%
"""

class Solution(object):
    def numBusesToDestination(self, routes, S, T):
        if S == T:
            return 0

        starts = []
        # { rid1: [stop1, stop2, stop3...], id2: [..], ... }
        routeSet = {}
        for i in range(len(routes)):
            route = routes[i]
            routeSet[i] = set(route)
        # route connections { rid1: { rid2, rid3,...}, rid2: { rid1,..}... }
        connections = defaultdict(list)
        for i in routeSet:
            for stop in routeSet[i]:
                if stop == S:
                    starts.append(i)
                for j in routeSet:
                    if i == j:
                        continue
                    if stop in routeSet[j]:
                        connections[i].append(j)
        # BFS
        q = [(s, 1) for s in starts]
        seen = set()
        while len(q) > 0:
            route, steps = q.pop(0)
            if route in seen:
                continue
            seen.add(route)
            if T in routeSet[route]:
                return steps
            if route in connections:
                for rr in connections[route]:
                    q.append((rr, steps + 1))
        return -1

s = Solution()

a = [[1, 2, 7], [3, 6, 7]]
b = 1
c = 6
print(s.numBusesToDestination(a, b, c))

a = [[7, 12], [4, 5, 15], [6], [15, 19], [9, 12, 13]]
b = 15
c = 12
print(s.numBusesToDestination(a, b, c))

print("----")

"""
    3rd: similar to the 1st
    - similar to lc815, 1345
    - learned from others
    - but we clear each of the routes whenever after we put its stops in the BFS queue

    ht = {
        1: [0],
        2: [0],
        3: [1],
        6: [1],
        7: [0, 1]
    }

    - after we have seen stop1
        1. we put every stop from route0 in the queue
        2. we clean up route0 <- so that whenever we route back to route0, we dont need to traverse again

    ref:
    - https://leetcode.com/problems/bus-routes/discuss/122771/C%2B%2BJavaPython-BFS-Solution

    Time    O(RS + RS)
    Space   O(RS)
    376 ms, faster than 84.10%
"""

class Solution(object):
    def numBusesToDestination(self, routes, S, T):
        if S == T:
            return 0
        # stopId: related routeIds = { sid1: { rid1, rid2, rid3,...}, sid2: { rid1, rid2,..}... }
        connections = defaultdict(set)
        for i, route in enumerate(routes):
            for j in route:
                connections[j].add(i)
        # BFS
        q = [(S, 0)]
        seen = set()
        seen.add(S)
        while len(q) > 0:
            node, steps = q.pop(0)
            if node == T:
                return steps
            for routeId in connections[node]:
                for stop in routes[routeId]:
                    if stop not in seen:
                        seen.add(stop)
                        q.append((stop, steps + 1))
                # clean up routeId after it is considered
                routes[routeId] = []
        return -1

s = Solution()

a = [[1, 2, 7], [3, 6, 7]]
b = 1
c = 6
print(s.numBusesToDestination(a, b, c))

a = [[7, 12], [4, 5, 15], [6], [15, 19], [9, 12, 13]]
b = 15
c = 12
print(s.numBusesToDestination(a, b, c))


import re
import pandas as pd
import sys
import shutil

def remove_unicode(replace_or_list, filename):
    unicodes = {'ö': '\\"{o}',
                '–': '-',
                'ø': '{\o}'}

    with open(filename,'rt') as file:
        lines = file.readlines()
    with open(filename,'rt') as file:
        wholefile = file.read()
    if replace_or_list == 1:
        print("Ok. Just listing for now...")
        print('If you replace, the following changes will be made...')
        for line in lines:
            m = re.match('(.*author\s*=\s*\{(.*)\}\s*,)',line.rstrip())
            if m != None:
                author_line = m.group(1)
                author_names = m.group(2)
                for bad_char in unicodes.keys():
                    if(bad_char in author_names):
                        newname = re.sub(bad_char, unicodes[bad_char], author_names)
                        print('\t',author_names.ljust(55),"------->\t\t",newname)
    elif replace_or_list == 2:
        print("Ok. Replacing... and making a backup file .bak2")
        print("...............................................")
        shutil.copy2(filename, filename+'.bak2')
        print("Now replacing.")
        newfile = wholefile
        for bad_char in unicodes.keys():
            newfile = re.sub(bad_char, unicodes[bad_char], newfile)
        with open(filename, 'wt') as out:
            out.write(newfile)

def abbreviateit(replace_or_list, filename):
    '''
    Martin Forsythe wrote this in 2015
    '''
    df = pd.read_csv('Master_Journal_Abbreviations',sep='\t',index_col=0)
    journal_dict = df['abbrev'].to_dict()

    with open(filename,'rt') as file:
        lines = file.readlines()
    with open(filename,'rt') as file:
        wholefile = file.read()

    if replace_or_list == 1:
        print("Ok. Just listing for now...")
        print('If you replace, the following changes will be made...')
        for line in lines:
            m = re.match('(.*journal\s*=\s*\{(.*)\}\s*,)',line.rstrip())
            if m!=None:
                journal_line = m.group(1)
                journal = m.group(2)

                journal_key = re.sub('^The ','',journal)

                if journal_key in journal_dict.keys():
                    abbrev = journal_dict[journal_key]
                    print('\t',journal.ljust(55),"------->\t\t",abbrev)

    elif replace_or_list == 2:
        print("Ok. Replaceing... and making a backup file .bak")
        print("...............................................")
        shutil.copy2(filename, filename+'.bak')
        print("Now replacing.")
        newfile = re.sub('The Journal', 'Journal', wholefile)
        for journal_key in journal_dict.keys():
            newfile = re.sub(journal_key, journal_dict[journal_key], newfile)
        with open(filename, 'wt') as out:
            out.write(newfile)
        print("After replacement your bibliography contains the following journals:")
        list_of_journals = []
        for line in lines:
            m = re.match('(.*journal\s*=\s*\{(.*)\}\s*,)',line.rstrip())
            if m!=None:
                journal_line = m.group(1)
                journal = m.group(2)
                list_of_journals.append(journal)
        for j in set(list_of_journals):
            print ('\t',j)

def check_for_no_doi(filename):
    with open(filename,'rt') as file:
        lines = file.readlines()
    linenumber = -1
    entry_key_linenumbers = []
    entry_types = []
    cite_keys = []
    for line in lines:
        linenumber+=1
        if re.match('\s*@\w*',line) != None:
            entry_type = line.split('{')[0]
            cite_key = line.split('{')[1].rstrip(',\n')
            entry_key_linenumbers.append(linenumber)
            cite_keys.append(cite_key)
            entry_types.append(entry_type)

    df = pd.DataFrame()
    df['type'] = entry_types
    df['cite_key'] = cite_keys
    df['start'] = entry_key_linenumbers
    df['end'] = entry_key_linenumbers[1:len(entry_key_linenumbers)]+[len(lines)]

    doi_list = []
    url_present_list = []
    for id in df.index.values:
        entry_lines = lines[df.loc[id]['start']:df.loc[id]['end']]
        url_present = False
        doi = ''
        for line in entry_lines:
            if re.match('\s*doi',line) !=None:
                doi = line.split('{')[1].split('}')[0]
            if re.match('\s*url',line)!=None:
                url_present = True
        url_present_list.append(url_present)
        doi_list.append(doi)
    df['url'] = url_present_list
    df['doi'] = doi_list
    df.sort(['type','doi','cite_key'],inplace=True)
    # print df[['cite_key','doi']]

    # PRINT OUT REPEATED DOIs:

    problems = df.copy()
    problems = problems[problems['type']=='@article']
    problems = problems[problems['doi']=='']
    print(problems)

def check_for_dupes(filename):
    with open(filename,'rt') as file:
        lines = file.readlines()
    linenumber = -1
    entry_key_linenumbers = []
    entry_types = []
    cite_keys = []
    for line in lines:
        linenumber+=1
        if re.match('\s*@\w*',line) != None:
            entry_type = line.split('{')[0]
            cite_key = line.split('{')[1].rstrip(',\n')
            entry_key_linenumbers.append(linenumber)
            cite_keys.append(cite_key)
            entry_types.append(entry_type)

    df = pd.DataFrame()
    df['type'] = entry_types
    df['cite_key'] = cite_keys
    df['start'] = entry_key_linenumbers
    df['end'] = entry_key_linenumbers[1:len(entry_key_linenumbers)]+[len(lines)]

    doi_list = []
    url_present_list = []
    for id in df.index.values:
        entry_lines = lines[df.loc[id]['start']:df.loc[id]['end']]
        url_present = False
        doi = ''
        for line in entry_lines:
            if re.match('\s*doi',line) !=None:
                doi = line.split('{')[1].split('}')[0]
            if re.match('\s*url',line)!=None:
                url_present = True
        url_present_list.append(url_present)
        doi_list.append(doi)
    df['url'] = url_present_list
    df['doi'] = doi_list
    df.sort(['type','doi','cite_key'],inplace=True)
    problems = df.copy()
    problems = problems[problems['doi']!='']
    ids = problems["doi"]
    print(problems[ids.isin(ids[ids.duplicated()])].sort("doi")[['cite_key','doi']])

if __name__ == "__main__":
    if len(sys.argv)!=2:
        print("Please provide input arguments. \n" \
              "Example usage: python Abbreviabibtex.py bibliography.bib \n" \
              "The program will then query you for 'replace' or 'list' \n")
        exit()
    bibfile = sys.argv[1]
    replace_or_list = int(input("Should I make replacements or list possible ones? [options: 0 to skip, 1 to list, 2 to replace]: "))
    if(replace_or_list != 0):
        abbreviateit(replace_or_list, bibfile)

    check_no_dois = int(input("Should I check for missing DOIs? [options: 0 to skip, 1 to check]: "))
    if(check_no_dois == 1):
        check_for_no_doi(bibfile)

    check_dupes = int(input("Should I check for duplicate entries? [options: 0 to skip, 1 to check]: "))
    if(check_no_dois == 1):
        check_for_dupes(bibfile)

    check_unicode = int(input("Should I replace or list unicode characters? [options: 0 to skip, 1 to list, 2 to replace]: "))
    if(replace_or_list != 0):
        remove_unicode(check_unicode, bibfile)


from math import pi
import numpy as np

def rotationMatrixToXYZ(R):
    """
    R = [[x1,x2,x3],
         [y1,y2,y3],
         [z1,z2,z3]]
    """
    beta = np.arctan2(-R[2][0],np.sqrt(R[0][0]**2+R[1][0]**2))
    if np.abs(np.abs(beta)-pi/2)<np.finfo(float).eps:
        gema = np.arctan2(R[0][1],R[1][1])
        beta = pi/2
        alpha = 0
    else:
        gema = -np.arctan2(R[0][1],R[1][1])
        beta = -pi/2
        alpha = 0
    return [gema,beta,alpha]

工业机器人/作业二/旋转矩阵到XYZ固定角.py

旋转矩阵到XYZ固定角.py