import numpy as np

try:
    import pydca
except ImportError as e:
    print("Error: Could not import pydca. Please make sure it is installed and available in your system.",e)
    def plmdca():
        print("Function plmdca cannot be called as the module pydca is not available.")

    def mfdca():
        print("Function mfdca cannot be called as the module pydca is not available.")
else:
    def plmdca(filtered_alignment_file,
               sequence_type='protein',
               seqid=0.8,
               lambda_h=1.0,
               lambda_J=20.0,
               num_threads=10,
               max_iterations=500,
               verbose=False,
               msa_file_format='fasta'):
        plmdca_inst = pydca.plmdca.PlmDCA(msa_file=filtered_alignment_file,
                                          biomolecule=sequence_type,
                                          seqid = seqid,
                                          lambda_h=lambda_h,
                                          lambda_J = lambda_J,
                                          max_iterations = max_iterations,
                                          num_threads = num_threads,
                                          verbose = verbose,
                                          msa_file_format=msa_file_format)

        potts_model = plmdca_inst.get_potts_model()
        # Move gaps to the beginning
        qq = [20, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
        potts_model['h'] = potts_model['h'][:,qq]
        potts_model['J'] = potts_model['J'][:,:,qq,:][:,:,:,qq]
        potts_model['L'] = plmdca_inst.num_sequences
        return potts_model

    def mfdca(filtered_alignment_file):
        mfdca_inst = pydca.meanfield_dca.MeanFieldDCA(filtered_alignment_file,'protein')
        N = mfdca_inst.sequences_len
        q = mfdca_inst.num_site_states

        reg_fi = mfdca_inst.get_reg_single_site_freqs()
        reg_fij = mfdca_inst.get_reg_pair_site_freqs()

        corr_mat = mfdca_inst.construct_corr_mat(reg_fi, reg_fij)

        couplings = mfdca_inst.compute_couplings(corr_mat)
        fields = mfdca_inst.compute_fields(couplings)

        couplings=couplings.reshape(N,q-1,N,q-1)
        fields = np.array([a for a in fields.values()])

        fields = np.concatenate([np.zeros([N,1]),fields],axis=1)
        couplings = np.concatenate([np.zeros([N,1,N,q-1]),couplings],axis=1)
        couplings = np.concatenate([np.zeros([N,q,N,1]),couplings],axis=3)
        couplings = couplings.transpose(0,2,1,3)

        potts_model = {'h':fields,'J':couplings,'N':N,'q':q}
        return potts_model


import socket

if __name__ == '__main__':
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

    server_address = ('localhost', 8080)
    print('connecting to localhost on port 8080')

    try:
        sock.connect(server_address)
        print('Client is sending a message')
        sock.send('GET / HTTP/1.1'.encode(encoding='UTF-8'))

        data = sock.recv(4096)
        data = data.decode(encoding='UTF-8')
        print('Recv: ' + data)

    finally:
        print('Closing client connection')
        sock.close()


"""
=====
Decay
=====

This example showcases a sinusoidal decay animation.
"""

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation

from IPython.display import HTML

MILLIS_PER_SECOND = 1_000
DEFAULT_FPS = 24

def data_gen(t=0):
    cnt = 0
    while cnt < 1000:
        cnt += 1
        t += 0.1
        yield t, np.sin(2*np.pi*t) * np.exp(-t/10.)

def init():
    ax.set_ylim(-1.1, 1.1)
    ax.set_xlim(0, 10)
    del xdata[:]
    del ydata[:]
    line.set_data(xdata, ydata)
    return line,

def run(data):
    # update the data
    t, y = data
    xdata.append(t)
    ydata.append(y)
    xmin, xmax = ax.get_xlim()

    if t >= xmax:
        ax.set_xlim(xmin, 2*xmax)
        ax.figure.canvas.draw()
    line.set_data(xdata, ydata)

    return line,

def create_animation(fig, plt, animate, length_seconds=4, frames_per_second=DEFAULT_FPS):
    #Ref: https://github.com/khiner/notebooks/blob/master/ipython_animation.py
    anim = animation.FuncAnimation(fig, animate, frames=int(length_seconds * frames_per_second), interval=MILLIS_PER_SECOND/frames_per_second)
    video = HTML(anim.to_html5_video())
    plt.close()
    return video

if __name__ == "__main__":

    fig, ax = plt.subplots()
    line, = ax.plot([], [], color='red')
    ax.grid()
    xdata, ydata = [], []

    ani = animation.FuncAnimation(fig, run, data_gen, blit=False, interval=10,
                                  repeat=False, init_func=init)
    plt.show()

    # add this: vid = create_animation(fig, plt, animate)


import logging
import time

import requests

from .urls import UNIPOLSAI_BASE, LOGIN_URL, HOME_URL, POST_LOGIN, API_URL
from .utils import PositionData
from .secrets import PLATE

logging.basicConfig(level=logging.WARNING, format="%(asctime)s - %(name)s - %(levelname)s - %(message)s")
logger = logging.getLogger(__name__)

class Unipolsai:
    def __init__(self, creds: dict, headers: dict):
        """Define Unipolsai object

        :param creds: dict with username and password
        :param headers: dict with headers needed to authenticate, see documentation.
        """
        self.creds = creds
        self.session = requests.session()
        self.session.headers.update(headers)
        self.is_authenticated = False

    def authenticate(self):
        """Authenticate the instance on the site
        :return: True if authentication was succesfull
        """
        self.session.head(UNIPOLSAI_BASE)
        self.session.post(UNIPOLSAI_BASE + LOGIN_URL, data=self.creds)
        self.session.head(UNIPOLSAI_BASE + HOME_URL)
        self._check_auth()
        if not self.is_authenticated:
            raise ConnectionError("There was some error connecting to the API")
        return self.is_authenticated

    def get_position(self, plate: str = PLATE, update: bool = False):
        """Get the latest position retrieved from the GPS Unibox

        :param plate: plate of the vehicle you want to locate
        :param update: if True it will request an update of the position and start a polling waiting for a new position
        :return: PositionData object with the last position retrieved
        """
        if not plate:
            raise AttributeError("If PLATE is not set in secrets.py you have to pass it as an argument")
        if not self._check_auth():
            self.authenticate()
        response = self.session.get(
            url=UNIPOLSAI_BASE + API_URL.format(plate=str(plate).upper(),
                                                update=str(update).lower())
        )
        if response.ok:
            if response.json().get("operationResult").get("type") == 0:
                raw_position = response.json().get('lastPosition')
                parsed_position = PositionData.parse_raw_position(raw_position)
                if update:
                    new_position = self._poll_position(plate=plate, last_position=parsed_position)
                    if new_position is None:
                        logger.warning("Requested updated position, couldn't return it. (Probably needed more time)")
                        logger.debug(str(parsed_position))
                        return parsed_position
                    logger.info("Requested updated position, returned it.")
                    logger.debug(str(new_position))
                    return new_position
                logger.info("Requested position without updating")
                return parsed_position
        else:
            print(str(response.status_code) + str(response.content))

    def _check_auth(self) -> bool:
        """Check if authentication was succesfull or not
        :return: True if authentication was succesfull, False if not
        """
        response = self.session.post(
            url=UNIPOLSAI_BASE + POST_LOGIN,
            data={'channel': "TPD_Web"})
        self.is_authenticated = response.status_code == 200
        if not self.is_authenticated:
            logger.error("Authentication failed: {}".format(response.content))
        return self.is_authenticated

    def _poll_position(self, plate: str, last_position: PositionData, initial_delay: int = 40, delay: int = 12,
                       backoff=1, tries: int = 5):
        import datetime
        """ This method polls the api to see if the position is changed since the update request

        :param plate: Plate of the vehicle
        :param last_position: Last position of the vehicle
        :param initial_delay: Seconds to wait before starting the polling
        :param delay: Seconds to wait after each try
        :param backoff: Multiplier for the delay
        :param tries: Number of tries
        :return: The new location if found, None if not able to get a different position
        """
        now = datetime.datetime.now().timestamp()
        ten_min_ago = str(now - (10 * 60))[:10]
        if ten_min_ago < last_position.unix_timestamp:
            logger.debug("5m ago: {} | lastPos: {}".format(ten_min_ago, last_position.unix_timestamp))
            logger.info("Requested an update too soon, returning the last position")
            # since the api won't respond I just skip that and return it instantly
            return last_position
        logger.debug("Waiting initial {} seconds".format(initial_delay))
        time.sleep(initial_delay)
        for n in range(tries):
            try:
                new_position = self.get_position(plate)
                if new_position.unix_timestamp == last_position.unix_timestamp:
                    logger.debug("#{}. Still not updated. Delay: {}".format(n, delay))
                    time.sleep(delay)
                    delay = int(delay * backoff)
                else:
                    logger.debug("Found new position on #{} after {} seconds".format(n, initial_delay + delay))
                    return new_position
            except AttributeError as a_e:
                logger.warning("Attribute Error: {}".format(a_e))
                pass
            except ConnectionError as c_e:
                logger.warning("Connection Error: {}".format(c_e))
        return None

    def __del__(self):
        logger.debug("Logging off")
        try:
            response = self.session.get(UNIPOLSAI_BASE + "myportal/logout", headers={"Connection": "close"})
        except requests.ConnectionError:
            # Don't really understand this
            pass
        logger.info("Succesfully logged off")
        self.session.close()


import io
import wordcloud
import matplotlib.pyplot as plt

def calculate_frequencies(file_contents):
    # Here is a list of punctuations and uninteresting words you can use to process your text
    punctuations = '''!()-[]{};:'"\,<>./?@#$%^&*_~'''
    uninteresting_words = ["the", "a", "not", "in", "may", "then", "theres", "for", "on", "to", "if", "is", "it", "of", "and", "or", "an", "as", "i", "me", "my", \
    "we", "our", "ours", "you", "your", "yours", "he", "she", "him", "his", "her", "hers", "its", "they", "them", \
    "their", "what", "which", "who", "whom", "this", "that", "am", "are", "was", "were", "be", "been", "being", \
    "have", "has", "had", "do", "does", "did", "but", "at", "by", "with", "from", "here", "when", "where", "how", \
    "all", "any", "both", "each", "few", "more", "some", "such", "no", "nor", "too", "very", "can", "will", "just"]

    # Remove punctuations from the text
    for char in file_contents:
        if char in punctuations:
            file_contents = file_contents.replace(char, "")

    # Convert the text to lowercase and split it into words
    words = file_contents.lower().split()

    # Remove uninteresting words from the list of words
    filtered_words = [word for word in words if word not in uninteresting_words]

    # Create a dictionary of word frequencies
    word_freq = {}
    for word in filtered_words:
        if word not in word_freq:
            word_freq[word] = 1
        else:
            word_freq[word] += 1

    # Create a WordCloud object and generate the image
    cloud = wordcloud.WordCloud()
    # wordcloud = WordCloud(width=800, height=400, max_words=50, background_color="white").generate(text)
    cloud = wordcloud.WordCloud(width=1366, height=768,background_color="black")
    cloud.generate_from_frequencies(word_freq)
    return cloud.to_array()

def _upload():
    uploaded_file = input("Upload a file:")
    with open(uploaded_file, 'r') as f:
        file_contents = f.read()
    # Call the calculate_frequencies() function with the file contents
    myimage = calculate_frequencies(file_contents)

    # Display the word cloud image using matplotlib
    plt.imshow(myimage, interpolation='nearest')
    plt.axis('off')
    plt.show()

_upload()


import os
import Image
import math
import platform
import time
class getevopt(object):
	def __init__(self):
		if platform.system() == "Windows":
			import pygame.camera
			pygame.camera.init()
			clist = pygame.camera.list_cameras()

			if not clist:
				raise ValueError("Sorry, no cameras detected.")

			self.cam = pygame.camera.Camera(clist[0], (2304,1536), "YUYV") # define camera
	def capture(self, imagestring):
		import pygame.camera
		MyPlatform = platform.system()

		if MyPlatform == "Linux":
			execute("sudo fswebcam -q --jpeg 95 -d /dev/video0 -i 0 -r 2304x1536 --no-banner --no-timestamp %s"% imagestring) # -p YUYV, capture image

		elif MyPlatform == "Windows":
			#use pygame to capture image
			self.cam.start()
			surface = pygame.Surface((2304,1536))
			image = self.cam.get_image(surface)
			pygame.image.save(image, imagestring)
			self.cam.stop()

		time.sleep(0.25)
	def GetB(self, imagestring):
		image = Image.open(imagestring)
		pix = image.load()
		sumb = 0
		for x in range(image.size[0]):
			for y in range(image.size[1]):
				b = pix[x,y][0]*0.2126 + pix[x,y][1]*0.7152 + pix[x,y][2]*0.0722
				sumb += b
		bpre = sumb/(image.size[0]*image.size[1])
		return bpre
	def main(self):
		# take image with set ev
		os.system("v4l2-ctl --set-ctrl exposure_absolute=1000")

		timestart = time.time()
		self.capture("ev.jpg")
		timeused = time.time()-timestart

		bpre = self.GetB()

		evopt = 1000 + math.log(bpre,2) - math.log(2500/2, 2) # 2500/2 is just temporary

		print(evopt)
		return evopt

clas = getevopt()

sumb = 0
loopcount = 0
avgb = 0
while True:
	loopcount += 1
	#clas.capture("B opt images/%s.jpg"% str(loopcount))
	sumb += clas.GetB("B opt images/%s.jpg"% str(loopcount))
	avgb = sumb/loopcount
	print(avgb)

# x = open("evopt.txt")
# x.write(str(evopt))
# x.close()


def get_property_value(self, name):
        """Return the value of a property.

        The base implementation handles:

        - ``{DAV:}lockdiscovery`` and ``{DAV:}supportedlock`` using the
          associated lock manager.
        - All other *live* properties (i.e. name starts with ``{DAV:}``) are
          delegated to self.getLivePropertyValue()
        - Finally, other properties are considered *dead*, and are handled  using
          the associated property manager, if one is present.
        """
        # Return table field as property
        tableName, primKey = self.provider._split_path(self.path)
        if primKey is not None:
            ns, localName = util.split_namespace(name)
            if ns == (tableName + ":"):
                conn = self.provider._init_connection()
                fieldlist = self.provider._get_field_list(conn, tableName)
                if localName in fieldlist:
                    val = self.provider._get_field_by_primary_key(
                        conn, tableName, primKey, localName
                    )
                    conn.close()
                    return val
                conn.close()
        # else, let default implementation return supported live and dead properties
        return super(MySQLBrowserResource, self).get_property_value(name)


#write a program replace each string with an integer value in a given list of strings. the
#replacement integer value should be sum of ascci values of each character of the same string

hr = ["Ganges","Godavari","Brahmaputra","Narmada","Yamuna","Mahanadi","Kaveri","Tapti"]
for i in range(0,len(hr)):
    c = 0
    for j in hr[i]:
        x=ord(j)
        c=c+x
    hr[i] = c
print(hr)


import pygame
import sys
import math
import random

# Inicialização do Pygame
pygame.init()

# Definições de tela
width, height = 800, 600
screen = pygame.display.set_mode((width, height))
pygame.display.set_caption('Simulador de Futebol')

# Cores
white = (255, 255, 255)
green = (0, 255, 0)
blue = (0, 0, 255)
red = (255, 0, 0)

# Número de robôs
num_robots = 5

# Posições iniciais dos robôs e bola
robot_positions = [[random.randint(50, 750), random.randint(50, 550)] for _ in range(num_robots)]
ball_pos = [random.randint(50, 750), random.randint(50, 550)]

# Velocidade dos robôs
robot_speed = 2

# Carregar imagens
robot_image = pygame.image.load('horngirl.png')
robot_rect = robot_image.get_rect()

# Loop principal
while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()

    # Encontrar o robô mais próximo da bola
    closest_robot_index = min(range(num_robots), key=lambda i: math.sqrt((robot_positions[i][0] - ball_pos[0])**2 + (robot_positions[i][1] - ball_pos[1])**2))

    # Atualizar posição do robô mais próximo em direção à bola
    angle = math.atan2(ball_pos[1] - robot_positions[closest_robot_index][1], ball_pos[0] - robot_positions[closest_robot_index][0])
    robot_positions[closest_robot_index][0] += robot_speed * math.cos(angle)
    robot_positions[closest_robot_index][1] += robot_speed * math.sin(angle)

    # Verificar se o robô mais próximo tocou na bola
    distance_to_ball = math.sqrt((ball_pos[0] - robot_positions[closest_robot_index][0])**2 + (ball_pos[1] - robot_positions[closest_robot_index][1])**2)
    if distance_to_ball < 20:
        # Se o robô mais próximo tocou na bola, mova a bola para uma nova posição aleatória
        ball_pos = [random.randint(50, 750), random.randint(50, 550)]

    # Desenhar campo de futebol
    screen.fill(green)
    pygame.draw.rect(screen, white, (50, 50, width - 100, height - 100), 2)

    # Desenhar robôs
    for i in range(num_robots):
        robot_rect.center = (int(robot_positions[i][0]), int(robot_positions[i][1]))
        screen.blit(robot_image, robot_rect)

    # Desenhar bola
    pygame.draw.circle(screen, blue, (int(ball_pos[0]), int(ball_pos[1])), 10)

    # Atualizar a tela
    pygame.display.flip()

    # Controlar a taxa de quadros
    pygame.time.Clock().tick(60)


from config import bots_list
from common_exceptions import IllegalApiBotManagerActionTypeException
from api.manage_data import DataManager
import warnings

class BotManager:
    def __init__(self):
        self.bot_list = bots_list
        self.data_manager = DataManager()

    def execute_the_bot_task(self, task_description_json, user_session):
        bot_name = task_description_json['task']['bot_name']
        bot = self.bot_list[bot_name]['bot_class']()
        shop_name = self.bot_list[bot_name]['shop']
        action_type = task_description_json['task']['action_type']
        profiles_idx, billing_idx, shipping_idx, proxies_idx, items_idx = \
            self.get_the_idx_for_the_data_types(task_description_json)

        profiles, billing, shipping, proxies, items = self.get_the_users_data(user_session=user_session,
                                                                              shop_name=shop_name,
                                                                              profile_idx=profiles_idx,
                                                                              billing_idx=billing_idx,
                                                                              shipping_idx=shipping_idx,
                                                                              items_idx=items_idx,
                                                                              proxies_idx=proxies_idx)

        if action_type == 'buy':
            item_link = task_description_json['task']['item_link']
            self.buy(bot, item_link=item_link, profiles=profiles, billing=billing, shipping=shipping, proxies=proxies)
        elif action_type == 'register':
            self.register(bot, profiles=profiles, billing=billing, shipping=shipping, proxies=proxies)
        elif action_type == 'login':
            self.login(bot, profiles=profiles)
        elif action_type == 'execute_whole_buying_process':
            self.execute_the_bot_task(bot, user_session=user_session)
        else:
            raise IllegalApiBotManagerActionTypeException(action_type)

    def get_the_users_data(self, user_session, profile_idx, shop_name, billing_idx, shipping_idx, proxies_idx, items_idx):
        ''' The function which gets the data for the bot execution, data like profiles or billing user data '''
        profiles = self.data_manager.profiles.get_the_data(session=user_session)
        billing = self.data_manager.billing.get_the_data(session=user_session)
        shipping = self.data_manager.shipping.get_the_data(session=user_session)
        proxies = self.data_manager.proxies.get_the_data(session=user_session)
        items = self.data_manager.items.get_the_data(session=user_session)
        # Getting the right data by the idx
        profiles = self.get_the_right_data_by_id(data_id=profile_idx, data=profiles, shop_name=shop_name)
        billing = self.get_the_right_data_by_id(data_id=billing_idx, data=billing, shop_name=shop_name)
        shipping = self.get_the_right_data_by_id(data_id=shipping_idx, data=shipping, shop_name=shop_name)
        proxies = self.get_the_right_data_by_id(data_id=proxies_idx, data=proxies, shop_name=shop_name)
        items = self.get_the_right_data_by_id(data_id=items_idx, data=items, shop_name=shop_name)

        return profiles, billing, shipping, proxies, items

    @staticmethod
    def get_the_right_data_by_id(data_id, shop_name, data):
        ''' Getting one instance by id of  the needed data with the correct shop '''
        data_with_correct_shop = []
        for instance in data:
            if instance['shop']['name'] == shop_name:
                data_with_correct_shop.append(instance)
        try:
            return data_with_correct_shop[data_id]
        except IndexError:
            warnings.warn('The data by the index {} doesn\'t exist'.format(data_id))
            return None

    @staticmethod
    def get_the_idx_for_the_data_types(task_description_json):
        profiles_idx = task_description_json['task']['profiles_id']
        billing_idx = task_description_json['task']['billing_id']
        shipping_idx = task_description_json['task']['shipping_id']
        proxies_idx = task_description_json['task']['proxies_id']
        items_idx = task_description_json['task']['item_id']

        return profiles_idx, billing_idx, shipping_idx, proxies_idx, items_idx

    @staticmethod
    def buy(bot, item_link, profiles=None, billing=None, shipping=None, proxies=None):
        bot.buy_item(item_link=item_link, billing_data=billing, profile_data=profiles, proxies_data=proxies,
                     shipping_data=shipping)

    @staticmethod
    def register(bot, profiles=None, billing=None, shipping=None, proxies=None):
        bot.register(billing_data=billing, shipping_data=shipping, profile_data=profiles, proxies_data=proxies)

    @staticmethod
    def login(bot, profiles):
        bot.login(profiles_data=profiles)

    def execute_whole_buying_process(self, bot, profiles, billing, shipping, proxies, items):
        pass


# assset - актив. Подразумевается, что это конкретный элемент из активов в портфеле на счете у брокера
import datetime
import typing

from tinkoff.invest import (
    PortfolioPosition
)
from tinkoff.invest.grpc.operations_pb2 import OperationsResponse, Operation

from traider.responses.user_info_responses import (
    AssetsShow,
    ShowMyMoney,
    CurrentAsset
)
from traider.traider_client import TraiderClient

class PortfolioUserInfo(TraiderClient):
    def __init__(self):
        super().__init__()
        self._portfolio = self._operations.get_portfolio(account_id=self.id_)

    def __create_asset_item(self, item: PortfolioPosition) -> AssetsShow:
        """Создает объект AssetsShow, который исспользуется для отображения
        усеченной информации об Активе, отображенного в списке всех активов.
        """
        item_name = self._get_asset_item(
            item.instrument_type, item.figi).name
        return AssetsShow(
            name=item_name,
            figi=item.figi,
            amount=self.resp_to_float(item.quantity),
            average_price=self.resp_to_float(
                item.average_position_price),
            item_type=item.instrument_type
        )

    def get_total_balance(self) -> ShowMyMoney:
        portfolio = self._portfolio.total_amount_portfolio
        return ShowMyMoney(
            units=portfolio.units,
            currency=portfolio.currency,
            yield_=self.resp_to_float(self._portfolio.expected_yield))

    def get_list_of_assets(self) -> list[AssetsShow]:
        my_assets = []
        for pos in self._portfolio.positions:
            my_assets.append(self.__create_asset_item(pos))
        return my_assets

    def __sum_price(self, item: PortfolioPosition) -> float:
        """Рассчет сумы всех активов после продажи"""
        amount = self.resp_to_float(item.quantity)
        avg_price = self.resp_to_float(item.average_position_price)
        exp_yield = self.resp_to_float(item.expected_yield)
        nkd = self.resp_to_float(item.current_nkd)
        tax = exp_yield * 0.013 if exp_yield else 0
        return (amount * avg_price) + exp_yield + (nkd * amount) - tax

    def get_price_after_selling(self) -> float:
        positions = self._portfolio.positions
        sell_sum = [self.__sum_price(item) for item in positions]
        sum_without_comission = sum(sell_sum)
        return sum_without_comission - (sum_without_comission * 0.003)

    def __get_current_asset_item(
            self, item: PortfolioPosition) -> CurrentAsset:
        return CurrentAsset(
            name=self._get_asset_item(
                item.instrument_type, item.figi).name,
            amount=self.resp_to_float(item.quantity),
            current_price=self.resp_to_float(item.current_price),
            average_price=self.resp_to_float(item.average_position_price),
            figi=item.figi,
            nkd=self.resp_to_float(item.current_nkd)
        )

    def get_current_asset(self, figi_callback: str) -> CurrentAsset | str:
        """Передается в переменную figi_callback строка вида
        ,например, Figi_HND123LKJ.
        """
        figi = figi_callback.split('_')[1]
        item = [i for i in self._portfolio.positions if i.figi == figi]
        if item:
            return self.__get_current_asset_item(item[0])
        return 'ничего не нафдено'

class UserOperations(TraiderClient):
    def __init__(self):
        super().__init__()

    @staticmethod
    def _days_int_to_datetime(days_ago: int) -> datetime:
        """Метод перевода количества дней в дату, предшествующую текущей на указанное количество дней."""
        today = datetime.datetime.now()
        delta = datetime.timedelta(days=days_ago)
        return today - delta

    def get_last_operations(
            self, days_ago: int = 10,
            figi: typing.Optional[str] = None) -> list[Operation]:
        """Возвращает последние операции пользователя за определенное количество дней.
            :param days_ago количество дней за которое необходимо узнать об операциях.
            :param figi неоьязательный аргумент для поиска операций по его идентификатору
        """
        params = {
            'account_id': self.id_,
            'from_': self._days_int_to_datetime(days_ago),
            'to': datetime.datetime.utcnow(),
        }
        if figi:
            params.update({'figi': figi})
            return self._operations.get_operations(**params).operations
        return self._operations.get_operations(**params).operations

user_info = PortfolioUserInfo()
user_operations = UserOperations()


from __future__ import absolute_import, division, print_function
import sys, os
import re
import libtbx.load_env

boost_python_include_pat = re.compile(r"#include\s*<boost(?:/|_)python");

def run(modules):
  directory_paths = [ libtbx.env.dist_path(m) for m in modules ]
  line_counts_in_files_of_type = {}
  for d in directory_paths:
    for root, dirs, files in os.walk(d):
      for f in files:
        if f.startswith('.'): continue
        _, ext = os.path.splitext(f)
        if ext in ('.pyo', '.pyc'): continue
        boost_python_binding = False
        n_lines = 0
        with open(os.path.join(root,f)) as fo:
          for li in fo:
            n_lines += 1
            if (not boost_python_binding
                and boost_python_include_pat.search(li)):
              boost_python_binding = True
        if boost_python_binding:
          file_type = "Boost.Python"
        elif not ext:
          file_type = "unknown"
        else:
          file_type = ext[1:]
        line_counts_in_files_of_type.setdefault(file_type, []).append(n_lines)
  print("Lines of code in %s" % ', '.join(modules))
  print("%-15s%8s" % ('extension', '#lines'))
  output = []
  for file_type, line_counts in line_counts_in_files_of_type.items():
    cnt = sum(line_counts)
    output.append((cnt, "%-15s%8d" % (file_type, cnt)))
  output.sort(reverse=True)
  output = [ entry[1] for entry in output ]
  print('\n'.join(output))

if __name__ == '__main__':
  run(sys.argv[1:])


# -*- coding: utf-8 -*-
import sys

from PyQt5.QtGui import QIcon

import Main_window as main_win
import qsm_n
import sj_n
import table
import sj_w
import qsm_w
import win_sub
import win_obj
import sj_win_sub
import sj_win_obj
import demo_main as demo
import numpy as np

from PyQt5.QtWidgets import QApplication, QMainWindow, QFileDialog
from PyQt5 import QtCore
import qdarkstyle
from docx import Document
from docx.shared import Pt
from docx.enum.text import WD_PARAGRAPH_ALIGNMENT

class main_win_Ui(QMainWindow, main_win.Ui_MainWindow):
    def __init__(self):
        super(main_win_Ui, self).__init__()
        self.setupUi(self)

class sj_w_Ui(QMainWindow, sj_w.Ui_Dialog):
    def __init__(self):
        super(sj_w_Ui, self).__init__()
        self.setupUi(self)

class qsm_w_Ui(QMainWindow, qsm_w.Ui_Dialog):
    def __init__(self):
        super(qsm_w_Ui, self).__init__()
        self.setupUi(self)

class table_Ui(QMainWindow, table.Ui_Dialog):
    def __init__(self):
        super(table_Ui, self).__init__()
        self.setupUi(self)

if __name__ == '__main__':
    QtCore.QCoreApplication.setAttribute(QtCore.Qt.AA_EnableHighDpiScaling, True)

    app = QApplication(sys.argv)
    app.setStyleSheet(qdarkstyle.load_stylesheet_pyqt5())
    main_win = main_win_Ui()
    main_win.setWindowIcon(QIcon('app_icon.ico'))
    main_win.show()

    sj_w = sj_w_Ui()
    qsm_w = qsm_w_Ui()
    win_sub = win_sub.MatrixInputApp()
    # win_obj = win_obj_old.DynamicGridLayoutWidget()
    win_obj = win_obj.MatrixCalculator()
    sj_win_sub = sj_win_sub.MatrixInputApp()

    # sj_win_obj = sj_win_obj_old.DynamicGridLayoutWidget()
    sj_win_obj = sj_win_obj.MatrixCalculator()
    qsm_n = qsm_n.MatrixCalculator()
    sj_n = sj_n.MatrixCalculator()
    table = table_Ui()

    def sub_ww():
        try:
            x = qsm_w
            zg = [x.zg11, x.zg12, x.zg13, x.zg14, x.zg15, x.zg16, x.zg17,
                  x.zg21, x.zg22, x.zg23,
                  x.zg31, x.zg32, x.zg33, x.zg34,
                  x.zg41, x.zg42, x.zg43, x.zg44,
                  x.zg51, x.zg52]
            sub = win_sub.sub_w[5:]
            for i in range(len(sub)):
                zg[i].setText(str(sub[i]))
            win_sub.close()
        except:
            print('error')
        return

    def obj_ww():
        try:
            x = qsm_w
            kg = [x.kg11, x.kg12, x.kg13, x.kg14, x.kg15, x.kg16, x.kg17,
                  x.kg21, x.kg22, x.kg23,
                  x.kg31, x.kg32, x.kg33, x.kg34,
                  x.kg41, x.kg42, x.kg43, x.kg44,
                  x.kg51, x.kg52]
            obj = win_obj.obj_w
            for i in range(len(obj)):
                kg[i].setText(str(obj[i]))
            win_obj.close()
        except:
            print('error')
        return

    def zh_ww():
        try:
            x = qsm_w
            zh = [x.zh11, x.zh12, x.zh13, x.zh14, x.zh15, x.zh16, x.zh17,
                  x.zh21, x.zh22, x.zh23,
                  x.zh31, x.zh32, x.zh33, x.zh34,
                  x.zh41, x.zh42, x.zh43, x.zh44,
                  x.zh51, x.zh52]
            zhw = demo.combine2_W(win_sub.sub_w, win_obj.obj_w)
            for i in range(len(zhw)):
                zh[i].setText(str(zhw[i]))
        except:
            print('error')
        return

    def save_ww():
        qsm_w.close()
        main_win.label_qsm_w.setText("组合权重计算成功！")

    def save_nn():
        qsm_n.close()
        main_win.label_qsm_n.setText("确定度计算成功！")

    def res():
        try:
            zhw = demo.combine2_W(win_sub.sub_w, win_obj.obj_w)
            L, level = demo.cal_L(qsm_n.matrix, zhw)
            main_win.lable_qsm_level.setText(f"隶属度:{L},\n可靠性:{level}")
        except:
            main_win.lable_qsm_level.setText("请先完成上面的步骤！")
        return

    def save():
        try:
            doc = Document()
            project = main_win.lineEdit_project.text()
            name = main_win.lineEdit_name.text()  # 负责人
            start = main_win.lineEdit.text()  # 开工时间
            end = main_win.lineEdit_2.text()  # 竣工时间
            run = main_win.lineEdit_3.text()  # 开始运营时间

            sub_input = win_sub.matrices  # 比较矩阵
            sub = win_sub.sub_w  # 主观权重
            X = win_obj.input_values  # 客观权重打分值
            obj_input = [[round(X[j] / X[i], 3) for i in range(len(X))] for j in range(len(X))]
            obj = win_obj.obj_w  # 客观权重
            zhw = demo.combine2_W(sub, obj)  # 组合权重
            n_input = qsm_n.input_values
            n_matrix = qsm_n.matrix  # 单因素矩阵
            L, level = demo.cal_L(qsm_n.matrix, zhw)
            text = '\n'.join(["全寿命阶段", f"项目名称：{project}", f"负责人：{name}",
                              f"开工时间：{start}，竣工时间：{end}，开始运营时间：{run}",
                              f"比较矩阵：{sub_input}", f"主观权重：{sub}",
                              f"客观权重计算输入：{obj_input}", f"客观权重：{obj}", f"组合权重：{zhw}",
                              f"确定度计算输入：{n_input}", f"单因素矩阵：{n_matrix}",
                              f"隶属度：{L}", f"可靠性等级：{level}"])
            print(text)
            doc.add_paragraph().add_run("全寿命阶段").bold = True
            text = '\n'.join([f"项目名称：{project}", f"负责人：{name}",
                              f"开工时间：{start}，竣工时间：{end}，开始运营时间：{run}",
                              f"可靠性等级：{level}"])
            doc.add_paragraph(text)

            # 定义表格数据

            doc.add_paragraph().add_run("步骤1：权重计算").bold = True
            doc.add_paragraph().add_run("1. 主观权重计算：\n        将问卷调查的数据进行整理作为主观权重计算的输入数据，得到比较矩阵如表1-表6所示")

            # 比较矩阵
            zb_name = ['材料因素U1', '结构抗变形能力因素U2', '水文地质条件因素U3',
                       '施工期影响因素','运营期影响因素',
                       '管片材料U11', '管片质量U12', '防水材料类型U13', '防水材料老化特性U14', '密封垫构型/防水能力U15', '密封垫固定形式U16', '密封垫布置形式U17',
                       '纵缝接头刚度U21', '环缝抗剪刚度U22', '内部结构类型U23',
                       '水压U31', '不均匀地层U32', '温度影响U33', '水位影响U34',
                       '施工期上浮变形U41', '拼装精度U42', '姿态控制U43', '成型管片U44',
                       '水位影响U51', '纵向应力松弛U52'
                       ]
            hzb1 = zzb1 = zb_name[:5]
            hzb2 = zzb2 = zb_name[5:12]
            hzb3 = zzb3 = zb_name[12:15]
            hzb4 = zzb4 = zb_name[15:19]
            hzb5 = zzb5 = zb_name[19:23]
            hzb6 = zzb6 = zb_name[23:]

            hzb_1 = [hzb1, hzb2, hzb3, hzb4,hzb5,hzb6]
            zzb_1 = [zzb1, zzb2, zzb3, zzb4,zzb5,zzb6]
            data_1 = sub_input

            table_name = ['表1 准则层评价指标比较矩阵A', '表2 材料因素U1评价指标比较矩阵A', '表3 结构抗变形能力因素U2评价指标比较矩阵A',
                          '表4 水文地质条件因素U3评价指标比较矩阵A', '表5 施工期影响因素U4评价指标比较矩阵A', '表6 运营期影响因素U5评价指标比较矩阵A']
            for i in range(len(table_name)):
                create_table_with_title(doc, table_name[i], hzb_1[i], zzb_1[i], len(data_1[i]), len(data_1[i][0]),
                                        data_1[i])

            # 主观权重
            doc.add_paragraph().add_run('通过改进的层次分析法可以得到盾构隧道全寿命阶段防水可靠性评价指标的主观权重值如表7所示。')
            # sub = [9.876, 8.765, 7.654,6.543, 5.432, 4.321, 3.210, 2.109, 1.098]
            data_2 = [[x] for x in sub[5:]]
            hzb_2 = ['影响因素', '主观权重']
            zzb_2 = zb_name[5:]

            create_table_with_title(doc, '表7 盾构隧道全寿命阶段防水可靠性评价指标主观权重值', hzb_2, zzb_2, len(data_2), len(data_2[0]), data_2)
            # 客观权重
            doc.add_paragraph().add_run('2. 客观权重计算：\n        采用层次分析法原理将每个评价指标因素对防水能力的影响程度进行两两对比得到评判矩阵如表8所示')
            # obj_input = [[1, 1], [1, 1]]
            data_3 = obj_input
            hzb_3 = zzb_3 = zb_name[5:]
            zzb_3 = [i[-3:] for i in zzb_3]
            create_table_with_title(doc, '表8 评价指标因素对防水能力影响程度的评判矩阵', hzb_3, zzb_3, len(data_3), len(data_3[0]), data_3)

            doc.add_paragraph().add_run(
                '采用求解矩阵最大特征根的方法计算判断矩阵的最大特征值及其对应的特征向量，并对最大特征向量进行归一化处理得到盾构隧道全寿命阶段防水可靠性评价指标客观权重值如表9所示')
            # obj = [9.876, 8.765, 7.654, 6.543, 5.432, 4.321, 3.210, 2.109, 1.098]
            data_4 = [[x] for x in obj]
            hzb_4 = ['影响因素', '客观权重']
            zzb_4 = zb_name[5:]
            create_table_with_title(doc, '表9 盾构隧道全寿命阶段防水可靠性评价指标客观权重值', hzb_4, zzb_4, len(data_4), len(data_4[0]), data_4)

            # 组合权重
            doc.add_paragraph().add_run(
                f'3. 组合权重计算\n        根据博弈论法对得到的主、客观权重进行综合计算得到组合权重。以将组合权重与主、客观权重之间的离差极小化作为目标，计算得到的主观权重如表10所示。')
            # zh_w = [9.876, 8.765, 7.654, 6.543, 5.432, 4.321, 3.210, 2.109, 1.098]
            data_5 = np.array([sub[5:], obj, zhw]).T
            hzb_5 = ['主观权重', '客观权重', '组合权重']
            zzb_5 = zb_name[5:]
            create_table_with_title(doc, '表10 盾构隧道全寿命阶段防水可靠性评价指标主、客观权重值', hzb_5, zzb_5, len(data_5), len(data_5[0]),
                                    data_5)
            # 单因素确定度计算
            doc.add_paragraph().add_run("步骤二：单因素确定度计算").bold = True
            doc.add_paragraph().add_run("根据需要评价项目的实际情况得到盾构隧道防水全寿命阶段可靠性评价指标的实际取值如表11所示")
            # n_input = [9.876, 8.765, 7.654, 6.543, 5.432, 4.321, 3.210, 2.109, 1.098]
            data_6 = [[x] for x in n_input]
            hzb_6 = ['影响因素', '取值']
            zzb_6 = zb_name[5:]
            create_table_with_title(doc, '表11 盾构隧道全寿命阶段防水可靠性评价指标实际取值', hzb_6, zzb_6, len(data_6), len(data_6[0]), data_6)

            # n_matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
            data_7 = n_matrix
            hzb_7 = ['一级', '二级', '三级', '四级', '五级']
            zzb_7 = zb_name[5:]
            zzb_7 = [i[-3:] for i in zzb_7]
            create_table_with_title(doc, '表12 盾构隧道全寿命阶段防水可靠性评价指标单因素确定度', hzb_7, zzb_7, len(data_7), len(data_7[0]),
                                    data_7)

            # 隶属度
            doc.add_paragraph().add_run("步骤三：盾构隧道全寿命阶段防水体系可靠性等级计算").bold = True
            doc.add_paragraph().add_run("根据计算得到的组合权重和单因素确定度，采用加权平均法通过公式将地层评价结果传递给上一层，进而得到盾构隧道设计阶段防水可靠性评价等级结果如表13所示")
            # L = [0.1,0.1,0.1,0.1,0.1]
            data_8 = [L]
            hzb_8 = ['一级（低可靠性）', '二级（较低可靠性）', '三级（中等可靠性）', '四级（较高可靠性）', '五级（高可靠性）']
            zzb_8 = ['隶属度计算值']
            create_table_with_title(doc, '表13 盾构隧道全寿命阶段防水可靠性评价等级结果', hzb_8, zzb_8, len(data_8), len(data_8[0]),
                                    data_8)

            doc.add_paragraph().add_run(f'根据计算得到的综合确定度，按照隶属度最大原则得到最终的隶属度等级为{level}')

            options = QFileDialog.Options()
            file_name, _ = QFileDialog.getSaveFileName(caption='Save File', directory='',
                                                       filter="Word Files (*.docx);;All Files (*)", options=options)

            doc.save(file_name)
            main_win.lable_qsm_save.setText("导出成功！")
        except:
            main_win.lable_qsm_save.setText("导出失败，请按照要求完成操作！")
        return

    def sj_sub_ww():
        try:
            x = sj_w
            zg = [x.zg11, x.zg12, x.zg13, x.zg14, x.zg15, x.zg16, x.zg17,
                  x.zg21, x.zg22, x.zg23,
                  x.zg31, x.zg32, x.zg33, x.zg34]
            sub = sj_win_sub.sub_w[3:]
            for i in range(len(sub)):
                zg[i].setText(str(sub[i]))
            sj_win_sub.close()
        except:
            print("error")
        return

    def sj_obj_ww():
        try:
            x = sj_w
            kg = [x.kg11, x.kg12, x.kg13, x.kg14, x.kg15, x.kg16, x.kg17,
                  x.kg21, x.kg22, x.kg23,
                  x.kg31, x.kg32, x.kg33, x.kg34]
            obj = sj_win_obj.obj_w
            for i in range(len(obj)):
                kg[i].setText(str(obj[i]))
            sj_win_obj.close()
        except:
            print("error")
        return

    def sj_zh_ww():
        try:
            x = sj_w
            zh = [x.zh11, x.zh12, x.zh13, x.zh14, x.zh15, x.zh16, x.zh17,
                  x.zh21, x.zh22, x.zh23,
                  x.zh31, x.zh32, x.zh33, x.zh34]
            zhw = demo.combine2_W(sj_win_sub.sub_w, sj_win_obj.obj_w)
            for i in range(len(zhw)):
                zh[i].setText(str(zhw[i]))
        except:
            print('error')
        return

    def sj_save_ww():
        sj_w.close()
        main_win.label_5.setText("权重计算成功！")
        return

    def sj_save_nn():
        sj_n.close()
        main_win.label_6.setText("确定度计算成功！")
        return

    def sj_res():
        try:
            zhw = demo.combine2_W(sj_win_sub.sub_w, sj_win_obj.obj_w)
            L, level = demo.cal_L(sj_n.matrix, zhw)
            main_win.lable_sj_level.setText(f"隶属度:{L},\n可靠性:{level}")
        except:
            main_win.lable_sj_level.setText("请先完成上面步骤！")
        return

    def create_table_with_title(doc, name, hzb, zzb, rows, cols, data):
        # 表名
        paragraph = doc.add_paragraph()
        paragraph.add_run(name).bold = True
        paragraph.alignment = WD_PARAGRAPH_ALIGNMENT.CENTER
        paragraph.paragraph_format.space_after = Pt(0)

        # 创建表格
        table = doc.add_table(rows=rows + 1, cols=cols + 1)
        table.style = 'Table Grid'

        # 设置表格中的横坐标
        for i in range(cols):
            cell = table.cell(0, i + 1)
            cell.text = hzb[i]
            cell.paragraphs[0].alignment = WD_PARAGRAPH_ALIGNMENT.CENTER
        # for i in range(rows+1):
        #     cell = table.cell(i, 0)
        #     cell.width = Cm(5)
        # 设置表格中的纵坐标
        for i in range(rows):
            cell = table.cell(i + 1, 0)
            cell.text = zzb[i]

        # 设置表格内容
        for i in range(rows):
            for j in range(cols):
                cell = table.cell(i + 1, j + 1)
                if i < len(data) and j < len(data[i]):
                    cell.text = str(data[i][j])
                    cell.paragraphs[0].alignment = WD_PARAGRAPH_ALIGNMENT.CENTER
                        # "{:.3f}".format(data[i][j])

        doc.add_paragraph("")

    def sj_save():
        try:
            doc = Document()
            project = main_win.lineEdit_project.text()
            name = main_win.lineEdit_name.text()  # 负责人
            start = main_win.lineEdit.text()  # 开工时间
            end = main_win.lineEdit_2.text()  # 竣工时间
            run = main_win.lineEdit_3.text()  # 开始运营时间

            sub_input = sj_win_sub.matrices  # 比较矩阵
            sub = sj_win_sub.sub_w # 主观权重
            X = sj_win_obj.input_values  # 客观权重打分值
            obj_input = [[round(X[j] / X[i], 3) for i in range(len(X))] for j in range(len(X))]
            obj = sj_win_obj.obj_w  # 客观权重
            zhw = demo.combine2_W(sub, obj)  # 组合权重
            n_input = sj_n.input_values
            n_matrix = sj_n.matrix  # 单因素矩阵
            L, level = demo.cal_L(sj_n.matrix, zhw)

            text = '\n'.join([f"项目名称：{project}", f"负责人：{name}",
                              f"开工时间：{start}，竣工时间：{end}，开始运营时间：{run}",
                              f"比较矩阵：{sub_input}", f"主观权重：{sub}",
                              f"客观权重计算输入：{obj_input}", f"客观权重：{obj}", f"组合权重：{zhw}",
                              f"确定度计算输入：{n_input}", f"单因素矩阵：{n_matrix}",
                              f"隶属度：{L}", f"可靠性等级：{level}"])
            print(text)

            doc.add_paragraph().add_run("设计阶段").bold = True
            # level = '5级'
            text = '\n'.join([f"项目名称：{project}", f"负责人：{name}",
                              f"开工时间：{start}，竣工时间：{end}，开始运营时间：{run}",
                              f"可靠性等级：{level}"])
            doc.add_paragraph(text)

            # 定义表格数据

            doc.add_paragraph().add_run("步骤1：权重计算").bold = True
            doc.add_paragraph().add_run("1. 主观权重计算：\n        将问卷调查的数据进行整理作为主观权重计算的输入数据，得到比较矩阵如表1-表4所示")

            # 比较矩阵
            zb_name = ['材料因素U1', '结构抗变形能力因素U2', '水文地质条件因素U3',
                       '管片材料U11', '管片质量U12', '防水材料类型U13', '防水材料老化特性U14', '密封垫构型/防水能力U15', '密封垫固定形式U16', '密封垫布置形式U17',
                       '纵缝接头刚度U21', '环缝抗剪刚度U22', '内部结构类型U23',
                       '水压U31', '不均匀地层U32', '温度影响U33', '水位影响U34',
                       ]
            hzb1 = zzb1 = zb_name[:3]
            hzb2 = zzb2 = zb_name[3:10]
            hzb3 = zzb3 = zb_name[10:13]
            hzb4 = zzb4 = zb_name[13:]

            hzb_1 = [hzb1, hzb2, hzb3, hzb4]
            zzb_1 = [zzb1, zzb2, zzb3, zzb4]
            # sub_input = [[[1, 1], [1, 1]], [[1, 1], [1, 1]], [[1, 1], [1, 1]], [[1, 1], [1, 1]]]
            # data1, data2, data3, data4 = sub_input
            data_1 = sub_input

            table_name = ['表1 准则层评价指标比较矩阵A', '表2 材料因素U1评价指标比较矩阵A', '表3 结构抗变形能力因素U2评价指标比较矩阵A', '表4 水文地质条件因素U3评价指标比较矩阵A']
            for i in range(len(table_name)):
                create_table_with_title(doc, table_name[i], hzb_1[i], zzb_1[i], len(data_1[i]), len(data_1[i][0]),
                                        data_1[i])

            # 主观权重
            doc.add_paragraph().add_run('通过改进的层次分析法可以得到盾构隧道设计阶段防水可靠性评价指标的主观权重值如表5所示。')
            # sub = [9.876, 8.765, 7.654,6.543, 5.432, 4.321, 3.210, 2.109, 1.098]
            data_2 = [[x] for x in sub[3:]]
            hzb_2 = ['影响因素','主观权重']
            zzb_2 = zb_name[3:]

            create_table_with_title(doc, '表5 盾构隧道设计阶段防水可靠性评价指标主观权重值', hzb_2, zzb_2, len(data_2), len(data_2[0]), data_2)
            # 客观权重
            doc.add_paragraph().add_run('2. 客观权重计算：\n        采用层次分析法原理将每个评价指标因素对防水能力的影响程度进行两两对比得到评判矩阵如表6所示')
            # obj_input = [[1, 1], [1, 1]]
            data_3 = obj_input
            hzb_3 = zzb_3 = zb_name[3:]
            zzb_3 = [i[-3:] for i in zzb_3]
            create_table_with_title(doc, '表6 评价指标因素对防水能力影响程度的评判矩阵', hzb_3, zzb_3, len(data_3), len(data_3[0]), data_3)

            doc.add_paragraph().add_run('采用求解矩阵最大特征根的方法计算判断矩阵的最大特征值及其对应的特征向量，并对最大特征向量进行归一化处理得到盾构隧道设计阶段防水可靠性评价指标客观权重值如表7所示')
            # obj = [9.876, 8.765, 7.654, 6.543, 5.432, 4.321, 3.210, 2.109, 1.098]
            data_4 = [[x] for x in obj]
            hzb_4 = ['影响因素', '客观权重']
            zzb_4 = zb_name[3:]
            create_table_with_title(doc, '表7 盾构隧道设计阶段防水可靠性评价指标客观权重值', hzb_4, zzb_4, len(data_4), len(data_4[0]), data_4)

            # 组合权重
            # n1 = '公式1'
            doc.add_paragraph().add_run(f'3. 组合权重计算\n        根据博弈论法对得到的主、客观权重进行综合计算得到组合权重。以将组合权重与主、客观权重之间的离差极小化作为目标，计算得到的组合权重如表8所示。')
            # zh_w = [9.876, 8.765, 7.654, 6.543, 5.432, 4.321, 3.210, 2.109, 1.098]
            data_5 = np.array([sub[3:], obj, zhw]).T
            hzb_5 = ['主观权重','客观权重', '组合权重']
            zzb_5 = zb_name[3:]
            create_table_with_title(doc, '表8 盾构隧道设计阶段防水可靠性评价指标主、客观权重值', hzb_5, zzb_5, len(data_5), len(data_5[0]), data_5)

            # 单因素确定度计算
            doc.add_paragraph().add_run("步骤二：单因素确定度计算").bold = True
            doc.add_paragraph().add_run("根据需要评价项目的实际情况得到盾构隧道防水设计阶段可靠性评价指标的实际取值如表9所示")
            # n_input = [9.876, 8.765, 7.654, 6.543, 5.432, 4.321, 3.210, 2.109, 1.098]
            data_6 = [[x] for x in n_input]
            hzb_6 = ['影响因素', '取值']
            zzb_6 = zb_name[3:]
            create_table_with_title(doc, '表9 盾构隧道设计阶段防水可靠性评价指标实际取值', hzb_6, zzb_6, len(data_6), len(data_6[0]), data_6)

            # n_matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
            data_7 = n_matrix
            doc.add_paragraph().add_run("通过公式求解每个评价指标隶属于某一层次的单因素确定性程度，计算得到的结果如表10所示")
            hzb_7 = ['一级','二级','三级','四级','五级']
            zzb_7 = zb_name[3:]
            zzb_7 = [i[-3:] for i in zzb_7]
            create_table_with_title(doc, '表10 盾构隧道设计阶段防水可靠性评价指标单因素确定度', hzb_7, zzb_7, len(data_7), len(data_7[0]),data_7)

            # 隶属度
            doc.add_paragraph().add_run("步骤三：盾构隧道设计阶段防水体系可靠性等级计算").bold = True
            doc.add_paragraph().add_run("根据计算得到的组合权重和单因素确定度，采用加权平均法通过公式将地层评价结果传递给上一层，进而得到盾构隧道设计阶段防水可靠性评价等级结果如表11所示")
            data_8 = [L]
            hzb_8 = ['一级（低可靠性）', '二级（较低可靠性）', '三级（中等可靠性）', '四级（较高可靠性）', '五级（高可靠性）']
            zzb_8 = ['隶属度计算值']
            create_table_with_title(doc, '表11 盾构隧道设计阶段防水可靠性评价等级结果', hzb_8, zzb_8, len(data_8), len(data_8[0]),
                                    data_8)

            doc.add_paragraph().add_run(f'根据计算得到的综合确定度，按照隶属度最大原则得到最终的隶属度等级为{level}')

            options = QFileDialog.Options()
            file_name, _ = QFileDialog.getSaveFileName(caption='Save File', directory='',
                                                       filter="Word Files (*.docx);;All Files (*)", options=options)

            doc.save(file_name)
            main_win.lable_sj_lsave.setText("导出成功！")

        except:
            main_win.lable_sj_lsave.setText("导出失败，请按照要求完成操作！")
        return

    main_win.sj_w.clicked.connect(
        lambda: {sj_w.show()}
    )
    main_win.qsm_w.clicked.connect(
        lambda: {qsm_w.show()}
    )

    # 权重计算
    # 设计阶段
    sj_w.pushButton_s1.clicked.connect(
        lambda: {sj_win_sub.show()}
    )

    sj_w.pushButton_s2.clicked.connect(
        lambda: {sj_win_obj.show()}
    )

    sj_w.pushButton_s3.clicked.connect(
        sj_zh_ww
    )

    sj_w.pushButton_s4.clicked.connect(
        sj_save_ww
    )
    sj_win_sub.save_button.clicked.connect(
        sj_sub_ww
    )
    sj_win_obj.save_button.clicked.connect(
        sj_obj_ww
    )
    # 全寿命阶段
    qsm_w.pushButton_s1.clicked.connect(
        lambda: {win_sub.show()}
    )

    qsm_w.pushButton_s2.clicked.connect(
        lambda: {win_obj.show()}
    )
    qsm_w.pushButton_s3.clicked.connect(
        zh_ww
    )
    qsm_w.pushButton_s4.clicked.connect(
        save_ww
    )
    win_sub.save_button.clicked.connect(
        sub_ww
    )
    win_obj.save_button.clicked.connect(
        obj_ww
    )

    # 确定度计算
    main_win.sj_n.clicked.connect(
        lambda: {sj_n.show()}
    )
    sj_n.pushButton_fig.clicked.connect(
        lambda: {table.show()}
    )
    sj_n.pushButton_save.clicked.connect(
        sj_save_nn
    )

    main_win.qsm_n.clicked.connect(
        lambda: {qsm_n.show()}
    )
    qsm_n.pushButton_fig.clicked.connect(
        lambda: {table.show()}
    )
    qsm_n.pushButton_save.clicked.connect(
        save_nn
    )

    # 可靠性评价
    main_win.qsm_level.clicked.connect(
        res
    )
    main_win.qsm_save.clicked.connect(
        save
    )
    main_win.sj_level.clicked.connect(
        sj_res
    )
    main_win.sj_save.clicked.connect(
        sj_save
    )
    sys.exit(app.exec_())


from django.shortcuts import get_object_or_404
from rest_framework import filters, viewsets
from rest_framework.pagination import LimitOffsetPagination
from rest_framework.permissions import AllowAny

from posts.models import Comment, Group, Post

from .mixins import GetPostViewSet
from .permissions import AuthorOrReadOnly
from .serializers import (CommentSerializer, FollowSerializer, GroupSerializer,
                          PostSerializer)

class GroupViewSet(viewsets.ReadOnlyModelViewSet):
    queryset = Group.objects.all()
    permission_classes = (AllowAny,)
    serializer_class = GroupSerializer

class PostViewSet(viewsets.ModelViewSet):
    queryset = Post.objects.all()
    serializer_class = PostSerializer
    permission_classes = (AuthorOrReadOnly,)
    pagination_class = LimitOffsetPagination

    def perform_create(self, serializer):
        serializer.save(author=self.request.user)

class CommentViewSet(viewsets.ModelViewSet):
    queryset = Comment.objects.all()
    serializer_class = CommentSerializer
    permission_classes = (AuthorOrReadOnly,)

    def get_post(self):
        post = get_object_or_404(Post, id=self.kwargs.get("post_id"))
        return post

    def get_queryset(self):
        post = self.get_post()
        return post.comments.all()

    def perform_create(self, serializer):
        post = self.get_post()
        serializer.save(author=self.request.user, post=post)

class FollowViewSet(GetPostViewSet):
    serializer_class = FollowSerializer
    filter_backends = (filters.SearchFilter,)
    search_fields = ('following__username',)

    def perform_create(self, serializer):
        serializer.save(user=self.request.user)

    def get_queryset(self):
        user = self.request.user
        return user.follower.all()


#!/usr/bin/env python
from Bio import SeqIO, Seq
from re import compile
import numpy as np
from sys import argv, stderr

p = compile("[actg]")
f = SeqIO.parse(open(argv[1]), "fasta")
#lowercase masked intron contigs

ep_hint_length = 10

contig_coords = {}
for rec in f:
  aseq = str(rec.seq)
  strip_seq = p.sub('', aseq)
  coords = np.zeros((len(aseq) + 1,), dtype=int)

  newseq = ""
  coord_d = {}
  i, j = 0, 0

  for b in aseq:
    i += 1
    if b.islower():
      j += 1
    else:
      coords[i] = i - j

  contig_coords[rec.name] = coords

for line in open(argv[2]):
  atoms = line.split()
  contig = atoms[0]
  prog = atoms[1]
  src = atoms[2]

  try:
    if contig in contig_coords:
      s, e = contig_coords[contig][int(atoms[3])], contig_coords[contig][int(atoms[4])]
      score = atoms[5]
      strand = atoms[6]
      note = atoms[-1]

      if e - s + 1 == ep_hint_length:
        print("%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s" % (contig, prog, src, s, e, score, strand, ".", note))

  except IndexError:
    stderr.write("EP hint out of bounds: %s %s %s" % (contig, atoms[3], atoms[4]))


#!flask/bin/python
from flask import Flask, request, jsonify, make_response, abort
import cPickle as pickle

from main import *

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

app = Flask(__name__)

#app.run(threaded=True)

questions = [
	{
		'qId': 1,
		'qText': 'Dummy Question',
		'qParts': [],
		'qFocus': [],
		'qFocRoots': [],
		'qMod': [],
		'qClass': [],
		'qPnoun': [],
		'qSubj': [],
		'qTransPhrase': [],
		'qTranslation': [],
		'qQuery': [],
		'qRelated_doc_ids': [],
		'qRelated_doc_titles': [],
		'qRelated_doc_texts': [],
		'done': False
		}
	]

question = []

@app.route('/hc-api/v0.1/dev', methods=['GET'])
def get_questions():
	return jsonify({'questions':questions})

@app.route('/hc-api/v0.1/devMass', methods=['POST'])
def mass_evaluate():
	print("HC_API: Running Mass Evaluator")
	if not request.json or not 'evalDataFile' in request.json:
		abort(400)

	dataPath = request.json['evalDataFile']
	topDocsNum = int(request.json['topDocs']) # we don't use it in mass, right?

	# READ DATA FILE (to fill these lists:)

	questionList, focusListAnnotatedT, modListAnnotatedT, classListAnnotated, parsedBefore, answerList = mainReadDataFile(dataPath)

	# RUN the SYSTEM on EVERY QUESTION (to fill these lists:)

	#total = len(questionList) # just for debugging
	# ['dummy']*total

	if topDocsNum == 1:
		bypassDocs=False
	else:
		bypassDocs=True

	focusListFoundT, modListFoundT, classListFound, transPhraseList, transList, relatedDocs, answerFoundInDocs, queries = mainEval(questionList, answerList, parsedBefore, dataPath, topDocs=topDocsNum, bypassDocs=bypassDocs)
	# format of relatedDocs -> [[titles, texts], [titles, texts], ...]

	print("HC_API: Compiling response ...")
	responseData = {
		'questionTexts': questionList,
		'answerList': answerList,
		'focusListAnnoT': focusListAnnotatedT,
		'focusListFoundT': focusListFoundT,
		'modListAnnoT': modListAnnotatedT,
		'modListFoundT': modListFoundT,
		'classListAnno': classListAnnotated,
		'classListFound': classListFound,
		'transPhraseList': transPhraseList,
		'transList': transList,
		'relatedDocs': relatedDocs,
		'answerFoundDocs': answerFoundInDocs,
		'queries': queries
			}

	print("HC_API: Posting response...")
	return jsonify({'responseData':responseData}), 201

@app.route('/hc-api/v0.1/dev', methods=['POST'])
def post_question():
	print("HC_API: Running Single")
	if not request.json or not 'questionText' in request.json:
		abort(400)

	print("\n\n\n=================\n\n")
	#print(request.json['topDocs'])
	print("\n\n\n=================\n\n")

	qText = request.json['questionText']

	topDocs = int(request.json['topDocs'])

	qObj = mainParse(qText)

	qFoc, qFocRoots, qMod, qClass, qPnoun, qSubj = mainAnalyze(qObj, False, False)

	qTerms = mainBuildQuery(qObj)

	docs = mainQuerySingle(count=topDocs)

	titles, texts = mainRelated(docs)

	transPhrase = " ".join([ qPnoun, qMod + qFoc ])
	translation = mainTranslate(transPhrase)

	print("HC_API: Compiling response...")
	question = {
		'qId': questions[-1]['qId'] + 1,
		'qText': qObj.questionText,
		'qParts': qObj.questionParts,
		'qFocus': qFoc,
		'qFocRoots': qFocRoots,
		'qMod': qMod,
		'qClass': qClass,
		'qPnoun': qPnoun,
		'qSubj': qSubj,
		'qTransPhrase': transPhrase,
		'qTranslation': translation,
		'qQuery': str(qTerms),
		'qRelated_doc_ids': docs,
		'qRelated_doc_titles': titles,
		'qRelated_doc_texts': texts,
		'done': True
		}

	questions.append(question)

	print("HC_API: Posting response...")
	return jsonify({'question':question}), 201

"""
@app.route('/')
def index():
        return "Hello, World!"
"""

@app.errorhandler(404)
def not_found(error):
    return make_response(jsonify({'error': 'Not found'}), 404)

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


# imported the requests library
import requests
import os
from bs4 import BeautifulSoup
import re
import urllib.request
# from urllib.request import Request, urlopen
import lxml
username = os.getlogin()
filestartswith1 = "coal"
filestartswith2 = "dynomite"
host_site = "https://archive.wrccdc.org/images/2020/wrccdc-2020-invitationals/rock.bottom/"
user_agent = 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.7) Gecko/2009021910 Firefox/3.0.7'
headers={'User-Agent':user_agent,}
request=urllib.request.Request(host_site,None,headers) #The assembled request
response = urllib.request.urlopen(request)
data = response.read() # The data u need
soup = BeautifulSoup(data, "lxml")
file_names = []
for link in soup.findAll('a'):
    if str(link).find(".ova") != -1:
        file_names.append(link.get('href'))
    else:
        pass
