import os
import urllib
from ConfigParser import ConfigParser, NoSectionError, NoOptionError

from swift.common.swob import HTTPBadRequest, HTTPLengthRequired, \
    HTTPRequestEntityTooLarge

constraints_conf = ConfigParser()
constraints_conf.read('/etc/swift/swift.conf')

def constraints_conf_int(name, default):
    try:
        return int(constraints_conf.get('swift-constraints', name))
    except (NoSectionError, NoOptionError):
        return default

#: Max file size allowed for objects
MAX_FILE_SIZE = constraints_conf_int('max_file_size',
                                     5368709122)  # 5 * 1024 * 1024 * 1024 + 2
#: Max length of the name of a key for metadata
MAX_META_NAME_LENGTH = constraints_conf_int('max_meta_name_length', 128)
#: Max length of the value of a key for metadata
MAX_META_VALUE_LENGTH = constraints_conf_int('max_meta_value_length', 256)
#: Max number of metadata items
MAX_META_COUNT = constraints_conf_int('max_meta_count', 90)
#: Max overall size of metadata
MAX_META_OVERALL_SIZE = constraints_conf_int('max_meta_overall_size', 4096)
#: Max size of any header
MAX_HEADER_SIZE = constraints_conf_int('max_header_size', 8192)
#: Max object name length
MAX_OBJECT_NAME_LENGTH = constraints_conf_int('max_object_name_length', 1024)
#: Max object list length of a get request for a container
CONTAINER_LISTING_LIMIT = constraints_conf_int('container_listing_limit',
                                               10000)
#: Max container list length of a get request for an account
ACCOUNT_LISTING_LIMIT = constraints_conf_int('account_listing_limit', 10000)
#: Max account name length
MAX_ACCOUNT_NAME_LENGTH = constraints_conf_int('max_account_name_length', 256)
#: Max container name length
MAX_CONTAINER_NAME_LENGTH = constraints_conf_int('max_container_name_length',
                                                 256)

#: Query string format= values to their corresponding content-type values
FORMAT2CONTENT_TYPE = {'plain': 'text/plain', 'json': 'application/json',
                       'xml': 'application/xml'}

def check_metadata(req, target_type):
    """
    Check metadata sent in the request headers.

    :param req: request object
    :param target_type: str: one of: object, container, or account: indicates
                        which type the target storage for the metadata is
    :returns: HTTPBadRequest with bad metadata otherwise None
    """
    prefix = 'x-%s-meta-' % target_type.lower()
    meta_count = 0
    meta_size = 0
    for key, value in req.headers.iteritems():
        if isinstance(value, basestring) and len(value) > MAX_HEADER_SIZE:
            return HTTPBadRequest('Header Line Too Long')
        if not key.lower().startswith(prefix):
            continue
        key = key[len(prefix):]
        if not key:
            return HTTPBadRequest(body='Metadata name cannot be empty',
                                  request=req, content_type='text/plain')
        meta_count += 1
        meta_size += len(key) + len(value)
        if len(key) > MAX_META_NAME_LENGTH:
            return HTTPBadRequest(
                body='Metadata name too long; max %d' % MAX_META_NAME_LENGTH,
                request=req, content_type='text/plain')
        elif len(value) > MAX_META_VALUE_LENGTH:
            return HTTPBadRequest(
                body='Metadata value too long; max %d' % MAX_META_VALUE_LENGTH,
                request=req, content_type='text/plain')
        elif meta_count > MAX_META_COUNT:
            return HTTPBadRequest(
                body='Too many metadata items; max %d' % MAX_META_COUNT,
                request=req, content_type='text/plain')
        elif meta_size > MAX_META_OVERALL_SIZE:
            return HTTPBadRequest(
                body='Total metadata too large; max %d'
                % MAX_META_OVERALL_SIZE,
                request=req, content_type='text/plain')
    return None

def check_object_creation(req, object_name):
    """
    Check to ensure that everything is alright about an object to be created.

    :param req: HTTP request object
    :param object_name: name of object to be created
    :returns HTTPRequestEntityTooLarge: the object is too large
    :returns HTTPLengthRequired: missing content-length header and not
                                 a chunked request
    :returns HTTPBadRequest: missing or bad content-type header, or
                             bad metadata
    """
    if req.content_length and req.content_length > MAX_FILE_SIZE:
        return HTTPRequestEntityTooLarge(body='Your request is too large.',
                                         request=req,
                                         content_type='text/plain')
    if req.content_length is None and \
            req.headers.get('transfer-encoding') != 'chunked':
        return HTTPLengthRequired(request=req)
    if 'X-Copy-From' in req.headers and req.content_length:
        return HTTPBadRequest(body='Copy requests require a zero byte body',
                              request=req, content_type='text/plain')
    if len(object_name) > MAX_OBJECT_NAME_LENGTH:
        return HTTPBadRequest(body='Object name length of %d longer than %d' %
                              (len(object_name), MAX_OBJECT_NAME_LENGTH),
                              request=req, content_type='text/plain')
    if 'Content-Type' not in req.headers:
        return HTTPBadRequest(request=req, content_type='text/plain',
                              body='No content type')
    if not check_utf8(req.headers['Content-Type']):
        return HTTPBadRequest(request=req, body='Invalid Content-Type',
                              content_type='text/plain')
    if 'x-object-manifest' in req.headers:
        value = req.headers['x-object-manifest']
        container = prefix = None
        try:
            container, prefix = value.split('/', 1)
        except ValueError:
            pass
        if not container or not prefix or '?' in value or '&' in value or \
                prefix[0] == '/':
            return HTTPBadRequest(
                request=req,
                body='X-Object-Manifest must in the format container/prefix')
    return check_metadata(req, 'object')

def check_mount(root, drive):
    """
    Verify that the path to the device is a mount point and mounted.  This
    allows us to fast fail on drives that have been unmounted because of
    issues, and also prevents us for accidentally filling up the root
    partition.

    :param root:  base path where the devices are mounted
    :param drive: drive name to be checked
    :returns: True if it is a valid mounted device, False otherwise
    """
    if not (urllib.quote_plus(drive) == drive):
        return False
    path = os.path.join(root, drive)
    return os.path.exists(path) and os.path.ismount(path)

def check_float(string):
    """
    Helper function for checking if a string can be converted to a float.

    :param string: string to be verified as a float
    :returns: True if the string can be converted to a float, False otherwise
    """
    try:
        float(string)
        return True
    except ValueError:
        return False

def check_utf8(string):
    """
    Validate if a string is valid UTF-8 str or unicode and that it
    does not contain any null character.

    :param string: string to be validated
    :returns: True if the string is valid utf-8 str or unicode and
              contains no null characters, False otherwise
    """
    if not string:
        return False
    try:
        if isinstance(string, unicode):
            string.encode('utf-8')
        else:
            string.decode('UTF-8')
        return '\x00' not in string
    # If string is unicode, decode() will raise UnicodeEncodeError
    # So, we should catch both UnicodeDecodeError & UnicodeEncodeError
    except UnicodeError:
        return False


# Library
import uvicorn
from fastapi import FastAPI
from features import feature
import numpy as np
import pandas as pd
import pickle

# Create the app object
app = FastAPI()

# Model load
pickleIn = open('model.pkl','rb')
classifier = pickle.load(pickleIn)

# Create a index page
@app.get('/')
def index():
    return {'message':'Hello World!'}

# HTTP POST request is made to the "/predict" endpoint.
@app.post('/predict')

# This function handles the POST request to the "/predict" endpoint. It accepts data of type "feature" and assigns it to a variable named "data."
def predictDiabetes(data:feature):

    # Converts the incoming data into a Python dictionary. This makes it easier to work with the data later.
    data = data.dict()

    # Assign the data from the dictionary to relevant variables.
    Pregnancies=data['Pregnancies']
    Glucose=data['Glucose']
    BMI=data['BMI']
    DiabetesPedigreeFunction=data['DiabetesPedigreeFunction']

    # Stores the prediction result in a variable.
    prediction = classifier.predict([[Pregnancies,Glucose,BMI,DiabetesPedigreeFunction]])

    # If the prediction is 1, it is diabetes and if the prediction is 0, it is not diabetes.
    if(prediction[0]==1):
        prediction="Diabetes"
    else:
        prediction="Not-Diabetes"
    return {
        'prediction': prediction
    }

# Will run on http://127.0.0.1:8000
if __name__ == '__main__':
    uvicorn.run(app, host='127.0.0.1', port=8000)


"""Shared functions for migrations"""
import flatdict
from yaml import dump

from lib.dekickrc import (
    dekickrc_tmpl_parse_value,
    get_dekickrc_flat,
    get_dekickrc_tmpl_flat,
)
from lib.fs import chown
from lib.settings import DEKICKRC_PATH

def dekickrc_save_flat(dekickrc_flat: flatdict.FlatDict):
    """Saves flat dict to .dekickrc.yml file"""
    with open(DEKICKRC_PATH, "w", encoding="utf-8") as yaml_file:
        dump(dekickrc_flat.as_dict(), yaml_file)
        chown(DEKICKRC_PATH)

