#!/usr/bin/env python3
# -------------------------------------------------------------
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements.  See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership.  The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License.  You may obtain a copy of the License at
#
#   http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied.  See the License for the
# specific language governing permissions and limitations
# under the License.
#
# -------------------------------------------------------------

import itertools
from os.path import join
from utils_misc import split_rowcol, config_writer, mat_type_check

# This file contains configuration settings for data generation
DATA_FORMAT = 'binary'

MATRIX_TYPE_DICT = {'dense': '0.9',
                    'sparse': '0.01'}

FAMILY_NO_MATRIX_TYPE = ['clustering', 'stats1', 'stats2']

def multinomial_datagen(matrix_dim, matrix_type, datagen_dir, config_dir):
    path_name = '.'.join(['multinomial', matrix_type, str(matrix_dim)])
    datagen_write = join(datagen_dir, path_name)
    save_path = join(config_dir, path_name)

    row, col = split_rowcol(matrix_dim)

    numSamples = row
    numFeatures = col
    sparsity = MATRIX_TYPE_DICT[matrix_type]
    num_categories = '150'
    intercept = '0'
    X = join(datagen_write, 'X.data')
    Y = join(datagen_write, 'Y.data')
    fmt = DATA_FORMAT

    config = [numSamples, numFeatures, sparsity, num_categories, intercept,
              X, Y, fmt, '1']

    config_writer(save_path + '.json', config)

    return save_path

def binomial_datagen(matrix_dim, matrix_type, datagen_dir, config_dir):
    path_name = '.'.join(['binomial', matrix_type, str(matrix_dim)])
    datagen_write = join(datagen_dir, path_name)
    save_path = join(config_dir, path_name)

    row, col = split_rowcol(matrix_dim)

    numSamples = row
    numFeatures = col
    maxFeatureValue = '5'
    maxWeight = '5'
    loc_weights = join(datagen_write, 'weight.data')
    loc_data = join(datagen_write, 'X.data')
    loc_labels = join(datagen_write, 'Y.data')
    noise = '1'
    intercept = '0'
    sparsity = MATRIX_TYPE_DICT[matrix_type]
    tranform_labels = '1'
    fmt = DATA_FORMAT

    config = [numSamples, numFeatures, maxFeatureValue, maxWeight, loc_weights, loc_data,
              loc_labels, noise, intercept, sparsity, fmt, tranform_labels]
    config_writer(save_path + '.json', config)

    return save_path

def regression1_datagen(matrix_dim, matrix_type, datagen_dir, config_dir):
    path_name = '.'.join(['regression1', matrix_type, str(matrix_dim)])
    datagen_write = join(datagen_dir, path_name)
    save_path = join(config_dir, path_name)

    row, col = split_rowcol(matrix_dim)

    numSamples = row
    numFeatures = col
    maxFeatureValue = '5'
    maxWeight = '5'
    loc_weights = join(datagen_write, 'weight.data')
    loc_data = join(datagen_write, 'X.data')
    loc_labels = join(datagen_write, 'Y.data')
    noise = '1'
    intercept = '0'
    sparsity = MATRIX_TYPE_DICT[matrix_type]
    tranform_labels = '1'
    fmt = DATA_FORMAT

    config = [numSamples, numFeatures, maxFeatureValue, maxWeight, loc_weights, loc_data,
              loc_labels, noise, intercept, sparsity, fmt, tranform_labels]
    config_writer(save_path + '.json', config)

    return save_path

def regression2_datagen(matrix_dim, matrix_type, datagen_dir, config_dir):
    path_name = '.'.join(['regression2', matrix_type, str(matrix_dim)])
    datagen_write = join(datagen_dir, path_name)
    save_path = join(config_dir, path_name)

    row, col = split_rowcol(matrix_dim)

    numSamples = row
    numFeatures = col
    maxFeatureValue = '5'
    maxWeight = '5'
    loc_weights = join(datagen_write, 'weight.data')
    loc_data = join(datagen_write, 'X.data')
    loc_labels = join(datagen_write, 'Y.data')
    noise = '1'
    intercept = '0'
    sparsity = MATRIX_TYPE_DICT[matrix_type]
    tranform_labels = '1'
    fmt = DATA_FORMAT

    config = [numSamples, numFeatures, maxFeatureValue, maxWeight, loc_weights, loc_data,
              loc_labels, noise, intercept, sparsity, fmt, tranform_labels]
    config_writer(save_path + '.json', config)

    return save_path

def clustering_datagen(matrix_dim, matrix_type, datagen_dir, config_dir):

    path_name = '.'.join(['clustering', matrix_type, str(matrix_dim)])
    datagen_write = join(datagen_dir, path_name)
    save_path = join(config_dir, path_name)
    row, col = split_rowcol(matrix_dim)

    X = join(datagen_write, 'X.data')
    Y = join(datagen_write, 'Y.data')
    YbyC = join(datagen_write, 'YbyC.data')
    C = join(datagen_write, 'C.data')
    nc = '50'
    dc = '10.0'
    dr = '1.0'
    fbf = '100.0'
    cbf = '100.0'

    config = dict(nr=row, nf=col, nc=nc, dc=dc, dr=dr, fbf=fbf, cbf=cbf, X=X, C=C, Y=Y,
                  YbyC=YbyC, fmt=DATA_FORMAT)

    config_writer(save_path + '.json', config)
    return save_path

def stats1_datagen(matrix_dim, matrix_type, datagen_dir, config_dir):

    path_name = '.'.join(['stats1', matrix_type, str(matrix_dim)])
    datagen_write = join(datagen_dir, path_name)
    save_path = join(config_dir, path_name)

    row, col = split_rowcol(matrix_dim)

    DATA = join(datagen_write, 'X.data')
    TYPES = join(datagen_write, 'types')
    TYPES1 = join(datagen_write, 'set1.types')
    TYPES2 = join(datagen_write, 'set2.types')
    INDEX1 = join(datagen_write, 'set1.indices')
    INDEX2 = join(datagen_write, 'set2.indices')
    MAXDOMAIN = '1100'
    SETSIZE = '20'
    LABELSETSIZE = '10'

    # NC should be less than C and more than num0
    # NC = 10 (old value)
    # num0 = NC/2
    # num0 < NC < C
    # NC = C/2
    NC = int(int(col)/2)

    config = dict(R=row, C=col, NC=NC, MAXDOMAIN=MAXDOMAIN, DATA=DATA, TYPES=TYPES, SETSIZE=SETSIZE,
                  LABELSETSIZE=LABELSETSIZE, TYPES1=TYPES1, TYPES2=TYPES2, INDEX1=INDEX1,
                  INDEX2=INDEX2, fmt=DATA_FORMAT)

    config_writer(save_path + '.json', config)

    return save_path

def stats2_datagen(matrix_dim, matrix_type, datagen_dir, config_dir):

    path_name = '.'.join(['stats2', matrix_type, str(matrix_dim)])
    datagen_write = join(datagen_dir, path_name)
    save_path = join(config_dir, path_name)
    row, col = split_rowcol(matrix_dim)

    D = join(datagen_write, 'X.data')
    Xcid = join(datagen_write, 'Xcid.data')
    Ycid = join(datagen_write, 'Ycid.data')
    A = join(datagen_write, 'A.data')

    config = dict(nr=row, nf=col, D=D, Xcid=Xcid, Ycid=Ycid,
                  A=A, fmt=DATA_FORMAT)

    config_writer(save_path + '.json', config)
    return save_path

def dimreduction_datagen(matrix_dim, matrix_type, datagen_dir, config_dir):

    path_name = '.'.join(['dimreduction', matrix_type, str(matrix_dim)])
    datagen_write = join(datagen_dir, path_name)
    save_path = join(config_dir, path_name)
    row, col = split_rowcol(matrix_dim)

    R = row
    C = col
    OUT = join(datagen_write, 'X.data')

    config = dict(R=R, C=C, OUT=OUT, FMT=DATA_FORMAT)

    config_writer(save_path + '.json', config)
    return save_path

def config_packets_datagen(algo_payload, matrix_type, matrix_shape, datagen_dir, dense_algos, config_dir):
    """
    This function has two responsibilities. Generate the configuration files for
    datagen algorithms and return a dictionary that will be used for execution.

    algo_payload : List of tuples
    The first tuple index contains algorithm name and the second index contains
    family type.

    matrix_type: String
    Type of matrix to generate e.g dense, sparse, all

    matrix_shape: String
    Shape of matrix to generate e.g 100k_10

    datagen_dir: String
    Path of the data generation directory

    dense_algos: List
    Algorithms that support only dense matrix type

    config_dir: String
    Location to store

    return: Dictionary {string: list}
    This dictionary contains algorithms to be executed as keys and the path of configuration
    json files to be executed list of values.
    """

    config_bundle = {}
    distinct_families = set(map(lambda x: x[1], algo_payload))

    # Cross Product of all configurations
    for current_family in distinct_families:
        current_matrix_type = mat_type_check(current_family, matrix_type, dense_algos)
        config = list(itertools.product(matrix_shape, current_matrix_type))
        # clustering : [[10k_1, dense], [10k_2, dense], ...]
        config_bundle[current_family] = config

    config_packets = {}
    for current_family, configs in config_bundle.items():
        config_packets[current_family] = []
        for size, type in configs:
            family_func = current_family.lower() + '_datagen'
            conf_path = globals()[family_func](size, type, datagen_dir, config_dir)
            config_packets[current_family].append(conf_path)

    return config_packets


#!/usr/bin/env python3
from ev3dev2.motor import MoveTank, OUTPUT_A, OUTPUT_D
from ev3dev2.sensor.lego import GyroSensor
from ev3dev2.button import Button
from ev3dev2.sensor.lego import ColorSensor
import time
import logging

logging.basicConfig(level=logging.DEBUG,
        format='%(asctime)s %(levelname)5s: %(message)s')
log = logging.getLogger(__name__)

gyro_sensor = GyroSensor()
tank_pair = MoveTank(OUTPUT_A, OUTPUT_D)
button = Button()
cs = ColorSensor()

try:
    while not button.any():
        press = input("f to go forward, s to stop, b to go backwards, r to go right for 90 degrees, R to go right for 180 degrees, l to go left for 90 degrees, L to go left for 180 degrees, and e to exit the program")
        time.sleep(0.5)
        intensity = cs.reflected_light_intensity
        angle = gyro_sensor.angle

        if press == "f":
            tank_pair.on(left_speed = 50, right_speed = 50)
            print("going forward")

        elif press == "s":
            tank_pair.on(left_speed = 0, right_speed = 0)
            print("stopping")

        elif press == "b":
            tank_pair.on(left_speed = -50, right_speed = -50)
            print("going backwards")

        elif press == "r":
            tank_pair.on(left_speed = 25, right_speed = 0)
            print("going right")

        elif press == "90r":
            log.info('Angle in Degree ' + str(angle) + ' Reflected light intensity ' + str(intensity))
            print(angle)
            tank_pair.on(left_speed = 25, right_speed = 0)
            gyro_sensor.wait_until_angle_changed_by(90)
            change_in_angle = abs(gyro_sensor.angle - angle)
            log.info('Angle Changed by ' + str(change_in_angle))
            print(change_in_angle)
            tank_pair.on(left_speed = 0, right_speed = 0)
            print("going right for 90 degrees")

        elif press == "180r":
            log.info('Angle in Degree ' + str(angle) + ' Reflected light intensity ' + str(intensity))
            print(angle)
            tank_pair.on(left_speed = 25, right_speed = 0)
            gyro_sensor.wait_until_angle_changed_by(180)
            change_in_angle = abs(gyro_sensor.angle - angle)
            log.info('Angle Changed by ' + str(change_in_angle))
            print(change_in_angle)
            tank_pair.on(left_speed = 0, right_speed = 0)
            print("going right for 180 degrees")

        elif press == "l":
            tank_pair.on(left_speed = 0, right_speed = 25)
            print("going right")

        elif press == "90l":
            log.info('Angle in Degree ' + str(angle) + ' Reflected light intensity ' + str(intensity))
            print(angle)
            tank_pair.on(left_speed = 0, right_speed = 25)
            gyro_sensor.wait_until_angle_changed_by(90)
            change_in_angle = abs(gyro_sensor.angle - angle)
            log.info('Angle Changed by ' + str(change_in_angle))
            print(change_in_angle)
            tank_pair.on(left_speed = 0, right_speed = 0)
            print("going left for 90 degrees")

        elif press == "180l":
            log.info('Angle in Degree ' + str(angle) + ' Reflected light intensity ' + str(intensity))
            print(angle)
            tank_pair.on(left_speed = 0, right_speed = 25)
            gyro_sensor.wait_until_angle_changed_by(180)
            change_in_angle = abs(gyro_sensor.angle - angle)
            log.info('Angle Changed by ' + str(change_in_angle))
            print(change_in_angle)
            tank_pair.on(left_speed = 0, right_speed = 0)
            print("going left for 180 degrees")

        elif press == "e":
            break
            tank_pair.on(left_speed = 0, right_speed = 0)