print(file_names)
for file_name in file_names:
    if file_name.startswith(filestartswith1) or file_name.startswith(filestartswith2):
        print("Downloading", file_name, "from", host_site, "...")
        path = "C:\\Users\\" + username + "\\Downloads\\Original-ova\\" + file_name
        file_url = host_site + "/" + file_name
        # URL of the image to be downloaded is defined as image_url
        r = requests.get(file_url) # create HTTP response object
        # send a HTTP request to the server and save
        # the HTTP response in a response object called r
        with open(path,'wb') as f:
            # Saving received content as a png file in
            # binary format
            # write the contents of the response (r.content)
            # to a new file in binary mode.
            f.write(r.content)
        print(file_name," download finished")


import tensorflow as tf

import skimage.transform, skimage.color
import numpy as np

def np_image_random(image,
                    rotate_angle=[-10, 10],
                    rescale=[0.8, 1.2],
                    whiten=False,
                    normalize=True,
                    hsv=True
                    ):
    """
    image should be a ndarray, dtype float
    """
    o_shape = image.shape
    if rotate_angle is not None:
        rotate_angle = np.random.random() * (rotate_angle[1] - rotate_angle[0]) + rotate_angle[0]
        image = skimage.transform.rotate(image, rotate_angle, mode='edge')
    if rescale is not None:
        rescale = np.random.random() * (rescale[1] - rescale[0]) + rescale[0]
        image = skimage.transform.rescale(image, scale=rescale, mode='edge')

    if whiten:
        image -= np.mean(image, axis=0)
        cov = np.dot(image.T, image) / image.shape[0]
        U, S, V = np.linalg.svd(cov)
        Xrot = np.dot(image, U)
        image = Xrot / np.sqrt(S + 1e-5)
    if normalize:
        image = image - np.mean(image, axis=0)
        image = image / np.std(image, axis=0)

        image = (image - np.min(image, axis=0)) / (np.max(image, axis=0) - np.min(image, axis=0))

    if hsv:
      image = skimage.color.rgb2hsv(image)

    return image