def dekickrc_add_default_values():
    """Adds missing fields to the .dekickrk.yml file based on .dekickrc.tmpl.yml"""

    dekickrc_flat = get_dekickrc_flat()
    tmpl_flat = get_dekickrc_tmpl_flat()

    for path, value in tmpl_flat.items():
        if path not in dekickrc_flat:
            var = dekickrc_tmpl_parse_value(str(value))

            if var["default"] != "" and var["required"]:
                dekickrc_flat[path] = var["default"]

    dekickrc_save_flat(dekickrc_flat)

def dekickrc_remove_unused_values():
    """Removes unused fields from the .dekickrk.yml file"""

    dekickrc_flat = get_dekickrc_flat()
    tmpl_flat = get_dekickrc_tmpl_flat()

    for key in dekickrc_flat.keys():  # pylint: disable=consider-using-dict-items
        if key not in tmpl_flat:
            del dekickrc_flat[key]

    dekickrc_save_flat(dekickrc_flat)


#Django
from django.db import models
from django.contrib.auth.models import AbstractUser
from django.core.validators import RegexValidator

#abstract cride.util
from cride.utils.models import CRideModel

class User(CRideModel,AbstractUser):
    email=models.EmailField(
        "Email adress",
        unique=True,
        error_messages={
            "unique":"A user with  that email already exist."
        }
    )

    phone_regex=RegexValidator(regex=r'\+?1?\d{9,15}$',
    message="Phone number must be enteredin the  format +999999999. Up  to 15  digits allowed.")
    phone_number=models.CharField(validators=[phone_regex],max_length=17,blank=True)

    USERNAME_FIELD="email"

    REQUIRED_FIELDS=["username","first_name","last_name"]

    is_client=models.BooleanField(
        "Client status",
        default=True,
        help_text="help easily distinguish user"
    )

    is_verfied=models.BooleanField(
        "Verified",
        default=False,
        help_text="Set to true  when the user have verified its email adress"
    )

    def __str__(self):
        return self.username

    def get_short_name(self):
        return self.username


#! /usr/bin/env python3.8
# encoding: utf-8
import open3d as o3d
import copy
import numpy as np
import math
import rospy
from geometry_msgs.msg import PoseStamped
from pyquaternion import Quaternion
from sensor_msgs.msg import PointCloud2, PointField
from sensor_msgs import point_cloud2
from std_msgs.msg import Header

## 函数区
# 考虑x/y方向的路径
def XdirectionZigPath(xmin,xmax,ymin,ymax,Nx):
    paths = []
    dx = float(xmax-xmin)/(Nx-1)  # the y step-over
    flag=1      #奇偶分别
    path=[]
    for n in range(0,Nx):
        x = xmin+n*dx              # current y-coordinate
        # if (n==Nx-1):
        #     assert( x==xmax)
        # elif (n==0):
        #     assert( x==xmin)
        if flag==1:
            p1 = [x,ymin,0]   # start-point of line
            p2 = [x,ymax,0]   # end-point of line
            # print(flag)
        if flag==-2:
            p1 = [x,ymax,0]   # start-point of line
            p2 = [x,ymin,0]   # end-point of line
            # print(flag)
        path.append(p1)       # add the line to the path
        path.append(p2)
        flag=~flag
        # paths.append(path)
    return path

