import requests

product_id = input("Give me pk of Item ")

endpoint = f"http://127.0.0.1:8000/api/products/{int(product_id)}/delete/"

get_response = requests.delete(endpoint)

print("-"*20)

print(get_response.status_code)


import tensorflow as tf
import numpy as np
from os import listdir
from os.path import isfile, join
import cv2

onlyfiles = [f for f in listdir('preprocessed') if isfile(join('preprocessed', f))]
names = []

for i in onlyfiles:
    names.append(i[0])
img =[]

for index in range(len(onlyfiles)):
    img.append(cv2.imread("preprocessed/" +  onlyfiles[index],1))

arr = np.empty((len(img),img[0].shape[0],img[0].shape[1],img[0].shape[2]))
arr1 = np.empty((len(img),img[0].shape[0],img[0].shape[1],img[0].shape[2]))
for i in range(len(img)):
    arr[i] = np.array(img[i])
    arr1[i] = cv2.resize(arr[i],(img[0].shape[1],img[0].shape[0]))

arr2 = np.empty(len(names))
for i in range(len(names)):
    arr2[i] = ord(names[i])-ord('A')
training_images = arr1[0:6000]
training_labels = arr2[0:6000]
test_images = arr1[6000:len(arr1)]
test_labels = arr2[6000:len(arr2)]
training_images=training_images/255.0
test_images=test_images/255.0
print(training_labels[1])
print(names[1])
cv2.imshow('img1',training_images[1])

#training_images = training_images/255.0
#test_images = test_images/255.0
model = tf.keras.models.Sequential([
  tf.keras.layers.Conv2D(64, (3,3), activation='relu', input_shape=(img[0].shape[0],img[0].shape[1],img[0].shape[2])),
  tf.keras.layers.MaxPooling2D(2, 2),
  tf.keras.layers.Conv2D(64, (3,3), activation='relu'),
  tf.keras.layers.MaxPooling2D(2,2),
  tf.keras.layers.Flatten(),
  tf.keras.layers.Dense(128, activation='relu'),
  tf.keras.layers.Dense(26, activation='softmax')
])

model.compile(optimizer = 'adam', loss = 'sparse_categorical_crossentropy', metrics=['accuracy'])
model.fit(training_images,training_labels,epochs = 5)

test_loss = model.evaluate(test_images, test_labels)
model.save('my_model.h5')
#index = 521
#cv2.imshow('image1',img[index])
#print(names[index])
#cv2.waitKey(0)


import os
import webbrowser
import subprocess
import pyttsx3
import speech_recognition as sr
import random
import datetime

engine =pyttsx3.init()
voices = engine.getProperty('voices')
rate = engine.getProperty('rate')
engine.setProperty('rate', 170)
r=sr.Recognizer()

random.seed()
#asking to continue dictionary///////
asktocont={1:"Do you want to continue?", 2:"Something else?", 3:"Maybe, you want something?",4:"Please, say no, i want  to go!"}
amount_asktocont=0
for i in asktocont:
	amount_asktocont+=1

#GREETINGS //////////
greetings={1:"Hello, my name is Hans!",2:"Hi, Hans is here!",3:"Welcome to my kingdom,buddy!",4:"Greetings, my boss!"}
#amount of frases////////////////////
amount = 0
for i in greetings:
	amount+=1
num = random.randint(1,amount)
if num==1:
	engine.say(greetings[1])
	engine.runAndWait()
if num ==2:
	engine.say(greetings[2])
	engine.runAndWait()
if num ==3:
	engine.say(greetings[3])
	engine.runAndWait()
if num ==4:
	engine.say(greetings[4])
	engine.runAndWait()
ans = "yes"
while ans == "yes":

		#LISTENING///////////
	with sr.Microphone() as source:
		r.adjust_for_ambient_noise(source)
		engine.say("What can i do for you?")
		engine.runAndWait()
		print("What can i do for you?: ")
		audio= r.listen(source)
	try:
		command=r.recognize_google(audio)
		engine.say(command)
		engine.runAndWait()
		print(command)
	except sr.UnknownValueError:
		print("Could not undertand audio")
	except sr.RequestError as e:
		print("Could not request results; {0}".format(e))

		#COMMANDS////////////////////////////////////

		#what can u do////////////
	if command == "commands" or command == "show the commands" or command == "command" or command == "what can you do" or command == "what do you can":
		print("Aviable commands:")
		engine.say("Here you can see the avaible commands.")
		engine.runAndWait()
		print("Open the browser")
		print("Open link")
		print("Search the web")
		print("Open telegram")
		print("Tell me the date")
		print("What is the time")
		print("Today or this day")

		#date/////////////////
	if command == "tell me the date" or command == "date" or command == "the date":
		datevar = datetime.date.today().strftime("%B %d, %Y")
		print(datevar)
		engine.say(datevar)
		engine.runAndWait()

		#time/////////////////////
	if command  == "what is the time" or command == "time" or command == "show time":
		datevar = datetime.datetime.now().strftime("%I:%M%p")
		print(datevar)
		engine.say(datevar)
		engine.runAndWait()

		#everything about this day/////////////
	if command == "today" or command == "this day":
		datevar = datetime.datetime.now().strftime("%I:%M%p on %B %d, %Y")
		print(datevar)
		engine.say("Today is "); engine.say(datevar)
		engine.runAndWait()

		#open the browser///////////////////
	if command == "open the browser" or command == "browser":
		engine.say("Okay, my boss!")
		engine.runAndWait()
		webbrowser.open('http://google.com')

		#open the link////////////////////////
	if command == "open link" or command == "link":
		link = input("Enter your link: ")
		webbrowser.open(link)

		#serch the web////////////////////////
	if command == "search the web" or command == "search" or command == "web" or command == "search web":
		with sr.Microphone() as source:
			r.adjust_for_ambient_noise(source)
			engine.say("What do you want to search?")
			engine.runAndWait()
			print("What do you want to search?")
			audio= r.listen(source)
		try:
			whattosearch = r.recognize_google(audio)
			engine.say(whattosearch)
			engine.runAndWait()
			print(whattosearch)
		except sr.UnknownValueError:
			print("Could not undertand audio")
		except sr.RequestError as e:
			print("Could not request results; {0}".format(e))
		url = "https://www.google.com.ua/search?q={0}".format(whattosearch)
		webbrowser.open(url)

		#open telegram/////////////////
	if command == "open telegram" or command == "telegram":
		os.system("telegram-desktop")

	#do you want to continue////////////////
	with sr.Microphone() as source:
		r.adjust_for_ambient_noise(source)
		#choosing what to say/////////////4
		num=random.randint(1,amount_asktocont)
		engine.say(asktocont[num])
		engine.runAndWait()
		print(asktocont[num])
		audio= r.listen(source)
	try:
		ans=r.recognize_google(audio)
		print(ans)
	except sr.UnknownValueError:
		print("Could not undertand audio")
		break
	except sr.RequestError as e:
		print("Could not request results; {0}".format(e))

#ENDING////////////////
endings = {1:"Goodbye, boss, i love you!", 2:"See you later!", 3:"Have a nice day", 4:"So, i can do everything i want?"}
#amount/////////
amount = 0
for i in endings:
	amount+=1
num = random.randint(1,amount)
engine.say(endings[num])
engine.runAndWait()


"""
Stacked Autoencoder
"""
from collections import OrderedDict
import numpy as np

import tensorflow as tf
from tensorflow.contrib import layers, framework

def show_reconstructed_digits(X, outputs, model_path = None, n_test_digits = 2):
    with tf.Session() as sess:
        if model_path:
            saver.restore(sess, model_path)
        X_test = mnist.test.images[:n_test_digits]
        outputs_val = outputs.eval(feed_dict={X: X_test})

    fig = plt.figure(figsize=(8, 3 * n_test_digits))
    for digit_index in range(n_test_digits):
        plt.subplot(n_test_digits, 2, digit_index * 2 + 1)
        plot_image(X_test[digit_index])
        plt.subplot(n_test_digits, 2, digit_index * 2 + 2)
        plot_image(outputs_val[digit_index])

class tfStackedAutoEncoder(object):
    """
    Train a Stacked AE in a single graph, using multiple "phases"
    """

    def __init__(self, h_layers, lr=1e-2, l2_pen=1e-4, nb_epoch=100,
            batch_size=None, act_fn='elu'):
        self.h_layers = h_layers
        self.lr = lr
        self.nb_epoch = nb_epoch
        self.batch_size = batch_size
        self.l2_pen = l2_pen

        if act_fn == 'elu':
            self.act_fn=tf.nn.elu
        elif act_fn == 'relu':
            self.act_fn = tf.nn.relu
        else:
            self.act_fn = act_fn

        self.reg_fn = layers.l2_regularizer(l2_pen)
        self.init_fn = layers.variance_scaling_initializer()

    def fit(self, X):
        X_data = X

        X = tf.placeholder(tf.float32, shape=(None,X_data.shape[-1]))

        # create weights/bias dictionary
        layer_shapes = [X_data.shape[1]] + self.h_layers + [X_data.shape[1]]
        w_dict = OrderedDict()
        b_dict = OrderedDict()
        with tf.name_scope('vars'):
            for i in range(len(layer_shapes)-1):
                w_name = 'w_%i'%i
                b_name = 'b_%i'%i
                w_shape = (layer_shapes[i],layer_shapes[i+1])
                w_dict[w_name] = tf.Variable(self.init_fn(w_shape), dtype=tf.float32, name=w_name)
                b_shape = layer_shapes[i+1]
                b_dict[b_name] = tf.Variable(tf.zeros(b_shape), dtype=tf.float32, name=b_name)

        # create layers
        layers = {}
        layers[0] = X
        with tf.name_scope('layers'):
            for i, (w,b) in enumerate(zip(w_dict.values(),b_dict.values())):
                if i < len(w_dict)-1:
                    layers[i+1] = self.act_fn(tf.matmul(layers[i],w)+b)
                else:
                    layers[i+1] = tf.matmul(layers[i],w)+b

        # create phases
        mid_idx = int((len(w_dict)-1) / 2)
        n_phases = mid_idx
        phase_training_ops = []

        for phase_idx in range(n_phases):
            pass