except(KeyboardInterrupt):
    print('interrupt')
    tank_pair.on(left_speed = 0, right_speed = 0)


import json
import logging
import os

from scanners import utils

workers = 1
pa11y = os.environ.get("PA11Y_PATH", "pa11y")
headers = [
    "redirectedTo",
    "typeCode",
    "code",
    "message",
    "context",
    "selector"
]

def get_from_pshtt_cache(domain):
    pshtt_cache = utils.cache_path(domain, "pshtt")
    pshtt_raw = open(pshtt_cache).read()
    pshtt_data = json.loads(pshtt_raw)
    if type(pshtt_data) == list:
        pshtt_data = pshtt_data[0]
    return pshtt_data

def get_domain_to_scan(pshtt_data, domain):
    domain_to_scan = None

    redirect = pshtt_data.get('Redirect', None)
    if redirect:
        domain_to_scan = pshtt_data.get('Redirect To')
    else:
        domain_to_scan = domain
    return domain_to_scan

def get_a11y_cache(domain):
    return utils.cache_path(domain, "a11y")

def domain_is_cached(cache):
    return os.path.exists(cache)

def cache_is_not_forced(options):
    return options.get("force", False) is False

def cache_errors(errors, domain, cache):
    cachable = json.dumps({'results': errors})
    logging.debug("Writing to cache: %s" % domain)
    content = cachable
    destination = cache
    utils.write(content, destination)

def run_a11y_scan(domain, cache):
    logging.debug("[%s][a11y]" % domain)
    pa11y = os.environ.get("PA11Y_PATH", "pa11y")
    command = [pa11y, domain, "--reporter", "json", "--config", "config/pa11y_config.json", "--level", "none", "--timeout", "300000"]
    raw = utils.scan(command)
    if raw:
        results = json.loads(raw)
    else:
        results = [{
            'typeCode': '',
            'code': '',
            'message': '',
            'context': '',
            'selector': '',
            'type': ''
        }]

    cache_errors(results, domain, cache)

    return results

def get_errors_from_scan_or_cache(domain, options):
    a11y_cache = get_a11y_cache(domain)
    the_domain_is_cached = domain_is_cached(a11y_cache)
    the_cache_is_not_forced = cache_is_not_forced(options)
    logging.debug("the_domain_is_cached: %s" % the_domain_is_cached)
    logging.debug("the_cache_is_not_forced: %s" % the_cache_is_not_forced)

    # the_domain_is_cached: True
    # the_cache_is_not_forced: False
    results = []
    if the_domain_is_cached and the_cache_is_not_forced:
        logging.debug("\tCached.")
        raw = open(a11y_cache).read()
        data = json.loads(raw)
        if not data.get('invalid'):
            logging.debug("Getting from cache: %s" % domain)
            results = data.get('results')
    else:
        logging.debug("\tNot cached.")
        results = run_a11y_scan(domain, a11y_cache)
    return results

def scan(domain, options):
    logging.debug("[%s][a11y]" % domain)

    pshtt_data = get_from_pshtt_cache(domain)
    domain_to_scan = get_domain_to_scan(pshtt_data, domain)
    errors = get_errors_from_scan_or_cache(domain_to_scan, options)

    for data in errors:
        logging.debug("Writing data for %s" % domain)
        yield [
            domain_to_scan,
            data['typeCode'],
            data['code'],
            data['message'],
            data['context'],
            data['selector']
        ]


"""
Purpose of this script is to demo an example of a canvas

"""

from tkinter import Canvas, Tk, Frame, BOTH

class Example(Frame):

    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):
        self.master.title('Example 2 : Lines')
        self.pack(fill=BOTH, expand=1)

        canvas = Canvas(self)
        canvas.create_line(15, 25, 200, 25)
        canvas.create_line(300, 35, 300, 200, dash=(4, 2))
        canvas.create_line(55, 85, 155, 85, 105, 180, 55, 85)

        canvas.pack(fill=BOTH, expand=1)

root = Tk()

ex = Example()
root.geometry('400x250+300+300')
root.mainloop()


print("hello")
def function():
    num1 = int(raw_input("enter your bigest number: "))
    num2 = int(raw_input("enter number: "))
    num3 = int(raw_input("enter number: "))
    if(num1 > num2 and num1 > num3):
        print("your first number is the bigest")
    elif(num2 > num1 and num2 > num3):
        print("liar your 2nd number is the biges")
    elif(num3 > num1 and num3 > num2):
        print("liar your 3th number is the bigest")
    else:
        print("no of the numbers is the bigest liar")
function()


"""
1) Ask the user for an integer between 1 and 10 (inclusive). If the number they give is outside of the specified range, raise a ValueError and inform them that their choice was invalid.

2) Below you'll find a divide function. Write exception handling so that we catch ZeroDivisionError exceptions, TypeError exceptions, and other kinds of ArithmeticError.

divide(a, b)
	print(a / b)
3) Below you'll find an itemgetter function that takes in a collection, and either a key or index. Catch any instances of KeyError or IndexError, and write the exception to a file called log.txt, along with the arguments that caused this issue. Once you have written to the log file, reraise the original exception.

def itemgetter(collection, identifier):
	return collection[identifier]

"""

# 1 Solutions
user_input = int(input("Enter any number from 1 to 10 "))

if user_input  in range(1,11):
    print(f"Your number is {user_input}")
else:
    raise ValueError("Not in range")

# 2 Solutions

def divide(a, b):
    try:
        result =  a/b
    except ZeroDivisionError:
        print("We cannot divide any number with zero")
    except TypeError:
        print("Number cant be be divisible by letters")
    except ArithmeticError:
        print("Cant proceed further. Number is too large")

    else:
        # print(result)
        print(round(result,2))

divide(54444,703)

# 3 Solutions

def log_exception(exception, fn, **kwargs):
	values = ", ".join(f"{key}={value!r}" for key, value in kwargs.items())

	with open("log.txt", "a") as log_file:
		log_file.write(f"Exception: {exception}, Function: {fn}, Values: {values}\n")

def itemgetter(collection, identifier):
	try:
		return collection[identifier]
	except (IndexError, KeyError, TypeError) as ex:
		log_exception(ex, "itemgetter", collection=collection, identifier=identifier)
		raise


## if
# x = int(input("input x:"))
x = 123
if x < 123:
    print("less 123")
elif x == 123:
    print("equals 123")
else:
    print("than 123")

## while
a = 123
while a >=0:
    print(a)
    a -= 1

## for
array = ['aa','bb','cc']
for item in array:
    print(item,len(item),item.capitalize())

length = range(len(array))
for i in length:
    print(array[i])

print("for loop in range()")

## FAQ
array = [{'aa':1},{'bb':2}]
for key in array:
    # print(key.items())
    for value in key.items():
        print(key,value)

## range()
for i in range(5):
    print(i)

print(len(range(1,61)))

i = range(1,100,3)
for n in i:
    print(n)

## for and else
## like finally{...}
for n in range(3):
    if n % 2 ==0:
        print(n,'偶数')
else:
        print(n,"基数")

## 嵌套循环
for i in range(2,16):
    for j in range(2,i):
        if i % j ==0:
            print(i,"=",j,"*",i//j)
            break # 退出循环
            # continue
    else:
        print(i,"奇数")

array = [1,2,3,4,5]
for item in array:
    print(item,end=",")

# array.each {|item| puts item}

## pass
# while True:
#     pass

# class Type:
#     pass


from collections import deque

visited = []

class Avnode:
    def __init__(self, data=0):
        self.data = data
        self.next = None

class Graph(object):
    """docstring for Graph"""

    def __init__(self, nv, ne=0):
        super(Graph, self).__init__()
        self.nv = nv
        self.ne = ne
        self.ah = []
        for i in range(self.nv + 1):
            tmp = Avnode(i)
            self.ah.append(tmp)

def main():
    firstline = input()
    v, e = [int(i) for i in firstline.split(' ')]
    G = BuildG(v, e)
    OutputE(G)

def Init_Graph(v):
    for i in range(v + 1):
        visited.append(0)
    G = Graph(v)

    return G

def OutputE(G):
    for i in range(1, G.nv + 1):
        cnt = BFS(G, i)

        for j in range(1, G.nv + 1):
            visited[j] = 0
        print('{0}: {1:.2f}%'.format(i, cnt * 100 / G.nv))

def BuildG(v, e):
    G = Init_Graph(v)
    for i in range(e):
        edges = input()
        v1, v2 = [int(k) for k in edges.split(' ')]
        Insert_E(G, v1, v2)
    return G

def Insert_E(G, v1, v2):

    av = Avnode(v2)
    av.next = G.ah[v1].next  # 将点插入到头部
    G.ah[v1].next = av

    av2 = Avnode(v1)
    av2.next = G.ah[v2].next  # 无向图两边都要插入；
    G.ah[v2].next = av2

def BFS(G, v):
    visited[v] = 1
    cnt = 1
    queue = deque()
    last = v
    queue.append(v)

    tail = 0
    level = 0
    while queue != deque([]):
        v = queue.popleft()
        w = G.ah[v].next
        while w:
            if not visited[w.data]:
                visited[w.data] = 1
                cnt += 1
                tail = w.data
                queue.append(w.data)
            w = w.next

        if v == last:
            level += 1
            last = tail
        if level == 6:
            break
    return cnt

if __name__ == '__main__':
    main()


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

from selenium import webdriver
import requests
import re

from settings import CHROMEDRIVER_EXECUTABLE_PATH, SELENIUM_IMPLICITLY_WAIT
from settings import REQUESTS_TIMEOUT

# # selenium
# CHROMEDRIVER_EXECUTABLE_PATH = 'F:/chromedriver_win32/chromedriver.exe'
# SELENIUM_IMPLICITLY_WAIT = 10
#
# # requests
# REQUESTS_TIMEOUT = 10

def requests_init():
    params = {}

    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36',
        # 'User-Agent': get_ua()  # 获取随机 UA头
    }

    # ip, port = get_proxy_ip()  # 获取随机 代理IP
    # ip, port = ('116.196.81.58', '3128')
    # proxies = {
    #     'http': 'http://{}:{}'.format(ip, port),
    #     'https': 'http://{}:{}'.format(ip, port),
    # }
    proxies = {}  # 不使用代理

    timeout = REQUESTS_TIMEOUT

    return params, headers, proxies, timeout