# 得到步进x/y方向的路径
def feedPath(path,step,step_num):
    flag=1      #奇偶分别
    fpath=[]
    n=len(path)
    for i in range(n//2):
        for j in range(step_num):
            if flag==1:
                p=[path[2*i][0],path[2*i][1]+j*step,path[2*i][2]]
            if flag==-2:
                p=[path[2*i][0],path[2*i][1]-j*step,path[2*i][2]]
            fpath.append(p)
        flag=~flag
    return fpath

# 依据点云坐标得到z方向的坐标
def ZdirectionPath(fpath,points,normals,scan_height,rapid_height):
    zpath=[]
    npath=[]
    n=len(fpath)
    # 初始点
    zpath.append([fpath[0][0],fpath[0][1],rapid_height])
    npath.append([0,0,-1])
    # 中间点
    for i in range(n):
        temp=[]
        for m in range(len(points)):
            temp.append(math.sqrt((fpath[i][0]-points[m][0])**2+(fpath[i][1]-points[m][1])**2))
        min_value=np.min(temp)
        min_index=np.argmin(temp)
        # print(min_value)
        threshold=0.004     #阈值可修改
        if min_value<threshold:
            scan_z=points[min_index][2]+scan_height
            zpath.append([fpath[i][0],fpath[i][1],scan_z])
            npath.append([normals[min_index][0],normals[min_index][1],normals[min_index][2]])
    # 结束点
    zpath.append([fpath[n-1][0],fpath[n-1][1],rapid_height])
    npath.append([0,0,-1])
    # 修改初始点和结束点

    return zpath,npath

# 主函数
if __name__ == "__main__":
    mesh_frame = o3d.geometry.TriangleMesh.create_coordinate_frame(size=0.1, origin=[0, 0, 0])
    data = o3d.io.read_point_cloud("./src/data/point_cloud/pointcloud_1.pcd")
    # o3d.visualization.draw_geometries([data,mesh_frame])
    # 红色：x
    # 绿色：y
    # 蓝色：z

    # 使用欧拉角创建旋转矩阵
    pcd = copy.deepcopy(data).translate((0, 0, -0.24))
    # o3d.visualization.draw_geometries([pcd,mesh_frame])

    # 旋转网格
    R = mesh_frame.get_rotation_matrix_from_xyz((np.pi, 0, 0))
    pcd.rotate(R, center=(0, 0, 0))
    R = mesh_frame.get_rotation_matrix_from_xyz((0, 0, np.pi/12))
    pcd.rotate(R, center=(0, 0, 0))
    # o3d.visualization.draw_geometries([pcd,mesh_frame])

    # 交互选区
    vis = o3d.visualization.VisualizerWithVertexSelection()
    vis.create_window(window_name='select region holding shift', visible=True)
    vis.add_geometry(pcd)
    vis.run()
    point = vis.get_picked_points()
    vis.destroy_window()
    # print(point[0].index, np.asarray(point[0].coord))
    # 原文链接：https://blog.csdn.net/qq_45912037/article/details/127096161

    point_temp=[]
    for i in range(len(point)):
        point_temp.append(point[i].coord)

    outlier_cloud = o3d.geometry.PointCloud()# 传入3d点云
    outlier_cloud.points = o3d.utility.Vector3dVector(point_temp)  # point_points 二维 numpy 矩阵,将其转换为 open3d 点云格式

    o3d.visualization.draw_geometries([outlier_cloud,mesh_frame])

    # 计算法向量
    outlier_cloud.estimate_normals(
        search_param=o3d.geometry.KDTreeSearchParamKNN(knn=200)                        # 计算近邻的20个点
    )
    o3d.geometry.PointCloud.orient_normals_to_align_with_direction(outlier_cloud, orientation_reference=np.array([0.0, 0.0, -1.0]))  #设定法向量在z轴方向上，全部z轴正方向一致
    normals = np.array(outlier_cloud.normals)    # 法向量结果与点云维度一致(N, 3)
    points = np.array(outlier_cloud.points)
    # print(points)

    # 法向量可视化
    o3d.visualization.draw_geometries([outlier_cloud,mesh_frame],
                                         window_name="Open3d",
                                         point_show_normal=True,
                                         width=800,   # 窗口宽度
                                         height=600)  # 窗口高度

    # 获取工件x/y方向的最大值和最小值
    xmin=np.min(points[:,0])
    xmax=np.max(points[:,0])
    ymin=np.min(points[:,1])
    ymax=np.max(points[:,1])
    # 确定x方向分Nx条线
    Nx=20  # number of lines in the x-direction
    path = XdirectionZigPath(xmin,xmax,ymin,ymax,Nx)
    # print(path)

    # 设置每条线走几步
    step_num=20
    step=(ymax-ymin)/(step_num-1)
    fpath=feedPath(path,step,step_num)

    scan_height=0.01
    rapid_height=0.2
    zpath,npath=ZdirectionPath(fpath,points,normals,scan_height,rapid_height)
    # print(zpath)

    # 将路径画在点云上,可视化
    #绘制顶点
    lines=[]
    for i in range(len(zpath)-1):
        l=[i,i+1]
        lines.append(l) #连接的顺序
    color = [[0, 0, 0.8] for i in range(len(lines))]
    #添加顶点，点云
    points_pcd = o3d.geometry.PointCloud()# 传入3d点云
    points_pcd.points = o3d.utility.Vector3dVector(zpath)  # point_points 二维 numpy 矩阵,将其转换为 open3d 点云格式
    points_pcd.paint_uniform_color([0, 0.8, 0]) #点云颜色
    points_pcd.normals= o3d.utility.Vector3dVector(npath)
    #绘制线条
    lines_pcd = o3d.geometry.LineSet()
    lines_pcd.lines = o3d.utility.Vector2iVector(lines)
    lines_pcd.colors = o3d.utility.Vector3dVector(color) #线条颜色
    lines_pcd.points = o3d.utility.Vector3dVector(zpath)
    # 可视化
    o3d.visualization.draw_geometries([points_pcd,lines_pcd,outlier_cloud,mesh_frame])
    o3d.visualization.draw_geometries([points_pcd,lines_pcd,mesh_frame],point_show_normal=True)
'''
    # 发布话题
    rospy.init_node("pathplan_select")
    pub = rospy.Publisher("pathplanning_select",PoseStamped,queue_size=10)
    count=0
    rate=rospy.Rate(1)
    ps = PoseStamped()
    while not rospy.is_shutdown():
        # x/y/z坐标
        ps.pose.position.x=zpath[count][0]
        ps.pose.position.y=zpath[count][1]
        ps.pose.position.z=zpath[count][2]

        # 构建旋转矩阵
        rotate_matrix=[[0,0,0],[0,0,0],[0,0,0]]
        Z = np.array([npath[i][0], npath[i][1], npath[i][2]])
        X = np.array([Z[1], -Z[0], 0])
        Z = Z/np.linalg.norm(Z)
        X = X/np.linalg.norm(X)
        rotate_matrix[0][2]=Z[0]
        rotate_matrix[1][2]=Z[1]
        rotate_matrix[2][2]=Z[2]
        rotate_matrix[0][0]=X[0]
        rotate_matrix[1][0]=X[1]
        rotate_matrix[2][0]=X[2]
        # 计算叉乘
        Y = np.cross(Z,X)
        Y = Y/np.linalg.norm(Y)
        rotate_matrix[0][1]=Y[0]
        rotate_matrix[1][1]=Y[1]
        rotate_matrix[2][1]=Y[2]
        rotateMatrix = np.array(rotate_matrix)
        print(rotateMatrix)
        q = Quaternion(matrix=rotateMatrix)
        ps.pose.orientation.x=q.x
        ps.pose.orientation.y=q.y
        ps.pose.orientation.z=q.z
        ps.pose.orientation.w=q.w
        # 发布话题
        pub.publish(ps)
        rospy.loginfo("%s",str(ps))

        count+=1
        if count>=len(zpath):
            rospy.loginfo("len%d",len(zpath))
            break
'''


"""
Conisider:
- A string, S of length N where S= C sub 0 C sub 1 ... C sub n-1
- An integer, K, where K is a factor of N

We can split S into (S/K)  substrings, where each substring, T sub i, consists of a continguious block of K characters in S.
Then, use each T sub i to create string U sub i such thaht
-The characters in U sub i are a subsequence of the characters in T sub i.
-Any repeat occurrence of a character is removed from the string such that each character in U sub i occurs exactly once.
In other words, if the character at some index J in T sub i occurs at a previous index < J in T sub i, then do not include the character in string U sub i.

Given S and K, print (N/K) lines where each line i denotes string U sub i.

"""

import textwrap
def merge_the_tools(string, k):
    # string is the given element to analyze
    # k is the directed size of substrings

    # Break string into elements of size k
    subStr = textwrap.wrap(string, k)

    # Eliminate duplicates in each element of subStr and print
    for each in subStr:
        each = list(dict.fromkeys(each))
        print(''.join(each))

if __name__ == '__main__':
    string, k = input(), int(input())
    merge_the_tools(string, k)


import pandas as pd
import pkgutil
from io import BytesIO

def load_bank(classifier=True):
    bank = pd.read_csv(
        BytesIO(
            pkgutil.get_data('loadbank', 'bank/bank.csv')
        ),
        sep=';',
    )
    bank_category = (
        bank.select_dtypes(
            include=object
        ).apply(
            lambda x: x.astype('category'),
            axis=0
        )
    )
    bank_numeric = bank.select_dtypes(
        include=int
    )
    if classifier:
        y = bank_category.y
        X = pd.concat(
            [bank_category, bank_numeric],
            axis=1
        ).drop(
            ['y'], axis=1
        )
    else:
        y = bank_numeric.balance
        X = pd.concat(
            [bank_category, bank_numeric],
            axis=1
        ).drop(
            ['balance'], axis=1
        )
    return X, y

def load_bank_classifier():
    return load_bank(classifier=True)

def load_bank_regressor():
    return load_bank(classifier=False)


#compiled smoke simulation code

import numpy as np
import matplotlib.pyplot as plt

# Creates initial density and velocity arrays

a0 = np.zeros((20,20))    #create iniital density array
a = np.zeros((20,20))        #create next density array

for i in range (8,12):
    for j in range (8,12):
        a0[i,j]=1

N = a0.shape[0]-2   #sets N as 2 less than the number of grid cells per plot side

dt = .04   #defining dt

visc =  .1   #defining viscosity constant

#h0 = np.zeros((100,100)) #creates initial horizontal and vertical velocity array
#v0 = np.zeros((100,100))
#
#for i in range (45,55):
#    for j in range (45,55):
#        v0[i,j] = 1
#        h0[i,j] = 1
#
#v = np.zeros((100,100))
#h = np.zeros((100,100))

# Smaller velocity array for visualization

h0 = np.zeros((20,20)) #creates initial horizontal and vertical velocity array
v0 = np.zeros((20,20))

for i in range (8,12):
    for j in range (8,12):
        v0[i,j] = 1
        h0[i,j] = 1

v = np.zeros((20,20))
h = np.zeros((20,20))

#N = 18

#visualizes initial velocity array

#plt.quiver(v0, h0, units = 'x', scale = .5)
#plt.show()

#N = 18   #sets N as 2 less than the number of grid cells per plot side

# using "loc" to indicate the local variable version of N

def draw_array(a1):   #flips i and j in the plot to correspond with desired conventions
    plt.imshow(np.transpose(a1), origin = "lower", cmap="spectral", interpolation = "none")
    plt.colorbar()
    plt.show(block=False)
    plt.draw()

def draw_vector_field(h, v, scale):    #h and v are the arrays containing horizontal and vertical components of the vector field
    plt.quiver(h.transpose(),v.transpose(), units = "x", scale = scale )
    plt.show()

def set_bnd (N_loc, b, array):
    for i in range (1,N_loc+1):
        if b==1:
            array[0,i]= -array[1,i]
            array[N_loc+1, i] = -array[N_loc, i]
        else:
            array[0,i] = array[1,i]
            array[N_loc+1 ,i] = array[N_loc, i]

        if b==2:
            array[i,0] = -array[i,1]
            array[i,N_loc + 1] = -array[i, N_loc]
        else:
            array[i,0] = array[i,1]
            array[i, N_loc+1] = array[i, N_loc]

    array[0,0] = 0.5*(array[1,0]+ array[0,1])
    array[0, N_loc + 1] = 0.5*(array[1,N_loc + 1] + array[0, N_loc])
    array[N_loc + 1, 0] = 0.5*(array[N_loc,0] + array[N_loc + 1,1])
    array[N_loc + 1, N_loc + 1] = 0.5*(array[N_loc, N_loc + 1] + array[N_loc + 1, N_loc])

def diffuse(N_loc, dens_array, dens_array0, diff, dt, b):
    c = dt*diff*N_loc*N_loc
    k=0
    while (k<20):
        for i in range (1,N_loc+1):
            for j in range (1,N_loc+1):
                dens_array[i,j]=(dens_array0[i,j]+c*(dens_array[i-1,j] + dens_array[i+1,j] + dens_array[i,j-1] + dens_array[i, j+1]))/(1+4*c)
        k = k + 1

    set_bnd(N_loc,b,dens_array)

def advect(N_loc, b, dens_array, dens_array0, h_vel, v_vel, dt):
    dt0 = dt*N_loc
    for i in range (1,N_loc+1):
        for j in range (1, N_loc+1):
            x = i - dt0*v_vel[i,j]
            y = j - dt0*h_vel[i,j]

            if (x<0.5):
                x=0.5

            if (x > N_loc + 0.5):
                x = N_loc + 0.5

            i0 = int(x)
            i1 = i0 + 1

            if (y<0.5):
                y=0.5
            if (y > N_loc + 0.5):
                y = N_loc + 0.5

            j0 = int(y)
            j1 = j0 +1

            s1 = x-i0
            s0 = 1-s1
            t1 = y-j0
            t0 = 1-t1

            dens_array[i,j] = s0*(t0*dens_array0[i0,j0] + t1*dens_array0[i0,j1]) + s1*(t0*dens_array0[i1,j0] + t1*dens_array0[i1,j1])

    set_bnd(N_loc, b, dens_array)

def project(N_loc, h_vel, v_vel, p, div):
    h = 1.0/N_loc
    k=0
    for i in range (1,N_loc+1):
        for j in range (1,N_loc+1):
            div[i,j] = -0.5*h*(h_vel[i+1,j] - h_vel[i-1,j] + v_vel[i,j+1] - v_vel[i,j-1])
            p[i,j] = 0
    set_bnd(N_loc, 0, div)
    set_bnd(N_loc, 0, p)

    draw_array(div)

    while k<20:
        for i in range (1,N_loc+1):
            for j in range (1,N_loc+1):
                p[i,j] = (div[i,j]+p[i-1,j] + p[i+1,j] + p[i,j-1] + p[i,j+1])/4
        set_bnd(N_loc, 0, p)
        k = k+1

    draw_array(p)

    for i in range (1, N_loc+1):
        for j in range (1, N_loc+1):
            h_vel[i,j] -= 0.5*(p[i+1,j] - p[i-1,j])/h
            v_vel[i,j] -= 0.5*(p[i,j+1] - p[i,j-1])/h
    set_bnd(N_loc, 1, h_vel)
    set_bnd(N_loc, 2, v_vel)

def vel_step(N_loc, h_vel, v_vel, h_vel0, v_vel0, visc, dt):

    diffuse(N_loc, h_vel, h_vel0, visc, dt, 1)
    draw_vector_field(h_vel,v_vel,0.5)

    diffuse(N_loc, v_vel, v_vel0, visc, dt, 2)
    draw_vector_field(h_vel,v_vel,0.5)

    project(N_loc, h_vel, v_vel, h_vel0, v_vel0)
    draw_vector_field(h_vel,v_vel,0.5)

    h_vel0, h_vel = h_vel, h_vel0
    v_vel0, v_vel = v_vel, v_vel0

    advect (N_loc, 1, h_vel, h_vel0, h_vel0, v_vel0, dt)
    draw_vector_field(h_vel,v_vel,0.5)

    advect (N_loc, 2, v_vel, v_vel0, h_vel0, v_vel0, dt)
    draw_vector_field(h_vel,v_vel,0.5)

    project (N_loc, h_vel, v_vel, h_vel0, v_vel0)
    draw_vector_field(h_vel,v_vel,0.5)

#Smoke simulation loop

#while True:
#    vel_step(N, h, v, h0, v0, visc, dt)
#    diffuse (N, a, a0, visc, dt, 0)
#    a0, a = a, a0
#    advect(N, 0, a, a0, h0, v0, dt) #Stam's code has h and v rather than h0 and v0 passed in here, although for whatever reason this seems to make the advection more effective. Why?
#    a0, a = a, a0
#    draw_array(a0)
#    draw_vector_field(h0,v0,0.5)

#Visualizing velocity fields at each stage through "vel_step" function

#vel_step (N, h, v, h0, v0, visc, dt)
#draw_vector_field(h0,v0,0.5)
#
#project(N, h0, v0, h, v)
#draw_vector_field(h0,v0,0.5)

while True:
    diffuse(N, a, a0, visc, dt, 0)
    a, a0 = a0, a
    draw_array(a0)


import random
from pctemplate import *

def charcreate():
    hp = random.randrange(1,10)
    init = random.randrange(1,8)
    return Warrior(hp, init)

class Warrior(Pctemplate):
    def __init__(self, hp = 0, init = 0):
        self.hp = hp
        self.init = init
        self.defense = 0
        self.dmgmod = 1
        self.pt = True
        self.pots = 1
        print("'Tis but a scratch!")

    def turn(self, opponent):

        action = {
            "Swordattack"  : self.swordattack,
            "Shieldblock"  : self.shieldblock,
            "Healthpotion" : self.healthpotion
        }

        self.defense = 0

        while True:
            print("Choose your action:")
            print("""
            Swordattack
            Shieldblock
            Healthpotion""")
            self.move = input()
            if self.move in ("Swordattack", "Shieldblock", "Healthpotion"):
                self.move = action.get(self.move)
                self.move(opponent)
                break
            else:
                print("Not a valid action")

    def swordattack(self, opponent):
        print("Swordattack")
        dmg =random.randrange(1,7)
        opponent.get_dmg(dmg)

    def shieldblock(self, opponent):
        print("Shieldblock")
        self.defense = random.randrange(1, 4)

    def healthpotion(self, opponent):
        print("Healthpotion")
        if self.pots > 0:
            self.pots -= 1
            self.get_healing(random.randrange(1,4))
        else:
            print("No more Pots")
            self.turn(opponent)


from PySide2.QtWidgets import QMainWindow, QFileDialog, QMessageBox, QTableWidgetItem, QGraphicsScene, QDialog
from ui.ui_existencia import Ui_Dialog
from PySide2.QtCore import Slot
from models.libro import Libro
from models.sucursal import Sucursal
from models.libro_sucursal import LibroSucursal

class ExistenciaWindow(QDialog):
    def __init__(self, existencia = None):
        super(ExistenciaWindow, self).__init__()
        self.ui = Ui_Dialog()
        self.ui.setupUi(self)
        self.existencia = existencia

        self.ui.push_cancelar.clicked.connect(self.onClose)
        self.ui.push_guardar.clicked.connect(self.onSave)

        self.sucursales = Sucursal().getAll()
        self.libros = Libro().getAll()

        for sucursal in self.sucursales:
            self.ui.combo_sucursal.addItem(sucursal['nombre'])

        for libro in self.libros:
            self.ui.combo_libro.addItem(libro['titulo'], libro['codigo'])

        if existencia is not None:
            index = self.ui.combo_sucursal.findText(self.existencia['sucursal'])
            self.ui.combo_sucursal.setCurrentIndex(index)
            index = self.ui.combo_libro.findData(self.existencia['libro_id'])
            self.ui.combo_libro.setCurrentIndex(index)
            self.ui.spin_cantidad.setValue(existencia['existencia'])

    @Slot()
    def onClose(self):
        self.done(0)

    @Slot()
    def onSave(self):
        libro = self.libros[self.ui.combo_libro.currentIndex()]['codigo']
        sucursal = self.ui.combo_sucursal.currentText()
        cantidad = self.ui.spin_cantidad.value()
        registro = LibroSucursal( sucursal=sucursal, libro=libro, existencia=cantidad)
        if self.existencia is not None:
            registro._key[0]=self.existencia['libro_id']
            registro._key[1]=self.existencia['sucursal']
            registro.update()
        else:
            registro.save()
        self.done(0)


from petrol_locations import app
from flask.testing import FlaskClient
import pytest
from unittest.mock import MagicMock, patch

@pytest.fixture
def setup_app():
    app.config['TESTING'] = True
    app.config['WTF_CSRF_ENABLED'] = False
    app.config["SECRET_KEY"] = "test"
    return app

def test_app_running(setup_app):
    with setup_app.test_client() as client:
        response = client.get("/")
        assert response.status_code == 200

def test_app_visible(setup_app):
    with setup_app.test_client() as client:
        response = client.get("/")
        assert b'Petrol station map' in response.data


from heapq import heappop, heappush
import itertools
import copy

from constants import CellState, Actions
dist = {
    "FORWARD": 1,
    "U_TURN": 1,
    "TURN_LEFT": 1,
    "TURN_RIGHT": 1
}

def __isAllowed(state, x, y):
    if x < 0 or x >= state.grid.height: return False
    if y < 0 or y >= state.grid.width: return False
    return True

def explore_new(state, x, y, direction):
    state.robot.set_robot(x, y, direction)

def virtual_explore(state, x, y, direction):
    state.robot.set_robot(x, y, direction)
    for sensor in state.robot.sensors:
        all_sensable_cells = sensor.get_all_cells(x, y, direction)
        for cell in all_sensable_cells:
            _x, _y = cell
            if not __isAllowed(state, _x, _y):
                break
            if state.explored_grid[_x][_y].is_same(CellState.FREE):
                continue
            elif state.explored_grid[_x][_y].is_same(CellState.OBSTACLE):
                break
            elif state.explored_grid[_x][_y].is_same(CellState.UNKNOWN):
                return True
    return False

def virtual_sense(state, action):
    # used to get a approximate next_state
    # virtual_sense won't change state
    x, y, direction = state.robot.next_state(action, state.x, state.y, state.direction)
    state_copy = copy.deepcopy(state)
    state_copy.robot.set_robot(x, y, direction)
    state_copy.x = x
    state_copy.y = y
    state_copy.direction = direction
    explored_grid_before_predict = copy.deepcopy(state.explored_grid)
    sensed_cells_state = {}
    for sensor in state_copy.robot.sensors:
        # predict and update state_copy.explored_map and num_explored
        sensed_cells_state.update(sensor.get_cells_state_with_explored_grid(x, y, direction, state_copy))
    for sensed_cell in sensed_cells_state.keys():
        x, y = sensed_cell
        if explored_grid_before_predict[x][y].is_same(CellState.UNKNOWN):
            state_copy.num_explored += 1
    if state_copy.num_explored == 300:
        state_copy.is_terminal = True
        # print("virtual sense:", next_state.num_explored)
    return state_copy

# def dijkstra(state):
#     # virtual wall can walk, but will stuck at corner, see case1.jpg
#     if state.num_explored == 300:
#         return 1
#     pq = []  # list of entries arranged in a heap
#     entry_finder = {}  # mapping of tasks to entries
#     REMOVED = '<removed-task>'  # placeholder for a removed task
#     counter = itertools.count()  # unique sequence count
#
#     def add_task(task, priority=0):
#         'Add a new task or update the priority of an existing task'
#         if task in entry_finder:
#             remove_task(task)
#         count = next(counter)
#         entry = [priority, count, task]
#         entry_finder[task] = entry
#         heappush(pq, entry)
#
#     def remove_task(task):
#         'Mark an existing task as REMOVED.  Raise KeyError if not found.'
#         entry = entry_finder.pop(task)
#         entry[-1] = REMOVED
#
#     def pop_task():
#         'Remove and return the lowest priority task. Raise KeyError if empty.'
#         while pq:
#             priority, count, task = heappop(pq)
#             if task is not REMOVED:
#                 del entry_finder[task]
#                 return task
#         raise KeyError('pop from an empty priority queue')
#
#     distance = {}
#     task = (state.x, state.y, state.direction)
#     distance[task] = 0
#     visited = set()
#     add_task(task, distance[task])
#     while pq:
#         task = pop_task()
#         visited.add(task)
#         x, y, direction = task
#         #
#         # temp_state = copy.deepcopy(state)
#         # virtual_explore(temp_state, x, y, direction)
#         # if temp_state.num_explored != state.num_explored:
#         #     return distance[task]
#
#         for action in Actions:
#             next_x, next_y, next_direction = state.robot.next_state(action, x, y, direction)
#             next_task = (next_x, next_y, next_direction)
#
#             # check is allowed
#             if not state.grid.is_allowed(next_x, next_y):
#                 continue
#
#             # find the shortest distance to the first unexplored cell
#             if state.explored_grid[next_x][next_y].is_same(CellState.UNKNOWN):
#                 return distance[task]+dist[action.name]
#
#             if state.grid[next_x][next_y].is_same(CellState.OBSTACLE):
#                 continue
#
#             # if state.grid.is_virtual_wall(next_x, next_y):
#             #     continue
#             distance[next_task] = distance[task]+dist[action.name]
#             if next_task not in visited:
#                 add_task(next_task, distance[next_task])

def dijkstra(state):
    # shortest distance to sense unexplored area
    if state.num_explored == 300:
        return 1.0
    pq = []  # list of entries arranged in a heap
    entry_finder = {}  # mapping of tasks to entries
    REMOVED = '<removed-task>'  # placeholder for a removed task
    counter = itertools.count()  # unique sequence count

    def add_task(task, priority=0):
        'Add a new task or update the priority of an existing task'
        if task in entry_finder:
            remove_task(task)
        count = next(counter)
        entry = [priority, count, task]
        entry_finder[task] = entry
        heappush(pq, entry)

    def remove_task(task):
        'Mark an existing task as REMOVED.  Raise KeyError if not found.'
        entry = entry_finder.pop(task)
        entry[-1] = REMOVED

    def pop_task():
        'Remove and return the lowest priority task. Raise KeyError if empty.'
        while pq:
            priority, count, task = heappop(pq)
            if task is not REMOVED:
                del entry_finder[task]
                return task
        raise KeyError('pop from an empty priority queue')

    distance = {}
    x, y, direction = state.x, state.y, state.direction
    task = (x, y, direction)
    distance[task] = 1.0
    visited = set()
    add_task(task, distance[task])
    # print("initial append to pq:", task, distance[task])
    while pq:
        task = pop_task()
        visited.add(task)
        x, y, direction = task

        if virtual_explore(state, x, y, direction):
            # print(x, y, direction, distance[task])
            return distance[task]

        for _action in Actions:
            _x, _y, _direction = state.robot.next_state(_action, x, y, direction)
            _task = (_x, _y, _direction)
            if (_x, _y, _direction) in visited:
                continue

            # check is allowed
            if not __isAllowed(state, _x, _y):
                continue

            if state.explored_grid.is_virtual_wall(_x, _y):
                visited.add((_x, _y, _direction))
                continue

            if state.explored_grid[_x][_y].is_same(CellState.OBSTACLE):
                visited.add((_x, _y, _direction))
                continue

            if _task not in visited:
                distance[_task] = distance[task] + dist[_action.name]
                # print("append to pq:", _task, distance[_task])
                add_task(_task, distance[_task])

    raise("There exist cells that are unable to reach")

def total_number_newly_explore_given_steps(state, action, num_step):
    pass

def discontinuous_unexplored_cells(state):
    pass


import scipy.io

import tensorflow as tf
import numpy as np

VGG19_LAYERS = (
    'conv1_1', 'relu1_1', 'conv1_2', 'relu1_2', 'pool1',

    'conv2_1', 'relu2_1', 'conv2_2', 'relu2_2', 'pool2',

    'conv3_1', 'relu3_1', 'conv3_2', 'relu3_2', 'conv3_3',
    'relu3_3', 'conv3_4', 'relu3_4', 'pool3',

    'conv4_1', 'relu4_1', 'conv4_2', 'relu4_2', 'conv4_3',
    'relu4_3', 'conv4_4', 'relu4_4', 'pool4',

    'conv5_1', 'relu5_1'
)

def load_net(data_path):

    """
    Loads parameters from data_path (path to .mat file)

    Args:
        data_path: (string) path to saved net
    """

    parameter_dict = scipy.io.loadmat(data_path)
    del parameter_dict['__version__']
    del parameter_dict['__globals__']
    del parameter_dict['__header__']

    return parameter_dict

def net_preloaded(parameter_dict, input_image, num_freeze=0):

    """
    Generates layers of VGG net. Returns a dictionary of the neural net

    Args:
        parameter_dict: (dict) Dictionary holding all the weights for the network
        input_image: (tf tensor) Placegolder tensor with shape of input image
        num_freeze: (int) number of layers to freeze in network
    """

    net = {}
    current = input_image

    for i, layer_name in enumerate(VGG19_LAYERS):

        if i < num_freeze:
            freeze = True
        else:
            freeze = False

        kind = layer_name[:4]

        if kind == 'conv':

            weights = parameter_dict['w' + layer_name]
            bias = parameter_dict['b' + layer_name].reshape(-1)
            current = _conv_layer(current, weights, bias, layer_name, freeze)

        elif kind == 'relu':
            current = tf.nn.relu(current)

        elif kind == 'pool':
            current = _pool_layer(current)

        net[layer_name] = current

    assert len(net) == len(VGG19_LAYERS)

    return net

def _conv_layer(input, weights, bias, layer_name, freeze):

    """
    Create a conv-layer from the input parameters and returns it.

    Args:
        input: (tensor) Input to the conv layer
        weights: (numpy array) Weight matrix for conv layer
        bias: (numpy array) Bais vector for layer
        layer_name: (string) Name of the layer
        freeze: (bool) tells whether layer should be constant or trainable
    """

    if freeze:
        conv = tf.nn.conv2d(input, tf.constant(weights, name="w" + layer_name), strides=(1, 1, 1, 1),
            padding='SAME')
        bias = tf.constant(bias, name="b" + layer_name)
        return tf.nn.bias_add(conv, bias)

    else:
        w = tf.get_variable("w" + layer_name, initializer=tf.Variable(weights))
        b = tf.get_variable("b" + layer_name, initializer=tf.Variable(bias))

        conv = tf.nn.conv2d(input, w, strides=(1, 1, 1, 1),
                padding='SAME')

        return tf.nn.bias_add(conv, b)

def _pool_layer(input):

    """
    Create a and returns a max pool layer

    Args:
        input: (tensor) Input to the max pool layer
    """

    return tf.nn.max_pool(input, ksize=(1, 2, 2, 1), strides=(1, 2, 2, 1),
            padding='SAME')

def preprocess(image, mean_pixel):

    """
    Subtract mean pixel value to an image

    Args:
        image: (numpy array) Image to subtract mean from
        mean_pixel: (int) mean pixel value to subtract
    """

    return image - mean_pixel

def unprocess(image, mean_pixel):

    """
    Subtract mean pixel value to an image

    Args:
        image: (numpy array) Image to subtract mean from
        mean_pixel: (int) mean pixel value to subtract
    """

    return image + mean_pixel

def save_parameters(sess, extra_parameters, file_name):

    """
    Saves the parameters trained in sess, in file 'trained_vgg_net.m'
    extra_parameters is a dictionary of additional parameters to save

    Args:
        sess: (tf session) Session to save computational graph from
        extra_parameters: (dict) Contains extra parameters neccessary for the network
        file_name: (string) Name of file
    """

    graph = tf.get_default_graph()
    parameter_dict = {}

    for i, layer_name in enumerate(VGG19_LAYERS):
        kind = layer_name[:4]
        if kind == 'conv':
            parameter_dict['w' + layer_name] = sess.run(graph.get_tensor_by_name('net/w' + layer_name + ':0'))
            parameter_dict['b' + layer_name] = sess.run(graph.get_tensor_by_name('net/b' + layer_name + ':0'))

    parameter_dict.update(extra_parameters)

    scipy.io.savemat(file_name, parameter_dict)

    return file_name


from os import walk
from os.path import splitext

def get_direction_file_name(path_dir):
    result = {}
    for root, dirs, files in walk(path_dir):
        for file in files:
            name, extension = splitext(file)
            if extension not in result:
                result[extension] = []
            result[extension].append(name)
    return result

test_path = './Resources'
file_path = './directory_traversal-report.txt'
all_extensions = get_direction_file_name(test_path)
with open(file_path, 'w') as file:
    for extension, files in sorted(all_extensions.items(), key=lambda x: x[0]):
        file.write(extension + '\n')
        for curr_file in files:
            file.write(f'- - - {curr_file}{extension}\n')

Python Advanced/File Handling Exercise/directory_traversal.py


"""Implementations of Python fundamental objects for xpython."""
import collections
import inspect
import linecache
import types
from copy import copy
from sys import stderr
from xdis import CO_GENERATOR, CO_ITERABLE_COROUTINE, iscode
from xdis.version_info import PYTHON3, PYTHON_VERSION_TRIPLE

if PYTHON_VERSION_TRIPLE >= (3, 4):
    from xpython.stdlib.types34 import _AsyncGeneratorWrapper
else:

    class _AsyncGeneratorWrapper:
        pass

import xpython.stdlib.inspect3 as inspect3
import xpython.stdlib.inspect2 as inspect2

import six

PY2 = not PYTHON3

def make_cell(value):
    # Thanks to Alex Gaynor for help with this bit of twistiness.
    # Construct an actual cell object by creating a closure right here,
    # and grabbing the cell object out of the function we create.
    fn = (lambda x: lambda: x)(value)
    if PYTHON3:
        return fn.__closure__[0]
    else:
        return fn.func_closure[0]

# It might be the case that this is more useful in Python 2.x
# which doesn't seem to show traceback of interpreted code.
# Python 3.x does this but it also shows junk at the end.
Traceback = collections.namedtuple("_Traceback", "tb_frame tb_lasti tb_lineno tb_next")
try:
    _Traceback.tb_frame.__doc__ = "frame object at this level"
    _Traceback.tb_lasti.__doc__ = "index of last attempted instruction in bytecode"
    _Traceback.tb_lineno.__doc__ = "current line number in Python source code"
    _Traceback.tb_next.__doc__ = "next inner traceback object (called by this level)"
except:
    pass

# Code with these names have an implicit .0 in them
COMPREHENSION_FN_NAMES = frozenset(
    ("<setcomp>", "<dictcomp>", "<listcomp>", "<genexpr>")
)

class Function:
    """Function(name, code, globals, argdefs, closure, vm,  kwdefaults={},
                annotations={}, doc=None, qualname=None)

    Create a function object in vm from a code object and a dictionary.
    The name string overrides the name from the code object.
    The optional argdefs tuple specifies the default argument values.
    The optional closure tuple supplies the bindings for free variables.

    In contrast to `types.Function`, parameters appear in the order
    the CPython generates them; also there is an additional parameter
    `vm` which appears last.

    As a convenience, in contrast to types.FunctionType we allow
    setting `kwdefaults` and `annotations`.

    Parameter vm should always be set. The caller should also set __qualname__
    as appropriate.
    """

    __slots__ = [
        "func_code",  # Python 2.x
        "func_name",
        "func_defaults",
        "func_closure",
        "__code__",  # Python 3.x
        "__name__",
        "__defaults__",
        "__kwdefaults__",
        "__closure__",
        # rest
        "func_globals",
        "func_locals",
        "func_dict",
        "__dict__",
        # "__doc__" is filled in by the doc comment above.
        "_vm",
        "_func",
    ]

    def __init__(
        self,
        name,
        code,
        globs,
        argdefs,
        closure,
        vm,
        kwdefaults={},
        annotations={},
        doc=None,
        qualname=None,
    ):
        self._vm = vm
        self.version = vm.version
        self.__doc__ = doc

        if name is not None and not isinstance(name, str):
            raise TypeError(
                "Function() argument 1 (name) must None or string, not %s" % type(name)
            )

        if not iscode(code):
            raise TypeError(
                "Function() argument 2 (code) must be code, not %s" % type(code)
            )

        if not isinstance(globs, dict):
            raise TypeError(
                "Function() argument 3 (argdefs) must be dict, not %s" % type(globs)
            )

        if closure is not None and not isinstance(closure, tuple):
            raise TypeError(
                "Function() argument 5 (closure) must None or tuple, not %s"
                % type(closure)
            )

        if not vm:
            raise TypeError("Function() argument 6 (vm) must be passed")

        # Function field names below change between Python 2.7 and 3.x.
        # We create attributes for both names. Other code in this file assumes
        # 2.7ish names, while bytecode for 3.x will use 3.x names.
        # TODO: be more stringent based on vm version.
        self.func_code = self.__code__ = code
        self.func_name = self.__name__ = name or code.co_name
        self.func_defaults = self.__defaults__ = tuple(argdefs) if argdefs else tuple()
        self.func_closure = self.__closure__ = closure

        self.func_globals = globs
        self.func_locals = vm.frame.f_locals
        self.__dict__ = {"version": vm.version, "_vm": vm}

        self.__doc__ = (
            code.co_consts[0] if hasattr(code, "co_consts") and code.co_consts else None
        )

        if vm.version >= (3, 0):
            self.__annotations__ = annotations
            self.__kwdefaults__ = kwdefaults
            if vm.version >= (3, 4):
                self.__qualname__ = qualname if qualname else self.__name__
            else:
                assert qualname is None
        else:
            assert annotations == {}
            assert kwdefaults == {}

        # In Python 3.x is varous generators and list comprehensions have a .0 arg
        # but inspect doesn't show that. In the various MAKE_FUNCTION routines,
        # we will detect this and store True in this field when appropriate.
        if not argdefs and self.__name__.split(".")[-1] in COMPREHENSION_FN_NAMES:
            self.has_dot_zero = True
        else:
            self.has_dot_zero = False

        # From byterun.py:
        #   Sometimes, we need a real Python function. This is for that.
        #
        #
        # An elaboration of the above pity comment may be helpful.
        # Until this project emulates more functions, we rely heavily
        # on some built-in, or standard library
        # functions. `__build_class__` is an example of a builtin;
        # `import` is another example.  Many of Python's standard
        # library inspect routines require native functions, not our
        # emulated classes and types.
        #
        # For the `inspect` module, we've started providing equivalent
        # alternatives, but overall more of this needs to be done.
        #
        # The intent in providing native functions is for use in type
        # testing, mostly. The functios should not be run, since that defeats our
        # ability to trace functions.
        kw = {"argdefs": self.func_defaults}
        if closure:
            kw["closure"] = tuple(make_cell(0) for _ in closure)

        if not isinstance(code, types.CodeType) and hasattr(code, "to_native"):
            try:
                code = code.to_native()
            except:
                pass

        if isinstance(code, types.CodeType):
            try:
                self._func = types.FunctionType(code, globs, **kw)
                if vm.version >= 3.0:
                    # Above, types.FunctionType() above doesn't allow passing
                    # in the following attributes, so we set them as
                    # assignments below.
                    self._func.__kwdefaults__ = kwdefaults
                    self._func.__annotations__ = annotations
                    pass
            except:
                self._func = None
        else:
            # cross version interpreting... FIXME: fix this up
            self._func = None

    def __repr__(self):  # pragma: no cover
        return "<Function %s at 0x%08x>" % (self.func_name, id(self))

    def __get__(self, instance, owner):
        if instance is not None:
            return Method(instance, owner, self)
        version = self.version if hasattr(self, "version") else PYTHON_VERSION_TRIPLE
        if version < (3, 0):
            return Method(None, owner, self)
        else:
            return self

    def __call__(self, *args, **kwargs):
        if self.has_dot_zero:
            # D'oh! http://bugs.python.org/issue19611 Py2 doesn't know how to
            # inspect set comprehensions, dict comprehensions, or generator
            # expressions properly.  They are always functions of one argument,
            # so just do the right thing.
            assert len(args) == 1 and not kwargs, "Surprising comprehension!"
            callargs = {".0": args[0]}
        elif self._func and self.version[:2] == PYTHON_VERSION_TRIPLE[:2]:
            # Perhaps this branch can go and we just use the others.
            # It will require a *lot* more code from inspect.py to be added:
            # classes Signature, Parameter, etc.
            callargs = inspect.getcallargs(self._func, *args, **kwargs)

            # The problem with the above is that we are testing with self._func
            # the function may have changed dynamically.
            # See 3.7.7. test_keywordonlyarg.py

            # To catch dynamic changes, we'll run a second check
            if self.version >= (3, 0):
                inspect3.getcallargs(self, *args, **kwargs)
            else:
                inspect2.getcallargs(self, *args, **kwargs)
        else:
            if self.version >= (3, 0):
                callargs = inspect3.getcallargs(self, *args, **kwargs)
            else:
                callargs = inspect2.getcallargs(self, *args, **kwargs)

        frame = self._vm.make_frame(
            self.func_code, callargs, self.func_globals, {}, self.__closure__
        )
        if self.__code__.co_flags & CO_GENERATOR:
            qualname = self.__qualname__ if self._vm.version >= (3, 4) else None
            gen = Generator(
                g_frame=frame, name=self.__name__, qualname=qualname, vm=self._vm
            )
            if self.__code__.co_flags & CO_ITERABLE_COROUTINE:
                gen = _AsyncGeneratorWrapper(gen)
                frame.generator = gen
                return gen

            frame.generator = gen
            retval = gen
        else:
            retval = self._vm.eval_frame(frame)
        return retval

# FIXME: go over. Not sure how close This is supposed to be
# like type.MethodType
class Method(object):
    """Create a bound instance method object."""

    def __init__(self, obj, _class, func):
        self.__doc__ = obj.__doc__
        self.im_self = obj
        self.im_class = _class
        self.im_func = func

        if hasattr(func, "func_code"):
            self.func_code = func.func_code
        if hasattr(func, "__name__"):
            self.__name__ = func.__name__
        if hasattr(func, "__code__"):
            self.__code__ = func.__code__

        # This causes failure
        # self.__name__ = obj.__name__

    def __repr__(self):  # pragma: no cover
        name = "%s.%s" % (self.im_class.__name__, self.im_func.func_name)
        if self.im_self is not None:
            return "<Bound Method %s of %s>" % (name, self.im_self)
        else:
            return "<Unbound Method %s>" % (name,)

    def __call__(self, *args, **kwargs):
        if self.im_self is not None:
            return self.im_func(self.im_self, *args, **kwargs)
        else:
            return self.im_func(*args, **kwargs)

class Cell(object):
    """A fake cell for closures.

    Closures keep names in scope by storing them not in a frame, but in a
    separate object called a cell.  Frames share references to cells, and
    the LOAD_DEREF and STORE_DEREF opcodes get and set the value from cells.

    This class acts as a cell, though it has to jump through two hoops to make
    the simulation complete:

        1. In order to create actual FunctionType functions, we have to have
           actual cell objects, which are difficult to make. See the twisty
           double-lambda in __init__.

        2. Actual cell objects can't be modified, so to implement STORE_DEREF,
           we store a one-element list in our cell, and then use [0] as the
           actual value.

    """

    def __init__(self, value):
        self.contents = value

    def get(self):
        return self.contents

    def set(self, value):
        self.contents = value

class Block(object):
    """
    Block(type, handler, level)

    The equivalent of CPython's PyFrame_BlockSetup()

    The are used in "try" and "with" statements; before Python 3.8 also in opcodes
    associated with `for` (`SETUP_LOOP`) and `except` (`SETUP_EXCEPT`).

    From Python Include/frameobject.h:

    int b_type;                 /* what kind of block this is */
    int b_handler;              /* where to jump to find handler */
    int b_level;                /* value stack level to pop to */

    """

    def __init__(self, type, handler, level):
        self.type = type
        self.handler = handler
        self.level = level
        return

    def __repr__(self):
        if self.handler is None:
            return "<Block type: %s, stack level: %d" % (self.type, self.level)
        else:
            return "<Block type: %s, end offset: @%d, stack level: %d" % (
                self.type,
                self.handler,
                self.level,
            )

class Frame(object):
    def __init__(
        self,
        f_code,
        f_globals,
        f_locals,
        f_back,
        version=PYTHON_VERSION_TRIPLE,
        closure=None,
    ):
        self.f_code = f_code
        self.f_globals = f_globals
        self.f_locals = f_locals
        self.f_back = f_back
        self.stack = []
        self.f_trace = None

        # event args is used in tracing/debugging callback.
        self.event_flags = None

        # brkpt is a mapping bytecode offset to the opcode value that was
        # smasshed by overwriting it with the pseudo opcode BRKPT.
        # After a breakpoint is serviced, this opcode needs to be run.
        self.brkpt = {}

        if f_back and f_back.f_globals is f_globals:
            # If we share the globals, we share the builtins.
            self.f_builtins = f_back.f_builtins
        else:
            try:
                self.f_builtins = f_globals["__builtins__"]
                if hasattr(self.f_builtins, "__dict__"):
                    self.f_builtins = self.f_builtins.__dict__
            except KeyError:
                # No builtins! Make up a minimal one with None.
                self.f_builtins = {"None": None}

        self.f_lineno = f_code.co_firstlineno

        # Python 2.2.3 initializes this to 0. But by 2.4.6 it is initialized to -1.
        # Note that this has to be coordinated with parse_byte_and_args() of pyvm.py
        # and other places which is why we don't set it to the more correct -1.
        self.f_lasti = -1

        if f_code.co_cellvars:
            self.cells = {}
            if not f_back.cells:
                f_back.cells = {}
            for var in f_code.co_cellvars:
                # Make a cell for the variable in our locals, or None.
                cell = Cell(self.f_locals.get(var))
                f_back.cells[var] = self.cells[var] = cell
        else:
            self.cells = None

        if f_code.co_freevars:
            if not self.cells:
                self.cells = {}
            for i, var in enumerate(f_code.co_freevars):
                if closure:
                    # print("XXX", f_code.co_freevars[i], closure[i].get())
                    # if f_code.co_freevars[i] == "c" and  closure[i].get() == 5:
                    #     from trepan.api import debug; debug()
                    self.cells[var] = closure[i]
                else:
                    # FIXME: this branch is probably wrong.
                    # Also check all calls of Frame and make_frame() in vm to ensure we
                    # pass a function's closure attribute.
                    assert isinstance(f_back.cells[i], Cell), "f_back.cells[%d]: %r" % (
                        i,
                        f_back.cells[i],
                    )
                    self.cells[var] = f_back.cells[var]
                pass
            pass

        self.block_stack = []
        self.generator = None
        self.version = version

        # These are sentinal or bogus values to start out.
        # eval_frame will adjust inst_index.
        self.inst_index = -1
        self.fallthrough = False
        self.last_op = None
        return

    def __repr__(self):  # pragma: no cover
        return "<Frame at 0x%08x: %r:%d @%d>" % (
            id(self),
            self.f_code.co_filename,
            self.f_lineno,
            self.f_lasti,
        )

    def line_number(self):
        """Get the current line number the frame is executing."""
        # We don't keep f_lineno up to date, so calculate it based on the
        # instruction address and the line number table.
        lnotab = self.f_code.co_lnotab
        byte_increments = six.iterbytes(lnotab[0::2])
        line_increments = six.iterbytes(lnotab[1::2])

        byte_num = 0
        line_num = self.f_code.co_firstlineno

        for byte_incr, line_incr in zip(byte_increments, line_increments):
            if isinstance(byte_incr, str):
                byte_incr = ord(byte_incr)

            byte_num += byte_incr
            if byte_num > self.f_lasti:
                break
            if isinstance(line_incr, str):
                line_incr = ord(line_incr)

            line_num += line_incr

        return line_num

class Traceback(object):
    def __init__(self, frame):
        self.tb_next = frame.f_back
        self.tb_lasti = frame.f_lasti
        self.tb_lineno = frame.f_lineno
        self.tb_frame = frame

    # Note: this can be removed when we have our own compatibility traceback.
    def print_tb(self, limit=None, file=stderr):
        """Like traceback.tb, but is a method."""
        tb = self
        while tb:
            f = tb.tb_frame
            filename = f.f_code.co_filename
            lineno = f.line_number()
            print(
                '  File "%s", line %d, in %s' % (filename, lineno, f.f_code.co_name),
                file=file,
            )
            linecache.checkcache(filename)
            line = linecache.getline(filename, lineno, f.f_globals)
            if line:
                print("    " + line.strip(), file=file)
            tb = tb.tb_next

def traceback_from_frame(frame):
    tb = None

    while frame:
        next_tb = Traceback(copy(frame))
        next_tb.tb_next = tb
        tb = next_tb
        frame = frame.f_back
    return tb

class Generator(object):
    def __init__(self, g_frame, name, qualname, vm):
        self.gi_frame = g_frame
        self.vm = vm
        self.name = vm
        self.started = False
        self.finished = False
        self.gi_running = False
        self.gi_code = g_frame.f_code
        self.__name__ = g_frame.f_code.co_name
        self.__qualname__ = qualname if g_frame.version >= (3, 4) else None

    def __iter__(self):
        return self

    def next(self):
        return self.send(None)

    def send(self, value=None):
        if not self.started and value is not None:
            raise TypeError("Can't send non-None value to a just-started generator")
        self.gi_frame.stack.append(value)
        self.started = True
        self.running = True
        val = self.vm.resume_frame(self.gi_frame)
        if self.finished:
            self.running = False
            raise StopIteration(val)
        return val

    __next__ = next

if __name__ == "__main__":
    frame = Frame(
        traceback_from_frame.__code__, globals(), locals(), None,
        PYTHON_VERSION_TRIPLE
    )
    print(frame)

    class Foo(object):
        "Class Foo docstring"

        def bar(self):
            "This is a docstring"
            return

    foo = Foo()
    myMfoo = Method(foo.bar, Foo, Foo.bar)
    Mfoo = types.MethodType(foo.bar, Foo)
    # Should __name__, _func and __self__ match?
    for attr in "__doc__".split():
        assert getattr(Mfoo, attr) == getattr(myMfoo, attr), attr

    for attr in "__name__ __doc__ __qualname__".split():
        print(getattr(foo.bar, attr), attr)
        assert getattr(foo.bar, attr) == getattr(myMfoo.im_func, attr), attr


# Напишите программу, которая принимает две строки вида “a/b” - дробь с числителем и знаменателем.
# Программа должна возвращать сумму и произведение* дробей. Для проверки своего кода используйте модуль fractions.

from math import gcd
import fractions

a1, b1 = map(int, input("Первая дробь через /: ").split('/'))
a2, b2 = map(int, input("Вторая дробь через /: ").split('/'))

if b1 == b2:
    print('{}/{}'.format(a1+a2, b1))
else:
    b3 = int(b1*b2/gcd(b1, b2))
    a3 = int(b3/b1*a1+b3/b2*a2)
    res = gcd(a3, b3)
    res1 = int(a3/res)
    res2 = int(b3/res)
    print('Сумма {}/{}'.format(res1, res2))

'''
f1 = fractions.Fraction(1, 3)
f2 = fractions.Fraction(4, 5)
print(f1 + f2)
'''


from django.test import TestCase
from rest_framework import status
from faker import Faker
from rest_framework.test import APIClient
from django.urls import reverse

from symptoms.tests.factories import HistoryFactory
from users.tests.factories import UserFactory
from symptoms.models import Sintoma, Historial
from alergias.utils import get_random_choices
from symptoms.serializers import HistorialSerializer

fake = Faker()

class TestHistory(TestCase):
    fixtures = ['sintomas_categorias.json', 'sintomas']

    @classmethod
    def setUp(self):
        self.history_url = reverse('historial-list')
        self.client_test = APIClient()
        self.user = UserFactory()
        self.client_test.force_authenticate(self.user)
        symptoms_id = [symptom.id for symptom in Sintoma.objects.all()]
        self.symptoms_selected = get_random_choices(symptoms_id, 5)

    def test_create_history(self):
        response = self.client_test.post(
            self.history_url,
            {
                'sintomas': self.symptoms_selected,
            }
        )

        self.assertEqual(response.status_code, status.HTTP_201_CREATED)

        db_history = HistorialSerializer(Historial.objects.first()).data
        response_history = response.data

        self.assertEqual(response_history, db_history)

    def test_create_history_with_empty_symptoms(self):
        response = self.client_test.post(
            self.history_url
        )

        self.assertEqual(response.status_code, status.HTTP_201_CREATED)

        db_history = HistorialSerializer(Historial.objects.first()).data
        response_history = response.data

        self.assertEqual(response_history, db_history)

    def test_get_history(self):
        HistoryFactory.create_batch(10, symptoms=self.symptoms_selected, usuario=self.user)
        response = self.client_test.get(self.history_url)
        self.assertEqual(response.status_code, status.HTTP_200_OK)

        db_history = HistorialSerializer(Historial.objects.all(), many=True).data
        response_history = response.data

        self.assertEqual(response_history, db_history)

    def test_delete_symptom(self):
        HistoryFactory(symptoms=self.symptoms_selected, usuario=self.user)
        history_id = Historial.objects.first().id

        response = self.client_test.delete(f'{self.history_url}{history_id}/')
        self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT)
        self.assertIsNone(Historial.objects.first())