if __name__=='__main__':
    tf.reset_default_graph()
    from keras.datasets.mnist import load_data
    (xtrain,xtest),(ytrain,ytest) = load_data()
    from sklearn.preprocessing import StandardScaler, MinMaxScaler
    xtrain = MinMaxScaler((0,1)).fit_transform(xtrain.astype('float64').reshape(xtrain.shape[0],-1))

    h_layers = [300, 150, 300]
    act_fn = 'elu'
    lr = 1e-2
    l2_pen = 1e-4
    sae = tfStackedAutoEncoder(h_layers=h_layers)
    layers = sae.fit(xtrain)


from matplotlib import pyplot as plt

stat_files = [
    ('Libre', [
        'stats_dtlz1_3.txt',
        ]),
    ('NSGA2', [
        'stats_dtlz1_3__nsga2_1.txt',
        'stats_dtlz1_3__nsga2_2.txt',
        'stats_dtlz1_3__nsga2_3.txt',
    ]),
]

# Get color
def get_color():
    for color in ['b', 'g', 'r']:
        yield color
clrs = get_color()

def show_stats_for_one_file(alg, stats):  # evals, hv, uni
    plt.plot([e[0] for e in stats], [e[1] for e in stats], clrs.next() + '-', label=alg, linewidth=2)

def show_stats_for_files(alg, stats):  # (evals, [hvs], [uni])
    clr = clrs.next()
    plt.plot([e[0] for e in stats], [min(e[1]) for e in stats], clr + '-', label=alg, linewidth=2)
    plt.plot([e[0] for e in stats], [sum(e[1])/len(e[1]) for e in stats], clr + '-', label=alg)
    plt.plot([e[0] for e in stats], [max(e[1]) for e in stats], clr + '-', label=alg, linewidth=2)
    plt.fill_between([e[0] for e in stats], [min(e[1]) for e in stats], [max(e[1]) for e in stats], color=clr, alpha='0.3')

def parse_stats_for_one_file(files):
    open_f = open(files[0], 'r')
    stats = []
    for line in open_f:
        stats.append([float(e) for e in line.split()])
    open_f.close()
    return stats

def parse_stats_for_files(fs):
    stats = []     # [ev, hv, uni]  [ev, hv, uni]  [ev, hv, uni]
    for f in fs:
        stats.append(parse_stats_for_one_file([f]))
    merged = []
    for i in range(len(stats[0])):
        merged.append((stats[0][i][0], [s[i][1] for s in stats], [s[i][2] for s in stats]))
    return merged

if __name__ == '__main__':
    for alg, files in stat_files:
        print('Showing', alg)
        if len(files) == 1:
            show_stats_for_one_file(alg, parse_stats_for_one_file(files))
        else:
            show_stats_for_files(alg, parse_stats_for_files(files))
    plt.ylabel('Hyper volume')
    plt.xlabel('Trials')
    plt.show()


import os
from typing import Union, Optional
import gridfs
import pika
import json

from flask import Flask, request, send_file, Response
from flask_pymongo import PyMongo
from bson.objectid import ObjectId

from auth import validate
from auth_svc import access
from storage import util

# Create server
server = Flask(__name__)

# Allow PyMongo to manage connections between server and mongo video/mp3 db (store video and converted mp3 files)
mongo_vid = PyMongo(server, uri="mongodb://host.minikube.internal:27017/videos")
mongo_mp3 = PyMongo(server, uri="mongodb://host.minikube.internal:27017/mp3s")

# Use MongoDB grid fs (grid file storage) (i.e. spec for storing large files in shards)
# (one collection stores file chunks, other collection stores metadata)
fs_vid = gridfs.GridFS(mongo_vid.db)
fs_mp3 = gridfs.GridFS(mongo_mp3.db)

# Create connection to RabbitMQ (queue to send messages for video processing jobs)
connection = pika.BlockingConnection(pika.ConnectionParameters(host="rabbitmq"))
channel = connection.channel()

# login route
@server.route("/login", methods=["POST"])
def login() -> Union[Optional[str], tuple[str, Optional[int]]]:
    # Attempt to log user in
    token, err = access.login(request)

    # Return result
    if err != None:
        return token
    else:
        return err

# video upload route
@server.route("/upload", methods=["POST"])
def upload() -> Union[str, tuple[str, int]]:
    # Attempt to valid user's provided JWT token
    valid_access, err = validate.validate_token(request)
    if err:
        return err

    # Deserialize JSON access string to Python string
    valid_access = json.loads(valid_access)

    # Check if user has admin privileges
    if valid_access["admin"]:
        if len(request.files) != 1:
            return "Only one file required", 400

        for f in request.files.values():
            # Upload file
            err = util.upload(f, fs_vid, channel, valid_access)

            # Return error
            if err:
                return err

        return "Upload successful", 200
    else:
        return "Unauthorized user", 401

# MP3 download route
@server.route("/download", methods=["GET"])
def download() -> Union[tuple[str, int], Response]:
    # Attempt to valid user's provided JWT token
    valid_access, err = validate.validate_token(request)
    if err:
        return err

    # Deserialize JSON access string to Python string
    valid_access = json.loads(valid_access)

    # Check if user has admin privileges
    if valid_access["admin"]:
        # Check that mp3 file ID exists
        fid = request.args.get("fid")
        if fid is None:
            return "File ID must be provided", 401

        # Retrieve MP3 file from fs_mp3
        try:
            mp3_file = fs_mp3.get(ObjectId(fid))
            return send_file(mp3_file, download_name=f"{fid}.mp3")
        except Exception as err:
            print(err)
            return "Internal server error", 400
    return "Unauthorized user", 401

if __name__ == "__main__":
    server.run(host="0.0.0.0", port=8080)


# -*- coding: utf-8 -*-
"""
Created on Sat Apr 10 03:09:12 2021

@author: Alice
"""

import os
import dash
import dash_table
import json
import numpy as np
import pandas as pd
import plotly.graph_objects as go
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output, State
from dash.exceptions import PreventUpdate
from plotly.offline import plot
from utils import diff_dashtable, get_table_data, update_table_data

app = dash.Dash(__name__)
app.title = 'MerryDining - Restaurant Portal'
statuses = ['empty', 'reserved', 'occupied']
diets = ['none', 'vegan', 'vegetarian', 'gluten-free', 'kosher', 'halal']
allergies = ['none', 'dairy', 'peanuts', 'soy', 'shellfish']
def layout_function():
    return html.Div([
    html.Div(id='topbar', children=[html.Img(id='icon', src='/assets/favicon.ico'),
                                    html.H5("MerryDining", 'title')]),
    dcc.Graph(id='choropleth'),

    dash_table.DataTable(
        id='restaurant-table',
        columns=[{"name": ["Table ID"], "id": "tableid"},
                 {"name": ["Status"], "id": "status", "presentation": "dropdown"},
                 {"name": ["Diet"], "id": "diet", "presentation": "dropdown"},
                 {"name": ["Allergy"], "id": "allergy", "presentation": "dropdown"}],
        editable=True,
        data=get_table_data().to_dict(orient='records'),
        dropdown={
            'status': {'options': [{'label': i, 'value': i} for i in statuses],
                     'clearable':False},
            'diet': {'options': [{'label': i, 'value': i} for i in diets],
                     'clearable':False},
            'allergy': {'options': [{'label': i, 'value': i} for i in allergies],
                        'clearable':False}
        }
    ),

    html.Br(),
    dcc.Store(id="diff-store"),
    html.Div(id="data-diff")
])

app.layout = layout_function

# track changes in restaurant table
@app.callback(
    [Output("diff-store", "data"),
     Output("data-diff", "children")],
    [Input("restaurant-table", "data_timestamp")],
    [State("restaurant-table", "data"),
     State("restaurant-table", "data_previous"),
     State("diff-store", "data")],
)
def capture_diffs(ts, data, data_previous, diff_store_data):
    if ts is None:
        raise PreventUpdate
    diff_store_data = diff_store_data or {}

    changed_rows = diff_dashtable(data, data_previous, 'tableid')
    diff_store_data[ts] = changed_rows
    if diff_store_data:
        response = []
        for row in changed_rows:
            response = update_table_data(row['tableid'], row['status'], row['diet'], row['allergy'])
        return diff_store_data, str(response)#str(changed_rows)

    return diff_store_data, "No Changes to DataTable"

# create and display restaurant map
@app.callback(
    Output(component_id="choropleth", component_property="figure"),
    Input("restaurant-table", "data"))
def display_choropleth(input_table):
    with open(os.path.join(os.path.dirname(__file__), 'map_full.geojson'), "r") as f:
        geo_world = json.load(f)

    # get data directly from table
    df = pd.DataFrame.from_dict(input_table)

    colorscales = [[0.0, 'rgb(255, 232.05, 214.2)'],
                   [0.5, 'rgb(255, 181.0, 130.1)'],
                   [1.0, 'rgb(255, 132.6, 51.0)']]
    tickdict = {"empty": 0.0, "reserved": 0.9, "occupied": 2.0}
    hover_template_choro="Table %{customdata[0]}" \
                         "<extra>Status: %{customdata[1]}
" \
                         "Diet: %{customdata[2]}