def distort_color(image, thread_id=0, scope=None):
    """Distort the color of the image.

  Each color distortion is non-commutative and thus ordering of the color ops
  matters. Ideally we would randomly permute the ordering of the color ops.
  Rather then adding that level of complication, we select a distinct ordering
  of color ops for each preprocessing thread.

  Args:
    image: Tensor containing single image.
    thread_id: preprocessing thread ID.
    scope: Optional scope for op_scope.
  Returns:
    color-distorted image
  """
    with tf.op_scope([image], scope, 'distort_color'):
        color_ordering = thread_id % 2

        if color_ordering == 0:
            image = tf.image.random_brightness(image, max_delta=32. / 255.)
            image = tf.image.random_saturation(image, lower=0.5, upper=1.5)
            image = tf.image.random_hue(image, max_delta=0.2)
            image = tf.image.random_contrast(image, lower=0.5, upper=1.5)
        elif color_ordering == 1:
            image = tf.image.random_brightness(image, max_delta=32. / 255.)
            image = tf.image.random_contrast(image, lower=0.5, upper=1.5)
            image = tf.image.random_saturation(image, lower=0.5, upper=1.5)
            image = tf.image.random_hue(image, max_delta=0.2)

        # The random_* ops do not necessarily clamp.
        image = tf.clip_by_value(image, 0.0, 1.0)
        return image