def requests_get_url(url):
    # ================================ 生成 requests 的 get 方法的参数 ================================
    params, headers, proxies, timeout = requests_init()  # 可在 requests_init 方法中写 获取随机UA头，代理IP
    # =================================================================================================

    # ================================ 请求网页 ================================
    response = requests.get(url=url, params=params, headers=headers, proxies=proxies, timeout=timeout)
    html_str = response.text
    # ==========================================================================

    # ================================ 设置网页编码 ================================
    charset = requests.utils.get_encodings_from_content(html_str)  # 从html的meta中抽取
    '''
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    '''
    if not charset:
        charset = [response.apparent_encoding]  # apparent_encoding 返回真实编码  # 由程序分析出编码
    response.encoding = charset[0]
    html_str = response.text
    # ==============================================================================

    return html_str

def selenium_init():
    # 获取随机 UA头
    user_agent = None

    # 获取随机 代理IP
    # ip, port = ('114.55.236.62', '3128')
    ip, port = (None, None)

    # ================================ 浏览器 ================================
    # 设置浏览器
    chrome_options = webdriver.ChromeOptions()

    # 设置无界面浏览
    # chrome_options.set_headless(True)
    chrome_options.add_argument('--headless')

    # 设置 user_agent
    if user_agent:
        chrome_options.add_argument('user-agent={}'.format(user_agent))

    # 设置代理 IP
    if ip and port:
        chrome_options.add_argument("--proxy-server=http://{0}:{1}".format(ip, port))
        # 一定要注意，=两边不能有空格，不能是这样--proxy-server = http://202.20.16.82:10152

    # 浏览器
    browser = webdriver.Chrome(executable_path=CHROMEDRIVER_EXECUTABLE_PATH,
                               chrome_options=chrome_options)  # chromedriver.exe 的路径
    browser.maximize_window()  # 窗口最大化
    browser.implicitly_wait(SELENIUM_IMPLICITLY_WAIT)  # 隐式等待。如果找到，就继续执行，如果没找到就等待10s
    # ========================================================================

    return browser

def selenium_get_url(url, browser=None):
    use_def_browser = False  # 是否使用方法内创建的浏览器
    # 传参时，没有 browser 的话，将使用该方法内部创建的浏览器，将在该方法最后关闭浏览器，不返回 browser
    # 传参时，传入 browser 的话，将使用外部传入的浏览器，该方法将不会关闭传入的浏览器，返回 browser
    # 若使用外部浏览器  # 注意在外部关闭浏览器
    # 若要使用不同随机UA头，随机IP 请求网页的话建议使用方法的内部浏览器（只传入 url）
    # 若要使用同一个UA头，同一个IP 请求网页的话建议使用外部浏览器（传入 url 和 browser）
    # 在外部创建浏览器时，可以使用 selenium_init 方法
    try:
        if not browser:  # 创建浏览器
            use_def_browser = True  # 更改旗标
            browser = selenium_init()  # 可在 selenium_init 方法中写 获取随机UA头，代理IP

        # 请求网页
        browser.get(url)

        # # 切换到新打开的页面
        # current_window = browser.current_window_handle
        # all_handles = browser.window_handles
        # for handle in all_handles:
        #     if handle != current_window:
        #         browser.switch_to.window(handle)

        html_str = browser.page_source

        if not use_def_browser:
            return html_str, browser
        else:
            return html_str
    except Exception as e:
        print(str(e))
    finally:
        if browser and use_def_browser:
            browser.quit()

def html_str_noise_reduce(html_str):
    re_comment = re.compile('<!--[^>]*-->')  # HTML注释
    html_str = re_comment.sub('', html_str)  # 去掉HTML注释  # 去除单行的注释，且注释中的内容不含>

    # re_script = re.compile('<s*script[^>]*>[^<]*<s*/s*scripts*>', re.I)  # 去除 Script
    # html_str = re_script.sub('', html_str)

    re_style = re.compile('<s*style[^>]*>[^<]*<s*/s*styles*>', re.I)  # style
    html_str = re_style.sub('', html_str)  # 去掉 style

    return html_str

if __name__ == '__main__':
    # browser = selenium_init()

    url = 'https://news.sina.com.cn/roll/'
    # html_str = requests_get_url(url)  # requests
    html_str = selenium_get_url(url)  # selenium 使用内部浏览器
    # html_str = selenium_get_url(url, browser)  # selenium 使用外部浏览器
    # browser.quit()
    print(html_str)


import math
import numpy
import functions
import re
import pickle
from matplotlib import pyplot as plt
from matplotlib.pyplot import savefig
from sympy import symbols, Number
from sympy import latex
from sympy.parsing.sympy_parser import parse_expr
from anastruct import SystemElements
from pylatex import Document, Section, Subsection, Figure, Alignat, Command, NoEscape, Package, Subsubsection, \
    LineBreak