"\
                         "Allergies: %{customdata[3]}</extra>"

    df["status_z"] = df["status"].replace(tickdict)

    # Create figure
    fig = go.Figure(go.Choropleth(geojson=geo_world,
                                  locations=df['tableid'],
                                  z=df['status_z'],
                                  zmin=0,
                                  zmax=2,
                                  customdata=np.stack(([df['tableid'], df['status'], df['diet'], df['allergy']]), axis=-1),
                                  hovertemplate=hover_template_choro,
                                  text=df['tableid'],
                                  colorscale=colorscales,
                                  colorbar_tickvals=list(tickdict.values()),
                                  colorbar_ticktext=list(tickdict.keys()),
                                  colorbar_tickmode="array",
                                  colorbar_x=-0.03,
                                  colorbar_y=0,
                                  colorbar_yanchor="bottom",
                                  colorbar_thickness=10,
                                  colorbar_tickfont_family="Poppins",
                                  colorbar_title_text="Table Status",
                                  colorbar_title_font_family="Poppins"))
    fig.update_layout(dragmode=False,
                      font_family="Poppins",
                      margin={"r":0,"t":0,"l":0,"b":0})
    fig.update_geos(center=dict(lon=0.002, lat=0.002),
                    lataxis_range=[-0.005, 0.006],
                    lonaxis_range=[-0.005, 0.006],
                    visible=False)

    df_dots = pd.json_normalize(geo_world['features'])
    hover_template_scatter="Table %{customdata[0]}
" \
                         "Status: %{customdata[1]}
" \
                         "Diet: %{customdata[2]}
"\
                         "Allergies: %{customdata[3]}"
    # add dietary dots
    diet_colors = {'halal': '#76ac49', 'vegan': '#faff00',
                   'vegetarian': '#aeff6a', 'kosher':'#589ad6', 'gluten-free': '#fc620b'}
    for diet in list(diet_colors.keys()):
        df_dots_diet = df_dots[df['diet'].str.contains(diet)]
        df_diet = df[df['diet'].str.contains(diet)]
        fig.add_trace(go.Scattergeo(
            lon = df_dots_diet['properties.center'].apply(lambda x: x[0])+0.0001,
            lat = df_dots_diet['properties.center'].apply(lambda x: x[1]),
            name = diet,
            marker = dict(
                size = 20,
                opacity = 0.7,
                color = diet_colors[diet]),
            customdata=np.stack(([df_diet['tableid'], df_diet['status'],
                                  df_diet['diet'], df_diet['allergy']]), axis=-1),
            hovertemplate=hover_template_scatter))
    # add allergy dots
    allergy_colors = {'dairy': '#4ff4ff', 'peanuts': '#fff84f', 'soy': '#a9a53b',
                      'shellfish': '#942288'}
    for allergy in list(allergy_colors.keys()):
        df_dots_allergy = df_dots[df['allergy'].str.contains(allergy)]
        df_allergy = df[df['allergy'].str.contains(allergy)]
        fig.add_trace(go.Scattergeo(
            lon = df_dots_allergy['properties.center'].apply(lambda x: x[0])-0.0001,
            lat = df_dots_allergy['properties.center'].apply(lambda x: x[1]),
            name = allergy,
            marker = dict(
                size = 20,
                opacity = 0.7,
                color = allergy_colors[allergy]),
            customdata=np.stack(([df_allergy['tableid'], df_allergy['status'],
                                  df_allergy['diet'], df_allergy['allergy']]), axis=-1),
            hovertemplate=hover_template_scatter))
    return fig

if __name__ == '__main__':
    app.run_server(debug=True)


import sys
import os
import numpy as np
import matplotlib
matplotlib.use('Agg')
from matplotlib import pyplot as plt
from argparse import ArgumentParser

from clair.utils import setup_environment

def plot_tensor(ofn, XArray):
    plot = plt.figure(figsize=(15, 8))

    plot_min = -30
    plot_max = 30
    plot_arr = ["A+", "C+", "G+", "T+", "A-", "C-", "G-", "T-"]

    plt.subplot(4, 1, 1)
    plt.xticks(np.arange(0, 33, 1))
    plt.yticks(np.arange(0, 8, 1), plot_arr)
    plt.imshow(XArray[0, :, :, 0].transpose(), vmin=0, vmax=plot_max, interpolation="nearest", cmap=plt.cm.hot)
    plt.colorbar()

    plt.subplot(4, 1, 2)
    plt.xticks(np.arange(0, 33, 1))
    plt.yticks(np.arange(0, 8, 1), plot_arr)
    plt.imshow(XArray[0, :, :, 1].transpose(), vmin=plot_min, vmax=plot_max, interpolation="nearest", cmap=plt.cm.bwr)
    plt.colorbar()

    plt.subplot(4, 1, 3)
    plt.xticks(np.arange(0, 33, 1))
    plt.yticks(np.arange(0, 8, 1), plot_arr)
    plt.imshow(XArray[0, :, :, 2].transpose(), vmin=plot_min, vmax=plot_max, interpolation="nearest", cmap=plt.cm.bwr)
    plt.colorbar()

    plt.subplot(4, 1, 4)
    plt.xticks(np.arange(0, 33, 1))
    plt.yticks(np.arange(0, 8, 1), plot_arr)
    plt.imshow(XArray[0, :, :, 3].transpose(), vmin=plot_min, vmax=plot_max, interpolation="nearest", cmap=plt.cm.bwr)
    plt.colorbar()

    plot.savefig(ofn, dpi=300, transparent=True, bbox_inches='tight')
    plt.close(plot)

def create_png(args):
    f = open(args.array_fn, 'r')
    array = f.read()
    f.close()
    import re
    array = re.split("\n", array)
    array = [x for x in array if x]
    print(array)

    splitted_array = []
    for i in range(len(array)):
        splitted_array += re.split(",", array[i])

    print("splitted array length")
    print(len(splitted_array))
    print(splitted_array[0])
    # for i in range(len(splitted_array)):
    #     splitted_array[i] = int(splitted_array[i])

    XArray = np.array(splitted_array, dtype=np.float32).reshape((-1, 33, 8, 4))
    XArray[0, :, :, 1] -= XArray[0, :, :, 0]
    XArray[0, :, :, 2] -= XArray[0, :, :, 0]
    XArray[0, :, :, 3] -= XArray[0, :, :, 0]

    _YArray = np.zeros((1, 16))
    varName = args.name
    print("Plotting %s..." % (varName), file=sys.stderr)

    # Create folder
    if not os.path.exists(varName):
        os.makedirs(varName)

    # Plot tensors
    plot_tensor(varName+"/tensor.png", XArray)

def ParseArgs():
    parser = ArgumentParser(
        description="Visualize tensors and hidden layers in PNG")

    parser.add_argument('--array_fn', type=str, default="vartensors",
                        help="Array input")

    parser.add_argument('--name', type=str, default=None,
                        help="output name")

    args = parser.parse_args()

    if len(sys.argv[1:]) == 0:
        parser.print_help()
        sys.exit(1)

    return args

def main():
    args = ParseArgs()
    setup_environment()
    create_png(args)

if __name__ == "__main__":
    main()


from itertools import chain

from django.contrib.auth.models import User
from django import forms
from django.db.models import CharField, Value

from .models import Review, Ticket, UserFollows

def get_users_viewable_reviews(user: User):
    # Get it own reviews
    user_reviews = Review.objects.filter(user__username=user.username)
    user_reviews = user_reviews.annotate(
        content_type=Value('REVIEW', CharField()))
    return user_reviews

def get_users_viewable_tickets(user: User):
    # Get it own tickets
    user_tickets = Ticket.objects.filter(user__username=user.username)
    user_tickets = user_tickets.annotate(
        content_type=Value('TICKET', CharField()))
    return user_tickets

def get_followed_users_viewable_reviews(user: User):
    # Get reviews of followed users
    users_follow = UserFollows.objects.filter(user__username=user.username)
    followers_reviews = Review.objects.none()
    for user_follow in users_follow:
        user_follow_review = Review.objects.filter(
            user__username=user_follow.followed_user.username)
        user_follow_review = user_follow_review.annotate(
            content_type=Value('REVIEW', CharField()))
        followers_reviews = chain(followers_reviews, user_follow_review)
    return followers_reviews

def get_followed_users_viewable_tickets(user: User):
    # Get tickets of followed users
    users_follow = UserFollows.objects.filter(user__username=user.username)
    followers_tickets = Ticket.objects.none()
    for user_follow in users_follow:
        user_follow_ticket = Ticket.objects.filter(
            user__username=user_follow.followed_user.username)
        user_follow_ticket = user_follow_ticket.annotate(
            content_type=Value('TICKET', CharField()))
        followers_tickets = chain(followers_tickets, user_follow_ticket)
    return followers_tickets

def get_followed_users(user: User):
    # Get the list of all users followed by user
    users_follow = UserFollows.objects.filter(user=user)
    followed = []
    for user_follow in users_follow:
        followed.append(user_follow.followed_user)
    return followed

def get_users_subscriber(user: User):
    # Get the list of all users which follow the user
    users_follow = UserFollows.objects.filter(followed_user=user)
    followers = []
    for user_follow in users_follow:
        followers.append(user_follow.user)
    return followers

def get_user_by_id(id: str):
    return User.objects.filter(id=id)

def get_user_by_name(username: str):
    return User.objects.filter(username=username)

def get_users_by_name(username: str):
    return User.objects.filter(username__icontains=username)

def get_ticket_by_pk(pk: str):
    ticket = Ticket.objects.filter(pk=pk)
    ticket = ticket.annotate(
        content_type=Value('REVIEW', CharField()))
    return ticket

def get_review_by_pk(pk: str):
    review = Review.objects.filter(pk=pk)
    review = review.annotate(
        content_type=Value('REVIEW', CharField()))
    return review

def get_all_reviews():
    # Get all reviews
    reviews = Review.objects.all()
    reviews = reviews.annotate(
        content_type=Value('REVIEW', CharField()))
    return reviews

def save_ticket(request, form: forms):
    ticket = Ticket()
    ticket.title = form.cleaned_data["title"]
    ticket.description = form.cleaned_data["description"]
    ticket.user = request.user
    ticket.image = request.FILES.get('image_download', None)
    ticket.save()
    return ticket