def distort_image(image, height, width, bbox, thread_id=0, scope=None):
    """Distort one image for training a network.

  Distorting images provides a useful technique for augmenting the data
  set during training in order to make the network invariant to aspects
  of the image that do not effect the label.

  Args:
    image: 3-D float Tensor of image
    height: integer
    width: integer
    bbox: 3-D float Tensor of bounding boxes arranged [1, num_boxes, coords]
      where each coordinate is [0, 1) and the coordinates are arranged
      as [ymin, xmin, ymax, xmax].
    thread_id: integer indicating the preprocessing thread.
    scope: Optional scope for op_scope.
  Returns:
    3-D float Tensor of distorted image used for training.
  """
    with tf.op_scope([image, height, width, bbox], scope, 'distort_image'):

        # NOTE(ry) I unceremoniously removed all the bounding box code.
        # Original here: https://github.com/tensorflow/models/blob/148a15fb043dacdd1595eb4c5267705fbd362c6a/inception/inception/image_processing.py

        distorted_image = image

        # This resizing operation may distort the images because the aspect
        # ratio is not respected. We select a resize method in a round robin
        # fashion based on the thread number.
        # Note that ResizeMethod contains 4 enumerated resizing methods.
        resize_method = thread_id % 4
        distorted_image = tf.image.resize_images(distorted_image, height,
                                                 width, resize_method)
        # Restore the shape since the dynamic slice based upon the bbox_size loses
        # the third dimension.
        distorted_image.set_shape([height, width, 3])
        if not thread_id:
            tf.image_summary('cropped_resized_image',
                             tf.expand_dims(distorted_image, 0))

        # Randomly flip the image horizontally.
        distorted_image = tf.image.random_flip_left_right(distorted_image)

        # Randomly distort the colors.
        distorted_image = distort_color(distorted_image, thread_id)

        if not thread_id:
            tf.image_summary('final_distorted_image',
                             tf.expand_dims(distorted_image, 0))
        return distorted_image