class Teacher():

    ss = SystemElements()
    blankss = pickle.dumps(ss)
    eq = functions.eq
    functions.n.clear()
    total_moment = ''
    total_point = ''
    total_point_y = ''
    total_point_x = ''
    total_load_y = ''
    total_load_x = ''
    roll_dist = ''
    By = ''
    Bx = ''
    Ay = ''
    Ax = ''
    EM = ''
    EFy = ''
    EFx = ''
    Ba = None
    Vx = []
    Vy = []
    Vxs = []
    angle = []
    eq_load = {}
    list_load_y = {}
    list_load_x = {}

    def reset(self):
        self.total_moment = self.total_point = self.total_point_x = self.total_point_y = self.roll_dist = \
            self.By = self.Bx = self.Ay = self.Ax = self.EM = self.EFy = self.EFx = self.total_load_x = \
            self.total_load_y = self.Bstring = ''
        self.Ba = None
        self.Vx.clear()
        self.Vy.clear()
        self.Vxs.clear()
        self.angle.clear()
        self.eq_load = {}
        self.list_load_x = {}
        self.list_load_y = {}
        self.ss = pickle.loads(self.blankss)

    def get_hinged_info(self, hinged, node_map):
        if hinged:
            self.idh = hinged[0].id
            _, self.xh, self.yh, self.fxh, self.fyh, _ = self.fetcher(node_map.get(self.idh))
            self.Ax = f'{-self.fxh:.2f}'
            self.Ay = f'{-self.fyh:.2f}'

    def get_roll_info(self, roll, node_map, roll_direction):
        for c in range(len(roll)):
            self.idr = roll[0].id
            _, xr, yr, self.fxr, self.fyr, _ = self.fetcher(node_map.get(self.idr))
            self.Bx = f'{-self.fxr:.2f}'
            self.By = f'{-self.fyr:.2f}'
            self.roll_dist_x = f'{xr - self.xh:.2f}i'
            self.roll_dist_y = f'{yr - self.yh:.2f}j'

    def get_fixed_info(self, fixed, node_map):
        if fixed:
            self.idf = fixed[0].id
            _, self.xe, self.ye, self.fxe, self.fye, self.tye = self.fetcher(node_map.get(self.idf))
            self.EM = f'{-self.tye:.2f}'
            self.EFy = f'{-self.fye:.2f}'
            self.EFx = f'{-self.fxe:.2f}'

    def get_element_angle(self, c, node_map):
        if node_map.get(c+1):
            _, xi, yi, _, _, _ = self.fetcher(node_map.get(c))
            _, xf, yf, _, _, _ = self.fetcher(node_map.get(c + 1))

            if c != len(node_map) + 1:
                self.ss.add_element([[xi, yi], [xf, yf]])
            if (xf - xi) != 0:
                self.angle.append(numpy.arctan((yf - yi) / (xf - xi)))
            elif (xf - xi) == 0:
                self.angle.append(numpy.arctan((yf - yi) / 1e-100))

    def add_supports(self, c, hinged, roll, fixed):
        if hinged and roll:
            if roll[0].id == c:
                self.ss.point_load(self.idr, -self.fxr, -self.fyr)

            if hinged[0].id == c:
                self.ss.point_load(self.idh, -self.fxh, -self.fyh)

        if fixed:
            if fixed[0].id == c:
                self.ss.point_load(self.idf, -self.fxe, -self.fye)
                self.ss.moment_load(self.idf, self.tye)

    def map_loads(self, c, node_map, p, xq, yq):
        if c in p.keys():
            id_, x, y, _, _, _ = self.fetcher(node_map.get(c))
            fx = p[id_][0]
            fy = -p[id_][1]

            if fx != 0:
                self.total_point_x += f' {fx:.2f}'

            if y - yq != 0:
                if fx != 0:
                    self.total_point += f' + {fx:.2f}i \cdot {y - yq:.2f}j'

            if fy != 0:
                self.total_point_y += f' {fy:.2f}'

            if float(x) - float(xq) != 0:
                if fy != 0:
                    self.total_point += f' + {fy:.2f}j \cdot {x - xq:.2f}i'

            self.ss.point_load(id_, fx, fy)

    def get_qload_values(self, c, q, qi, xi, xf, yi, yf):
        pos = ((xf - xi) ** 2 + (yf - yi) ** 2) ** 0.5
        iload = ((-qi.get(c) + -q.get(c)) * pos) / 2

        yload = -(math.cos(self.angle[c - 1] + math.pi) * iload)
        xload = math.sin(self.angle[c - 1] + math.pi) * iload
        cg = (pos / 3) * (float(qi.get(c) + 2 * float(q.get(c))) / (float(qi.get(c)) + float(q.get(c))))
        height = math.sin(self.angle[c - 1]) * cg
        base = math.cos(self.angle[c - 1]) * cg

        return pos, iload, yload, xload, cg, height, base

    def map_qloads(self, c, node_map, df, xq, yq, q, qi):
        if c in df.keys():
            x = symbols('x')
            id_, xi, yi, _, _, _ = self.fetcher(node_map.get(c))
            _, xf, yf, _, _, _ = self.fetcher(node_map.get(c + 1))

            pos, iload, yload, xload, cg, height, base = self.get_qload_values(c, q, qi, xi, xf, yi, yf)

            if round(xload, 2) != 0:
                self.total_load_x += f' + {xload:.2f}'
                if float(f'{height + yi - yq:.2f}') != 0:
                    self.total_moment += f' + {xload:.2f}i \cdot {height + yi - yq:.2f}j'

            if round(yload, 2) != 0:
                self.total_load_y += f' + {yload:.2f}'
                if round(base + xi - yq, 2) != 0:
                    self.total_moment += f' + {yload:.2f}j \cdot {base + xi - xq:.2f}i'

            self.list_load_x.update({c: self.total_load_x})
            self.list_load_y.update({c: self.total_load_y})
            q_part = ((((qi.get(c) - q.get(c)) / (6 * pos)) * x ** 2) * 3 - ((qi.get(c) / 2) * x) * 2)
            self.eq_load.update({c: str(latex(self.round_expr(q_part, 2)))})

            self.ss.q_load(-q.get(c), -qi.get(c), float(id_))

    def map_moments(self, c, node_map, m, moment):
        if c in m.keys():
            id_ = node_map.get(c).id
            if moment.get(c) > 0:
                self.total_moment += f' + {moment.get(c)}k'
            elif moment.get(c) < 0:
                self.total_moment += f' {moment.get(c)}k'
            self.ss.moment_load(float(id_), moment.get(c))

    def solver(self, hinged, roll, roll_direction, fixed, moment, point, q, qi, node_map):
        self.reset()
        if (len(hinged) == 1 and len(roll) == 1) or len(fixed) == 1:
            p = point
            m = moment
            df = q

            self.get_hinged_info(hinged, node_map)

            self.get_roll_info(roll, node_map, roll_direction)

            self.get_fixed_info(fixed, node_map)

            if fixed:
                yq = self.ye
                xq = self.xe
            elif hinged and roll:
                yq = self.yh
                xq = self.xh

            plt.style.use('default')
            for c in range(1, len(node_map)+1):
                self.get_element_angle(c, node_map)

                self.add_supports(c, hinged, roll, fixed)

                self.map_loads(c, node_map, p, xq, yq)

                self.map_qloads(c, node_map, df, xq, yq, q, qi)

                self.map_moments(c, node_map, m, moment)

                self.Vy.append(self.total_point_y)
                self.Vx.append(self.total_point_x)

                if c-1 in df.keys():
                    if self.list_load_y.get(c-1) is not None:
                        self.Vy[c-1] += self.list_load_y.get(c-1)
                    if self.list_load_x.get(c-1) is not None:
                        self.Vx[c-1] += self.list_load_x.get(c-1)

                if fixed:
                    if fixed[0].id == c:
                        if moment.get(c) is not None:
                            moment.update({c: moment.get(c) + float(self.EM)})
                        else:
                            moment.update({c: float(self.EM)})

                self.ss.show_structure()
                savefig(f'Settings\\figs\\structure{c}')

            plt.style.use('dark_background')
            self.savior(hinged, roll, roll_direction, fixed, node_map, moment, df)

    def fetcher(self, pool):
        id_ = pool.id
        x = pool.vertex.x
        y = pool.vertex.y
        fx = pool.Fx
        fy = pool.Fy
        ty = pool.Ty
        return id_, x, y, fx, fy, ty

    def savior(self, hinged, roll, roll_direction, fixed, node_map, moment, df):
        doc = Document(document_options="a4paper,12pt", documentclass="article")
        doc.preamble.append(NoEscape(r"""
                \usepackage[left=1.5cm,right=1.5cm,top=2cm,bottom=2cm]{geometry}
                \usepackage{setspace}
                \onehalfspacing
                \usepackage[portuguese]{babel}
                \usepackage{indentfirst}
                \usepackage{graphicx}
                \usepackage{caption}
                \usepackage{amsmath}
                \usepackage{multicol}
                \usepackage[colorlinks=true,linkcolor=black,anchorcolor=black,citecolor=black,filecolor=black,menucolor=black,runcolor=black,urlcolor=black]{hyperref}
                \usepackage{cals, ragged2e, lmodern}
                \usepackage{pdflscape}
                \usepackage{float}
                \usepackage{breqn}
                \usepackage{gensymb}
                \usepackage{helvet}
                \renewcommand{\familydefault}{\sfdefault}

                \title{Cálculos da Estrutura}
                \author{}
                """))

        doc.append(NoEscape(r"""
                \maketitle
                """))

        self.filter_strings()

        with doc.create(Section('Imagem da Estrutura')):

            with doc.create(Figure(position='H')) as fig_estrutura:
                fig_estrutura.add_image("figs\\structure", width='500px')
                fig_estrutura.add_caption(NoEscape(r'\label{fig:estrutura} Imagem da estrutura com apoios e carregamentos'))

        with doc.create(Section('Fazendo o diagrama de corpo livre')):
            with doc.create(Figure(position='H')) as fig_corpolivre:
                if hinged and roll:
                    fig_corpolivre.add_image("figs\\diagram1", width='500px')
                elif fixed:
                    fig_corpolivre.add_image("figs\\diagram2", width='500px')
                fig_corpolivre.add_caption(NoEscape(r'\label{fig:corpolivre} Diagrama de corpo livre'))

        with doc.create(Section('Calculando a reação dos apoios')):

            if fixed:
                with doc.create(Subsection('Realizando cálculo do momento no engaste')):
                    with doc.create(Alignat(numbering=False, escape=False)) as sum_M:
                        sum_M.append(r'\sum{M} &= 0 \\')
                        sum_M.append(r'M &= F \cdot d \\')
                doc.append(NoEscape(r'\begin{dmath*}'))
                doc.append(NoEscape(f'{self.total_moment + self.total_point} {self.get_signal(self.EM)} M = 0 \\\\'))
                doc.append(NoEscape(r'\end{dmath*}'))
                doc.append(NoEscape(r'\begin{dmath*}'))
                doc.append(NoEscape(f'M = {abs(float(self.EM))}'))
                doc.append(NoEscape(r'\end{dmath*}'))

                with doc.create(Subsection('Fazendo a somatória das forças em Y para obter a reação em Y no engaste')):
                    with doc.create(Alignat(escape=False, numbering=False)) as sum_Fy:
                        sum_Fy.append(r'\sum{Fy} = 0 \\')
                        sum_Fy.append(f'{self.total_point_y + self.total_load_y} {self.get_signal(self.EFy)} Fy = 0' r'\\')
                        sum_Fy.append(f'Fy = {abs(float(self.EFy))}')

                with doc.create(Subsection('Fazendo a somatória das forças em X para obter a reação em X no engaste')):
                    with doc.create(Alignat(escape=False, numbering=False)) as sum_Fx:
                        sum_Fx.append(r'\sum{Fx} = 0 \\')
                        sum_Fx.append(f'{self.total_point_x + self.total_load_x} {self.get_signal(self.EFx)} Fx = 0' r'\\')
                        sum_Fx.append(f'Fx = {abs(float(self.EFx))}')

            elif hinged and roll:
                roll_angle = roll_direction.get(self.idr)
                with doc.create(Subsection('Realizando cálculo do momento no apoio fixo')):
                    with doc.create(Alignat(numbering=False, escape=False)) as sum_M:
                        sum_M.append(r'\sum{M} &= 0 \\')
                        sum_M.append(r'M &= F \cdot d')
                    if roll_angle == math.pi/2:
                        doc.append(NoEscape(r'\begin{dmath*}'))
                        doc.append(NoEscape(self.symbol_filter(f'{self.total_moment+self.total_point} {self.get_signal(self.Bx)} Bx \cdot {self.roll_dist_y} = 0 \\\\')))
                        doc.append(NoEscape(r'\end{dmath*}'))
                        doc.append(NoEscape(r'\begin{dmath*}'))
                        doc.append(NoEscape(f'Bx = {abs(float(self.Bx))}'))
                        doc.append(NoEscape(r'\end{dmath*}'))
                    elif roll_angle == 0:
                        doc.append(NoEscape(r'\begin{dmath*}'))
                        doc.append(NoEscape(self.symbol_filter(f'{self.total_moment+self.total_point} {self.get_signal(self.By)} By \cdot {self.roll_dist_x} = 0 \\\\')))
                        doc.append(NoEscape(r'\end{dmath*}'))
                        doc.append(NoEscape(r'\begin{dmath*}'))
                        doc.append(NoEscape(f'By = {abs(float(self.By))}'))
                        doc.append(NoEscape(r'\end{dmath*}'))
                    else:
                        rangle = round(roll_direction.get(self.idr) * 180/math.pi, 2)
                        Bangle = round(float(self.Bx) / math.sin(rangle * math.pi/180), 2)
                        doc.append(NoEscape(r'\begin{dmath*}'))
                        doc.append(NoEscape(self.symbol_filter(
                            f'{self.total_moment + self.total_point} {self.get_signal(self.By)} B_{{{rangle}\degree}} \cdot cos({rangle}\degree) \cdot {self.roll_dist_x} {self.get_signal(self.Bx)} B_{{{rangle}\degree}} \cdot sen({rangle}\degree) \cdot {self.roll_dist_y} = 0 \\\\')))
                        doc.append(NoEscape(r'\end{dmath*}'))
                        doc.append(NoEscape(r'\begin{dmath*}'))
                        doc.append(NoEscape(f'B_{{{rangle}\degree}} = {Bangle}'))
                        doc.append(NoEscape(r'\end{dmath*}'))
                        doc.append(NoEscape(r'\begin{dmath*}'))
                        doc.append(NoEscape(f'B_x = {Bangle} * sen({rangle}\degree)'))
                        doc.append(NoEscape(r'\end{dmath*}'))
                        doc.append(NoEscape(r'\begin{dmath*}'))
                        doc.append(NoEscape(f'B_x = {round(float(self.Bx), 2)}'))
                        doc.append(NoEscape(r'\end{dmath*}'))
                        doc.append(NoEscape(r'\begin{dmath*}'))
                        doc.append(NoEscape(f'B_y = {Bangle} * cos({rangle}\degree)'))
                        doc.append(NoEscape(r'\end{dmath*}'))
                        doc.append(NoEscape(r'\begin{dmath*}'))
                        doc.append(NoEscape(f'B_y = {round(float(self.By), 2)}'))
                        doc.append(NoEscape(r'\end{dmath*}'))

                with doc.create(Section('Refazendo o diagrama de corpo livre')):
                    with doc.create(Figure(position='H')) as fig_corpolivre:
                        fig_corpolivre.add_image("figs\\diagram2", width='500px')
                        fig_corpolivre.add_caption(NoEscape(r'\label{fig:corpolivre} Diagrama de corpo livre'))

                with doc.create(Subsection('Fazendo a somatória das forças em Y para obter a reação em Y no apoio fixo')):
                    with doc.create(Alignat(escape=False, numbering=False)) as sum_Fy:
                        sum_Fy.append(r'\sum{Fy} = 0 \\')
                        if round(float(self.By), 2) != 0:
                            sum_Fy.append(self.symbol_filter(f'{self.total_point_y}{self.total_load_y} + {float(self.By):.2f} {self.get_signal(self.Ay)} Ay = 0' r'\\'))
                        else:
                            sum_Fy.append(self.symbol_filter(f'{self.total_point_y}{self.total_load_y} {self.get_signal(self.Ay)} Ay = 0' r'\\'))
                        sum_Fy.append(f'Ay = {abs(float(self.Ay))}')

                with doc.create(Subsection('Fazendo a somatória das forças em X para obter a reação em X no apoio fixo')):
                    with doc.create(Alignat(escape=False, numbering=False)) as sum_Fx:
                        sum_Fx.append(r'\sum{Fx} = 0 \\')
                        if float(f'{float(self.Bx):.2f}') != 0:
                            sum_Fx.append(self.symbol_filter(f'{self.total_point_x}{self.total_load_x} + {float(self.Bx):.2f} {self.get_signal(self.Ax)} Ax = 0' r'\\'))
                        else:
                            sum_Fx.append(self.symbol_filter(f'{self.total_point_x}{self.total_load_x} {self.get_signal(self.Ax)} Ax = 0' r'\\'))
                        sum_Fx.append(f'Ax = {abs(float(self.Ax))}')

            with doc.create(Subsection('Desenhando as reações dos apoios')):
                with doc.create(Figure(position='H')) as fig_apoios:
                    fig_apoios.add_image("figs\\supports", width='500px')
                    fig_apoios.add_caption(NoEscape(r'\label{fig:apoios} Reações dos apoios'))

        with doc.create(Section('Calculando os esforços internos')):

            doc.append('A partir da integral da força cortante, é obtido o momento fletor.')
            doc.append(LineBreak())
            doc.append('A constante de integração será o momento no nó final da seção anterior.')
            doc.append(LineBreak())

            eq = self.eq
            x = symbols("x")
            if hinged and roll:
                self.idh = hinged[0].id
                self.idr = roll[0].id
            elif fixed:
                self.idf = fixed[0].id

            for c in range(len(eq)):

                vx = ''
                vy = ''
                vx = self.symbol_filter(self.Vx[c])
                vy = self.symbol_filter(self.Vy[c])
                V = ''
                M = ''
                const = ''

                if hinged and roll:
                    if c + 1 >= self.idh:
                        _, _, _, fx, fy, _ = self.fetcher(node_map.get(self.idh))
                        if float(fx) != 0:
                            vx += f' + {-fx:.2f}'
                        if float(fy) != 0:
                            vy += f' + {-fy:.2f}'

                    if c + 1 >= self.idr:
                        _, _, _, fx, fy, _ = self.fetcher(node_map.get(self.idr))
                        if fx != 0:
                            vx += f' + {-fx:.2f}'
                        if fy != 0:
                            vy += f' + {-fy:.2f}'

                elif fixed:
                    if c + 1 >= float(self.idf):
                        _, _, _, fx, fy, _ = self.fetcher(node_map.get(self.idf))
                        if fx != 0:
                            vx += f' + {-fx:.2f}'
                        if fy != 0:
                            vy += f' + {-fy:.2f}'

                if c != 0:
                    _, xi, yi, _, _, _ = self.fetcher(node_map.get(c))
                    _, xf, yf, _, _, _ = self.fetcher(node_map.get(c + 1))
                    pos = ((xf - xi) ** 2 + (yf - yi) ** 2) ** 0.5

                vxc = vx
                vyc = vy
                if not vxc:
                    vxc = "0"
                if not vyc:
                    vyc = "0"

                if (abs(self.angle[c]) != 0) and (abs(self.angle[c]) != (math.pi / 2)):
                    # signals = self.get_signal_vectors(numpy.radians(90) - self.angle[c], vxc, vyc)
                    signals = self.get_signal_vectors(functions.n[c], vxc, vyc, self.angle[c], "cos")
                    vy = f'{signals[0]} ({vyc}) \cdot cos({90-(self.angle[c] * 180 / math.pi):.2f}\degree) {signals[1]} ({vxc}) \cdot cos({self.angle[c] * 180 / math.pi:.2f}\degree)'
                    signals = self.get_signal_vectors(functions.eq[c][2], vxc, vyc, self.angle[c], "sin")
                    vx = f'{signals[0]} ({vyc}) \cdot sen({90-(self.angle[c] * 180 / math.pi):.2f}\degree) {signals[1]} ({vxc}) \cdot sen({self.angle[c] * 180 / math.pi:.2f}\degree)'
                    vxc = f'{signals[0]} (({vyc}) * {math.sin(numpy.radians(90)-self.angle[c])}) {signals[1]} (({vxc}) * {math.sin(self.angle[c])})'

                if vxc == '':
                    vxc = '0'

                if round(float(parse_expr(self.symbol_filter(vxc))), 2) == -round(functions.n[c], 2):
                    n = vx
                    v = vy
                else:
                    n = vy
                    v = vx

                if round(eq[c][0], 2) != 0:
                    M += f'{-eq[c][0]:.2f}x^3'
                    V += f'{-eq[c][0] * 3: .2f}x^2'

                if round(eq[c][1], 2) != 0:
                    M += f'+{-eq[c][1]:.2f}x^2'
                    V += f'+{-eq[c][1] * 2:.2f}x'

                if round(eq[c][2], 2) != 0:
                    M += f'+{-eq[c][2]:.2f}x'
                    V += f'+{-eq[c][2]:.2f}'

                if round(eq[c][3], 2) != 0:
                    M += f'+{-eq[c][3]:.2f}'

                if V == '':
                    V = '0'

                if M == '':
                    M = '0'

                if c != 0:
                    const += f"{-eq[c-1][0]:.2f} \cdot {pos:.2f}^3"
                    const += f" + {-eq[c-1][1]:.2f} \cdot {pos:.2f}^2"
                    const += f" + {-eq[c-1][2]:.2f} \cdot {pos:.2f}"
                    const += f" + {-eq[c-1][3]:.2f}"
                    numeric_const = (-eq[c-1][0] * pos**3) + (-eq[c-1][1] * pos**2) + (-eq[c-1][2] * pos) + -eq[c-1][3]

                with doc.create(Subsection(f'Cortando na Seção {c+1}')):
                    with doc.create(Figure(position='H')) as fig_secoes:
                        fig_secoes.add_image(f"figs\\structure{c+1}", width='500px')
                        fig_secoes.add_caption(NoEscape(r'\label{fig:secoes}' f"Seção {c+1}"))

                    with doc.create(Subsubsection(f"Força Normal")):
                        doc.append(NoEscape(r'\begin{dmath*}'))
                        doc.append(NoEscape(r'\sum{Fx} = 0 \\'))
                        doc.append(NoEscape(r'\end{dmath*}'))
                        doc.append(NoEscape(r'\begin{dmath*}'))
                        doc.append(NoEscape(r'{} + N = 0'.format(self.symbol_filter(n))))
                        doc.append(NoEscape(r'\end{dmath*}'))
                        doc.append(NoEscape(r'\begin{dmath*}'))
                        doc.append(NoEscape(r'N = {:.2f}'.format(float(functions.n[c]))))
                        doc.append(NoEscape(r'\end{dmath*}'))

                    with doc.create(Subsubsection(f"Força Cortante")):
                        doc.append(NoEscape(r'\begin{dmath*}'))
                        doc.append(NoEscape(r'\sum{Fy} = 0 \\'))
                        doc.append(NoEscape(r'\end{dmath*}'))
                        doc.append(NoEscape(r'\begin{dmath*}'))
                        if c+1 in df.keys() and self.eq_load.get(c + 1) is not None:
                            doc.append(NoEscape(r'{} - V = 0'.format(self.symbol_filter(f'{self.eq_load.get(c+1)} {v}'))))
                        else:
                            doc.append(NoEscape(r'{} - V = 0'.format(self.symbol_filter(v))))
                        doc.append(NoEscape(r'\end{dmath*}'))
                        doc.append(NoEscape(r'\begin{dmath*}'))
                        doc.append(NoEscape(r'V = {}'.format(self.symbol_filter(V))))
                        doc.append(NoEscape(r'\end{dmath*}'))

                    with doc.create(Subsubsection(f'Momento Fletor')):
                        doc.append(NoEscape(r'\begin{dmath*}'))
                        doc.append(NoEscape(f'M = \\int{self.symbol_filter(V)}  dx'))
                        doc.append(NoEscape(r'\end{dmath*}'))
                        doc.append(NoEscape(r'\begin{flushleft}'))
                        doc.append(f'Constante no nó {c+1}:')
                        doc.append(NoEscape(r'\end{flushleft}'))
                        if c != 0:
                            doc.append(NoEscape(r'\begin{dmath*}'))
                            if f'{c+1}: ' in str(moment):
                                doc.append(NoEscape(self.symbol_filter(f"c = {const} + {self.get_signal_constant(moment.get(c+1), numeric_const, -eq[c][3]):.2f}")))
                            else:
                                doc.append(NoEscape(self.symbol_filter(f"c = {const}")))
                            doc.append(NoEscape(r'\end{dmath*}'))
                        elif c == 0 and f'{c+1}: ' in str(moment):
                            doc.append(NoEscape(r'\begin{dmath*}'))
                            doc.append(self.symbol_filter(NoEscape(f'c = {self.get_signal_constant(moment.get(c+1), numeric_const, -eq[c][3]):.2f}')))
                            doc.append(NoEscape(r'\end{dmath*}'))
                        else:
                            doc.append(NoEscape(r'\begin{center}'))
                            doc.append(NoEscape(f'Não há momento no nó {c+1}, portanto c = 0'))
                            doc.append(NoEscape(r'\end{center}'))
                        doc.append(NoEscape(r'\begin{dmath*}'))
                        doc.append(NoEscape(r'M = {}'.format(self.symbol_filter(M))))
                        doc.append(NoEscape(r'\end{dmath*}'))

        with doc.create(Section('Desenhando os diagramas de esforços internos')):
            with doc.create(Subsection('Desenhando o diagrama da força normal:')):
                with doc.create(Figure(position='H')) as fig_normais:
                    fig_normais.add_image("figs\\axial", width='500px')
                    fig_normais.add_caption(NoEscape(r'\label{fig:normais} Força normal'))

            with doc.create(Subsection('Desenhando o diagrama da força cortante:')):
                with doc.create(Figure(position='H')) as fig_cortante:
                    fig_cortante.add_image("figs\\shear", width='500px')
                    fig_cortante.add_caption(NoEscape(r'\label{fig:cortante} Força cortante'))

            with doc.create(Subsection('Desenhando o diagrama do momento fletor:')):
                with doc.create(Figure(position='H')) as fig_momentofletor:
                    fig_momentofletor.add_image("figs\\moment", width='500px')
                    fig_momentofletor.add_caption(NoEscape(r'\label{fig:momento} Momento Fletor'))

        doc.generate_pdf(r'Settings\resolucao', compiler='pdflatex')
        doc.generate_tex(r'Settings\resolucao')

    def filter_strings(self):
        self.total_moment = self.symbol_filter(self.total_moment)
        self.total_point = self.symbol_filter(self.total_point)
        self.total_point_y = self.symbol_filter(self.total_point_y)
        self.total_point_x = self.symbol_filter(self.total_point_x)
        self.total_load_y = self.symbol_filter(self.total_load_y)
        self.total_load_x = self.symbol_filter(self.total_load_x)

    def symbol_filter(self, string):
        string = string.replace('- -', '+')
        string = string.replace('--', '+')
        string = string.replace('+ -', '-')
        string = string.replace('+-', '-')
        #string = string.replace('+ 0.00', '')
        #string = string.replace('- 0.00', '')
        search = re.search(r'\\cdot -(\d+\.\d+)', string)
        if search:
            string = re.sub(r'\\cdot -(\d+\.\d+)', f'\\\\cdot (-{search.group(1)})', string)
        return string

    def get_signal(self, string):
        if re.search(r'(-)', string):
            return '-'
        else:
            return '+'

    def get_signal_constant(self, moment, numeric_const, result):
        if math.isclose(round(moment + numeric_const, 2), round(result, 2), rel_tol=1e-2):
            return moment
        else:
            return -moment

    def get_signal_vectors(self, result, fx, fy, angle, op):
        rel_value = 1e-2
        result = round(result, 2)
        fx = parse_expr(fx)
        fy = parse_expr(fy)

        if op == "sin":
            fx = fx * math.sin(angle)
            fy = fy * math.sin(numpy.radians(90) - angle)
        elif op == "cos":
            fx = fx * math.cos(angle)
            fy = fy * math.cos(numpy.radians(90) - angle)

        if math.isclose(round(-fx + fy, 2), result, rel_tol=rel_value):
            return "-", "+"

        elif math.isclose(round(fx - fy, 2), result, rel_tol=rel_value):
            return "+", "-"

        elif math.isclose(round(fx + fy, 2), result, rel_tol=rel_value):
            return "+", "+"

        else:
            return "-", "-"

    def round_expr(self, expr, num_digits):
        return expr.xreplace({n: round(n, num_digits) for n in expr.atoms(Number)})