import threading
import time
import random

# 初始值
gMoney = 1000

# 生产总值
gTotal_Loop = 10

# 当前产生的数量值
gLoop = 0

# 创建锁
look = threading.Lock()

# 生产者
class Producers(threading.Thread):
    def run(self):
        global gMoney
        global gLoop
        while True:
            money = random.randint(100,1000)    #随机产生100-1000的数，并添加到初值当中

            look.acquire()
            # 判断，如果生产数值大于等于总数值，则退出循环
            if gLoop >= gTotal_Loop:
                look.release()
                break
            gMoney += money
            print('生产了：{0}，剩余：{1}'.format(money,gMoney))
            gLoop += 1  #每生产一次，数值就+1
            look.release()
            time.sleep(0.5)
# 消费者
class Consumer(threading.Thread):
    def run(self):
        global gMoney
        while True:
            money = random.randint(100,1000)

            look.acquire()
            # 待消费的数值大于或者等于时才消费
            if gMoney >= money:
                gMoney -= money
                print('消费了：{0}，剩余：{1}'.format(money,gMoney))
            else:
                # 判断，如果余数不足的情况下，判断生产的总数是否大于等于执行总数，如果是则退出，不用一直判断了
                if gLoop >= gTotal_Loop:
                    look.release()
                    break
                print('余额不足，要消费的数额是：{0}'.format(money))
            look.release()
            time.sleep(0.5)