def save_updated_ticket(request, form: forms, ticket: Ticket):
    ticket.title = form.cleaned_data["title"]
    ticket.description = form.cleaned_data["description"]
    image = request.FILES.get('image_download', None)
    if image is not None:
        ticket.image = image
    ticket.save()
    return ticket

def delete_ticket(ticket: Ticket):
    ticket.delete()

def save_review(request, form: forms):
    review = Review()
    if 'ticket_pk' in request.POST:
        review.ticket = get_ticket_by_pk(request.POST.get('ticket_pk'))[0]
        review.ticket.already_reviewed = True
    else:
        review.ticket = save_ticket(request, form)
    review.rating = form.cleaned_data["rating"]
    rating = int(review.rating)
    rating_empty_star = "12345"
    rating_full_star = rating_empty_star[:rating]
    rating_empty_star = rating_empty_star[rating:]
    review.rating_full_star = rating_full_star
    review.rating_empty_star = rating_empty_star
    review.headline = form.cleaned_data["headline"]
    review.body = form.cleaned_data["body"]
    review.user = request.user
    review.save()

def save_updated_review(request, form: forms, review: Review):
    if 'ticket_pk' in request.POST:
        review.ticket = get_ticket_by_pk(request.POST.get('ticket_pk'))[0]
        review.ticket.already_reviewed = True
    else:
        review.ticket = save_updated_ticket(request, form, review.ticket)
    review.rating = form.cleaned_data["rating"]
    rating = int(review.rating)
    rating_empty_star = "12345"
    rating_full_star = rating_empty_star[:rating]
    rating_empty_star = rating_empty_star[rating:]
    review.rating_full_star = rating_full_star
    review.rating_empty_star = rating_empty_star
    review.headline = form.cleaned_data["headline"]
    review.body = form.cleaned_data["body"]
    review.save()

def delete_review(review: Review):
    review.delete()

def save_subscribtion(user: User, followed_user: User):
    for user_follows in UserFollows.objects.all():
        # Check if this user is not always followed
        if (
                user_follows.user == user
                and
                user_follows.followed_user == followed_user):
            return
    user_follow = UserFollows()
    user_follow.user = user
    user_follow.followed_user = followed_user
    user_follow.save()

def delete_subscribtion(user: User, followed_user: User):
    # Get all users followed by user
    user_follow = UserFollows.objects.filter(
        user=user,
        followed_user=followed_user)
    user_follow.delete()
    # users_follow = UserFollows.objects.all()
    # for user_follow in users_follow:
    #     if (
    #             user_follow.user == user
    #             and
    #             user_follow.followed_user == followed_user):
    #         user_follow.delete()
    #         break

def username_exists(username):
    if User.objects.filter(username=username).exists():
        return True

    return False

def check_password_confirmation(form: forms):
    if (
            form.cleaned_data['password']
            ==
            form.cleaned_data['password_confirmation']):
        return True
    else:
        # The password confirmation doesn't correspond to the
        # password, we need to informed the user to its mistake.
        form.add_error(
            'password_confirmation',
            'Vous n\'avez pas renseigné '
            'deux fois le même mot de passe.')
        return False


# -*- coding: utf-8 -*-
#by liangwenhao
#第 0005 题：你有一个目录，装了很多照片，把它们的尺寸变成都不大于 iPhone5 分辨率的大小。

from PIL import Image, ImageOps
import os, os.path

L = [ x for x in os.listdir('.') if os.path.isfile(x) and os.path.splitext(x)[1]=='.jpg' ]
#os.path.splitext(path) 分离文件名与扩展名；默认返回(fname,fextension)元组，可做分片操作

for x in L:
    img = Image.open(x)#创建image对象
    xsize, ysize = img.size#获取高宽
    xsize = 500#设定高
    ysize = ysize * 500 // xsize#设定宽
    img = ImageOps.fit(img,(xsize,ysize))#修改尺寸
    img.save("out"+x)#保存


import cv2
import os

def get_frames(vdo_file_path, frame_count=0):
    vdo = cv2.VideoCapture(vdo_file_path)
    i = 0
    frame_skip = 30
    frame_count = frame_count
    while vdo.isOpened():
        ret, frame = vdo.read()
        if not ret:
            break
        if i > (frame_skip-1):
            frame_count += 1
            cv2.imwrite('./frames/' + 'frame_'+str(frame_count)+'.jpg', frame)
            i = 0
            continue
        i += 1
    vdo.release()
    cv2.destroyAllWindows()
    return frame_count

if __name__=='__main__':
    vdos_path = './vdos'
    file_names = os.listdir(vdos_path)
    frame_count = 0
    #total_frames = 0
    #print(len(file_names), file_names)
    for file_name in file_names:
        vdo_file_path = os.path.join(vdos_path, file_name)
        #print(vdo_file_path)
        frame_count = get_frames(vdo_file_path=vdo_file_path, frame_count=frame_count)
        #total_frames += frame_count
        print(frame_count)
    #print(total_frames)

    """ vdo_file_path = 'D:\\dataset\\rod data\\japan data\\vdo\\clips\\lot1.mp4'
    frame_count = get_frames(vdo_file_path=vdo_file_path, frame_count=frame_count)
    print(frame_count) """

""" video = cv2.VideoCapture(vdo_path)
count = 0
while(video.isOpened()):
    ret , frame = video.read()
    if ret == False:
        break

    count += 1
    cv2.imwrite('./frames/frame_'+str(count)+'.jpg', frame)

    #cv2.namedWindow('video',cv2.WINDOW_NORMAL)
    #cv2.imshow('video',frame)

    k=cv2.waitKey(1) & 0xFF
    if k==27:
        break
video.release()
cv2.destroyAllWindows() """


import threading
import time
import uuid
from collections import Counter

from django.conf import settings

import arrow
import billiard.compat
from celery.signals import (
    after_task_publish,
    before_task_publish,
    celeryd_after_setup,
    heartbeat_sent,
    task_failure,
    task_postrun,
    task_prerun,
    task_retry,
    task_success,
    task_unknown,
    worker_process_init,
)

from .. import _collector
from ..lib.error_handling import log_errors_and_send_to_rollbar
from ..models import LoggedTask
from ..stats.rabbitmq import send_rabbitmq_queue_stats

local = threading.local()

HEARTBEAT_METRICS_INTERVAL_SECONDS = 30
EXTRA_ERROR_QUEUE_TAGS_FN = settings.RANCH.get(
    "extra_error_queue_tags_fn", lambda task: []
)

def _mem_rss_bytes():
    """
    `billiard.compat.mem_rss()` returns the memory in kB that the worker
    is using. Celery uses `mem_rss()` to enforce worker memory limits;
    Ranch uses the same function to track worker RSS over time and RSS
    change after each task is run. We convert to bytes (`* 1000`) to
    make the metrics easier to understand.
    """
    return billiard.compat.mem_rss() * 1000

@before_task_publish.connect
@log_errors_and_send_to_rollbar
def add_metadata_to_task_headers(
    sender,
    body,
    exchange,
    routing_key,
    headers,
    properties,
    declare,
    retry_policy,
    **kwargs
):
    queued_at = arrow.get(headers.get("eta")).timestamp
    headers["__RANCH_QUEUED_AT"] = queued_at

@after_task_publish.connect
@log_errors_and_send_to_rollbar
def send_metrics_on_publish(sender, headers, body, exchange, routing_key, **kwargs):
    _collector.increment(
        "task.publish", value=1, tags={"task": headers.get("task", "unknown")}
    )

@task_prerun.connect
@log_errors_and_send_to_rollbar
def store_metadata_before_task_runs(
    sender, task_id, task, args, kwargs, **extra_kwargs
):
    local.task_received_at = time.time()
    try:
        local.task_queue = task.request.delivery_info.get("routing_key")
    except Exception:
        local.task_queue = None

    local.rss_before_bytes = _mem_rss_bytes()

    queued_at = getattr(task.request, "__RANCH_QUEUED_AT", None)
    if queued_at:
        wait_time_ms = (time.time() - queued_at) * 1000
        _collector.timing(
            "task.wait_time",
            value=wait_time_ms,
            tags={"task": task.name, "queue": local.task_queue},
        )

@task_postrun.connect
@log_errors_and_send_to_rollbar
def send_metrics_after_task_runs(
    sender, task_id, task, args, kwargs, retval, state, **extra_kwargs
):
    execution_time_ms = (time.time() - local.task_received_at) * 1000
    _collector.timing(
        "task.execution_time",
        value=execution_time_ms,
        tags={"task": task.name, "state": state, "queue": local.task_queue},
    )

    local.tasks_processed += 1
    _collector.gauge(
        "worker.tasks_processed",
        value=local.tasks_processed,
        tags={"queue": local.task_queue, "worker_id": local.worker_id},
    )

    current_rss_bytes = _mem_rss_bytes()

    _collector.gauge(
        "worker.rss_bytes",
        value=current_rss_bytes,
        tags={"queue": local.task_queue, "worker_id": local.worker_id},
    )

    rss_change_bytes = current_rss_bytes - local.rss_before_bytes
    _collector.increment(
        "task.rss_change_bytes",
        value=rss_change_bytes,
        tags={"task": task.name, "queue": local.task_queue},
    )

def _send_task_processed_metric(task_name, result):
    _collector.increment(
        "task.processed",
        value=1,
        tags={"task": task_name, "result": result, "queue": local.task_queue},
    )

@task_retry.connect
@log_errors_and_send_to_rollbar
def send_metrics_on_task_retry(sender, request, reason, einfo, **kwargs):
    _send_task_processed_metric(sender.name, "retry")

@task_success.connect
@log_errors_and_send_to_rollbar
def send_metrics_on_task_success(sender, result, *args, **kwargs):
    _send_task_processed_metric(sender.name, "success")