import zlib
import requests
def hello(event, context):
    req = event['extensions']['request']
    ndp_type = req.forms.get('ndp_type')
    obj_url = req.forms.get('proxy_link')

    data = None
    if(ndp_type == 'GET'):
        data = requests.get(obj_url).content
    else:
        data = event['data']
    data = process(data)
    if(ndp_type == 'PUT'):
        return requests.put(obj_url,data)
    return data

def process(data):
    return zlib.compress(data)


"""
Runtime: 112 ms, faster than 15.87% of Python3 online submissions for Remove Duplicates from Sorted Array.
Memory Usage: 14.5 MB, less than 97.54% of Python3 online submissions for Remove Duplicates from Sorted Array.
"""

class Solution:
    def removeDuplicates(self, nums: List[int]) -> int:
        nums[:] = sorted(list(set(nums)))
        return len(nums)

"""
[My Solution] After 3 months of 1st
Runtime: 788 ms, faster than 7.06% of Python3 online submissions for Remove Duplicates from Sorted Array.
Memory Usage: 15.6 MB, less than 5.74% of Python3 online submissions for Remove Duplicates from Sorted Array.
"""

class Solution:
    def removeDuplicates(self, nums: List[int]) -> int:
        if len(nums) == 0:
            return 0
        pos = 1
        container = nums[0]
        while(pos < len(nums)):
            if nums[pos] == container:
                nums.remove(nums[pos])
                if pos > 0:
                    pos = pos -1
            else:
                container = nums[pos]
            pos = pos +1
        return len(nums)