def main():
    # 创建3个消费者，进行消费
    for x in range(3):
        t1 = Consumer()
        t1.start()

    # 创建5个生产者进行生产
    for x in range(5):
        t1 = Producers()
        t1.start()

if __name__ == '__main__':
    main()


from flask import Flask, request, jsonify
from flask_cors import CORS
from database_manager import DatabaseManager
from course_tracker import CourseTracker
from sentiment_analyzer import SentimentAnalyzer
import collections

app = Flask(__name__)
CORS(app)

@app.route("/word_cloud", methods=['GET'])
def word_cloud():
    query = request.args.get("query")
    if query is None:
        return jsonify({"error": "missing query"}), 400

    db = DatabaseManager()
    comments = db.comments_containing(query)
    words = [word.lower() for c in comments for word in c.content.split()]
    counts = collections.Counter(words).most_common(25)
    return jsonify(dict(counts))

@app.route("/courses_by_popularity", methods=['GET'])
def courses_by_popularity():
    course_tracker = CourseTracker()
    db = DatabaseManager()
    analyzer = SentimentAnalyzer()
    sentiments = []
    for course in course_tracker.get_all_courses():
        course_comments = db.comments_containing(course.name)
        if len(course_comments) == 0:
            continue
        course_sentiments = [
            analyzer.analyze_sentiment(c.content) for c in course_comments
        ]
        avg_sentiment = sum(course_sentiments) / len(course_sentiments)
        sentiments.append({
            "course": course.name,
            "avg_sentiment": avg_sentiment
        })

    return jsonify(
        sorted(sentiments, key=lambda x: x["avg_sentiment"], reverse=True))