@task_failure.connect
@log_errors_and_send_to_rollbar
def send_metrics_on_task_failure(
    sender, task_id, exception, args, kwargs, traceback, einfo, **extra_kwargs
):
    _send_task_processed_metric(sender.name, "failure")

@task_unknown.connect
@log_errors_and_send_to_rollbar
def send_metrics_on_task_unknown(sender, name, id, message, exc, **kwargs):
    _collector.increment("task.unknown", value=1, tags={"task": name})

@celeryd_after_setup.connect
@log_errors_and_send_to_rollbar
def store_metadata_on_worker_parent_start(sender, instance, conf, **kwargs):
    local.worker_instance = instance
    local.app_config = conf

    # worker_queues is a dict of queue name to Celery queue instance, for
    # all queues this worker is configured to process
    # Don't freak out about the variable named amqp, yes it is
    # called this even if you're using Redis. Celery is jank.
    local.worker_queues = instance.app.amqp.queues

    # broker_type is a string, "amqp" or "redis" (or others but these
    # are the ones we expect to use)
    local.broker_type = instance.app.broker_connection().transport_cls

    local.last_send_on_heartbeat = 0

@worker_process_init.connect
@log_errors_and_send_to_rollbar
def store_metadata_on_worker_child_start(sender, **kwargs):
    # number of tasks processed over the lifetime of each worker *child* process
    local.tasks_processed = 0
    local.worker_id = str(uuid.uuid4())

def _send_queue_length_metrics():
    if local.broker_type == "amqp":
        send_rabbitmq_queue_stats(
            local.app_config["broker_url"], list(local.worker_queues.keys())
        )

def _error_queue_tags(task):
    tags = ["queue:{}".format(task.queue), "task:{}".format(task.task_name)]
    tags.extend(EXTRA_ERROR_QUEUE_TAGS_FN(task))
    return tuple(tags)

def _send_error_queue_metrics():
    tasks = LoggedTask.objects.all()
    counts = Counter(_error_queue_tags(task) for task in tasks)

    for tags, count in counts.items():
        _collector.gauge("queue.errors.length", value=count, tags=tags)

@heartbeat_sent.connect
@log_errors_and_send_to_rollbar
def send_queue_metrics_on_heartbeat(sender, **kwargs):
    if time.time() - HEARTBEAT_METRICS_INTERVAL_SECONDS < local.last_send_on_heartbeat:
        return

    _send_queue_length_metrics()
    _send_error_queue_metrics()

    local.last_send_on_heartbeat = time.time()


import pytest
import yaml

import calculator

# conftest.py文件放在项目下全局数据共享的地方，最好是放在项目根目录下
# 一般来说，conftest.py一般用来存放项目中的fixture方法
# conftest.py文件名字一定不能更换
# conftest.py文件就近生效（即如果在不同文件夹下，采取就近调用原则）
@pytest.fixture()
def fixtureStart():
    print("开始正向计算")
    # 在pytest当中，相当于激活了fixture的teardown操作，在yield后面的操作步骤，将被认为是teardown操作，
    # yield相当于return，能够返回数据，同时记录了上一次的执行位置，下一次继续执行
    cal = calculator.calculator()
    yield cal
    print("正向计算结束")

def getTestData():
    with open('../testData/testData1.yml') as data:
        data1 = yaml.safe_load(data)
        return data1

@pytest.fixture(params=getTestData())
def get_data(request):
    return request.param


from lxml import etree
from lxml.etree import SubElement
from lxml.builder import E
import spyne.const.xml as ns
from spyne.const.xml import WSDL11
from spyne.interface.wsdl.wsdl11 import check_method_port, _in_header_msg_suffix, _out_header_msg_suffix

def add_message_for_object(self, root, messages, obj, message_name):
    if obj is not None and not (message_name in messages):
        messages.add(message_name)

        message = SubElement(root, WSDL11("message"))
        if (message_name.endswith('Response')):
            message.set('name', message_name + 'Msg')
        elif (message_name.endswith('Fault')):
            message.set('name', f"{message_name.split('_')[0][:-6]}_{message_name.split('_')[1]}Msg")
            # import ipdb
            # ipdb.set_trace()
        else:
            message.set('name', message_name + 'RequestMsg')

        if isinstance(obj, (list, tuple)):
            objs = obj
        else:
            objs = (obj,)

        for obj in objs:
            part = SubElement(message, WSDL11("part"))
            if (message_name.endswith('Response')):
                part.set('name', message_name[:-8] + 'Result')
            elif (message_name.endswith('Fault')):
                part.set('name', message_name.split('_')[1])
        # <xsd:element name="sendMessageFault1_sendMessageFault" must match with method name
            else:
                part.set('name', message_name + 'Parameters')

            part.set('element', obj.get_element_name_ns(self.interface))

def add_port_type(self, service, root, service_name, types, url):
    cb_port_type = self._add_callbacks(service, root, types,
                                                            service_name, url)
    applied_service_name = self._get_applied_service_name(service)

    port_binding_names = []
    port_type_list = service.get_port_types()
    if len(port_type_list) > 0:
        for port_type_name in port_type_list:
            port_type = self._get_or_create_port_type(port_type_name)
            port_type.set('name', port_type_name)

            binding_name = self._get_binding_name(port_type_name)
            port_binding_names.append((port_type_name, binding_name))

    else:
        port_type = self._get_or_create_port_type(service_name)
        port_type.set('name', service_name)

        binding_name = self._get_binding_name(service_name)
        port_binding_names.append((service_name, binding_name))

    for method in service.public_methods.values():
        check_method_port(service, method)

        if method.is_callback:
            operation = SubElement(cb_port_type, WSDL11("operation"))
        else:
            operation = SubElement(port_type, WSDL11("operation"))

        operation.set('name', method.operation_name)

        if method.doc is not None:
            operation.append(E(WSDL11("documentation"), method.doc))

        operation.set('parameterOrder', method.in_message.get_element_name())

        op_input = SubElement(operation, WSDL11("input"))
        op_input.set('name', method.in_message.get_element_name() + 'Request')
        op_input.set('message',
                        method.in_message.get_element_name_ns(self.interface) + 'RequestMsg')

        if (not method.is_callback) and (not method.is_async):
            op_output = SubElement(operation, WSDL11("output"))
            op_output.set('name', method.out_message.get_element_name())
            op_output.set('message', method.out_message.get_element_name_ns(
                                                            self.interface) + 'Msg')

            if not (method.faults is None):
                for f in method.faults:
                    fault = SubElement(operation, WSDL11("fault"))
                    fault.set('name',  method.in_message.get_element_name() + 'Fault')
                    fault.set('message', '%s:%s' % (
                                    f.get_namespace_prefix(self.interface),
                                    f"{method.in_message.get_element_name()}_{method.in_message.get_element_name()}FaultMsg"))

    ser = self.service_elt_dict[applied_service_name]
    for port_name, binding_name in port_binding_names:
        self._add_port_to_service(ser, port_name, binding_name)

def add_bindings_for_methods(self, service, root, service_name,
                                    cb_binding):

    pref_tns = self.interface.get_namespace_prefix(self.interface.get_tns())
    input_binding_ns = ns.get_binding_ns(self.interface.app.in_protocol.type)
    output_binding_ns = ns.get_binding_ns(self.interface.app.out_protocol.type)

    def inner(method, binding):
        operation = etree.Element(WSDL11("operation"))
        operation.set('name', method.operation_name)

        soap_operation = SubElement(operation, input_binding_ns("operation"))
        soap_operation.set('soapAction', '')

        # get input
        input = SubElement(operation, WSDL11("input"))
        input.set('name', method.in_message.get_element_name() + 'Request')

        soap_body = SubElement(input, input_binding_ns("body"))
        soap_body.set('use', 'literal')

        # get input soap header
        in_header = method.in_header
        if in_header is None:
            in_header = service.__in_header__

        if not (in_header is None):
            if isinstance(in_header, (list, tuple)):
                in_headers = in_header
            else:
                in_headers = (in_header,)

            if len(in_headers) > 1:
                in_header_message_name = ''.join((method.name,
                                                    _in_header_msg_suffix))
            else:
                in_header_message_name = in_headers[0].get_type_name()

            for header in in_headers:
                soap_header = SubElement(input, input_binding_ns('header'))
                soap_header.set('use', 'literal')
                soap_header.set('message', '%s:%s' % (
                            header.get_namespace_prefix(self.interface),
                            in_header_message_name))
                soap_header.set('part', header.get_type_name())

        if not (method.is_async or method.is_callback):
            output = SubElement(operation, WSDL11("output"))
            output.set('name', method.out_message.get_element_name())

            soap_body = SubElement(output, output_binding_ns("body"))
            soap_body.set('use', 'literal')

            # get output soap header
            out_header = method.out_header
            if out_header is None:
                out_header = service.__out_header__

            if not (out_header is None):
                if isinstance(out_header, (list, tuple)):
                    out_headers = out_header
                else:
                    out_headers = (out_header,)

                if len(out_headers) > 1:
                    out_header_message_name = ''.join((method.name,
                                                    _out_header_msg_suffix))
                else:
                    out_header_message_name = out_headers[0].get_type_name()

                for header in out_headers:
                    soap_header = SubElement(output, output_binding_ns("header"))
                    soap_header.set('use', 'literal')
                    soap_header.set('message', '%s:%s' % (
                            header.get_namespace_prefix(self.interface),
                            out_header_message_name))
                    soap_header.set('part', header.get_type_name())

            if not (method.faults is None):
                for f in method.faults:
                    wsdl_fault = SubElement(operation, WSDL11("fault"))
                    # wsdl_fault.set('name', f.get_type_name())
                    wsdl_fault.set('name', method.in_message.get_element_name() + 'Fault')

                    soap_fault = SubElement(wsdl_fault, input_binding_ns("fault"))
                    # soap_fault.set('name', f.get_type_name())
                    soap_fault.set('name', method.in_message.get_element_name() + 'Fault')
                    soap_fault.set('use', 'literal')

        if method.is_callback:
            relates_to = SubElement(input, input_binding_ns("header"))

            relates_to.set('message', '%s:RelatesToHeader' % pref_tns)
            relates_to.set('part', 'RelatesTo')
            relates_to.set('use', 'literal')

            cb_binding.append(operation)

        else:
            if method.is_async:
                rt_header = SubElement(input, input_binding_ns("header"))
                rt_header.set('message', '%s:ReplyToHeader' % pref_tns)
                rt_header.set('part', 'ReplyTo')
                rt_header.set('use', 'literal')

                mid_header = SubElement(input, input_binding_ns("header"))
                mid_header.set('message', '%s:MessageIDHeader' % pref_tns)
                mid_header.set('part', 'MessageID')
                mid_header.set('use', 'literal')

            binding.append(operation)

    port_type_list = service.get_port_types()
    if len(port_type_list) > 0:
        for port_type_name in port_type_list:

            # create binding nodes
            binding = SubElement(root, WSDL11("binding"))
            binding.set('name', self._get_binding_name(port_type_name))
            binding.set('type', '%s:%s'% (pref_tns, port_type_name))

            transport = SubElement(binding, input_binding_ns("binding"))
            transport.set('style', 'document')
            transport.set('transport', self.interface.app.transport)

            for m in service.public_methods.values():
                if m.port_type == port_type_name:
                    inner(m, binding)

    else:
        # here is the default port.
        if cb_binding is None:
            cb_binding = SubElement(root, WSDL11("binding"))
            cb_binding.set('name', service_name)
            cb_binding.set('type', '%s:%s'% (pref_tns, service_name))

            transport = SubElement(cb_binding, input_binding_ns("binding"))
            transport.set('style', 'document')
            transport.set('transport', self.interface.app.transport)

        for m in service.public_methods.values():
            inner(m, cb_binding)

    return cb_binding