"""
[My Solution 2] After 13 days from 2nd Solution
Runtime: 100 ms, faster than 30.55% of Python3 online submissions for Remove Duplicates from Sorted Array.
Memory Usage: 15.4 MB, less than 5.74% of Python3 online submissions for Remove Duplicates from Sorted Array.
"""

class Solution:
    def removeDuplicates(self, nums: List[int]) -> int:
        if not nums:
            return 0
        a = 1
        while(a < len(nums)):
            b = nums[a-1]
            if nums[a] != b:
                a = a + 1
            else:
                del nums[a]
        return len(nums)

"""
[My Solution 3] Optimized based on Array Study - Use Two Pointers (2 days after last submission)
Runtime: 80 ms, faster than 89.90% of Python3 online submissions for Remove Duplicates from Sorted Array.
Memory Usage: 15.6 MB, less than 5.74% of Python3 online submissions for Remove Duplicates from Sorted Array.
"""

class Solution:
    def removeDuplicates(self, nums: List[int]) -> int:
        if not nums:
            return 0
        a = nums[0]
        count = 1
        for i in range(1, len(nums)):
            if nums[i] != a:
                count = count + 1
                a = nums[i]
                nums[count-1] = nums[i]
        return count


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

from flask import g
from flask import abort
from flask import jsonify
from flask import request
from flask import redirect
from flask import Blueprint
from flask import make_response
from flask import render_template

from .shop import Shop

s = Shop()
bp = Blueprint('st16', __name__, static_folder='static')

@bp.before_request
def before_request():
    g._selfurl = f"/{request.url_rule.rule.split('/')[1]}"
    _connect = getattr(g, '_database', None)
    if _connect is None:
        s.get_connect()
        g._database = s.connect

@bp.route("/delete", methods=['GET'])
def delete():
    s.remove_from_list(int(request.args.get("id", "")))
    return redirect(f"{g._selfurl}/")

@bp.route("/clear")
def clear_list():
    s.clear_current_list()
    return redirect(f"{g._selfurl}/")

@bp.route("/edit", methods=['GET', 'POST'])
def edit():
    if request.method == "GET":
        id = int(request.args.get("id", ""))
        t = request.args.get("type", "")
        return render_template(
            "asm1904/st16/form.html",
            type=t, data=s.get_phone(id),
            id=id, selfurl=g._selfurl)
    elif request.method == "POST":
        s.edit_list_entry(request.form)
        return redirect(f"{g._selfurl}/")

@bp.route("/add", methods=['GET', 'POST'])
def add():
    if request.method == "GET":
        t = request.args.get("type", "")
        return render_template(
            "asm1904/st16/form.html",
            type=t, selfurl=g._selfurl)
    elif request.method == "POST":
        s.add_list_entry(request.form)
        return redirect(f"{g._selfurl}/")

@bp.route("/import")
def import_list():
    s.import_list()
    return redirect(f"{g._selfurl}/")

@bp.route("/")
def show_list():
    return render_template(
        "asm1904/st16/list.html",
        mobile_list=s.get_list(),
        selfurl=g._selfurl)

@bp.errorhandler(403)
def api_ad(error):
    return make_response(jsonify({'status': 'Invalid method'}), 403)

@bp.errorhandler(400)
def api_br(error):
    return make_response(jsonify({'status': 'Invalid request'}), 400)

@bp.route("/api/entry/delete/<int:id>", methods=['DELETE'])
def api_delete(id):
    if request.method != 'DELETE':
        abort(403)
    s.remove_from_list(id)
    return jsonify({'status': 'Ok'})

@bp.route("/api/clear", methods=['DELETE'])
def api_clear_list():
    if request.method != 'DELETE':
        abort(403)
    s.clear_current_list()
    return jsonify({'status': 'Ok'})

@bp.route("/api/entry/edit/<int:id>", methods=['PUT'])
def api_edit(id):
    if request.method != 'PUT':
        abort(403)
    s.edit_list_entry(request.json)
    return jsonify({'status': 'Ok'})

@bp.route("/api/entry/add", methods=['POST'])
def api_add():
    if not request.json:
        abort(400)
    s.add_list_entry(request.json)
    return jsonify({'status': 'Ok'})

@bp.route("/api/get-list", methods=['GET'])
def api_get_list():
    mobile_shop = s.get_list()
    return jsonify({'list': mobile_shop})

@bp.route("/api/entry/get-type/<int:phone_id>", methods=['GET'])
def api_get_phone_type(phone_id):
    phone_type = s.get_phone_type(phone_id)
    return jsonify({'type': phone_type})

if __name__ == '__main__':
    pass


import glob, os
import time
start_time = time.time()
from pathlib import Path

#import tensorflow as tf
import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()
print(tf.__version__)
import matplotlib.pyplot as plt
from tensorflow.keras.preprocessing.image import load_img
from tensorflow.keras.preprocessing.image import img_to_array
from tensorflow.keras.applications.imagenet_utils import decode_predictions

physical_devices = tf.config.experimental.list_physical_devices('GPU')
assert len(physical_devices) > 0, "Not enough GPU hardware devices available"
config = tf.config.experimental.set_memory_growth(physical_devices[0], True)

import numpy as np
# import the models for further classification experiments
from tensorflow.keras.applications import (
        vgg16,
        resnet50,
        mobilenet,
        inception_v3
    )

# init the models
vgg_model = vgg16.VGG16(weights='imagenet')
inception_model = inception_v3.InceptionV3(weights='imagenet')
resnet_model = resnet50.ResNet50(weights='imagenet')
mobilenet_model = mobilenet.MobileNet(weights='imagenet')

def run_load_prediction(filename):
    # assign the image path for the classification experiments
    # load an image in PIL format
    original = load_img(filename, target_size=(224, 224))
    print('PIL image size',original.size)
    plt.imshow(original)
    plt.show()

    # convert the PIL image to a numpy array
    # IN PIL - image is in (width, height, channel)
    # In Numpy - image is in (height, width, channel)
    numpy_image = img_to_array(original)
    plt.imshow(np.uint8(numpy_image))
    plt.show()
    print('numpy array size',numpy_image.shape)

    # Convert the image / images into batch format
    # expand_dims will add an extra dimension to the data at a particular axis
    # We want the input matrix to the network to be of the form (batchsize, height, width, channels)
    # Thus we add the extra dimension to the axis 0.
    image_batch = np.expand_dims(numpy_image, axis=0)
    print('image batch size', image_batch.shape)
    plt.imshow(np.uint8(image_batch[0]))

    # prepare the image for the VGG model
    processed_image = resnet50.preprocess_input(image_batch.copy())

    # get the predicted probabilities for each class
    predictions = resnet_model.predict(processed_image)
    # print predictions
    # convert the probabilities to class labels
    # we will get top 5 predictions which is the default
    label = decode_predictions(predictions)
    # print VGG16 predictions
    for prediction_id in range(len(label[0])):
        print(label[0][prediction_id])

data_dir = Path('dsc650/assignments/assignment06/').joinpath('Data')
os.chdir(data_dir)
for filename in glob.glob("*.png"):
    print(filename)
    run_load_prediction(filename)


import logging
import torch
import torch.distributed as dist
import torch.multiprocessing as mp

from utils import comm

__all__ = ['launch']

def _find_free_port():
    import socket
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.bind(("", 0))
    port = sock.getsockname()[1]
    sock.close()
    return port

def launch(main_func, num_gpus_per_machine, num_machines=-1, machine_rank=0, dist_url=None, args=()):
    """
    :param main_func: a funtion that will be called bt 'main_func(*args)'
    :param num_machines:  the total number of machines
    :param machine_rank:  the rank of this machine
    :param dist_url: url to connect to for distributed training, including protocol
                            e.g. "tcp://127.0.0.1:8686"
    :param args:  arguments passed to main_func
    :return:
    """
    world_size = num_machines * num_gpus_per_machine
    if world_size > 1:
        if dist_url == "auto":
            assert num_machines == 1, "dist_url=auto cannot work with distributed training."
            port = _find_free_port()
            dist_url = f"tcp://127.0.0.1:{port}"
        mp.spawn(
            _distributed_worker,
            nprocs=num_gpus_per_machine,
            args=(main_func, world_size, num_gpus_per_machine, machine_rank, dist_url, args),
            daemon=False
        )
    else:
        main_func(*args)

def _distributed_worker(local_rank, main_func, world_size, num_gpus_per_machine, machine_rank, dist_url, args):
    assert torch.cuda.is_available(), "CUDA is not available. Please check your installation."
    global_rank = machine_rank * num_gpus_per_machine + local_rank
    try:
        dist.init_process_group(
            backend="NCCL", init_method=dist_url, world_size=world_size, rank=global_rank
        )
    except Exception as e:
        logger = logging.getLogger(__name__)
        logger.error("Process group URL: {}".format(dist_url))
        raise e
    # synchronize is needed here to prevent a possible timeout after calling init_process_group
    comm.synchronize()

    assert num_gpus_per_machine <= torch.cuda.device_count()
    torch.cuda.set_device(local_rank)

    assert comm._LOCAL_PROCESS_GROUP is None
    num_machines = world_size // num_gpus_per_machine
    for i in range(num_machines):
        ranks_on_i = list(range(i * num_gpus_per_machine, (i + 1) * num_gpus_per_machine))
        pg = dist.new_group(ranks_on_i)
        if i == machine_rank:
            comm._LOCAL_PROCESS_GROUP = pg

    main_func(*args)


from django.shortcuts import render, get_object_or_404, redirect
from .models import Writing
from django.core.paginator import Paginator
from django.utils import timezone
from .forms import SongLyrics

def new(request):
    return render(request, 'new.html')

def main(request):
    songs = Writing.objects
    songs_list = Writing.objects.all()
    paginator = Paginator(songs_list, 3)
    page = request.GET.get('page')
    posts = paginator.get_page(page)
    return render(request,'main.html',{'writings': songs, 'posts':posts, } )
# Create your views here.

def more(request,song_id):
    song_lyrics = get_object_or_404(Writing,pk = song_id)

    return render(request, 'lyrics.html',{'song':song_lyrics})

def create(request):
    song = Writing()
    song.title = request.GET['title']
    song.body = request.GET['lyrics']
    song.pub_date = timezone.datetime.now()
    song.save()
    return redirect('/lyrics/'+str(song.id))

def portfolio(request):
    return render(request, 'portfolio.html')

def songpost(request):
    if request.method == 'POST':
        form = SongLyrics(request.POST)
        if form.is_valid():
            post = form.save(commit=False)
            post.pub_date = timezone.now()
            post.save()
            return redirect('home')
    else:
        form = SongLyrics()
        return render(request, 'new.html', {'form':form})


# Import packages
import json
from datetime import datetime
import math

import pandas as pd
import numpy as np

# Uniswap v3 Relation mapping between feeAmount and tickSpacing
feeMapping = {
    "500":10,
    "3000":60,
    "10000":200
}

def tickcalc(input_data):
    return math.floor(
        np.log(math.sqrt(input_data)) / np.log(math.sqrt(1.0001))
    )