def eval_image(image, height, width, scope=None):
    """Prepare one image for evaluation.

  Args:
    image: 3-D float Tensor
    height: integer
    width: integer
    scope: Optional scope for op_scope.
  Returns:
    3-D float Tensor of prepared image.
  """
    with tf.op_scope([image, height, width], scope, 'eval_image'):
        # Crop the central region of the image with an area containing 87.5% of
        # the original image.
        image = tf.image.central_crop(image, central_fraction=0.875)

        # Resize the image to the original height and width.
        image = tf.expand_dims(image, 0)
        image = tf.image.resize_bilinear(image, [height, width],
                                         align_corners=False)
        image = tf.squeeze(image, [0])
        return image

def read_image(image_buffer, decoder, concatenate_input, height, width, train, concatnate_way='col'):
    """Decode and preprocess one image for evaluation or training.

  Args:
    image_buffer: JPEG encoded string Tensor
    bbox: 3-D float Tensor of bounding boxes arranged [1, num_boxes, coords]
      where each coordinate is [0, 1) and the coordinates are arranged as
      [ymin, xmin, ymax, xmax].
    train: boolean

  Returns:
    3-D float Tensor containing an appropriately scaled image

  Raises:
    ValueError: if user does not provide bounding box
  """

    image = decoder(image_buffer)
    if concatenate_input:
      return image

    image_shape = image.get_shape()
    if concatnate_way == 'col':
      image_group = tf.reshape(image, shape=(image_shape[0] / height, height, width))
    else:
      raise ValueError("Wrong concatnate_way! Original images should cancatante through cols")
    # if train:

    # Finally, rescale to [-1,1] instead of [0, 1)
    # image = tf.sub(image, 0.5)
    # image = tf.mul(image, 2.0)

    return image_group