from collections import defaultdict

def part1(l):
    s = sorted(l)
    s = [0] + s + [s[-1] + 3]
    diffs = defaultdict(int)
    for i, j in zip(s[:-1], s[1:]):
        diffs[j - i] += 1
    return diffs[1] * diffs[3]

def part2(l):
    s = sorted(l)
    s = [0] + s + [s[-1] + 3]
    counts = defaultdict(int, {0: 1})
    for i in s[1:]:
        # number of ways to get to adapter i =
        # all the ways to get to adapters (i - 3), (i - 2), (i - 1) then to adapter i
        counts[i] = counts[i - 3] + counts[i - 2] + counts[i - 1]
    return counts[s[-1]]

if __name__ == '__main__':
    with open('input.txt', 'r') as f:
        l = list(map(int, f.readlines()))
    print("Part 1:", part1(l))
    print("Part 2:", part2(l))


# coding: utf-8

from flask import render_template
from settings import app

@app.route('/', methods=('GET',))
def index():
    name = 'Smael'
    return render_template('book/index.html', name=name)

if __name__ == '__main__':
    app.run(debug=True)


from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, BooleanField, SubmitField, IntegerField,\
                      FloatField
from wtforms.fields.html5 import DateField
from wtforms.validators import ValidationError, DataRequired, Email, EqualTo
from bdf.models import User, Book, General, Auxilliere, Journal, Period_id, Type
from wtforms_alchemy.fields import QuerySelectField

def general_ID():
    return General.query

def aux_ID():
    return Auxilliere.query

def pid_ID():
    return Period_id.query

def type_ID():
    return Type.query

def jn_ID():
    return Journal.query

class AddBookForm(FlaskForm):
    id = IntegerField('Id', validators=[DataRequired()])
    date = DateField('date', validators=[DataRequired()])
    description = StringField('Description', validators=[DataRequired()])
    debit = IntegerField('Debit')
    credit = IntegerField('Credit')
    montant = FloatField('Montant', validators=[DataRequired()])
    AUX = StringField('Auxilliare')
    type = StringField('Type')
    REF = StringField('REF')
    JN = StringField('JN')
    PID = IntegerField('PID')
    CT = IntegerField('CT')
    submit = SubmitField('Submit')
    modify = SubmitField('Modify')
    delete = SubmitField('Delete')

class AddJnForm(FlaskForm):
    id = StringField('Journal', validators=[DataRequired()])
    name = StringField('name', validators=[DataRequired()])
    submit = SubmitField('Sign In')
    modify = SubmitField('Modify')
    delete = SubmitField('Delete')

class AddPidForm(FlaskForm):
    id = IntegerField('Period', validators=[DataRequired()])
    start = DateField('Start Date', validators=[DataRequired()])
    end = DateField('End Date', validators=[DataRequired()])
    submit = SubmitField('Submit')
    modify = SubmitField('Modify')
    delete = SubmitField('Delete')

class AddTypeForm(FlaskForm):
    id = StringField('Type', validators=[DataRequired()])
    name = StringField('name', validators=[DataRequired()])
    submit = SubmitField('Sign In')
    modify = SubmitField('Modify')
    delete = SubmitField('Delete')


import re
from datetime import datetime, time

import scrapy
from city_scrapers_core.constants import COMMISSION
from city_scrapers_core.items import Meeting
from city_scrapers_core.spiders import CityScrapersSpider

class ChiSsa42Spider(CityScrapersSpider):
    name = "chi_ssa_42"
    agency = "Chicago Special Service Area #42 71st St/Stony Island"
    timezone = "America/Chicago"
    start_urls = ["https://ssa42.org/ssa-42-meeting-dates/"]
    location = {
        "name": "",
        "address": "1750 E 71st St Chicago, IL 60649",
    }

    def parse(self, response):
        """
        `parse` should always `yield` Meeting items.

        Change the `_parse_title`, `_parse_start`, etc methods to fit your scraping
        needs.
        """
        for meeting in self._parse_meetings(response, upcoming=True):
            yield meeting

        yield scrapy.Request(
            "https://ssa42.org/minutes-of-meetings/",
            callback=self._parse_meetings,
        )

    def _parse_meetings(self, response, upcoming=False):
        """Parse meetings on upcoming and minutes pages"""
        today = datetime.now().replace(hour=0, minute=0)
        last_year = today.replace(year=today.year - 1)
        for item in response.css("article.entry p"):
            text = item.xpath("./text()").extract_first()
            if not re.match(r".*day, .*\d{4}", text or ""):
                continue
            start = self._parse_start(text)
            if (
                not start
                or (upcoming and start < today)
                or (
                    start < last_year
                    and not self.settings.getbool("CITY_SCRAPERS_ARCHIVE")
                )
            ):
                continue
            meeting = Meeting(
                title=self._parse_title(text),
                description="",
                classification=COMMISSION,
                start=start,
                end=None,
                time_notes="",
                all_day=False,
                location=self.location,
                links=self._parse_links(item),
                source=response.url,
            )
            meeting["status"] = self._get_status(meeting, text=text)
            meeting["id"] = self._get_id(meeting)
            yield meeting

    def _parse_title(self, text):
        """Parse or generate meeting title."""
        name = "SSA #42 Commission"
        if "closed" in text.lower():
            return "{} - Closed Meeting".format(name)
        return name

    def _parse_start(self, text):
        """
        Parse start date and time.
        """
        date_match = re.search(r"[a-zA-Z]{3,9} \d{1,2}([a-z,]{1,3})? \d{4}", text)
        time_match = re.search(r"\d{1,2}:\d{2}[ pam\.]{2,5}", text)
        if date_match:
            try:
                date_str = re.sub(
                    r"(?<=\d)[a-z]{2}",
                    "",
                    date_match.group().replace(",", ""),
                )
                dt = datetime.strptime(date_str, "%B %d %Y").date()
            except ValueError:
                dt = None
        if time_match:
            time_str = time_match.group().replace(".", "").replace(" ", "")
            tm = datetime.strptime(time_str, "%I:%M%p").time()
        else:
            tm = time(10)
        if dt:
            return datetime.combine(dt, tm)

    def _parse_links(self, item):
        """Parse or generate links."""
        docs = []
        for doc in item.css("a"):
            doc_text = doc.xpath("./text()").extract_first()
            if "agenda" in doc_text.lower():
                doc_note = "Agenda"
            elif "minutes" in doc_text.lower():
                doc_note = "Minutes"
            else:
                doc_note = doc_text
            docs.append({"href": doc.attrib["href"], "title": doc_note})
        return docs


from django.db import models

class SandType(models.Model):
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    name = models.CharField(max_char=256)
    notes = models.TextField()
    unit_size = models.DecimalField(decimal_places=2,
                                    max_digits=12,
                                    blank=True,
                                    null=True)
    price = models.DecimalField(decimal_places=2,
                                max_digits=2,
                                blank=True,
                                null=True)
    unit_price = models.DecimalField(decimal_places=2,
                                     max_digits=2,
                                     blank=True,
                                     null=True)

class Topdressing(models.Model):
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    topdress_date = models.DateField()
    sand = models.ForeignKey(SandType)

class GreenTopdressing(Topdressing):
    greens = models.ManyToManyField('courses.Green')

class TeeTopdressing(Topdressing):
    tees = models.ManyToManyField('courses.Tee')

class FairwayTopdressing(Topdressing):
    fairways = models.ManyToManyField('courses.Fairway')


from datetime import datetime

import pandas as pd

# Завантаження даних
csv_filename = f"currency_data/combined_data_currency_{datetime.today().date()}.csv"

# Read CSV file, treating missing values as 0 in the sentiment column
currency_data = pd.read_csv(
    csv_filename,
    skiprows=[0],
    names=[
        "Data",
        "Open",
        "High",
        "Low",
        "Close",
        "Adj Close",
        "Volume",
        "Currency",
        "sentiment",
    ],
    dtype={
        "Open": float,
        "High": float,
        "Low": float,
        "Close": float,
        "Adj Close": float,
        "Volume": int,
        "sentiment": float,  # Change the dtype to float to handle potential NaN values
    },
    na_values={"sentiment": 0},  # Specify how NaN values are represented in the CSV
)
currency_data["Data"] = pd.to_datetime(currency_data["Data"])