def pricetickcalc(input_data):
    return np.log(math.sqrt(input_data))/np.log(math.sqrt(1.0001))

def priceFromTick(input_data):
    return pow(1.0001, input_data)

def DateTimeConverter(input_date):
    return datetime.utcfromtimestamp(input_date).strftime('%Y-%m-%d %H:%M:%S')

class BollingerDayStrategy:
    '''
        Bollinger Band position recommendation and rebalancing
    '''

    def __init__(self, tickSpacing):

        # These are just base variables created for functionality of Bollinger, these will vary drastically for your own startegy

        # Base parameters, as Bollinger bands work on moving average and standard deviation
        self.mavg = 0
        self.std0 = 0
        self.price0 = 0
        self.currentTick = 0

        # Bollinger multipliers, we choose different for low, medium and high risk
        self.LOW_BOLLINGER = 6
        self.MED_BOLLINGER = 4
        self.HIGH_BOLLINGER = 2
        self.PAST_WINDOW = 10

        # Creating dictionaries for response
        self.activeLiquidityPeriod = {"low":0, "medium":0, "high":0}
        self.inactiveDays = {"low":0, "medium":0, "high":0}
        self.numberOfTransactions = {"low":0, "medium":0, "high":0}
        self.totalDays = 0
        self.tickSpacing = tickSpacing
        self.counterDays = 0
        self.date = None

        self.liquidityData = {
        "low": [],
        "medium": [],
        "high": []
        }

        self.currentPosition = {
        "low": {"positionPriceLower": 0, "positionPriceUpper":0},
        "medium": {"positionPriceLower": 0, "positionPriceUpper":0},
        "high": {"positionPriceLower": 0, "positionPriceUpper":0}
        }

        self.lastTradingDay = {
            "low":-10,
            "medium": -10,
            "high": -10
        }

        # Final Output
        self.recommendedPositions = {

            "low":{
                "date":[],
                "positionPriceLower": [],
                "positionPriceUpper": [],
                },
            "medium":{
                "date":[],
                "positionPriceLower": [],
                "positionPriceUpper": [],
                },
            "high":{
                "date":[],
                "positionPriceLower": [],
                "positionPriceUpper": [],
                }

        }

    def needsRebalancing(self, DAY_COUNTER):
        # If Position goes out of range, rebalance

        res = []
        if(float(self.price0[DAY_COUNTER])>=float(self.currentPosition["low"]["positionPriceLower"]) and float(self.price0[DAY_COUNTER])<=float(self.currentPosition["low"]["positionPriceUpper"])):
            res.append(False)
        else:
            res.append(True)

        if(float(self.price0[DAY_COUNTER])>=float(self.currentPosition["medium"]["positionPriceLower"]) and float(self.price0[DAY_COUNTER])<=float(self.currentPosition["medium"]["positionPriceUpper"])):
            res.append(False)
        else:
            res.append(True)

        if(float(self.price0[DAY_COUNTER])>=float(self.currentPosition["high"]["positionPriceLower"]) and float(self.price0[DAY_COUNTER])<=float(self.currentPosition["high"]["positionPriceUpper"])):
            res.append(False)
        else:
            res.append(True)

        return res

    # Creating position recommendation and rebalancer within the same one using Bollinger Bands
    def positionRecommender(self, DAY_COUNTER):

        positionResponse = {
            "liquidityData":
            {
                "low":[],
                "medium":[],
                "high":[]
            }
        }

        # Getting current tick from price
        currentTick = tickcalc(self.price0[DAY_COUNTER])
        currentTick_ = round(pricetickcalc(self.price0[DAY_COUNTER])/self.tickSpacing)*self.tickSpacing

        import pdb; pdb.set_trace()
        lool = 1

        # Low-risk strategy, standard Bollinger formula,  val - std*BOLLINGER_WIDTH
        llow = self.price0[DAY_COUNTER] - self.std0[DAY_COUNTER] * self.LOW_BOLLINGER
        lhigh = self.price0[DAY_COUNTER] + self.std0[DAY_COUNTER] * self.LOW_BOLLINGER

        # Edge case for negative price on band
        llow = self.price0[DAY_COUNTER] - (self.price0[DAY_COUNTER]/32) if llow<=0 else llow

        import pdb; pdb.set_trace()
        l_lowerTick = round(pricetickcalc(llow)/self.tickSpacing)*self.tickSpacing
        l_higherTick = round(pricetickcalc(lhigh)/self.tickSpacing)*self.tickSpacing

        # Edge case handling for same ticks, usually happens for USDC/USDT pools, can be modified according to your own STRATEGY
        if (l_lowerTick == l_higherTick):
            llow = priceFromTick(math.floor(currentTick/self.tickSpacing) * self.tickSpacing)
            lhigh = priceFromTick(math.ceil(currentTick/self.tickSpacing) * self.tickSpacing)

        # Add the recommendation to the response dictionary
        positionResponse["liquidityData"]["low"].append(( str(max(llow, 0)), str(max(self.price0[DAY_COUNTER], 0)), str(max(lhigh, 0))))

        # Medium-risk strategy
        mlow = self.price0[DAY_COUNTER] - self.std0[DAY_COUNTER] * self.MED_BOLLINGER
        # mhigh = self.price0[DAY_COUNTER] * self.price0[DAY_COUNTER]/mlow
        mhigh = self.price0[DAY_COUNTER] + self.std0[DAY_COUNTER] * self.MED_BOLLINGER
        mlow = self.price0[DAY_COUNTER] - (self.price0[DAY_COUNTER]/32) if mlow<=0 else mlow

        m_lowerTick = round(pricetickcalc(mlow)/self.tickSpacing)*self.tickSpacing
        m_higherTick = round(pricetickcalc(mhigh)/self.tickSpacing)*self.tickSpacing

        # Edge case handling
        if (m_lowerTick == m_higherTick):
            mlow = priceFromTick(math.floor(currentTick/self.tickSpacing) * self.tickSpacing)
            mhigh = priceFromTick(math.ceil(currentTick/self.tickSpacing) * self.tickSpacing)

        # Add the recommendation to the response dictionary
        positionResponse["liquidityData"]["medium"].append(( str(max(mlow, 0)), str(max(self.price0[DAY_COUNTER], 0)), str(max(mhigh, 0))))

        # High-risk strategy
        hlow = self.price0[DAY_COUNTER] - self.std0[DAY_COUNTER] * self.HIGH_BOLLINGER
        hhigh = self.price0[DAY_COUNTER] + self.std0[DAY_COUNTER] * self.HIGH_BOLLINGER
        # hhigh = self.price0[DAY_COUNTER] * self.price0[DAY_COUNTER]/hlow
        hlow = self.price0[DAY_COUNTER] - (self.price0[DAY_COUNTER]/32) if hlow<=0 else hlow

        h_lowerTick = round(pricetickcalc(hlow)/self.tickSpacing)*self.tickSpacing
        h_higherTick = round(pricetickcalc(hhigh)/self.tickSpacing)*self.tickSpacing

        # Edge case handling
        if (h_lowerTick == h_higherTick):
            hlow = priceFromTick(math.floor(currentTick/self.tickSpacing) * self.tickSpacing)
            hhigh = priceFromTick(math.ceil(currentTick/self.tickSpacing) * self.tickSpacing)

        # Add the recommendation to the response dictionary
        positionResponse["liquidityData"]["high"].append(( str(max(hlow, 0)), str(max(self.price0[DAY_COUNTER], 0)), str(max(hhigh, 0))))

        return positionResponse

    def simulate(self):
        # Running the strategy over the data provided

        # We need to run it based on PAST_WINDOW as for those initial days bollinger gives NaN, because it needs those days atleast
        # to calculate it's moving average and standard deviation, hence we start from PAST_WINDOW-1 counter
        for i in range(self.PAST_WINDOW-1, self.totalDays-1):
            self.counterDays += 1

            # Check if rebalance is needed for low, medium and high strategies
            rebalance = self.needsRebalancing(i+1)
            if(rebalance[0] or rebalance[1] or rebalance[2]):
                pos = self.positionRecommender(i+1)

                if(rebalance[0]): # Fow low risk
                    self.inactiveDays["low"] += 1

                    # Rebalance
                    # print("Rebalance 0 called")

                    self.lastTradingDay["low"] = self.counterDays
                    self.currentPosition["low"]["positionPriceLower"] = pos["liquidityData"]["low"][0][0]
                    self.currentPosition["low"]["positionPriceUpper"] = pos["liquidityData"]["low"][0][2]
                    self.recommendedPositions["low"]["positionPriceLower"].append(self.currentPosition["low"]["positionPriceLower"])
                    self.recommendedPositions["low"]["positionPriceUpper"].append(self.currentPosition["low"]["positionPriceUpper"])
                    self.recommendedPositions["low"]["date"].append(self.date[i])
                    self.numberOfTransactions["low"] += 1

                if(rebalance[1]): # Fow medium risk
                    self.inactiveDays["medium"] += 1

                    self.lastTradingDay["medium"] = self.counterDays
                    self.currentPosition["medium"]["positionPriceLower"] = pos["liquidityData"]["medium"][0][0]
                    self.currentPosition["medium"]["positionPriceUpper"] = pos["liquidityData"]["medium"][0][2]
                    self.recommendedPositions["medium"]["positionPriceLower"].append(self.currentPosition["medium"]["positionPriceLower"])
                    self.recommendedPositions["medium"]["positionPriceUpper"].append(self.currentPosition["medium"]["positionPriceUpper"])
                    self.recommendedPositions["medium"]["date"].append(self.date[i])
                    self.numberOfTransactions["medium"] += 1

                if(rebalance[2]): # For high risk
                    self.inactiveDays["high"] += 1

                    self.lastTradingDay["high"] = self.counterDays
                    self.currentPosition["high"]["positionPriceLower"] = pos["liquidityData"]["high"][0][0]
                    self.currentPosition["high"]["positionPriceUpper"] = pos["liquidityData"]["high"][0][2]
                    self.recommendedPositions["high"]["positionPriceLower"].append(self.currentPosition["high"]["positionPriceLower"])
                    self.recommendedPositions["high"]["positionPriceUpper"].append(self.currentPosition["high"]["positionPriceUpper"])
                    self.recommendedPositions["high"]["date"].append(self.date[i])
                    self.numberOfTransactions["high"] += 1
    def setValues(self, transactionResponse):

        # Calculating parameter values values
        self.mavg = pd.Series(transactionResponse["graphData"]["token1Price"]).rolling(self.PAST_WINDOW).mean()
        self.std0 = pd.Series(transactionResponse["graphData"]["token1Price"]).rolling(self.PAST_WINDOW).std()
        self.price0 = transactionResponse["graphData"]["token1Price"]
        self.price0[0] = self.price0[1]
        self.totalDays = len(self.price0)
        self.date = transactionResponse["graphData"]["datetime"]