#NOMBRE:JOSE BIZUET COLLAZO RUBIO
#CARRERA:INFORMATICA
#MATERIA:DESAROLLO DE APLICASIONES
#EJERCISIO O PRACTICA: PRACTICA_2.2_JOSEBIZUETCOLLAZORUBIO
fecha=input("fecha(formato ´dia, DD/MM´):")#(ESTO SE CONSIDERA COMO UN ESTRIN LITERAL )aqui indico que ingrese DOS DIGITOS PARA EL DIA Y DOS PARA EL MES
fecha=fecha.lower()#esto combierte las minusculas las letras pero si ya estan en minusculas no afectara en nada
diasemana=fecha[0:fecha.find(",")]#aqui extraremos los dias de la semana,tambien indico que empieze del cero asta el x numero de letras tendra el dia que ingrese para que la  coma se coloque
dianro=int(fecha[fecha.find(" ")+1:fecha.find("/")]) #aqui iniciamos en DD y enlugar de la como busacara la barra asi iniciara uno antes de la barra
mesnro=int(fecha[fecha.find("/")+1:])#aqui representamos el mes #aqui mostraremos uno despues de la bara asi como para el dia empezabamos uno despues del espasio
if dianro>31 or mesnro>12:#aqui colocamos la condicion que marcara la condicion incorrecta
    print("fecha incorrecta")
else:# aqui si la condicion es correcta continuara
    if diasemana in "lunes, martes, miercoles":#aqui preguntara los de la semana es, aqui se preguntara si se tomaron examenes lunes ,martes o el miercoles
        respuesta=input("¿setomaron examenes? S/N:")
        if respuesta.lower()=="s":
            aprobados=int(input("cantidad de aprobados:"))
            reprobados=int(input("cantidad de reprobados:"))
            print("porcentaje de aprobados:", (aprobados*100)/(aprobados+reprobados) ,"s" )#aqui calcularemos el porcentaje de aprobados y reprobados
    elif diasemana =="jueves":# si el dia de la semana se escribe jueves se ara otra cosa que es el siguiente codigo
        asistencia=int(input("porcentaje de asistencia:"))#este es el codigo que se ejecuta cuando introducimos el dia jueves
        if asistencia>50:  #si es mayor nos dira no asisitio la mayoria y si es menor de 50 pues nos dira asistio la mayoria                               #este es el codigo que se ejecuta cuando introducimos el dia jueves
            print("Asistencia la mayoria")
        else: print("No asistio la mayoria")
    elif diasemana =="viernes":#aqui en viernes en esta parte nos dira que se inicio un nuevo siclo al colocar 1/7
        if dianro==1 and (mesnro==1 or mesnro==7):
            print("comienzo de nuevo ciclo")
            alumno=int(input("cantidad de alumnos:"))#nos pedira el numero demmalumnos
            arancel=float(input("arancel:$"))#aqui escribiremos el arancel
            print("ingreso total:$", alumno*arancel)#nos arrojara el total del arancel y se finalizara el programa
    else:
        print("fcha incorrecta ")

print("fin del programa ")