# Розрахунок технічних індикаторів для кожної валютної пари
def calculate_technical_indicators(data):
    data["SMA_50"] = data["Close"].rolling(window=50).mean()
    data["SMA_200"] = data["Close"].rolling(window=200).mean()
    data["RSI"] = 100 - (
        100 / (1 + data["Close"].pct_change().rolling(window=14).mean())
    )
    data["MACD"] = (
        data["Close"].ewm(span=12, adjust=False).mean()
        - data["Close"].ewm(span=26, adjust=False).mean()
    )
    data["Signal_Line"] = data["MACD"].ewm(span=9, adjust=False).mean()
    data["Bollinger_Band_Upper"] = (
        data["Close"].rolling(window=20).mean()
        + 2 * data["Close"].rolling(window=20).std()
    )
    data["Bollinger_Band_Lower"] = (
        data["Close"].rolling(window=20).mean()
        - 2 * data["Close"].rolling(window=20).std()
    )
    return data

# Застосування функції до кожної валютної пари
currency_data = (
    currency_data.groupby("Currency")
    .apply(calculate_technical_indicators)
    .reset_index(drop=True)
)

# Вибірка необхідних стовпців для збереження
selected_columns = [
    "Data",
    "Open",
    "High",
    "Low",
    "Close",
    "Adj Close",
    "Volume",
    "Currency",
    "sentiment",
    "SMA_50",
    "SMA_200",
    "RSI",
    "MACD",
    "Signal_Line",
    "Bollinger_Band_Upper",
    "Bollinger_Band_Lower",
]

# Збереження оновленого DataFrame без перших двох стовпців
currency_data[selected_columns].to_csv(
    f"currency_data/currency_data_with_all_indicators_{datetime.today().date()}.csv",
    index=False,
)


wordScoresFilePath = "/home/pimania/projects/sentimentAnalysis/wordScores.txt"
delaySeconds = 100

def ensureWordScoresFile(wordScoresFilePath):
   try:
       with open(wordScoresFilePath) as wordScoresFile:
           pass
   except IOError:
       with open(wordScoresFilePath, "w") as wordScoresFile:
          pass

def getTwitterText():
   import tweepy
   try:
      auth = tweepy.auth.OAuthHandler("kqSndhybqhsSBcrY83ZpK2dkH", "EoJm0OmlZZmyhJOln7vIJg8en97NhVZQx0u9QSKKI7T9B7hvUg")
      auth.set_access_token("3685943952-BTfjGnef7QNdqnh9EMHtO5SInUcE2ZaROX9MMi8", "vD1q0887Cof3N8GKNQMHHW2Ad5vjFJCTsBONJZ47zNqC9")
      api = tweepy.API(auth)
   except:
      return False

   text = " ".join([tweet._json["text"] for tweet in api.search(q="good", count=100)]).lower() + " " + " ".join([tweet._json["text"] for tweet in api.search(q="bad", count=100)]).lower()

   sentences = text.replace("?", ".").replace("!", ".").split(". ")

   goodSentences = ". ".join([sentence for sentence in sentences if "good" in sentence])
   badSentences = ". ".join([sentence for sentence in sentences if "bad" in sentence])

   return [goodSentences, badSentences]

def getBadGoodRatio(wordScores):
   totalGoodScore = 0
   totalBadScore = 0

   for score in wordScores.values():
      if score > 0:
         totalGoodScore += score
      if score < 0:
         totalBadScore += score

   return abs(totalBadScore) / totalGoodScore

def getWordScores(goodText, badText):
   import string
   import re

   regex = re.compile('[%s]' % re.escape(string.punctuation))
   wordScores = {}

   goodWords = regex.sub('', goodText).split()
   badWords = regex.sub('', badText).split()

   for word in goodWords:
      wordScores[word] = wordScores.get(word, 0) + 1

   for word in badWords:
      wordScores[word] = wordScores.get(word, 0) - 1

   return wordScores

def getLastWordScores(wordScoresFilePath):
   import json

   with open(wordScoresFilePath) as wordScoresFile:
      try:
         lastWordScores = json.load(wordScoresFile)
      except:
         lastWordScores = {}

   return lastWordScores

def getNewWordScores(badGoodScoreRatio, wordScores, lastWordScores):
   for word in wordScores:
      if wordScores[word] > 0:
         wordScore = wordScores[word] * badGoodScoreRatio
      else:
         wordScore = wordScores[word]

      if word in lastWordScores:
         lastWordScores[word][0] += wordScore
         lastWordScores[word][1] += 1
      else:
         lastWordScores[word] = [0, 0]
         lastWordScores[word][0] += wordScore
         lastWordScores[word][1] += 1

   return lastWordScores

def main():
   while True:
      import json
      import time

      time.sleep(delaySeconds)
      ensureWordScoresFile(wordScoresFilePath)
      lastWordScores = getLastWordScores(wordScoresFilePath)

      try:
        twitterGoodtext, twitterBadtext = getTwitterText("good", "bad")
      except:
        print("Connection error...")
        continue

      wordScores = getWordScores(twitterGoodtext, twitterBadtext)

      badGoodScoreRatio = getBadGoodRatio(wordScores)
      newWordScores = getNewWordScores(badGoodScoreRatio, wordScores, lastWordScores)

      with open(wordScoresFilePath, "w") as wordScoresFile:
         json.dump(newWordScores, wordScoresFile)

main()


#!/usr/bin/env python
# coding=utf-8
'''
Author: JiangJi
Email: johnjim0816@gmail.com
Date: 2023-01-01 16:45:22
LastEditor: JiangJi
LastEditTime: 2023-03-29 13:08:50
Discription:
'''
from config.config import DefaultConfig

class AlgoConfig(DefaultConfig):
    '''算法超参数类
    '''
    def __init__(self) -> None:
        ## 设置 epsilon_start=epsilon_end 可以得到固定的 epsilon，即等于epsilon_end
        self.epsilon_start = 0.95  # epsilon 初始值
        self.epsilon_end = 0.01  # epsilon 终止值
        self.epsilon_decay = 500  # epsilon 衰减率
        self.gamma = 0.95  # 奖励折扣因子
        self.lr = 0.0001  # 学习率
        self.buffer_size = 100000  # buffer 大小
        self.batch_size = 64  # batch size
        self.target_update = 4  # target_net 更新频率
        self.value_layers = [
            {'layer_type': 'linear', 'layer_dim': ['n_states', 256],
             'activation': 'relu'},
            {'layer_type': 'linear', 'layer_dim': [256, 256],
             'activation': 'relu'},
            {'layer_type': 'linear', 'layer_dim': [256, 'n_actions'],
             'activation': 'none'}] # 神经网络层配置


import threading
import os
import time
import shutil
import subprocess
import sys
import datetime
import signal

sys.path.insert(0, '..')

import localconstants

"""
Python wrapper that spawns the Java lucene server process and restarts it if it dies.
"""

LUCENE_SERVER_VERSION = localconstants.LUCENE_SERVER_VERSION

def readServerOutput(p, port, startupEvent, failureEvent, eachLine):
  while True:
    l = p.stdout.readline().decode('utf-8')
    if l == '':
      if not startupEvent.isSet():
        failureEvent.set()
        startupEvent.set()
        raise RuntimeError('Server failed to start')
      else:
        break
    if 'listening on' in l:
      startupEvent.set()
    if eachLine is None:
      print('SVR: %s' % l.rstrip())
    else:
      eachLine(l.rstrip())

class RunServer:

  """
  Spawns java subprocess to run the Lucene server.
  """

  def __init__(self, port, path, eachLine=None):
    self.port = port
    startupEvent = threading.Event()
    failureEvent = threading.Event()

    #VERSION = '4.2.0-ALPHA'
    #VERSION = '4.2-SNAPSHOT'

    HEAP = localconstants.HEAP

    # -agentlib:yjpagent=sampling,disablej2ee
    cmd = '%s -Xms%s -Xmx%s -Xss228k -cp "../luceneserver/lib/*" org.apache.lucene.server.Server -maxHTTPThreadCount 2 -ipPort localhost:%s -stateDir %s' % (localconstants.JAVA_EXE, HEAP, HEAP, port, localconstants.ROOT_INDICES_PATH)

    print('SERVER CMD: %s' % cmd)

    self.p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)

    t = threading.Thread(target=readServerOutput, args=(self.p, port, startupEvent, failureEvent, eachLine))
    t.setDaemon(True)
    t.start()

    startupEvent.wait()
    if failureEvent.isSet():
      sys.exit(0)

  def isAlive(self):
    return self.p.poll() is None

  def killServer(self):
    try:
      self.send('shutdown', {})
    except:
      pass
    print('Find server pid to kill...')
    for line in os.popen('ps auxww | grep java | grep server.Server | grep "port %s" | grep -v grep' % self.port).readlines():
      pid = line.strip().split()[1]
      print('Kill server pid %s' % pid)
      try:
        os.kill(int(pid), signal.SIGKILL)
      except:
        pass

if __name__ == '__main__':

  while True:
    print()
    print('%s: START SERVER' % datetime.datetime.now())
    svr = RunServer(localconstants.SERVER_PORT, localconstants.ROOT_INDICES_PATH)

    try:
      while True:
        time.sleep(.2)
        if not svr.isAlive():
          print('NOT ALIVE')
          break
    finally:
      svr.killServer()

    time.sleep(1)


import time

import numpy as np
import pybullet

from pybullet_envs.env_bases import MJCFBaseBulletEnv
from .unitree_pybullet.StadiumScene import SinglePlayerStadiumScene