@app.route("/most_upvoted", methods=['GET'])
def most_upvoted():
    query = request.args.get("query", )
    n = request.args.get("n", type=int)
    if query is None:
        return jsonify({"error": "missing query"}), 400
    if n is None:
        return jsonify({"error": "missing n"}), 400

    db = DatabaseManager()
    comments = db.most_upvoted_comments_containing(query, n)
    comments.sort(key=lambda x: x.votes, reverse=True)
    return jsonify([c.to_dict() for c in comments])


# import websocket
# import json
# import sys, getopt
# try:
#     import thread
# except ImportError:
#     import _thread as thread
# from collections import deque

# queue = deque()
# websocket_params = {
#     'type': 'unsubscribe',
#     'product_ids': ['BTC-USD'],
#     'channels': [
#         {
#             'name': 'ticker'
#         }
#     ]
# }

# def on_message(ws, message):
#     queue.append(message['price'])

# def on_error(ws, error):
#     print(error)

# def on_close(ws):
#     print("### closed ###")

# def on_open(ws):
#     def run(*args):
#         ws.send(json.dumps(websocket_params))
#     thread.start_new_thread(run, ())

# def run():
#     print('run')
#     ws.run_forever()

# websocket.enableTrace(True)
# ws = websocket.WebSocketApp("wss://ws-feed.pro.coinbase.com",
#                                 on_open = on_open,
#                                 on_message = on_message,
#                                 on_error = on_error,
#                                 on_close = on_close)
# ws.on_open = on_open