def get_periodicfeatures(
        pfpickle,
        lcbasedir,
        outdir,
        fourierorder=5,
        # these are depth, duration, ingress duration
        transitparams=(-0.01,0.1,0.1),
        # these are depth, duration, depth ratio, secphase
        ebparams=(-0.2,0.3,0.7,0.5),
        pdiff_threshold=1.0e-4,
        sidereal_threshold=1.0e-4,
        sampling_peak_multiplier=5.0,
        sampling_startp=None,
        sampling_endp=None,
        starfeatures=None,
        timecols=None,
        magcols=None,
        errcols=None,
        lcformat='hat-sql',
        lcformatdir=None,
        sigclip=10.0,
        verbose=True,
        raiseonfail=False
):
    '''This gets all periodic features for the object.

    Parameters
    ----------

    pfpickle : str
        The period-finding result pickle containing period-finder results to use
        for the calculation of LC fit, periodogram, and phased LC features.

    lcbasedir : str
        The base directory where the light curve for the current object is
        located.

    outdir : str
        The output directory where the results will be written.

    fourierorder : int
        The Fourier order to use to generate sinusoidal function and fit that to
        the phased light curve.

    transitparams : list of floats
        The transit depth, duration, and ingress duration to use to generate a
        trapezoid planet transit model fit to the phased light curve. The period
        used is the one provided in `period`, while the epoch is automatically
        obtained from a spline fit to the phased light curve.

    ebparams : list of floats
        The primary eclipse depth, eclipse duration, the primary-secondary depth
        ratio, and the phase of the secondary eclipse to use to generate an
        eclipsing binary model fit to the phased light curve. The period used is
        the one provided in `period`, while the epoch is automatically obtained
        from a spline fit to the phased light curve.

    pdiff_threshold : float
        This is the max difference between periods to consider them the same.

    sidereal_threshold : float
        This is the max difference between any of the 'best' periods and the
        sidereal day periods to consider them the same.

    sampling_peak_multiplier : float
        This is the minimum multiplicative factor of a 'best' period's
        normalized periodogram peak over the sampling periodogram peak at the
        same period required to accept the 'best' period as possibly real.

    sampling_startp, sampling_endp : float
        If the `pgramlist` doesn't have a time-sampling Lomb-Scargle
        periodogram, it will be obtained automatically. Use these kwargs to
        control the minimum and maximum period interval to be searched when
        generating this periodogram.

    starfeatures : str or None
        If not None, this should be the filename of the
        `starfeatures-<objectid>.pkl` created by
        :py:func:`astrobase.lcproc.lcsfeatures.get_starfeatures` for this
        object. This is used to get the neighbor's light curve and phase it with
        this object's period to see if this object is blended.

    timecols : list of str or None
        The timecol keys to use from the lcdict in calculating the features.

    magcols : list of str or None
        The magcol keys to use from the lcdict in calculating the features.

    errcols : list of str or None
        The errcol keys to use from the lcdict in calculating the features.

    lcformat : str
        This is the `formatkey` associated with your light curve format, which
        you previously passed in to the `lcproc.register_lcformat`
        function. This will be used to look up how to find and read the light
        curves specified in `basedir` or `use_list_of_filenames`.

    lcformatdir : str or None
        If this is provided, gives the path to a directory when you've stored
        your lcformat description JSONs, other than the usual directories lcproc
        knows to search for them in. Use this along with `lcformat` to specify
        an LC format JSON file that's not currently registered with lcproc.

    sigclip : float or int or sequence of two floats/ints or None
        If a single float or int, a symmetric sigma-clip will be performed using
        the number provided as the sigma-multiplier to cut out from the input
        time-series.

        If a list of two ints/floats is provided, the function will perform an
        'asymmetric' sigma-clip. The first element in this list is the sigma
        value to use for fainter flux/mag values; the second element in this
        list is the sigma value to use for brighter flux/mag values. For
        example, `sigclip=[10., 3.]`, will sigclip out greater than 10-sigma
        dimmings and greater than 3-sigma brightenings. Here the meaning of
        "dimming" and "brightening" is set by *physics* (not the magnitude
        system), which is why the `magsarefluxes` kwarg must be correctly set.

        If `sigclip` is None, no sigma-clipping will be performed, and the
        time-series (with non-finite elems removed) will be passed through to
        the output.

    verbose : bool
        If True, will indicate progress while working.

    raiseonfail : bool
        If True, will raise an Exception if something goes wrong.

    Returns
    -------

    str
        Returns a filename for the output pickle containing all of the periodic
        features for the input object's LC.

    '''

    try:
        formatinfo = get_lcformat(lcformat,
                                  use_lcformat_dir=lcformatdir)
        if formatinfo:
            (fileglob, readerfunc,
             dtimecols, dmagcols, derrcols,
             magsarefluxes, normfunc) = formatinfo
        else:
            LOGERROR("can't figure out the light curve format")
            return None
    except Exception as e:
        LOGEXCEPTION("can't figure out the light curve format")
        return None

    # open the pfpickle
    if pfpickle.endswith('.gz'):
        infd = gzip.open(pfpickle)
    else:
        infd = open(pfpickle)
    pf = pickle.load(infd)
    infd.close()

    lcfile = os.path.join(lcbasedir, pf['lcfbasename'])
    objectid = pf['objectid']

    if 'kwargs' in pf:
        kwargs = pf['kwargs']
    else:
        kwargs = None

    # override the default timecols, magcols, and errcols
    # using the ones provided to the periodfinder
    # if those don't exist, use the defaults from the lcformat def
    if kwargs and 'timecols' in kwargs and timecols is None:
        timecols = kwargs['timecols']
    elif not kwargs and not timecols:
        timecols = dtimecols

    if kwargs and 'magcols' in kwargs and magcols is None:
        magcols = kwargs['magcols']
    elif not kwargs and not magcols:
        magcols = dmagcols

    if kwargs and 'errcols' in kwargs and errcols is None:
        errcols = kwargs['errcols']
    elif not kwargs and not errcols:
        errcols = derrcols

    # check if the light curve file exists
    if not os.path.exists(lcfile):
        LOGERROR("can't find LC %s for object %s" % (lcfile, objectid))
        return None

    # check if we have neighbors we can get the LCs for
    if starfeatures is not None and os.path.exists(starfeatures):

        with open(starfeatures,'rb') as infd:
            starfeat = pickle.load(infd)

        if starfeat['closestnbrlcfname'].size > 0:

            nbr_full_lcf = starfeat['closestnbrlcfname'][0]

            # check for this LC in the lcbasedir
            if os.path.exists(os.path.join(lcbasedir,
                                           os.path.basename(nbr_full_lcf))):
                nbrlcf = os.path.join(lcbasedir,
                                      os.path.basename(nbr_full_lcf))
            # if it's not there, check for this file at the full LC location
            elif os.path.exists(nbr_full_lcf):
                nbrlcf = nbr_full_lcf
            # otherwise, we can't find it, so complain
            else:
                LOGWARNING("can't find neighbor light curve file: %s in "
                           "its original directory: %s, or in this object's "
                           "lcbasedir: %s, skipping neighbor processing..." %
                           (os.path.basename(nbr_full_lcf),
                            os.path.dirname(nbr_full_lcf),
                            lcbasedir))
                nbrlcf = None

        else:
            nbrlcf = None

    else:
        nbrlcf = None

    # now, start processing for periodic feature extraction
    try:

        # get the object LC into a dict
        lcdict = readerfunc(lcfile)

        # this should handle lists/tuples being returned by readerfunc
        # we assume that the first element is the actual lcdict
        # FIXME: figure out how to not need this assumption
        if ( (isinstance(lcdict, (list, tuple))) and
             (isinstance(lcdict[0], dict)) ):
            lcdict = lcdict[0]

        # get the nbr object LC into a dict if there is one
        if nbrlcf is not None:

            nbrlcdict = readerfunc(nbrlcf)

            # this should handle lists/tuples being returned by readerfunc
            # we assume that the first element is the actual lcdict
            # FIXME: figure out how to not need this assumption
            if ( (isinstance(nbrlcdict, (list, tuple))) and
                 (isinstance(nbrlcdict[0], dict)) ):
                nbrlcdict = nbrlcdict[0]

        # this will be the output file
        outfile = os.path.join(outdir, 'periodicfeatures-%s.pkl' %
                               squeeze(objectid).replace(' ','-'))

        # normalize using the special function if specified
        if normfunc is not None:
            lcdict = normfunc(lcdict)

            if nbrlcf:
                nbrlcdict = normfunc(nbrlcdict)

        resultdict = {}

        for tcol, mcol, ecol in zip(timecols, magcols, errcols):

            # dereference the columns and get them from the lcdict
            if '.' in tcol:
                tcolget = tcol.split('.')
            else:
                tcolget = [tcol]
            times = _dict_get(lcdict, tcolget)

            if nbrlcf:
                nbrtimes = _dict_get(nbrlcdict, tcolget)
            else:
                nbrtimes = None

            if '.' in mcol:
                mcolget = mcol.split('.')
            else:
                mcolget = [mcol]

            mags = _dict_get(lcdict, mcolget)

            if nbrlcf:
                nbrmags = _dict_get(nbrlcdict, mcolget)
            else:
                nbrmags = None

            if '.' in ecol:
                ecolget = ecol.split('.')
            else:
                ecolget = [ecol]

            errs = _dict_get(lcdict, ecolget)

            if nbrlcf:
                nbrerrs = _dict_get(nbrlcdict, ecolget)
            else:
                nbrerrs = None

            #
            # filter out nans, etc. from the object and any neighbor LC
            #

            # get the finite values
            finind = np.isfinite(times) & np.isfinite(mags) & np.isfinite(errs)
            ftimes, fmags, ferrs = times[finind], mags[finind], errs[finind]

            if nbrlcf:

                nfinind = (np.isfinite(nbrtimes) &
                           np.isfinite(nbrmags) &
                           np.isfinite(nbrerrs))
                nbrftimes, nbrfmags, nbrferrs = (nbrtimes[nfinind],
                                                 nbrmags[nfinind],
                                                 nbrerrs[nfinind])

            # get nonzero errors
            nzind = np.nonzero(ferrs)
            ftimes, fmags, ferrs = ftimes[nzind], fmags[nzind], ferrs[nzind]

            if nbrlcf:

                nnzind = np.nonzero(nbrferrs)
                nbrftimes, nbrfmags, nbrferrs = (nbrftimes[nnzind],
                                                 nbrfmags[nnzind],
                                                 nbrferrs[nnzind])

            # normalize here if not using special normalization
            if normfunc is None:

                ntimes, nmags = normalize_magseries(
                    ftimes, fmags,
                    magsarefluxes=magsarefluxes
                )

                times, mags, errs = ntimes, nmags, ferrs

                if nbrlcf:
                    nbrntimes, nbrnmags = normalize_magseries(
                        nbrftimes, nbrfmags,
                        magsarefluxes=magsarefluxes
                    )
                    nbrtimes, nbrmags, nbrerrs = nbrntimes, nbrnmags, nbrferrs
                else:
                    nbrtimes, nbrmags, nbrerrs = None, None, None

            else:
                times, mags, errs = ftimes, fmags, ferrs

            if times.size > 999:

                #
                # now we have times, mags, errs (and nbrtimes, nbrmags, nbrerrs)
                #
                available_pfmethods = []
                available_pgrams = []
                available_bestperiods = []

                for k in pf[mcol].keys():

                    if k in PFMETHODS:

                        available_pgrams.append(pf[mcol][k])

                        if k != 'win':
                            available_pfmethods.append(
                                pf[mcol][k]['method']
                            )
                            available_bestperiods.append(
                                pf[mcol][k]['bestperiod']
                            )

                #
                # process periodic features for this magcol
                #
                featkey = 'periodicfeatures-%s' % mcol
                resultdict[featkey] = {}

                # first, handle the periodogram features
                pgramfeat = periodicfeatures.periodogram_features(
                    available_pgrams, times, mags, errs,
                    sigclip=sigclip,
                    pdiff_threshold=pdiff_threshold,
                    sidereal_threshold=sidereal_threshold,
                    sampling_peak_multiplier=sampling_peak_multiplier,
                    sampling_startp=sampling_startp,
                    sampling_endp=sampling_endp,
                    verbose=verbose
                )
                resultdict[featkey].update(pgramfeat)

                resultdict[featkey]['pfmethods'] = available_pfmethods

                # then for each bestperiod, get phasedlc and lcfit features
                for _ind, pfm, bp in zip(range(len(available_bestperiods)),
                                         available_pfmethods,
                                         available_bestperiods):

                    resultdict[featkey][pfm] = periodicfeatures.lcfit_features(
                        times, mags, errs, bp,
                        fourierorder=fourierorder,
                        transitparams=transitparams,
                        ebparams=ebparams,
                        sigclip=sigclip,
                        magsarefluxes=magsarefluxes,
                        verbose=verbose
                    )

                    phasedlcfeat = periodicfeatures.phasedlc_features(
                        times, mags, errs, bp,
                        nbrtimes=nbrtimes,
                        nbrmags=nbrmags,
                        nbrerrs=nbrerrs
                    )

                    resultdict[featkey][pfm].update(phasedlcfeat)

            else:

                LOGERROR('not enough finite measurements in magcol: %s, for '
                         'pfpickle: %s, skipping this magcol'
                         % (mcol, pfpickle))
                featkey = 'periodicfeatures-%s' % mcol
                resultdict[featkey] = None

        #
        # end of per magcol processing
        #
        # write resultdict to pickle
        outfile = os.path.join(outdir, 'periodicfeatures-%s.pkl' %
                               squeeze(objectid).replace(' ','-'))
        with open(outfile,'wb') as outfd:
            pickle.dump(resultdict, outfd, pickle.HIGHEST_PROTOCOL)

        return outfile

    except Exception as e:

        LOGEXCEPTION('failed to run for pf: %s, lcfile: %s' %
                     (pfpickle, lcfile))
        if raiseonfail:
            raise
        else:
            return None