class UnitreeBase(MJCFBaseBulletEnv):
    def __init__(self, robot,
        render=False,
        sim_timestep = 1./1000.,
        sim_frameskip = 10,
        sim_numSolverIterations = 10,
        do_hard_reset = False,
        lateralFriction_plane=0.8,
        spinningFriction_plane=0.1,
        rollingFriction_plane = 0.1,
        restitution_plane=0.0,
        COV_ENABLE_PLANAR_REFLECTION_plane= 0,
        COV_ENABLE_SHADOWS = False,
        **kwargs
        ):
        """
        Params:
            robot (object): Robot object
            render (bool): If True then a GUI will be opened. Slows down training
                process, though.
            sim_timestep (float): Time of a single step in simulation
            sim_frameskip (int): Number of sub-steps per step in simultion. Each one
                should take sim_timestep/sim_frameskip seconds.
                Higher numbers might lead to higher accuracy but takes more time.
            sim_numSolverIterations (int): Max number of iterations of the solver in
                simulation. The higher the more accurate but also slower.
            do_hard_reset (bool): If true then the urdf will be reloaded for each
                reset. Otherwise we try to reset the simulator state.
        """
        super().__init__(robot, render)
        self._p = None
        # parama
        self._param_sim_timestep = sim_timestep
        self._param_sim_frameskip = sim_frameskip
        self._param_do_hard_reset = do_hard_reset
        self._param_sim_numSolverIterations = sim_numSolverIterations
        self._param_init_camera_width = 320
        self._param_init_camera_height = 200
        self._param_lateralFriction_plane = lateralFriction_plane
        self._param_spinningFriction_plane = spinningFriction_plane
        self._param_rollingFriction_plane = rollingFriction_plane
        self._param_restitution_plane=restitution_plane
        self._param_COV_ENABLE_PLANAR_REFLECTION_plane= COV_ENABLE_PLANAR_REFLECTION_plane
        self._param_COV_ENABLE_SHADOWS = COV_ENABLE_SHADOWS

        self.stateId=-1
        self._set_sim_param = False
        self.camera_x = None
        self._environment_hooks = []
        self._projectM = None

        self._do_render = render
        self._do_render_camera_image = True

        state = self._robot_base_reset()
        self._observation_spec = {}
        for key, val in state.items():
            self._observation_spec[key] = (len(val),)
        self._action_spec = (len(self.robot.ordered_joints),)

    def create_single_player_scene(self, bullet_client):
        self.stadium_scene = SinglePlayerStadiumScene(
            bullet_client=bullet_client,
            gravity=9.8,
            timestep=self._param_sim_timestep,
            frame_skip=self._param_sim_frameskip,
            lateralFriction=self._param_lateralFriction_plane,
            spinningFriction = self._param_spinningFriction_plane,
            rollingFriction = self._param_rollingFriction_plane,
            restitution=self._param_restitution_plane,
            COV_ENABLE_PLANAR_REFLECTION_plane=self._param_COV_ENABLE_PLANAR_REFLECTION_plane,
            )
        return self.stadium_scene

    def get_observation_spec(self):
        """Returns dict of tubles defining the size of the states.

        Returns:
            dict: Size of the states.
        """
        return self._observation_spec

    def get_action_spec(self):
        """Returns the size/length of the expected actions.

        Returns:
            tuple: action length
        """
        return self._action_spec

    def reset(self):
        """Resets the simulator.

        Returns:
            state (dict): The dict contains four different states. 'j_pos' are the
                joint positions. 'j_vel' are the current velocities of the
                joint angles. 'base_pos' is the 3D position of the base of Daisy
                in the world. 'base_ori_euler' is the orientation of the robot
                in euler angles.
            reward (float): Reward achieved.
            done (bool): True if end of simulation reached. (Currently always False)
        """
        return self._robot_base_reset()

    def _robot_base_reset(self):
        """Resets the simulator.

        Returns:
            state (dict): The dict contains four different states. 'j_pos' are the
                joint positions. 'j_vel' are the current velocities of the
                joint angles. 'base_pos' is the 3D position of the base of Daisy
                in the world. 'base_ori_euler' is the orientation of the robot
                in euler angles.
            reward (float): Reward achieved.
            done (bool): True if end of simulation reached. (Currently always False)
        """
        self._do_reset_simulator_preparations()
        if (self.stateId>=0):
            self._p.restoreState(self.stateId)

        if self._p is not None and self._do_render:
            self._p.configureDebugVisualizer(pybullet.COV_ENABLE_RENDERING,0)
        state = super(UnitreeBase, self).reset()
        state['j_eff'] = [0.0 for _ in state['j_eff']]
        # state['j_eff'] contains the efforts produced from the last time step
        # We have to reset it here to zero or otherwise we have the wrong information

        # if not self._set_sim_param:
        #     # self._p.setPhysicsEngineParameter(enableFileCaching=0)
        #     self._set_sim_param = True

        # self.parts, self.jdict, self.ordered_joints, self.robot_body = self.robot.addToScene(self._p,
        #     self.stadium_scene.ground_plane_mjcf)

        if self._do_render:
            self._p.configureDebugVisualizer(pybullet.COV_ENABLE_RENDERING,1)
            # self._p.configureDebugVisualizer(pybullet.COV_ENABLE_GUI,1)

        if self._param_COV_ENABLE_SHADOWS:
            self._p.configureDebugVisualizer(pybullet.COV_ENABLE_SHADOWS, 1)
        if (self.stateId<0):
            self.stateId=self._p.saveState()
            print("saving state self.stateId:",self.stateId)

        self.camera_x = None
        self.camera_adjust()

        return state

    def step(self, a):
        """Applies action a and returns next state.

        Args:
            a (list or numpy array): List of actions. Lenght must be the same as
                get_action_spec() defines.

        Returns:
            state (dict): The dict contains four different states. 'j_pos' are the
                joint positions. 'j_vel' are the current velocities of the
                joint angles. 'base_pos' is the 3D position of the base of Daisy
                in the world. 'base_ori_euler' is the orientation of the robot
                in euler angles.
            reward (float): Reward achieved.
            done (bool): True if end of simulation reached. (Currently always False)

        """
        # Avoids the camera reset by the parent class
        return self._step(a)

    def _step(self, a):
        """Applies action a and returns next state.

        Args:
            a (list or numpy array): List of actions. Lenght must be the same as
                get_action_spec() defines.

        Returns:
            state (dict): The dict contains four different states. 'j_pos' are the
                joint positions. 'j_vel' are the current velocities of the
                joint angles. 'base_pos' is the 3D position of the base of Daisy
                in the world. 'base_ori_euler' is the orientation of the robot
                in euler angles.
            reward (float): Reward achieved.
            done (bool): True if end of simulation reached. (Currently always False)

        """
        if isinstance(a, np.ndarray):
            a = a.tolist()
        self.robot.apply_action(a)
        self.scene.global_step()
        self.camera_adjust()
        if self._do_render:
            self._p.configureDebugVisualizer(pybullet.COV_ENABLE_RENDERING,1)
        state = self.robot.calc_state()

        return state

    def camera_adjust(self):
        if self._p is None or not self._do_render:
            return
        self.camera._p = self._p
        x, y, z = self.robot.body_xyz
        if self.camera_x is not None:
            self.camera_x = x # 0.98*self.camera_x + (1-0.98)*x
        else:
            self.camera_x = x
        # self.camera.move_and_look_at(self.camera_x, y-2.0, 1.4, x, y, 1.0)
        lookat = [self.camera_x, y, z]
        distance = 2.0
        yaw = 10
        pitch = -20
        self._p.resetDebugVisualizerCamera(distance, yaw, pitch, lookat)

    def render_camera_image(self, pixelWidthHeight = None):
        if pixelWidthHeight is not None or self._projectM is None:
            if self._projectM is None:
                self._pixelWidth = self._param_init_camera_width
                self._pixelHeight = self._param_init_camera_height
            else:
                self._pixelWidth = pixelWidthHeight[0]
                self._pixelHeight = pixelWidthHeight[1]
            nearPlane = 0.01
            farPlane = 10
            aspect = self._pixelWidth / self._pixelHeight
            fov = 60
            self._projectM = self._p.computeProjectionMatrixFOV(fov, aspect,
                nearPlane, farPlane)

        x, y, z = self.robot.body_xyz
        lookat = [x, y, z]
        distance = 1.4
        pitch = 90
        yaw = 0
        roll = 0
        viewM = self._p.computeViewMatrixFromYawPitchRoll(
            cameraTargetPosition=lookat,
            distance=distance,
            yaw=yaw,
            pitch=pitch,
            roll=roll,
            upAxisIndex=2)

        # img_arr, depth_arr, mask_arr = pybullet.getCameraImage(self._pixelWidth, self._pixelHeight, viewM, self._projectM, shadow=0,renderer=pybullet.ER_BULLET_HARDWARE_OPENGL)
        img_arr = pybullet.getCameraImage(self._pixelWidth, self._pixelHeight, viewM, self._projectM, shadow=0, renderer=pybullet.ER_BULLET_HARDWARE_OPENGL)#, flags=pybullet.COV_ENABLE_SEGMENTATION_MARK_PREVIEW)

        w=img_arr[0] #width of the image, in pixels
        h=img_arr[1] #height of the image, in pixels
        rgb=img_arr[2] #color data RGB

        image = np.reshape(rgb, (h, w, 4)) #Red, Green, Blue, Alpha
        image = image * (1./255.)
        image = image[:,:,0:3]
        return image #, depth_arr, mask_arr

    def _do_reset_simulator_preparations(self, reload_scene=False):
        if self._param_do_hard_reset:
            self.stateId = -1
            if self._p is not None:
                self._p.resetSimulation()
            reload_scene = True

        if self.scene is not None:
            self.scene.cpp_world.numSolverIterations =  self._param_sim_numSolverIterations
            if reload_scene:
                self.scene.stadiumLoaded = 0