# run()

##########

# class A:
#     def printA(self):
#         print('A')
#         def printB():
#             print('B')
#         printB()
# a = A()
# a.printA()

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

# vals = [1,2,3]
# def get_val():
#     i = 0
#     while True:
#         i = (i+1) % 3
#         yield vals[i]

# count = 0
# for i in get_val():
#     print(i)
#     count += 1
#     if count >= 100:
#         break

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

import json
import asyncio
import websockets
from websockets import WebSocketServerProtocol

# @asyncio.coroutine
# def hello():
#     websocket_params = {
#         'type': 'subscribe',
#         'product_ids': ['BTC-USD'],
#         'channels': ['ticker']
#     }
#     websocket = yield from websockets.connect('wss://ws-feed.pro.coinbase.com')
#     print('1')
#     yield from websocket.send(json.dumps(websocket_params))
#     print('2')
#     while True:
#         greeting = yield from websocket.recv()
#         print(greeting)

# asyncio.get_event_loop().run_until_complete(hello())

async def hello():
    websocket_params = {
        'type': 'subscribe',
        'product_ids': ['BTC-USD'],
        'channels': ['ticker']
    }
    async with websockets.connect('wss://ws-feed.pro.coinbase.com') as websocket:
        await websocket.send(json.dumps(websocket_params))
        while True:
            response = await websocket.recv()
            yield response

async def loop():
    async for i in hello():
        print(i)

asyncio.get_event_loop().run_until_complete(loop())


class Solution(object):
    def findErrorNums(self, nums):
        length = len(nums)
        count = [0] * (length + 1)
        for x in nums:
            count[x] += 1
        for x in range(1, len(nums) + 1):
            if count[x] == 2:
                twice = x
            if count[x] == 0:
                never = x
        return twice, never