import os
from celery import Celery
from django.conf import settings
# Set the default Django settings module for the 'celery' program.
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'baul.settings')
app = Celery('baul')
app.config_from_object('django.conf:settings')
app.autodiscover_tasks(lambda: settings.INSTALLED_APPS)

@app.task(bind=True)
def debug_task(self):
    print(f'Request: {self.request!r}')


from flask import Blueprint,jsonify

import imp

beans = imp.load_package("beans","../beans")
services = imp.load_package("services","../services")
dao = imp.load_package("dao","../dao")

#from dao.UserDAO import registerUser
from beans.User import User
from services.IndexService import downloadLink,parseHTML, tokenize
from dao.UserDAO import registerUser, displayUsers
routes = Blueprint("routes",__name__)

@routes.route("/")
def default():
    user = User("arthur","arthur.grevin@gmail.com","mdp")
    user.history.append("history1")
    user.history.append("history2")
    return jsonify(user.serialize())

@routes.route("/absorber")
def linkAbsorber():
    return parseHTML("https://fr.wikipedia.org/wiki/Pharaon")

@routes.route("/register/<string:json>",methods=['POST','PUT'])
def register():
    user = request.get_json(force=True)
    user = User(user['login'],user['email'],user['password'])
    registerUser(user)
    return "test"

@routes.route("/test2")
def test2():
    displayUsers()
    return "test2"

@routes.route("/tokenize")
def tokenizeText():
    return tokenize("http://www.theverge.com/2015/12/10/9880594/microsoft-xbox-games-2016-interview-crackdown-3-quantum-break-recore")


import os
class Node:
    def __init__(self,data,prev=None,next=None):
        self.data = data
        self.prev = prev
        self.next = next

class CircularDoubleLinkedList:
    def __init__(self):
        self.head = None

    def insert_beg(self,num):
        node = Node(num)
        if self.head is None:
            node.prev,node.next = node,node
        else:
            current_node = self.head
            current_node.prev.next = node
            node.prev = current_node.prev
            current_node.prev = node
            node.next = current_node
        self.head = node

    def insert_end(self,num):
        node = Node(num)
        if self.head is None:
            node.prev,node.next = node,node
            self.head = node
        else:
            current_node = self.head
            current_node.prev.next = node
            node.prev = current_node.prev
            node.next = current_node
            current_node.prev = node

    def insert_nth(self,pos,num):
        node = Node(num)
        if pos==1:
            self.insert_beg(num)
        else:
            current_node = self.head
            for i in range(pos-2):
                current_node = current_node.next
            node.prev = current_node
            current_node.next.prev = node
            node.next = current_node.next
            current_node.next = node

    def display(self):
        node = self.head
        print("\n\n")
        i=1
        if node is not None:
            # print(node.data,end='->')
            # print(node.prev.data,"<--",node.data,"-->",node.next.data)
            print("\t Node : ",i,"\t[{",id(node.prev),"}<--{(",node.data,"),(",id(node),")}-->","{",id(node.next),"}]")
            i+=1
            node = node.next
        while node is not self.head:
            # print(node.data,end='->')
            # print(node.prev.data,"<--",node.data,"-->",node.next.data)
            print("\t Node : ",i,"\t[{",id(node.prev),"}<--{(",node.data,"),(",id(node),")}-->","{",id(node.next),"}]")
            i+=1
            node = node.next
        if i==1:
            print(None,"\n\n")

    def count(self):
        i = 0
        node = self.head
        if node is not None:
            i+=1
            node = node.next
        while node is not self.head:
            i+=1
            node = node.next
        return i

    def delete_beg(self):
        if self.head is None:
            print("Empty List")
            return

        current_node = self.head
        if current_node.next is current_node:
            del current_node
            self.head = None
        else:
            current_node.prev.next = current_node.next
            current_node.next.prev = current_node.prev
            self.head = current_node.next
            del current_node

    def delete_end(self):
        if self.head is None:
            print("Empty List")
            return

        current_node = self.head
        if current_node.next is current_node:
            del current_node
            self.head = None
        else:
            node = current_node.prev
            current_node.prev.prev.next = current_node
            current_node.prev = current_node.prev.prev
            del node

    def delete_nth(self,pos):
        if self.head is None:
            print("Empty List")
            return

        current_node = self.head
        if pos == 1:
            self.delete_beg()
        else:
            for i in range(pos-2):
                current_node = current_node.next
            node = current_node.next
            current_node.next = current_node.next.next
            current_node.next.prev = current_node
            del node

link = CircularDoubleLinkedList()
while True:
    os.system('cls')
    print("1. To insert at Begining")
    print("2. To display")
    print("3. To insert at end")
    print("4. To insert at nth")
    print("5. To count the nodes")
    print("6. To delete from begining")
    print("7. To delete from end")
    print("8. To delete from nth")
    print("0. To Exit")
    ch = int(input("Enter your choice : "))
    if ch==1:
        link.insert_beg(int(input("Enter a number you want to insert: ")))
        link.display()
    elif ch == 2:
        link.display()
    elif ch==3:
        link.insert_end(int(input("Enter a number you want to insert: ")))
        link.display()
    elif ch==4:
        pos = int(input("Enter the position: "))
        if pos>0 and pos<=link.count()+1:
            link.insert_nth(pos, int(input("Enter a number you want to insert: ")))
            link.display()
        else:
            print("Out of bound position")
            link.display()
    elif ch==5:
        print("Count: ",link.count())
    elif ch==6:
        link.delete_beg()
        link.display()
    elif ch==7:
        link.delete_end()
        link.display()
    elif ch==8:
        pos = int(input("Enter the position: "))
        if pos>0 and pos<=link.count():
            link.delete_nth(pos)
            link.display()
        else:
            print("Out of bound position")
            link.display()
    elif ch == 0:
        break
    input()


import frappe
from frappe_notification import (
    NotificationTemplate,
)
from .utils import validate_template_access

def fork_template(template: str):
    """
    Fork a template
    You will need read access on the template being forked
    """
    validate_template_access(template=template, ptype="read")

    d: NotificationTemplate = frappe.get_doc("Notification Template", template)
    fork = d.fork()

    return fork


# -*- coding: utf-8 -*-
import time

from DelgakaChecks import DelgakaChecks

__author__ = "delgaka"

"""
Chalange:

Print all factors number form a givem number

https://github.com/delgaka/Udemy_Computional_Think
"""

def define_the_prime_numbers(max_number):
    is_prime = [True] * (max_number + 1)
    is_prime[0] = False
    is_prime[1] = False
    list_of_primes = []
    for i in range(2, max_number + 1):
        if is_prime[i]:
            list_of_primes.append(i)

        for x in range(i*2, max_number + 1, i):
            is_prime[x] = False

    return list_of_primes

def main():
    max_number = input("Please, give an max integer number to find the : ")
    user_number = DelgakaChecks.input_to_number(max_number)
    # if the input is not a number, the program will as to run again with a number.
    start_time = time.time()
    if DelgakaChecks.is_number(max_number) and user_number:
        list_of_primes = define_the_prime_numbers(user_number)
        print("These are the prime numbers:")
        print(list_of_primes)
        print(len(list_of_primes))
    else:
        print("Please, try again with an integer number!")

    print("--- %s seconds ---" % (time.time() - start_time))

if __name__ == '__main__':
    main()


import wx
from wx.lib.agw.floatspin import FloatSpin

from shs.input.fdf_options import ChoiceLine, MeasuredLine, NumberLine, ThreeNumberLine

try:
    from geom import Geom
except ImportError:
    from shs.geom import Geom

class Bravais(ChoiceLine):
    label = 'Composition'
    choices = ['BCC', 'FCC', 'SC']
    optional = False

class LatticeConstant(MeasuredLine):
    label = 'Lattice constant'
    value = 1.
    digits = 2
    increment = 0.01
    units = ['Bohr', 'Ang']
    optional = False

class DistortionLevel(NumberLine):
    label = 'Distortion level (in %)'
    value = 0.
    digits = 0
    increment = 1.
    range_val = (0., 100.)
    optional = False

class SuperCell(ThreeNumberLine):
    label = 'Supercell'
    optional = False

class ACInitDialog(wx.Dialog):

    def __init__(self, *args, **kwds):
        self.types = kwds.pop('types')
        wx.Dialog.__init__(self, *args, **kwds)
        self.bravais = Bravais(self)
        self.type_label = []
        self.typefs = []
        if len(self.types) == 0:
            self.add_type_btn = wx.Button(self, -1, "Add type")
            self.add_type_btn.Bind(wx.EVT_BUTTON, self.add_type)
        else:
            for t in self.types:
                self.type_label.append(wx.StaticText(self, -1, t))
                self.typefs.append(FloatSpin(self, -1, min_val=0, value=1., digits=0))

        self.sc = SuperCell(self)

        self.alat = LatticeConstant(self)
        self.dist = DistortionLevel(self)
        self.__set_properties()
        self.__do_layout()

    def __set_properties(self):
        self.SetTitle("Initialize geometry")

    def __do_layout(self):
        comp_label = wx.StaticBox(self, -1, 'Composition')
        comp_sizer = wx.StaticBoxSizer(comp_label, wx.HORIZONTAL)
        self.comp_inside = wx.GridSizer(2, len(self.types), 2, 2)

        for l in self.type_label:
            self.comp_inside.Add(l, 0, wx.ALIGN_CENTER, 0)
        for fs in self.typefs:
            self.comp_inside.Add(fs, 0, wx.ALIGN_CENTER, 0)

        comp_sizer.Add(self.comp_inside, 1, wx.ALL | wx.EXPAND, 5)
        if len(self.types) == 0:
            comp_sizer.Add(self.add_type_btn, 0, wx.ALL | wx.EXPAND, 5)
        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer.Add(self.bravais.sizer, 0, wx.EXPAND, 0)
        sizer.Add(comp_sizer, 0, wx.ALL | wx.EXPAND, 5)
        sizer.Add(self.alat.sizer, 0, wx.EXPAND, 0)
        sizer.Add(self.sc.sizer, 0, wx.EXPAND, 0)
        sizer.Add(self.dist.sizer, 0, wx.EXPAND, 0)
        sizer.Add(self.CreateSeparatedButtonSizer(wx.OK|wx.CANCEL), 0, wx.ALL|wx.EXPAND, 5)

        self.SetSizer(sizer)
        self.Fit()
        self.Layout()

    def add_type(self, evt):
        self.comp_inside.Clear()
        self.comp_inside.SetCols(self.comp_inside.GetCols()+1)
        self.type_label.append(wx.TextCtrl(self, -1))
        self.typefs.append(FloatSpin(self, -1, min_val=0, value=1., digits=0))
        for l in self.type_label:
            self.comp_inside.Add(l, 0, wx.ALIGN_CENTER, 0)
        for fs in self.typefs:
            self.comp_inside.Add(fs, 0, wx.ALIGN_CENTER, 0)
        self.Fit()
        self.Layout()

    def init_geom(self):
        bravais = self.bravais.GetValue()
        alat, unit = self.alat.GetValue()
        sc = self.sc.GetValue()
        dist = self.dist.GetValue()
        if len(self.types) == 0:
            comp = dict(zip([il.GetValue() for il in self.type_label], [ifs.GetValue() for ifs in self.typefs]))
        else:
            comp = dict(zip(self.types, [ifs.GetValue() for ifs in self.typefs]))
        g = Geom()
        g.initialize(bravais, comp, sc, alat, unit, dist_level=dist)
        g.geom2opts()
        return g.opts["AtomicCoordinatesAndAtomicSpecies"]


import ceph

from charmhelpers.core.hookenv import (
    log,
    DEBUG,
    config,
    relation_ids,
    related_units,
    relation_get,
    relation_set,
    leader_set, leader_get,
    is_leader,
    remote_unit,
    Hooks, UnregisteredHookError,
    service_name,
    relations_of_type,
    status_set,
    local_unit, ERROR)

hooks = Hooks()

@hooks.hook('install.real')
@harden()
def install():
    execd_preinstall()
    add_source(config('source'), config('key'))
    apt_update(fatal=True)
    apt_install(packages=ceph.PACKAGES, fatal=True)

if __name__ == '__main__':
    try:
        hooks.execute(sys.argv)
    except UnregisteredHookError as e:
        log('Unknown hook {} - skipping.'.format(e))