def lambda_handler(event, context):

    # Creating output placeholders
    response = {}
    transactionResponse = {}

    try:
        # Getting the payload
        event = json.loads(event)
        payload = event["body"]

        feeAmount = payload["feeAmount"]
        # This is useful for determing the tick positions
        tickSpacing = feeMapping[str(feeAmount)]

    except Exception as e:

        # If any error faced in parsing the above keys

        s = str(e)
        print(s)
        response["statusCode"] = 400
        transactionResponse["error"] = True
        transactionResponse["message"] = s
        # transactionResponse["file"] = ""
        # transactionResponse["bucket"] = OUTPUT_BUCKET
        response["headers"] = {}
        response["headers"]["Content-Type"] = "application/json"
        # transactionResponse["score"] = "{:.5f}".format(0.00000)

        response["body"] = transactionResponse

        # Converting python dictionary to JSON Object
        response_JSON = response

        # Revert the Response
        return response_JSON

    try:
        # Reading the training file
        responseDf = pd.read_csv("competition_data/sample.csv")

        # Now we want only those rows where the price is actually changing, THIS CAN VARY FOR YOUR STRATEGY, THIS IS JUST FOR EXAMPLE
        newDf = responseDf["token1Price"].diff()
        responseDf = responseDf[newDf != 0.0]
        responseDf = responseDf.reset_index(drop=True)

        # Getting the data from the csv for strategy building, this will be passed to bollinger strategy later
        transactionResponse["graphData"] = {
            "sqrtPrice":list(responseDf["sqrtPrice"].astype(str)),
            "tick": list(responseDf["tick"].astype(str)),
            "price":list(pow(1.0001, responseDf["tick"].astype(float))),
            "token0Price": list(pd.to_numeric(responseDf["token0Price"])),
            "token1Price": list(pd.to_numeric(responseDf["token1Price"])),
            "datetime": responseDf["datetime"]
        }

        # Strategy Section - Bollinger
        # Creating the object for strategy
        bollinger1 = BollingerDayStrategy(tickSpacing)
        print("Object Created")

        # Passing the data
        bollinger1.setValues(transactionResponse)
        print("Values set")

        # Running the strategy
        bollinger1.simulate()

        # Setting output values
        transactionResponse["bollingerPositionRecommendations"] = bollinger1.recommendedPositions

        # Checking the output
        print("Bollinger response test")
        print(transactionResponse["bollingerPositionRecommendations"])

    except Exception as e:
        # If any error faced in parsing the above keys
        s = str(e)
        print(e)

        response["statusCode"] = 400
        transactionResponse["error"] = True
        transactionResponse["message"] = s
        # transactionResponse["file"] = ""
        # transactionResponse["bucket"] = OUTPUT_BUCKET
        response["headers"] = {}
        response["headers"]["Content-Type"] = "application/json"
        # transactionResponse["score"] = "{:.5f}".format(0.00000)

        response["body"] = transactionResponse

        # Converting python dictionary to JSON Object
        response_JSON = response

        # Revert the Response
        return response_JSON

    response["statusCode"] = 200
    transactionResponse["error"] = False
    transactionResponse["message"] = "Error free execution"
    # transactionResponse["file"] = output_path
    # transactionResponse["bucket"] = OUTPUT_BUCKET
    response["headers"] = {}
    response["headers"]["Content-Type"] = "application/json"
    # transactionResponse["score"] = "{:.5f}".format(0.00000)

    response["body"] = transactionResponse

    # Converting python dictionary to JSON Object
    response_JSON = response

    return response

if __name__ == "__main__":

    # This is just to make the data JSON style called, nothing particular, also it makes it lambda-compatible if needed
    input_data = {
          "body": {
            "address": "0x8ad599c3a0ff1de082011efddc58f1908eb6e6d8",
            "feeAmount":3000 # This is a required variable
          }
        }

    # Calling the handler
    input_json = json.dumps(input_data)
    print("Test JSON")
    print(input_json)
    result = lambda_handler(input_json,"Context")
    # print("Lambda Result")
    # print(result)


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

"""
===============================================================================
author: 赵明星
desc:   第三个模型，使用GBDT。
===============================================================================
"""

from sklearn import preprocessing
from sklearn.ensemble import GradientBoostingClassifier
import dataset.generate_train_and_test_set_for_day_x as FEATURE

import sys
reload(sys)
sys.setdefaultencoding('utf-8')

def train_and_predict(train_feature, train_label, test_feature, day_x, mode):
    scale_train_feature = preprocessing.scale(train_feature)
    clf = GradientBoostingClassifier(n_estimators=200)
    clf.fit(scale_train_feature, train_label)
    scale_test_feature = preprocessing.scale(test_feature)
    predict_labels = clf.predict(scale_test_feature)
    if mode == "dev":
        dev_feature, dev_label = FEATURE.get_day_x_week2_dev_set(
                day_x,
                predict_labels)
        scale_week2_dev = preprocessing.scale(dev_feature)
        week_2_labels = clf.predict(scale_week2_dev)
        return predict_labels, week_2_labels, dev_label
    else:
        week_2_test = FEATURE.get_day_x_week2_test_set(day_x, predict_labels)
        scale_week2_test = preprocessing.scale(week_2_test)
        week_2_labels = clf.predict(scale_week2_test)
        return predict_labels, week_2_labels

if __name__ == "__main__":
    pass


import clr
clr.AddReference('RevitAPI')
from Autodesk.Revit.DB import *

def HasVariableLayer(item):
	if hasattr(item, "GetCompoundStructure"):
		compstruc = item.GetCompoundStructure()
		if hasattr(compstruc, "VariableLayerIndex"):
			if compstruc.VariableLayerIndex == -1: return False
			else: return True
		else: return False
	else: return False

items = UnwrapElement(IN[0])

if isinstance(IN[0], list): OUT = [HasVariableLayer(x) for x in items]
else: OUT = HasVariableLayer(items)


# TO-DO: complete the helpe function below to merge 2 sorted arrays
def merge(arrA, arrB):
    merged_arr = []
    # TO-DO

    a = 0
    b = 0

    while a < len(arrA) and b < len(arrB):
        if arrA[a] < arrB[b]:
            merged_arr.append(arrA[a])
            a += 1
        else:
            merged_arr.append(arrB[b])
            b += 1
    merged_arr.extend(arrA[a:])
    merged_arr.extend(arrB[b:])

    return merged_arr

# TO-DO: implement the Merge Sort function below USING RECURSION
def merge_sort(arr):
    # TO-DO
    if len(arr) < 2:
        return arr
    mid = len(arr) // 2

    a = merge_sort(arr[mid:])
    b = merge_sort(arr[:mid])

    return merge(a, b)

    return arr

# # STRETCH: implement an in-place merge sort algorithm
# def merge_in_place(arr, start, mid, end):
#     # TO-DO

#     return arr

# def merge_sort_in_place(arr, l, r):
#     # TO-DO

#     return arr

# # STRETCH: implement the Timsort function below
# # hint: check out https://github.com/python/cpython/blob/master/Objects/listsort.txt
# def timsort( arr ):

#     return arr


#!/usr/bin/env python3

# Novojit Saha
# 02/10/19
# Calculating area of a trapezium using class

class Trapezium:
    def __init__(self, base1, base2, height):
        self.x = base1
        self.y = base2
        self.z = height

    def area(self):
        return 0.5 * (self.x + self.y) * self.z

input_base_1 = float( input('Base one value:') )
input_base_2 = float( input('Base two value:') )
input_height = float( input('Height value:') )

trap1 = Trapezium(input_base_1, input_base_2, input_height )
areaOfTrap1 = trap1.area()
print("The area of the trapezium is " + str(areaOfTrap1))


#!/usr/bin/env python3

# https://stackoverflow.com/questions/6908143/should-i-put-shebang-in-python-scripts-and-what-form-should-it-take

import sys
import argparse
import subprocess

def recibeConfig():
    parser = argparse.ArgumentParser(description='Saludar a la gente')
    parser.add_argument('--nombre',
                        help='nombre de quien quieres saludar',
                        default="Pepe"
                        )

    args = parser.parse_args()
    print(args)
    return args

def saludameSay(nombre):
    cmd = ['/bin/bash', '-c', "say \"{}\"".format(nombre)]
    print(cmd)
    subprocess.Popen(cmd)
    print("Saludado")

def main():
    # Pipeline

    print(sys.argv)

    # PASO 1 - Recibir flags y estandarizarlos en un dict
    config = recibeConfig()

    # PASO 2 - Saludar
    print("Hola {}".format(config.nombre))
    for _ in range(5):
        saludameSay(config.nombre)

    #df = getDatos(config.url)
    #df_clean = cleanDf(df)

if __name__=="__main__":
    main()


#
## 测试传输速度
#
# fengweizhi
# 采用TCP通信的客户端
# 可靠的TCP连接，创建连接时，客户端向服务端发起连接
# 由于服务器被动无限等待连接，需要先运行服务端，再运行客户端
# 发送"DISCONNECT"断开连接
import socket
import sys
# 创建一个socket，指定使用ipv4协议，指定使用面向流的TCP协议
tcp_cli_s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 建立连接
# 输入要连接服务端的IP地址
# 设置端口
#HOST = socket.gethostbyname(socket.gethostname())
#HOST = '192.168.38.1'
HOST = input("Please input the host: ")
print("the host is " + HOST)
PORT = int((input("Please input the port: ")))
print("Waiting for connection ....")
tcp_cli_s.connect((HOST, PORT))

# 接收主机消息
# 发送连接成功消息
recv_msg = tcp_cli_s.recv(1024)
print(str(recv_msg,encoding="utf-8"))
send_msg = "Successfully connected.  Hi,I am the Client!"
tcp_cli_s.sendall(bytes(send_msg,encoding="utf-8"))
#print("Please input your message")
print("input the test data: ")
#print("Send the next one after receiving the Server's message")
# 输入并发送消息
while (True):
    try:
        # 测试发送速度，每次发送100个0
        # 发送消息
        test_data = ""
        for i in range(100):
            test_data = test_data + "0"
        print(test_data)
        # my_message = input("the Client: ")
        tcp_cli_s.sendall(bytes(test_data, encoding="utf-8"))
        #t = t + 1
        # # 断开连接
        # if my_message == "DISCONNECT":
        #     break

        # # 接受消息
        # accpt_msg = str(tcp_cli_s.recv(1024), encoding="utf-8")
        # print("".join(("the Server: ", accpt_msg)))

    except Exception as err:
        print("Error: ", err)

# 关闭连接
tcp_cli_s.close()


# Copyright 2022 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).

from __future__ import annotations

import logging

from pants.backend.kotlin.target_types import KotlinFieldSet
from pants.core.goals.check import CheckRequest, CheckResult, CheckResults
from pants.engine.addresses import Addresses
from pants.engine.rules import Get, MultiGet, collect_rules, rule
from pants.engine.target import CoarsenedTargets
from pants.engine.unions import UnionRule
from pants.jvm.compile import (
    ClasspathEntryRequest,
    ClasspathEntryRequestFactory,
    FallibleClasspathEntry,
)
from pants.jvm.resolve.key import CoursierResolveKey
from pants.util.logging import LogLevel

logger = logging.getLogger(__name__)

class KotlincCheckRequest(CheckRequest):
    field_set_type = KotlinFieldSet
    tool_name = "kotlinc"

@rule(desc="Check compilation for Kotlin", level=LogLevel.DEBUG)
async def kotlinc_check(
    request: KotlincCheckRequest,
    classpath_entry_request: ClasspathEntryRequestFactory,
) -> CheckResults:
    coarsened_targets = await Get(
        CoarsenedTargets, Addresses(field_set.address for field_set in request.field_sets)
    )

    # NB: Each root can have an independent resolve, because there is no inherent relation
    # between them other than that they were on the commandline together.
    resolves = await MultiGet(
        Get(CoursierResolveKey, CoarsenedTargets([t])) for t in coarsened_targets
    )

    results = await MultiGet(
        Get(
            FallibleClasspathEntry,
            ClasspathEntryRequest,
            classpath_entry_request.for_targets(component=target, resolve=resolve),
        )
        for target, resolve in zip(coarsened_targets, resolves)
    )

    # NB: We don't pass stdout/stderr as it will have already been rendered as streaming.
    exit_code = next((result.exit_code for result in results if result.exit_code != 0), 0)
    return CheckResults([CheckResult(exit_code, "", "")], checker_name=request.tool_name)

def rules():
    return (*collect_rules(), UnionRule(CheckRequest, KotlincCheckRequest))