from OCR import final_image

from datetime import datetime as dt

from tkinter import *
import tkinter
from tkinter.filedialog import askopenfilename
from tkinter import ttk, messagebox

WINDOW_SIZE="500x300"

global Xpense

class hello:
    def __init__(self):
        self.buttonHeight=20
        self.buttonWidth=50
        self.file1 = open('data.txt', "a")
        self.root = tkinter.Tk()
        self.root.title("Xpend")
        self.root.geometry(WINDOW_SIZE)
        self.root.resizable(0,0)
        self.root.iconbitmap(self, default="images\icon2.ico")
        self.mainFrame=Frame(self.root,bg="#15c674")
        self.mainFrame.pack_propagate(0)
        self.mainFrame.pack(fill="both",expand=1)
        self.mainp()
        self.root.mainloop()

    def but1fun(self):
        mamt = int(self.entryamt.get())
        mtag = self.entrytag.get()
        time = dt.now()
        text1 = str((mamt, mtag, time))
        self.file1.write(text1)
        self.label2 = Label(self.manualw, text="Transaction is successfully saved.")
        self.label2.grid(row=6, columnspan=3,padx=3,pady=3)
        self.file1.close()
        self.manualw.after(2000, lambda: self.manualw.destroy())

    def manualp(self):
        self.manualw = Tk()
        self.manualw.geometry("500x300")
        Label(self.manualw, text="Enter the amount").grid(row=0,padx=3,pady=3)
        self.entryamt = Entry(self.manualw)
        self.entryamt.grid(row=0, column=1,padx=3,pady=3)
        Label(self.manualw, text="Enter the tag").grid(row=1,padx=3,pady=3)
        self.entrytag = Entry(self.manualw)
        self.entrytag.grid(row=1, column=1,padx=3,pady=3)
        self.bsubmit = ttk.Button(self.manualw, text="Enter into file", command=self.but1fun)
        self.bsubmit.grid(row=4, columnspan=3,padx=3,pady=3)
        # self.bclear=Button(self.manualw,text="Clear contents",command=self.file1.truncate(0))
        # self.bclear.grid(row=5,columnspan=3)
        self.manualw.mainloop()

    def clickp(self):

        file_path = str(askopenfilename(initialdir="images\Sample Bills", title="Select bill image",
                                            filetypes=[("Image Files", "*.jpeg;*.jpg;*.png")]))
        final_image(str(file_path))
        #messagebox.showerror("Error","Image was not selected")

        """
        amt=final_image(str(file_path))
        label=Label(self.mainp,text=amt).grid(row=0)
        label.pack()
        """

    def msgp(self):
        #this functions will be improvied in a later build
        self.msgp = Tk()
        pass
        self.msgp.mainloop()

    def mainp(self):
        #this is the first window which displays as soon as the program runs
        self.photo = tkinter.PhotoImage(file="images\logo.gif")
        Label(self.mainFrame,image=self.photo).pack(pady=(0,15))
        self.manualb = ttk.Button(self.mainFrame, text="Enter transaction manually", command=self.manualp)
        self.manualb.pack(padx=3,pady=3)
        self.clickb = ttk.Button(self.mainFrame, text="Enter transaction by picture", command=self.clickp)
        self.clickb.pack(padx=3,pady=3)
        #the following comments are commented out as it belongs to message reading which will be added on in a later build

        #self.msgb = Button(self.root, text="Enter transaction from messages", command=self.msgp)
        #self.msgb.pack()

if __name__ == '__main__':
    hello()


#!/usr/bin/python

import os
import time

printed = 0
with open(f"presse/url.txt", 'r') as links:
    for link in links:
        printed = printed +1
        print(f"Downloading item number {printed}: {link}")
        os.system(f'python3 downloader.py {link}')
        time.sleep(5)


#
# @lc app=leetcode id=29 lang=python3
#
# [29] Divide Two Integers
#

# @lc code=start
class Solution:
    def divide(self, dividend: int, divisor: int) -> int:
        MAX_LIMIT = 2 ** 31 - 1
        MIN_LIMIT = -2 ** 31
        if divisor == 1:
            return dividend
        if divisor == -1:
            return MAX_LIMIT if dividend == MIN_LIMIT else -dividend

        # sign = (dividend > 0 and divisor > 0) or (dividend < 0 and divisor < 0)
        sign = (dividend > 0) is (divisor > 0)
        dividend = - dividend if dividend > 0 else dividend
        divisor = -divisor if divisor > 0 else divisor
        i = 0
        while dividend <= divisor:
            cusum = divisor
            j = 1
            while cusum >= dividend - cusum:
                cusum += cusum
                if j >= MAX_LIMIT - j:
                    j = MAX_LIMIT
                    break
                j += j
            if i >= MAX_LIMIT - j:
                i = MAX_LIMIT
                break
            i += j
            dividend -= cusum
        return i if sign else -i

# @lc code=end


# coding=utf-8
from __future__ import division
import xml.etree.ElementTree as ET
from biocluster.config import Config
import re
import collections
import json
import subprocess
import gridfs
import glob
import os
import sys
import pandas as pd
import json
import math
import numpy as np
from collections import OrderedDict

def choose_js_large(files):
    '''
    选择["dataset"][0]["source"][0]中最多的文件
    '''
    file_list = list()
    for file_ in files:
        file_pre = os.path.splitext(file_)
        file_js = file_pre + ".js"
        json_d = get_json_from_js(file_js)
        file_list.append([file_pre, file_js, len(json_d["dataset"][0]["source"][0])])

    file_list_sort = sorted(file_list, key=lambda x:x[2], reverse=True)
    return file_list[0][0]

def get_json_from_js(js_file):
    with open(js_file, 'r') as f:
        b = f.read()
        json_d = json.loads(b[14:])
    return json_d

def get_geneset_by_file_name(file_name):
    geneset_name = os.path.basename(file_name).split(".")[0]
    return geneset_name

def get_sample_by_file_name(file_name):
    sample_name = os.path.basename(file_name).split(".")[0]
    return sample_name

class ChartReport(object):
    def __init__(self):
        """
        设置数据库，连接到mongod数据库，kegg_ko,kegg_gene,kegg_pathway_png三个collections2
        """

        """
        class: sample[A1, B1], group[A, B], classify: [samples, groups], level[G, T], kind[ref, new, all], category[mRNA, lncRNA]
        """
        super(ChartReport, self).__init__()
        self.report_init()
        os.system("mkdir -p png")

    def report_init(self):
        '''
        "categroy_name": 目录
        "img": 静态图片名称, 通过glob.glob 匹配图片
        "name": "表达量统计图-堆积图",
        "main_coll": 主表collection名称
        "choose_func": 图片存在多张时通过该函数筛选图片
        "choose_main"
        '''
        self.convert_list = list()
        self.report_config_out = dict()
        self.report_config = {
            "110301": {
                "main_coll": "sg_specimen_after",
                "name": "碱基质量分布图",
                "img": "*.clean_qc_qual.box.pdf",
                "category_name": "测序数据质控-质控数据统计 "
            },
            "110302": {
                "main_coll": "sg_specimen_after",
                "name": "碱基错误率分布图",
                "img": "*.clean_qc_error.line.pdf",
                "category_name": "测序数据质控-质控数据统计 "
            },
            "110303": {
                "main_coll": "sg_specimen_after",
                "name": "碱基含量分布图",
                "img": "*.clean_qc_base.line.pdf",
                "category_name": "测序数据质控-质控数据统计 "
            },
            "120301": {
                "main_coll": "sg_assembly_len",
                "name": "转录本长度分布图",
                "img": "Transcript.length_distribution.columns.pdf",
                "category_name": "转录组从头组装-转录本长度分布"
            },
            "130101": {
                "main_coll": "sg_annotationstat",
                "name": "功能注释统计图-柱图",
                "img": "annot_gene_stat.column.pdf",
                "category_name": "转录组功能注释-功能注释统计"
            },
            "130301": {
                "main_coll": "sg_annotationnr",
                "name": "NR注释物种分布饼图",
                "img": "Gene.nr_species.pie.pdf",
                "category_name": "转录组功能注释-NR"
            },
            "130901": {
                "main_coll": "sg_annotationpfam",
                "name": "Pfam注释柱状图",
                "img": "Pfam.annotation_of_Gene.columns.pdf",
                "category_name": "转录组功能注释-Pfam"
            },
            "131001": {
                "main_coll": "sg_annotationcog",
                "name": "COG分类统计柱状图",
                "img": "COG_Gene.function_classification.columns.pdf",
                "category_name": "转录组功能注释-COG"
            },
            "131101": {
                "main_coll": "sg_annotationgo",
                "name": "GO分类统计图-BP",
                "img": "Gene_GO_level2.classification_BP.pie.pdf",
                "category_name": "转录组功能注释-GO"
            },
            "131201": {
                "main_coll": "sg_annotationkegg",
                "name": "Pathway分类统计柱状图",
                "img": "Gene_Histogram_of_KEGG.barline.barline.pdf",
                "category_name": "转录组功能注释-KEGG"
            },
            "150201": {
                "main_coll": "sg_tf",
                "name": "转录因子家族统计图",
                "img": "Unigene_TF.family.columns.pdf",
                "category_name": "转录因子家族分析-转录因子家族分析"
            },
            "160201": {
                "main_coll": "sg_expgraph",
                "name": "表达量分布图-盒型图",
                "img": "Genes_samples_exp.distribution.box.box.pdf",
                "category_name": "表达量统计- 表达量分布"
            },
            "160301": {
                "main_coll": "sg_expvenn",
                "name": "样本间 Venn图",
                "img": "all.exp.venn.pdf",
                "category_name": "样本关系分析"
            },

            "160401": {
                "main_coll": "sg_expcorr",
                "name": "样本间相关性热图",
                "img": "all.exp.heat_corr.pdf",
                "category_name": "样本关系分析"
            },
            "160501": {
                "main_coll": "sg_exppca",
                "name": "PCA图",
                "img": "all.exp_relation_pca.scatter.pdf",
                "category_name": "样本关系分析"
            },
            "170301": {
                "main_coll": "sg_diff",
                "name": "表达量差异统计柱状图",
                "img": "Gene.differential.summary.bar_h.bar.pdf",
                "category_name": "表达量差异统计"
            },
            "170401": {
                "main_coll": "diff_graph",
                "name": "表达量差异火山图",
                "img": "*.diff.volcano.volcano.pdf",
                "category_name": "表达量差异统计"
            },
            "170402": {
                "main_coll": "diff_graph",
                "name": "表达量差异散点图",
                "img": "*.diff.scatter.scatter.pdf",
                "category_name": "表达量差异统计"
            },
            "180101": {
                "main_coll": "sg_geneset_venn",
                "name": "Venn图",
                "img": "diff_genesets.analysis.venn.pdf",
                "category_name": "基因集分析-Venn分析"
            },
            "180201": {
                "main_coll": "sg_geneset_cluster",
                "name": "聚类热图",
                "img": "geneset.cluster.heat_corr.pdf",
                "category_name": "基因集分析-聚类分析"
            },
            "180301": {
                "main_coll": "sg_geneset_cluster",
                "name": "子聚类趋势图 ",
                "img": "cluster.*.line.pdf",
                "category_name": "基因集分析-聚类分析"
            },
            "180401": {
                "main_coll": "sg_geneset_cog_class",
                "name": "COG分类统计柱状图  ",
                "img": "*.cog_annot.gene_set.column.pdf",
                "category_name": "基因集功能注释--COG",
                "main_dict": {"gene_set": "get_geneset_by_file_name"}
            },
            "180501": {
                "main_coll": "sg_geneset_go_class",
                "name": "GO分类统计柱形图",
                "img": "*.go_annot.gene_set.column.pdf",
                "category_name": "基因集功能注释--GO",
                "main_dict": {"gene_set": "get_geneset_by_file_name"}
            },
            "180701": {
                "main_coll": "sg_geneset_go_enrich",
                "name": "GO富集分析结果图--柱形图(带折线）",
                "img": "*.go_enrich.gene_set.bar_line.pdf",
                "category_name": "基因集功能富集--GO",
                "main_dict": {"gene_set": "get_geneset_by_file_name"}
            },
            "180803": {
                "main_coll": "sg_geneset_kegg_enrich",
                "name": "KEGG富集分析结果图--气泡图",
                "img": "*.kegg_enrich.gene_setgo_enrich_buble1.pdf",
                "category_name": "基因集功能富集--KEGG",
                "main_dict": {"gene_set": "get_geneset_by_file_name"}
            },
            "180901": {
                "main_coll": "sg_geneset_kegg_class",
                "name": "Pathway分类统计柱状图",
                "img": "*.kegg_annot.*.column.pdf",
                "category_name": "基因集功能注释--KEGG",
                "main_dict": {"gene_set": "get_geneset_by_file_name"}
            },
            "190101": {
                "main_coll": "sg_cds",
                "name": "CDS长度分布图",
                "img": "Gene.length_distribution_of_CDS.columns.pdf",
                "category_name": "基因结构分析--CDS预测"
            },
            "190401": {
                "main_coll": "sg_snp",
                "name": "SNP位点统计图-柱状图",
                "img": "*.snp.pos_stat.pie.pdf",
                "category_name": "基因结构分析--SNP 分析"
            },
            "190502": {
                "main_coll": "sg_snp",
                "name": "SNP测序深度统计图-饼图",
                "img": "*.snp.pos_stat.pie.pdf",
                "category_name": "基因结构分析--SNP 分析"
            },
            "190701": {
                "main_coll": "sg_ssr",
                "name": "SSR统计图",
                "img": "SSR.stat.pie.pdf",
                "category_name": "基因结构分析--SSR分析"
            },
            "190702": {
                "main_coll": "sg_ssr",
                "name": "SSR类型分布统计图",
                "img": "",
                "category_name": "基因结构分析--SSR分析"
            }
        }

    def run(self, config="report_config.json"):
        self.filter_chart()
        # self.pdf2png()
        self.write_config(config)

    def write_config(self, config):
        with open(config, 'w') as fw:
            fw.write(json.dumps(self.report_config_out, indent=4, ensure_ascii=False).encode('utf8').decode())

    def filter_chart(self):
        '''
        过滤图片
        '''
        for img_id, img_dict in self.report_config.items():
            files = glob.glob(img_dict["img"])
            if len(files) > 1:
                pdf_choose = self.choose(files, img_dict)
            elif len(files) == 1:
                pdf_choose = files[0]
            else:
                print("该分析未找到结果图片 {}".format(img_dict))
                continue

            png_path = self.pdf2png(pdf_choose)

            self.report_config_out[img_id] = {
                "img": png_path + ".png",
                "pdf_choose": pdf_choose,
                "name": img_dict["name"],
                "category_name": img_dict["category_name"],
                "main_coll": img_dict["main_coll"]
            }

            if "main_dict" in img_dict:
                main_dict_out = self.convert_main_dict(img_dict["main_dict"], pdf_choose)
                self.report_config_out[img_id].update({
                    "main_dict": main_dict_out
                })

    def convert_main_dict(self, main_dict, pdf_choose):
        '''
        获取主表筛选字段
        '''
        main_dict_choosed = dict()
        for k, v in main_dict.items():
            func = globals()[v]
            main_dict_choosed[k] = func(pdf_choose)
        return main_dict_choosed

    def choose(self, files, img_dict):
        '''
        根据配置文件函数筛选图片
        '''
        if "choose_func" in img_dict:
            func_name = img_dict["choose_func"]
            func = globals()[func_name]
            choosed = files[0]
            try:
                choosed = func(files)
            except Exception as e:
                print("筛选图片错误")
                print(e)
            return choosed
        else:
            return files[0]

    def pdf2png(self, pdf_choose):
        png_path = os.path.splitext(os.path.basename(pdf_choose))[0]
        command = "gs -o png/{}.jpg -sDEVICE=jpeg  -r256 {} && convert png/{}.jpg png/{}.png".format(png_path, pdf_choose, png_path, png_path)
        os.system(command)
        return png_path

    # def pdf2png(self):
    #     os.system("mkdir -p png")
    #     for img_id, pdf_choose in self.convert_list:
    #         png_path = os.path.splitext(os.path.basename(pdf_choose))[0]
    #         command = "gs -o png/{}.jpg -sDEVICE=jpeg  -r256 {} && convert png/{}.jpg png/{}.png".format(png_path, pdf_choose, png_path, png_path)
    #         print(command)
    #         os.system(command)
    #         self.report_config_out[img_id] = {
    #             "img": png_path + ".png",
    #             ""
    #         }

if __name__ == '__main__':
    a = ChartReport()
    a.run()


from unittest.mock import MagicMock

import pytest
from serpentarium import MultiprocessingPlugin, PluginLoader

from common.agent_plugins import AgentPlugin, AgentPluginManifest, AgentPluginType
from common.event_queue import IAgentEventPublisher
from infection_monkey.exploit import IAgentBinaryRepository
from infection_monkey.i_puppet import UnknownPluginError
from infection_monkey.island_api_client import (
    IIslandAPIClient,
    IslandAPIError,
    IslandAPIRequestError,
)
from infection_monkey.puppet import PluginRegistry, PluginSourceExtractor

@pytest.fixture
def dummy_plugin_source_extractor() -> PluginSourceExtractor:
    return MagicMock(spec=PluginSourceExtractor)

@pytest.fixture
def dummy_plugin_loader() -> PluginLoader:
    return MagicMock(spec=PluginLoader)

@pytest.fixture
def dummy_agent_binary_repository() -> IAgentBinaryRepository:
    return MagicMock(spec=IAgentBinaryRepository)

@pytest.fixture
def dummy_agent_event_publisher() -> IAgentEventPublisher:
    return MagicMock(spec=IAgentEventPublisher)

@pytest.mark.parametrize(
    "error_raised_by_island_api_client, error_raised_by_plugin_registry",
    [(IslandAPIRequestError, UnknownPluginError), (IslandAPIError, IslandAPIError)],
)
def test_get_plugin__error_handling(
    dummy_plugin_source_extractor: PluginSourceExtractor,
    dummy_plugin_loader: PluginLoader,
    dummy_agent_binary_repository: IAgentBinaryRepository,
    dummy_agent_event_publisher: IAgentEventPublisher,
    error_raised_by_island_api_client: Exception,
    error_raised_by_plugin_registry: Exception,
):
    mock_island_api_client = MagicMock()
    mock_island_api_client.get_agent_plugin = MagicMock(
        side_effect=error_raised_by_island_api_client
    )
    plugin_registry = PluginRegistry(
        mock_island_api_client,
        dummy_plugin_source_extractor,
        dummy_plugin_loader,
        dummy_agent_binary_repository,
        dummy_agent_event_publisher,
    )

    with pytest.raises(error_raised_by_plugin_registry):
        plugin_registry.get_plugin("Ghost", AgentPluginType.PAYLOAD)

PLUGIN_NAME = "test_plugin"

@pytest.fixture
def agent_plugin() -> AgentPlugin:
    manifest = AgentPluginManifest(name=PLUGIN_NAME, plugin_type=AgentPluginType.EXPLOITER)
    return AgentPlugin(plugin_manifest=manifest, config_schema={}, source_archive=b"1234")

@pytest.fixture
def mock_island_api_client(agent_plugin) -> IIslandAPIClient:
    mock_island_api_client = MagicMock(spec=IIslandAPIClient)
    mock_island_api_client.get_agent_plugin = MagicMock(return_value=agent_plugin)

    return mock_island_api_client

@pytest.fixture
def mock_plugin_source_extractor() -> PluginSourceExtractor:
    return MagicMock(spec=PluginSourceExtractor)

@pytest.fixture
def mock_plugin_loader() -> PluginLoader:
    mock_plugin = MagicMock(spec=MultiprocessingPlugin)
    mock_plugin_loader = MagicMock(spec=PluginLoader)
    mock_plugin_loader.load_multiprocessing_plugin = MagicMock(return_value=mock_plugin)

    return mock_plugin_loader

@pytest.fixture
def plugin_registry(
    mock_island_api_client: IIslandAPIClient,
    mock_plugin_source_extractor: PluginSourceExtractor,
    mock_plugin_loader: PluginLoader,
    dummy_agent_binary_repository: IAgentBinaryRepository,
    dummy_agent_event_publisher: IAgentEventPublisher,
) -> PluginRegistry:
    return PluginRegistry(
        mock_island_api_client,
        mock_plugin_source_extractor,
        mock_plugin_loader,
        dummy_agent_binary_repository,
        dummy_agent_event_publisher,
    )

def test_load_plugin_from_island__only_downloaded_once(
    agent_plugin: AgentPlugin,
    mock_island_api_client: IIslandAPIClient,
    mock_plugin_source_extractor: PluginSourceExtractor,
    mock_plugin_loader: PluginLoader,
    plugin_registry: PluginRegistry,
):
    plugin_registry.get_plugin(PLUGIN_NAME, AgentPluginType.EXPLOITER)
    plugin_registry.get_plugin(PLUGIN_NAME, AgentPluginType.EXPLOITER)

    mock_island_api_client.get_agent_plugin.assert_called_once()
    mock_plugin_source_extractor.extract_plugin_source.assert_called_once()
    mock_plugin_loader.load_multiprocessing_plugin.assert_called_once()

def test_load_plugin_from_island__return_copy(
    agent_plugin: AgentPlugin,
    mock_island_api_client: IIslandAPIClient,
    mock_plugin_source_extractor: PluginSourceExtractor,
    mock_plugin_loader: PluginLoader,
    plugin_registry: PluginRegistry,
):
    plugin1 = plugin_registry.get_plugin(PLUGIN_NAME, AgentPluginType.EXPLOITER)
    plugin2 = plugin_registry.get_plugin(PLUGIN_NAME, AgentPluginType.EXPLOITER)

    assert plugin1.__class__ == plugin2.__class__
    assert plugin1.name == plugin2.name
    assert id(plugin1) != id(plugin2)


import pytest

from urllib.parse import urlencode

from lnurl.core import decode, encode, get, handle
from lnurl.exceptions import LnurlResponseException, InvalidLnurl, InvalidUrl
from lnurl.models import (
    LnurlAuthResponse,
    LnurlPayResponse,
    LnurlPayActionResponse,
    LnurlWithdrawResponse,
    LnurlPaySuccessAction,
)
from lnurl.types import Lnurl, Url

class TestDecode:
    @pytest.mark.parametrize(
        "bech32, url",
        [
            (
                "LNURL1DP68GURN8GHJ7UM9WFMXJCM99E5K7TELWY7NXENRXVMRGDTZXSENJCM98PJNWE3JX56NXCFK89JN2V3K"
                "XUCRSVTY8YMXGCMYXV6RQD3EXDSKVCTZV5CRGCN9XA3RQCMRVSCNWWRYVCYAE0UU",
                "https://service.io/?q=3fc3645b439ce8e7f2553a69e5267081d96dcd340693afabe04be7b0ccd178df",
            )
        ],
    )
    def test_decode(self, bech32, url):
        decoded_url = decode(bech32)
        assert isinstance(decoded_url, Url)
        assert decoded_url == str(decoded_url) == url
        assert decoded_url.host == "service.io"

    @pytest.mark.parametrize(
        "bech32",
        [
            "abcdef1qpzry9x8gf2tvdw0s3jn54khce6mua7lmqqqxw",
            "split1checkupstagehandshakeupstreamerranterredcaperred2y9e3w",
            "BC1QW508D6QEJXTDG4Y5R3ZARVARY0C5XW7KV8F3T4",
        ],
    )
    def test_decode_nolnurl(self, bech32):
        with pytest.raises(InvalidLnurl):
            decode(bech32)

class TestEncode:
    @pytest.mark.parametrize(
        "bech32, url",
        [
            (
                "LNURL1DP68GURN8GHJ7UM9WFMXJCM99E5K7TELWY7NXENRXVMRGDTZXSENJCM98PJNWE3JX56NXCFK89JN2V3K"
                "XUCRSVTY8YMXGCMYXV6RQD3EXDSKVCTZV5CRGCN9XA3RQCMRVSCNWWRYVCYAE0UU",
                "https://service.io/?q=3fc3645b439ce8e7f2553a69e5267081d96dcd340693afabe04be7b0ccd178df",
            )
        ],
    )
    def test_encode(self, bech32, url):
        lnurl = encode(url)
        assert isinstance(lnurl, Lnurl)
        assert lnurl.bech32 == bech32
        assert lnurl.url.host == "service.io"

    @pytest.mark.parametrize("url", ["http://service.io/"])
    def test_encode_nohttps(self, url):
        with pytest.raises(InvalidUrl):
            encode(url)

class TestHandle:
    """Responses from the LNURL playground: https://lnurl.bigsun.xyz/"""

    @pytest.mark.parametrize(
        "bech32",
        [("LNURL1DP68GURN8GHJ7MRWW4EXCTNZD9NHXATW9EU8J730D3H82UNV94KX7EMFDCLHGCT884KX7EMFDCNXKVFAXUMN2VF4XV6SPQ9K0W")],
    )
    def test_handle_auth(self, bech32):
        res = handle(bech32)
        assert isinstance(res, LnurlAuthResponse)
        assert res.tag == "login"
        assert res.callback.host == "lnurl.bigsun.xyz"
        assert hasattr(res, "k1")

    @pytest.mark.parametrize(
        "bech32",
        [("LNURL1DP68GURN8GHJ7MRWW4EXCTNZD9NHXATW9EU8J730D3H82UNV94MKJARGV3EXZAELWDJHXUMFDAHR6DEHX5CN2VE4K2GN78")],
    )
    def test_handle_withdraw(self, bech32):
        res = handle(bech32)
        assert isinstance(res, LnurlWithdrawResponse)
        assert res.tag == "withdrawRequest"
        assert res.callback.host == "lnurl.bigsun.xyz"
        assert res.default_description == "sample withdraw"
        assert res.max_withdrawable >= res.min_withdrawable

    @pytest.mark.parametrize("bech32", ["BC1QW508D6QEJXTDG4Y5R3ZARVARY0C5XW7KV8F3T4"])
    def test_handle_nolnurl(self, bech32):
        with pytest.raises(InvalidLnurl):
            handle(bech32)

    @pytest.mark.parametrize("url", ["https://lnurl.thisshouldfail.io/"])
    def test_get_requests_error(self, url):
        with pytest.raises(LnurlResponseException):
            get(url)

class TestPayFlow:
    """Full LNURL-pay flow interacting with https://lnurl.bigsun.xyz/"""

    @pytest.mark.xfail(raises=NotImplementedError)
    @pytest.mark.parametrize(
        "bech32", [("LNURL1DP68GURN8GHJ7MRWW4EXCTNZD9NHXATW9EU8J730D3H82UNV94CXZ7FLWDJHXUMFDAHR6V3EXYURYDEJSGPG7J")]
    )
    def test_pay_flow(self, bech32):
        res = handle(bech32)
        assert isinstance(res, LnurlPayResponse) is True
        assert res.tag == "payRequest"
        assert res.callback.host == "lnurl.bigsun.xyz"
        assert len(res.metadata.list()) >= 1
        assert res.metadata.text != ""

        query = urlencode({**res.callback.query_params, **{"amount": res.max_sendable}})
        url = "".join([res.callback.base, "?", query])

        res2 = get(url, response_class=LnurlPayActionResponse)
        res3 = get(url)
        assert res2.__class__ == res3.__class__
        assert res2.success_action is None or isinstance(res2.success_action, LnurlPaySuccessAction)
        assert res2.pr.h == res.metadata.h


import requests
import sys
import json
from itertools import groupby

class FootprintHandler:
    def __init__(self):
        self.footprints = []
        self.queryarea = []

    def fetch_footprint_data(self,queryarea):
        """
        Function that loads footprint data from OpenStreetMap

        Input: Location entry defined as a string or a list of strings
               containing the area name(s) or a tuple containing the longitude
               and longitude pairs for the bounding box of the area of interest
        Output: Footprint information parsed as a list of lists with each
                coordinate described in longitude and latitude pairs
        """
        def get_osm_footprints(queryarea):
            if isinstance(queryarea,str):
                # Search for the query area using Nominatim API:
                print(f"\nSearching for {queryarea}...")
                queryarea = queryarea.replace(" ", "+").replace(',','+')

                queryarea_formatted = ""
                for i, j in groupby(queryarea):
                    if i=='+':
                        queryarea_formatted += i
                    else:
                        queryarea_formatted += ''.join(list(j))

                nominatimquery = ('https://nominatim.openstreetmap.org/search?' +
                                  f"q={queryarea_formatted}&format=json")

                r = requests.get(nominatimquery)
                datalist = r.json()

                areafound = False
                for data in datalist:
                    queryarea_turboid = data['osm_id'] + 3600000000
                    queryarea_name = data['display_name']
                    if(data['osm_type']=='relation' and
                       'university' in queryarea.lower() and
                       data['type']=='university'):
                        areafound = True
                        break
                    elif (data['osm_type']=='relation' and
                         data['type']=='administrative'):
                        areafound = True
                        break

                if areafound==True:
                    print(f"Found {queryarea_name}")
                else:
                    sys.exit(f"Could not locate an area named {queryarea}. " +
                             'Please check your location query to make sure' +
                             'it was entered correctly.')

            elif isinstance(queryarea,tuple):
                pass
            else:
                sys.exit('Incorrect location entry. The location entry must be defined' +
                         ' as a string or a list of strings containing the area name(s)' +
                         ' or a tuple containing the longitude and latitude pairs for' +
                         ' the bounding box of the area of interest.')

            # Obtain and parse the footprint data for the determined area using Overpass API:
            if isinstance(queryarea,str):
                queryarea_printname = queryarea_name.split(",")[0]
            elif isinstance(queryarea,tuple):
                queryarea_printname = (f"the bounding box: [{queryarea[0]},"
                                       f"{queryarea[1]}, {queryarea[2]}, "
                                       f"{queryarea[3]}]")

            print(f"\nFetching footprint data for {queryarea_printname}...")
            url = 'http://overpass-api.de/api/interpreter'

            if isinstance(queryarea,str):
                query = f"""
                [out:json][timeout:5000];
                area({queryarea_turboid})->.searchArea;
                way["building"](area.searchArea);
                out body;
                >;
                out skel qt;
                """
            elif isinstance(queryarea,tuple):
                bbox = [min(queryarea[1],queryarea[3]),
                        min(queryarea[0],queryarea[2]),
                        max(queryarea[1],queryarea[3]),
                        max(queryarea[0],queryarea[2])]
                query = f"""
                [out:json][timeout:5000];
                way["building"]({bbox[0]},{bbox[1]},{bbox[2]},{bbox[3]});
                out body;
                >;
                out skel qt;
                """

            r = requests.get(url, params={'data': query})

            datalist = r.json()['elements']
            nodedict = {}
            for data in datalist:
                if data['type']=='node':
                   nodedict[data['id']] = [data['lon'],data['lat']]

            footprints = []
            for data in datalist:
                if data['type']=='way':
                    nodes = data['nodes']
                    footprint = []
                    for node in nodes:
                        footprint.append(nodedict[node])
                    footprints.append(footprint)

            print(f"Found a total of {len(footprints)} building footprints in {queryarea_printname}")
            return footprints

        self.queryarea = queryarea
        if isinstance(queryarea,str):
            self.footprints = get_osm_footprints(queryarea)
        elif isinstance(queryarea,tuple):
            self.footprints = get_osm_footprints(queryarea)
        elif isinstance(queryarea,list):
            self.footprints = []
            for query in queryarea:
                self.footprints.extend(get_osm_footprints(query))
        else:
            sys.exit('Incorrect location entry. The location entry must be defined' +
                     ' as a string or a list of strings containing the area name(s)' +
                     ' or a tuple containing the latitude and longitude pairs for' +
                     ' the bounding box of the area of interest.')

    def load_footprint_data(self,fpfile):
        """
        Function that loads footprint data from a GeoJSON file

        Input: A GeoJSON file containing footprint information
        Output: Footprint information parsed as a list of lists with each
                coordinate described in longitude and latitude pairs
        """
        with open(fpfile) as f:
            data = json.load(f)['features']

        self.footprints = []
        for count, loc in enumerate(data):
            self.footprints.append(loc['geometry']['coordinates'][0][0])


import gc
import os

import cv2
import numpy as np
import pandas as pd
from keras.preprocessing.image import ImageDataGenerator
from sklearn.model_selection import train_test_split

from config import BATCH_SIZE, IMG_SCALING, AUGMENTATION_DETAILS, BRIGHTNESS_AUGMENTATION_RANGE
from config import VALID_IMG_COUNT, TRAIN_DIR, INPUT_DIR, SAMPLES_PER_GROUP
from utils.rle_utils import masks_as_image

gc.enable()  # memory is tight

def make_image_gen(in_df, batch_size=BATCH_SIZE, img_scaling=IMG_SCALING, classify=False):
    all_batches = list(in_df.groupby('ImageId'))
    out_rgb, out_mask, labels = [], [], []
    while True:
        np.random.shuffle(all_batches)
        for c_img_id, c_masks in all_batches:
            rgb_path = os.path.join(TRAIN_DIR, c_img_id)
            c_img = cv2.imread(rgb_path)
            c_mask = np.expand_dims(masks_as_image(c_masks['EncodedPixels'].values), -1)
            label = [in_df[in_df.ImageId == c_img_id]['has_ship'].iloc[0]]
            if IMG_SCALING is not None:
                c_img = c_img[::img_scaling[0], ::img_scaling[1]]
                c_mask = c_mask[::img_scaling[0], ::img_scaling[1]]
            out_rgb.append(c_img)
            out_mask.append(c_mask)
            labels.append(label)
            if len(out_rgb) >= batch_size:
                if not classify:
                    yield np.stack(out_rgb, 0) / 255.0, np.stack(out_mask, 0)
                else:
                    yield np.stack(out_rgb, 0) / 255.0, np.array(labels)
                out_rgb, out_mask, labels = [], [], []
                gc.collect()

def create_aug_gen(in_gen, seed=None, classify=False):
    np.random.seed(seed if seed is not None else np.random.choice(range(9999)))
    data_gen = ImageDataGenerator(**AUGMENTATION_DETAILS, brightness_range=BRIGHTNESS_AUGMENTATION_RANGE)
    for in_x, in_y in in_gen:
        seed = np.random.choice(range(9999))
        # keep the seeds syncronized otherwise the augmentation to the images is different from the masks
        g_x = data_gen.flow(255 * in_x,
                            batch_size=in_x.shape[0],
                            seed=seed,
                            shuffle=True)
        if not classify:
            g_y = data_gen.flow(in_y,
                                batch_size=in_x.shape[0],
                                seed=seed,
                                shuffle=True)
            mask = next(g_y)
            mask = np.where(mask > 0.5, 1, 0)

        yield next(g_x) / 255.0, mask if not classify else in_y
        gc.collect()

def load_dataset():
    train = pd.read_csv(os.path.join(INPUT_DIR, "train_ship_segmentations_v2.csv"))
    return train

def get_unique_img_ids(df):
    df['ships'] = df['EncodedPixels'].map(lambda c_row: 1 if isinstance(c_row, str) else 0)
    unique_img_ids = df.groupby('ImageId').agg({'ships': 'sum'}).reset_index()
    unique_img_ids['has_ship'] = unique_img_ids['ships'].map(lambda x: 1.0 if x > 0 else 0.0)

    # some files are too small/corrupt
    unique_img_ids['file_size_kb'] = unique_img_ids['ImageId'].map(
        lambda c_img_id: os.stat(os.path.join(TRAIN_DIR, c_img_id)).st_size / 1024)
    return unique_img_ids[unique_img_ids['file_size_kb'] > 50]  # keep only +50kb files

def drop_empty_images(unique_img_ids):
    return unique_img_ids[unique_img_ids.ships != 0]

def get_balanced_dataset(unique_img_ids):
    return unique_img_ids.groupby('ships').apply(
        lambda x: x.sample(SAMPLES_PER_GROUP) if len(x) > SAMPLES_PER_GROUP else x)

def get_train_val_datasets(df, balanced_train_df):
    train_ids, valid_ids = train_test_split(balanced_train_df,
                                            test_size=VALID_IMG_COUNT,
                                            stratify=balanced_train_df['ships'])

    train_df = pd.merge(df, train_ids, on='ImageId')
    valid_df = pd.merge(df, valid_ids, on='ImageId')

    return train_df, valid_df

def split_validation_dataset(valid_df, classify):
    valid_gen = make_image_gen(valid_df, VALID_IMG_COUNT, classify=classify)
    return next(valid_gen)


import tkinter as tk
from tkinter import messagebox as mb
# ---------------------------------------------------- FLames Implementation -------------------------------------------------------------

name_1 = []
name_2 = []
count = 0
flag = True

# -------------------------------------------------------- Initialization ---------------------------------------------------------------

def Editing():

    name1 = str(entry1.get())
    name1 = name1.lower()
    name1 = name1.replace(" ", "")

    name2 = str(entry2.get())
    name2 = name2.lower()
    name2 = name2.replace(" ", "")

    if(name1.isalpha() == False or name2.isalpha() == False):
        Str = "The Entered name contains invalid characters. \nEnter the string again"
        mb.showerror("Error",Str)
        return

    if name1 == name2:
        Str = "Same names have been entered"
        mb.showerror("Error",Str)
        return

    cancel_comman_letters(name1, name2)
    letter_count()
    flames()

# ----------------------------------------- Cancellation of Comman letters between 2 names -----------------------------------------------

def cancel_comman_letters(name1, name2):

    global name_1
    global name_2

    name_1 = []
    name_2 = []

    for i in name1 :
        name_1.append(i)

    for j in name2 :
        name_2.append(j)

    for i in range (len(name_1)):

        for j in range (len(name_2)):

            if name_1[i] == name_2[j]:
                name_1[i] = '$'
                name_2[j] = '$'

# ------------------------------------------- Count the remaining letters left in the names ----------------------------------------------

def letter_count():

    global count
    count = 0

    for i in range (len(name_1)):
        if name_1[i] != '$':
            count = count + 1

    for j in range (len(name_2)):
        if name_2[j] != '$':
            count = count + 1

# ---------------------------------------------------- Finding the answer in FLAMES ------------------------------------------------------

def flames():
    # print("Performing Flames...")
    global count
    nc = count
    flames = ['f', 'l', 'a', 'm', 'e', 's']
    alter = []
    i = 0

    flag_check = True

    while flag_check == True:
        if i != count:
            i = i + 1

        if i == count:
            flames[i-1] = '*'
            i = i - 1

            for j in range (i, len(flames)):
                if flames[j] != '*':
                    alter.append(flames[j])
            for j in range (0, i):
                if flames[j] != '*':
                    alter.append(flames[j])

            flames = []
            for k in range (len(alter)):
                flames.append(alter[k])
            alter = []
            i = 0

            count = nc
        if i == len(flames):
            p = i
            count = count - p
            i = 0

        if len(flames) == 1:

            if flames[0] == 'f':
                mb.showinfo("Result", "They are FRIENDs")

            elif flames[0] == 'l':
                mb.showinfo("Result", "They are LOVEd by each other")

            elif flames[0] == 'a':
                mb.showinfo("Result", "One has AFFECTION towards the other")

            elif flames[0] == 'm':
                mb.showinfo("Result","They will marry each other")

            elif flames[0] == 'e':
                mb.showinfo("Result","They are ENEMIES")

            else:
                mb.showinfo("Result","SISTER!!!!")

            flag_check = False

# ---------------------------------------------------------------- GUI -------------------------------------------------------------------

GUI = tk.Tk()
GUI.geometry ( "450x350" )

winWidth = GUI.winfo_reqwidth()
winHeight = GUI.winfo_reqheight()
# print(winWidth,"     " ,winHeight)

posRight = int(GUI.winfo_screenwidth()/2 - winWidth)
posLeft = int(GUI.winfo_screenheight()/2 - winHeight)
# print(posRight," ",posLeft)

GUI.geometry( "+{}+{}" .format(posRight, posLeft))

GUI.resizable ( 0, 0 )
GUI.title ( "FLAMES" )

BN = tk.StringVar()
GN = tk.StringVar()

tk.Label( GUI, text = "Boy's Name : " ).place( x = 120, y = 50 )
tk.Label( GUI, text= "Girl's Name : " ).place( x = 120, y = 80 )

entry1 = tk.Entry(GUI, textvariable = BN)
entry1.place( x = 210, y = 50 )

entry2 = tk.Entry(GUI, textvariable = GN)
entry2.place( x = 210, y = 80 )

Result = tk.Label(GUI)
Result.grid( row = 5, column = 5)

tk.Button(GUI, text = "Submit",activebackground = "pink", activeforeground = "blue", command = Editing).place(x = 200, y = 120)

GUI.mainloop()


from django import forms

from .models import kacchi, sells

class kacchiForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super(kacchiForm, self).__init__(*args, **kwargs)
        self.fields['name'].widget.attrs = {
            'class': 'form-control col-md-6'
        }
        self.fields['description'].widget.attrs = {
            'class': 'form-control col-md-6'
        }
        self.fields['price'].widget.attrs = {
            'class': 'form-control col-md-6',
            'step': 'any',
            'min': '1',
        }

    class Meta:
        model = kacchi
        fields = ('name', 'description', 'price')

class sellsForm(forms.ModelForm):
     class Meta():
         model = sells
         fields = ('code','kacchi','number_of_plates','date_time','total_price')


#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import json
from importlib.machinery import SourceFileLoader
from os.path import expanduser, isfile, join
from pprint import pprint
from PyInquirer import prompt

def checksum_metric(key_name, client=None):
    """
    """

    check_questions = [
        {
            'type': 'confirm',
            'name': 'has_file',
            'message': 'Do you have an existing checksum config file to read from?'
        },
        {
            'type': 'input',
            'name': 'filename',
            'message': 'What is the path to the file:',
            'when': lambda check_answers: check_answers['has_file']
        },
        {
            'type': 'input',
            'name': 'hash_algo',
            'message': 'What is the hashing algorithm used (SHA1, SHA256, etc.)?',
            'when': lambda check_answers: check_answers['has_file']
        }
    ]

    check_answers = prompt(check_questions)

    if check_answers['has_file']:
        filename = check_answers['filename']

    # Gather from file if user chose to provide one
    # TODO: CREATE FUNCTION TO EXPAND FUNCTIONALITY TO JSON/POSIX
    if check_answers['has_file']:
        fields = {}
        i = 1

        algorithm = check_answers['hash_algo']

        # Parse checksum config files for values
        # Don't need to return the checksum since the file already exists
        if isfile(expanduser(filename)):
            if client == "Python" or client == "Python3":
                checksum_conf = SourceFileLoader(
                    'configfile', filename).load_module()

                files = checksum_conf.files

                for name, checksum in files.items():
                    name = "{0}.{1}".format(key_name, name)
                    key = "{0}{1}".format(key_name, i)
                    i += 1

                    fields.update(
                        {key: {'name': name, 'min': 1, 'max': 1, 'checksum': checksum, 'hash_algorithm': algorithm}})

            elif client == "PowerShell":
                with open(filename, 'r') as f:
                    data = json.load(f)

                for content in data:
                    name = "{0}.{1}".format(key_name, content['FileName'])
                    key = "{0}{1}".format(key_name, i)
                    checksum = content['Hash']
                    algorithm = content['HashAlgorithm']

                    i += 1

                    fields.update({key: {'name': name, 'min': 1, 'max': 1,
                                         'checksum': checksum, 'hash_algorithm': algorithm}})

            elif client == "POSIX":
                with open(filename, 'r') as f:
                    data = f.readlines()

                for content in data:
                    content = content.strip('\n').split()

                    # i[0] == filename and i[1] == the checksum
                    name = "{0}.{1}".format(key_name, content[0])
                    key = "{0}{1}".format(key_name, i)
                    i += 1

                    fields.update(
                        {key: {'name': name, 'min': 1, 'max': 1, 'checksum': content[1], 'hash_algorithm': algorithm}})

            return fields

        # The file doesn't exist if
        else:
            print("Invalid file. Please specify a valid file")

    # Gather file names and its hash directly from user at prompt
    else:
        get_files = True
        files = {}
        i = 1

        while get_files:

            file_questions = [
                {
                    'type': 'input',
                    'name': 'name',
                    'message': 'What is the name and full path of the file:'
                },
                {
                    'type': 'input',
                    'name': 'checksum',
                    'message': 'What is the checksum for this file:'
                },
                {
                    'type': 'input',
                    'name': 'hash_algo',
                    'message': 'What is the hashing algorithm used (SHA1, SHA256, etc.)?',
                },
                {
                    'type': 'confirm',
                    'name': 'get_files',
                    'message': 'Add another file to check?'
                }
            ]

            file_answers = prompt(file_questions)

            name = "{0}.{1}".format(key_name, file_answers['name'])
            key = "{0}{1}".format(key_name, i)

            files.update(
                {key: {'name': name,
                       'checksum': file_answers['checksum'], 'min': 1, 'max': 1, 'hash_algorithm': file_answers['hash_algo']}})

            if file_answers['get_files']:
                i += 1
            else:
                break

        return files

def configure_checksum(keys, all_metrics, archive_dir, client):
    """ Puts the checksum metric info in its necessary config file

    Accepts the keys that are generated in the configure_metrics py file
    and the whole output from that. Sorts through the keys and grabs the data
    and stores variables in a format that the language reads.
    """

    print("\n=====Configuring the checksum metric=====")

    hash_dict = {}
    hash_list_ps = []

    for key in keys:
        checksum_data = all_metrics[key]

        filename = '.'.join(checksum_data['name'].split('.')[1:])
        checksum = checksum_data['checksum']
        algorithm = checksum_data['hash_algorithm']

        if client == 'POSIX':
            hash_dict.update(
                {filename: {'checksum': checksum, 'algorithm': algorithm}})
        elif client == 'Python' or client == 'Python3':
            hash_dict.update({filename: checksum})

        elif client == 'PowerShell':
            _dict = {"FileName": filename, "Hash": checksum.upper(),
                     "HashAlgorithm": algorithm.upper()}

            hash_list_ps.append(_dict)

    if client == 'POSIX':
        checksum_dir = "{0}/POSIX/NodePingPUSHClient/modules/checksum".format(
            archive_dir)
        checksum_file = join(checksum_dir, "checksum.txt")
        checksum_type_file = join(checksum_dir, "checksum_type.txt")

        # Clear contents of checksum.txt file
        open(checksum_file, 'w').close()
        # Clear contents of checksum_type.txt file
        open(checksum_type_file, 'w').close()

        with open(checksum_file, 'a', newline='\n') as f:
            for key, value in hash_dict.items():
                line = "{0} {1}\n".format(key, value['checksum'])
                f.write(line)

        # Write the hashing algorithm type to file
        with open(checksum_type_file, 'w', newline='\n') as f:
            f.write(hash_dict[filename]['algorithm'].lower())

    elif client == 'Python' or client == 'Python3':
        checksum_dir = "{0}/{1}/NodePing{1}PUSH/metrics/checksum".format(
            archive_dir, client)

        checksum_file = join(checksum_dir, "config.py")

        # Clear contents of config.py file
        open(checksum_file, 'w').close()

        with open(checksum_file, 'a', newline='\n') as f:
            f.write("files = ")
            pprint(hash_dict, stream=f)
            f.write("\nhash_algorithm = \"{0}\"".format(algorithm.lower()))

    elif client == "PowerShell":
        checksum_dir = "{0}/{1}/NodePing{1}PUSH/modules/checksum".format(
            archive_dir, client)

        checksum_file = join(checksum_dir, "checksum.json")

        # Clear contents of the config.json file
        open(checksum_file, 'w').close()

        with open(checksum_file, 'w') as f:
            f.write(json.dumps(hash_list_ps, indent=8, sort_keys=True))


#  (C) Catchoom Technologies S.L.
#  Licensed under the MIT license.
#  https://github.com/catchoom/craftar-python/blob/master/LICENSE
#  All warranties and liabilities are disclaimed.

from optparse import OptionParser
import craftar

"""
Lists all your items. If needed, they can be limited to a specific collection.

- Requires an account and a collection with items at https://my.craftar.net
- The @api_key is your management api key. Get it at
https://my.craftar.net/accounts/apis/
- You can limit the result to a specific @collection.
- Don't set the @hostname, unless you are using a custom platform.
"""

def list_paginated_items(api_key, items_per_page=25, collection=None,
                         hostname=None):
    "List all items, paginated by @items_per_page"

    if hostname:
        craftar.settings.MANAGEMENT_HOSTNAME = hostname

    offset = 0

    while True:
        print("- Retrieving items %s to %s..." % (offset + 1,
                                                  offset + items_per_page))

        item_list = craftar.get_item_list(
            api_key=api_key,
            limit=items_per_page,
            offset=offset,
            collection=collection,
        )

        for i in item_list:
            print("%s: %s" % (i["uuid"], i["name"]))
        offset += items_per_page
        if len(item_list) < items_per_page:
            print("No more items!")
            return

if __name__ == '__main__':
    usage = "usage: %prog -a API_KEY [-c COLLECTION -H HOSTNAME]"
    parser = OptionParser(usage, version="%prog 1.0")
    parser.add_option('-a', '--api_key',
                      dest='api_key',
                      help="Management API key.")
    parser.add_option('-c', '--collection',
                      dest='collection',
                      default=False,
                      help='Collection UUID')
    parser.add_option('-H', '--hostname',
                      dest='hostname',
                      default=False,
                      help='CraftAR recognition API hostname')
    (options, args) = parser.parse_args()

    if not options.api_key:
        parser.error("Missing parameter: -a API_KEY")

    list_paginated_items(api_key=options.api_key,
                         collection=options.collection,
                         hostname=options.hostname)


from ivy import ivy_module as im
from ivy.ivy_compiler import ivy_from_string
from ivy.tk_ui import new_ui
from ivy import ivy_utils as iu

prog = """#lang ivy1.5

object obj = {
    type t
}

relation r(X:obj.t)

action a(x:obj.t) = {
local y:obj.t {
  if some z:s. z = z {
    y := y
}
}
}

type s

axiom forall X:s. X = X

"""

with im.Module():
    iu.set_parameters({'ui':'cti','ext':'ext','show_compiled':'true'})
    main_ui = new_ui()
    ui = main_ui.add(ivy_from_string(prog))
#     main_ui.answer("OK")
#     ui.check_inductiveness()
# #    ui = ui.cti
#     cg = ui.current_concept_graph
#     cg.show_relation(cg.relation('link(X,Y)'),'+')
#     cg.gather()
#     main_ui.answer("OK")
#     cg.strengthen()
#     main_ui.answer("OK")
#     ui.check_inductiveness()
# #    cg.show_relation(cg.relation('semaphore'),'+')
#     cg.gather()
#     main_ui.answer("View")
#     cg.bmc_conjecture(bound=1)
# #    main_ui.mainloop()


# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def goodNodes(self, root: TreeNode) -> int:
        count = 0
        maxVal = root.val
        def dfs(node , maxVal):
            if node is None:
                return
            if maxVal <= node.val:
                nonlocal count
                count += 1
                maxVal = node.val
            dfs(node.left,maxVal)
            dfs(node.right,maxVal)

        dfs(root,maxVal)
        return count


# -*- coding: utf-8 -*-
import argparse
import os
import sys
import cv2
import numpy as np
import torch
import xml.dom.minidom
from xml.etree.ElementTree import Element
from xml.etree.ElementTree import SubElement
from xml.etree.ElementTree import ElementTree

sys.path.append(os.path.dirname(os.getcwd()))

from train.model.UNet.unet_model import UNet
from CRAFT.predict import TextDetector
from train.utils.dataset import BasicDataset
from train.utils.utils import get_polygon_from_lines, is_pt_in_polygon

def convert_str_coord_to_int(str_coord):
    pts_str = str_coord.split(" ")
    pts = []
    for i in range(len(pts_str)):
        x, y = pts_str[i].split(",")
        pts.append([int(x), int(y)])

    return pts

def convert_pt_to_string(pts):
    pt_str = ""
    for pt in pts:
        if pt_str != "":
            pt_str += " "
        pt_str += str(int(pt[0])) + "," + str(int(pt[1]))

    return pt_str

def get_text_box_in_cell(cell, texts, text_status):
    inside_text = []
    for i in range(len(texts)):
        if not text_status[i]:
            center = np.mean(texts[i], axis=0)
            if is_pt_in_polygon(center, cell) >= 0:
                inside_text.append(texts[i])
                text_status[i] = True

    box = []
    if inside_text:
        minRect = cv2.minAreaRect(np.array(inside_text).reshape(-1, 2))
        box = cv2.boxPoints(minRect).astype(np.int)

    return box

class Predictor:
    def __init__(self, pretrained_model_path, text_model_path):
        self.img_size = (640, 640)

        self.net = UNet(n_channels=3, n_classes=2, bilinear=True)
        self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")

        self.net.to(device=self.device)
        self.net.load_state_dict(torch.load(pretrained_model_path, map_location=self.device))
        print('Loading weights from checkpoint ' + pretrained_model_path)

        self.out_threshold = 0.7
        self.text_detector = TextDetector(text_model_path)

    def get_masks(self, full_img):
        self.net.eval()

        img, scale_rate = BasicDataset.preprocess(full_img, self.img_size)
        img = torch.from_numpy(img)
        img = img.unsqueeze(0)
        img = img.to(device=self.device, dtype=torch.float32)

        with torch.no_grad():
            output = self.net(img)

            probs = torch.sigmoid(output)
            probs = probs.squeeze(0)
            masks = probs.cpu().numpy()
            masks = masks.transpose((1, 2, 0))

        # 二值化
        h, w = full_img.shape[:2]
        img_area = (int(round(w * scale_rate[0])), int(round(h * scale_rate[1])))
        masks = masks[: img_area[1], : img_area[0], :]
        masks = cv2.resize(masks, (w, h))
        masks = masks.transpose((2, 0, 1))

        masks = np.where(masks > self.out_threshold, 255, 0)

        return masks

    def get_cells_from_masks(self, masks):
        h, w = masks[0].shape[:2]
        area_thresh = h * w * 0.001

        lines = [[], []]  # 分别表示横线和竖线
        for i in range(len(masks)):
            mask = masks[i].astype("uint8")
            _, contours, hierarchy = cv2.findContours(mask, mode=cv2.RETR_EXTERNAL, method=cv2.CHAIN_APPROX_SIMPLE)

            for contour in contours:
                Mo = cv2.moments(contour)  # 求矩
                area = Mo["m00"]

                if area > area_thresh:
                    dim = 0 if i % 2 == 0 else 1
                    c_sort = sorted(contour.reshape(-1, 2), key=lambda x: x[dim])
                    line = [c_sort[0].tolist(), c_sort[-1].tolist()]

                    lines[dim].append(line)

        # 排序
        lines[0] = sorted(lines[0], key=lambda x: x[0][1])
        lines[1] = sorted(lines[1], key=lambda x: x[0][0])

        cells = []
        for i in range(len(lines[0]) - 1):
            for j in range(len(lines[1]) - 1):
                pts = get_polygon_from_lines([lines[1][j], lines[0][i], lines[1][j + 1], lines[0][i + 1]])
                cell = {"begin_row": i, "end_row": i, "begin_col": j, "end_col": j, "pts": pts}
                cells.append(cell)

        return cells

    def add_cell_to_result(self, table_xml, cells):
        for cell in cells:
            cell_xml = SubElement(table_xml, "cell")
            cell_xml.set("end-col", str(cell["end_col"]))
            cell_xml.set("end-row", str(cell["end_row"]))
            cell_xml.set("start-col", str(cell["begin_col"]))
            cell_xml.set("start-row", str(cell["begin_row"]))
            cell_coord = SubElement(cell_xml, "Coords")
            cell_coord.set("points", convert_pt_to_string(cell["pts"]))

    def predict(self, input_path, output_path):
        files = os.listdir(input_path + "/imgs")
        for file in files:
            name, type = file.split(".")
            if type == "xml":
                continue

            texts = self.text_detector.predict(os.path.join(input_path + "/imgs", file))
            text_status = [False] * len(texts)

            img = cv2.imread(os.path.join(input_path + "/imgs", file))

            gt_dom = xml.dom.minidom.parse(os.path.join(input_path + "/gt", name + ".xml"))
            gt_tables = gt_dom.documentElement.getElementsByTagName("table")

            root = Element("document")
            root.set("imgname", name)

            for i in range(len(gt_tables)):
                gt_table = gt_tables[i]
                table_coord_str = gt_table.firstChild.getAttribute("points")
                table_pts = convert_str_coord_to_int(table_coord_str)

                c_min = np.min(table_pts, axis=0)
                c_max = np.max(table_pts, axis=0)

                table_img = img[c_min[1]: c_max[1], c_min[0]: c_max[0]]
                masks = self.get_masks(table_img)

                cells = self.get_cells_from_masks(masks)

                offset = [c_min[0], c_min[1]]  # x和y的offset
                valid_cell = []
                for cell in cells:
                    for j in range(4):
                        cell["pts"][j] = [cell["pts"][j][0] + offset[0], cell["pts"][j][1] + offset[1]]

                    text_box = get_text_box_in_cell(cell["pts"], texts, text_status)
                    if text_box != []:
                        cell["pts"] = text_box
                        valid_cell.append(cell)

                table = SubElement(root, "table")
                table.set("id", str(i + 1))
                table_coord = SubElement(table, "Coords")
                table_coord.set("points", table_coord_str)

                self.add_cell_to_result(table, valid_cell)

            # 将xml文件保存在输出文件夹中
            xml_tree = ElementTree(root)
            xml_tree.write(os.path.join(output_path, name + ".xml"), encoding="utf-8")

def run():
    parser = argparse.ArgumentParser()

    parser.add_argument("-i", "--input", dest="input", help="input file path", required=True)
    parser.add_argument("-o", "--output", dest="output", help="output file directory", required=True)
    parser.add_argument("-p", "--model_path", dest="model", help="path of model", required=True)
    parser.add_argument("-t", "--text_model_path", dest="text_model", help="path of model", required=True)

    args = parser.parse_args()

    predictor = Predictor(args.model, args.text_model)
    predictor.predict(args.input, args.output)
    print("done")

if __name__ == "__main__":
    run()


import logging
import isceobj
import mroipac

from iscesys.ImageUtil.ImageUtil import ImageUtil as IU
from mroipac.ampcor.Ampcor import Ampcor
from isceobj import Constants as CN

logger = logging.getLogger('isce.insar.runRgoffset')

def runRgoffset(self):
    numLocationAcross =  self._insar.getNumberLocationAcrossPrf()
    numLocationDown =  self._insar.getNumberLocationDownPrf()
    firstAc = self._insar.getFirstSampleAcrossPrf()
    firstDown = self._insar.getFirstSampleDownPrf()

    #Fake amplitude image as a complex image
    imageAmp = self._insar.getResampAmpImage()
    objAmp = isceobj.createImage()
    objAmp.setAccessMode('read')
    objAmp.dataType = 'CFLOAT'
    objAmp.bands = 1
    objAmp.setFilename(imageAmp.filename)
    objAmp.setWidth(imageAmp.width)
    objAmp.createImage()
    widthAmp = objAmp.getWidth()
    intLength = objAmp.getLength()

    imageSim = self._insar.getSimAmpImage()
    objSim = isceobj.createImage()
    objSim.setFilename(imageSim.filename)
    objSim.setWidth(imageSim.width)
    objSim.dataType='FLOAT'
    objSim.setAccessMode('read')
    objSim.createImage()

    simWidth = imageSim.getWidth()
    simLength = imageSim.getLength()
    fs1 = self._insar.getReferenceFrame().getInstrument().getRangeSamplingRate()  ##check
    delRg1 = CN.SPEED_OF_LIGHT / (2*fs1)                                          ## if it's correct

    objAmpcor = Ampcor(name='insarapp_intsim_ampcor')
    objAmpcor.configure()
    objAmpcor.setImageDataType1('real')
    objAmpcor.setImageDataType2('mag')

    ####Adjust first and last values using window sizes
    xMargin = 2*objAmpcor.searchWindowSizeWidth + objAmpcor.windowSizeWidth
    yMargin = 2*objAmpcor.searchWindowSizeHeight + objAmpcor.windowSizeHeight

    if not objAmpcor.acrossGrossOffset:
        coarseAcross = 0
    else:
        coarseAcross = objAmpcor.acrossGrossOffset

    if not objAmpcor.downGrossOffset:
        coarseDown = 0
    else:
        coarseDown = objAmpcor.downGrossOffset

    offAc = max(firstAc, -coarseAcross) + xMargin + 1
    offDn = max(firstDown, -coarseDown) + yMargin + 1
    lastAc = int(min(widthAmp, simWidth-offAc) - xMargin -1)
    lastDn = int(min(intLength, simLength-offDn) - yMargin -1)

    if not objAmpcor.firstSampleAcross:
        objAmpcor.setFirstSampleAcross(offAc)

    if not objAmpcor.lastSampleAcross:
        objAmpcor.setLastSampleAcross(lastAc)

    if not objAmpcor.numberLocationAcross:
        objAmpcor.setNumberLocationAcross(numLocationAcross)

    if not objAmpcor.firstSampleDown:
        objAmpcor.setFirstSampleDown(offDn)

    if not objAmpcor.lastSampleDown:
        objAmpcor.setLastSampleDown(lastDn)

    if not objAmpcor.numberLocationDown:
        objAmpcor.setNumberLocationDown(numLocationDown)

    #set the tag used in the outfile. each message is precided by this tag
    #is the writer is not of "file" type the call has no effect
    self._stdWriter.setFileTag("rgoffset", "log")
    self._stdWriter.setFileTag("rgoffset", "err")
    self._stdWriter.setFileTag("rgoffset", "out")
    objAmpcor.setStdWriter(self._stdWriter)
    prf = self._insar.getReferenceFrame().getInstrument().getPulseRepetitionFrequency()

    objAmpcor.setFirstPRF(prf)
    objAmpcor.setSecondPRF(prf)

    if not objAmpcor.acrossGrossOffset:
        objAmpcor.setAcrossGrossOffset(coarseAcross)

    if not objAmpcor.downGrossOffset:
        objAmpcor.setDownGrossOffset(coarseDown)

    objAmpcor.setFirstRangeSpacing(delRg1)
    objAmpcor.setSecondRangeSpacing(delRg1)

    objAmpcor.ampcor(objSim,objAmp)

    # Record the inputs and outputs
    from isceobj.Catalog import recordInputsAndOutputs
    recordInputsAndOutputs(self._insar.procDoc, objAmpcor, "runRgoffset_ampcor", \
                  logger, "runRgoffset_ampcor")

    self._insar.setOffsetField(objAmpcor.getOffsetField())
    self._insar.setRefinedOffsetField(objAmpcor.getOffsetField())

    objAmp.finalizeImage()
    objSim.finalizeImage()


from importPy import *

class Event:
    None
def eega_importinfoevents(EEG, args):
    """
    This functions reads the event file and extract relevant info to integrate to the EEG struc

    Inputs :
    EEG : Raw MNE data ! Must have defined EEG.fileName
    args:
        filevent : txt file with events
        event0 : event use to align timings if not same (default : first common event)
        eventtype : event type for which extra info is collected (default : all event)
        latlim : tolerance in the latency (in samples) between the latency in the event and the EEG (default : 3)

    Output : EEG
    """

    #Input parameters
    print(" ### Importing informations of the events ###")
    pathIn = args[0]
    if(len(args)>1):
        event0 = args[1]
        if(type(event0) != list):
            event0 = [event0]
    else:
        event0 = []
    if(len(args)>2):
        eventtype = args[2]
    else:
        eventtype = []
    if(len(args)>3):
        latlim = args[3]
    else:
        latlim = 3

    #Find event in EEG file
    events,dic = mne.events_from_annotations(EEG)
    inv_map = {v: k for k, v in dic.items()}
    EEGEvent = []
    for i in range(len(events)):
        latency,v,ind = events[i]
        EEGEvent.append(Event())
        EEGEvent[i].latency = latency
        EEGEvent[i].type = inv_map[ind]

    if(eventtype == []):
        ev = []
        for e in range(len(EEGEvent)):
            if(EEGEvent[e].type not in ev):
                ev.append(strip(EEGEvent[e].type))
        eventtype = ev
    elif(type(eventtype) == str):
        eventtype = [strip(eventtype)]
    eventtype = unique(eventtype)
    if(event0 != []):
        if(type(event0) == str):
            if(event0.isnumeric()):
                event0 = [EEGEvent[int(event0)].type]
            else:
                event0 = [event0]

    #Reading the event-file

    if(not hasattr(EEG,"fileName")):
        raise ValueError("eega_importinfoevents : EEG raw missing field EEG.fileName")
    fileEvent =pathIn+"/"+EEG.fileName+".evt"

    #Read event file
    fid = open(fileEvent,"r")
    L = fid.read()
    L = L.split("\n")
    for i in range(0,len(L)):
        L[i]=L[i].split("\t")

    #Find line with columns names
    idx = 0
    while(L[idx][0] != "Code" and idx < len(L)):
        idx+=1
    Ename = L[idx]
    EnameOK = [True if L[idx][i] != [] else False for i in range(len(L[idx]))]

    if(i>=len(L)):
        raise ValueError("eega_importinfoevents : No row with column names found in evt file")

    #Data with event
    Ed = L[idx+1:]

    ## Convert all time to samples for the event file
    id_time = Ename.index('Onset') #Column with time
    id_type = Ename.index('Code') #Column with Code
    for ie in range(0,len(Ed)):
        if(len(Ed[ie])> id_time):
            t_txtx = Ed[ie][id_time]
            tpos = t_txtx.find(":")
            date = t_txtx[tpos-2:]
            date = date.split(":")
            t_sec = int(date[0])*60*60+int(date[1])*60+float(date[2])
            Ed[ie][id_time]=round(t_sec*EEG.info["sfreq"])
    for row in Ed:
        if(len(row)<id_time):
            print(row)
    TIMEevt = [row[id_time] for row in Ed if row != ['']]

    TYPEevt = [row[id_type] for row in Ed]

    ## Get all timing and names of the event for the EEG structure
    TIMEeeg = []
    TYPEeeg = []
    for ie in range(0,len(EEGEvent)):
        TIMEeeg.append(EEGEvent[ie].latency)
        TYPEeeg.append(EEGEvent[ie].type)

    ## Determine the events to use for alignement
    if(event0 == []):
        event0 = [value for value in TYPEeeg if value in TYPEevt]#Choose the event in both TYPEevt ant TYPEeeg
        event0 = [unique(event0)]
        if(event0 == []):
            raise ValueError("eega_importinfoevents : Commond event were not found")

    ## Align the times to the same t0

    #find time zero event
    t0_idx_evt = []
    t0_idx_eeg = []
    for i in range(0,len(event0)):
        for j in range(0,len(EEGEvent)):
            if(strip(EEGEvent[j].type) == strip(event0[i])):
                t0_idx_eeg.append(j)

        for j in range(0,len(TYPEevt)):
            if(strip(TYPEevt[j]) == strip(event0[i])):
                t0_idx_evt.append(j)
    t0_idx_evt.sort()
    t0_idx_eeg.sort()
    # check that all the events in the text file exist in the eeg structure
    if(len(t0_idx_eeg) != len(t0_idx_evt)):
        raise ValueError("eega_importinfoevents : Missmatch in the number of t0 events")

    # check that the difference in timing is constant
    idxjumps = []
    sum_idxjumps = 0
    for i in range(0,len(t0_idx_evt)):
        if(TIMEevt[t0_idx_evt[0]]-TIMEeeg[t0_idx_eeg[0]] >latlim):
            sum_idxjumps+=1
            idxjumps.append(1)
        else:
            idxjumps.append(0)
    if(sum_idxjumps == 0):
        print('Timings are aligned, nothing will be done.')
    elif(sum_idxjumps == 1):
        for i in range(0,len(event0)):
            print('Timing will be aligned based on the first event '+str(event0[i]))
    else:
        print("Dissaliging observed at "+str(sum_idxjumps)+" points!! The data will try to be realigned")

    #Bring to zero between jumps in the timing
    idxjumps = find(idxjumps)

    if(idxjumps != []):

        evt2align = [t0_idx_evt[i] for i in idxjumps]
        eeg2align = [t0_idx_eeg[i] for i in idxjumps]

        # First alignment, apply it for all times before and after
        print('Alignment 1')
        print(' - Alignment based on event %s, event %d in the event file, latency %d \n'%(TYPEevt[evt2align[0]], evt2align[0], TIMEevt[evt2align[0]]))
        print(' - Alignment based on event %s, event %d in the EEG structure, latency %d \n' %(TYPEeeg[evt2align[0]], eeg2align[0], TIMEeeg[eeg2align[0]]))
        t0 = TIMEevt[evt2align[0]] - TIMEeeg[eeg2align[0]]

        if(t0 != 0):
            print('--> A time difference %d samples was found between the event.\n'%(t0))

            for i in range(len(TIMEevt)):
                TIMEevt[i] -=t0
            for ie in range(len(Ed)):
                if(len(Ed[ie])>id_time):
                    Ed[ie][id_time] = Ed[ie][id_time] - t0

        #Further alignement if necessary
        if(len(idxjumps) > 1):
            for ij in range(1,len(idxjumps)):
                print('Alignment '+str(ij))
                print(' - Alignment based on event %s, event %d in the event file, latency %d \n'%(TYPEevt[evt2align[ij]], evt2align[ij], TIMEevt[evt2align[ij]]))
                print(' - Alignment based on event %s, event %d in the EEG structure, latency %d \n' %(TYPEeeg[evt2align[ij]], eeg2align[ij], TIMEeeg[eeg2align[ij]]))
                t0 = TIMEevt[evt2align[ij]] - TIMEeeg[eeg2align[ij]]

                if(t0 != 0):
                    print('--> A time difference %d samples was found between the event.\n'%(t0))

                    for i in range(evt2align[ij],len(TIMEevt)):
                        TIMEevt[i] -=t0
                    for ie in range(evt2align[ij],len(Ed)):
                        Ed[ie][id_time] = Ed[ie][id_time] - t0

    ##Indentify the events to which information will be added
    idxEv = []
    for i in range(len(EEGEvent)):
        idxEv.append(strip(EEGEvent[i].type) in eventtype)
    idxEv = find(idxEv)

    idxEd = []
    for i in range(len(TYPEevt)):
        vals = [0]*len(eventtype)
        if(strip(TYPEevt[i]) in eventtype):
            vals[eventtype.index(strip(TYPEevt[i]))] = 1
        idxEd.append(vals)

    Edev = []
    for i in range(len(Ed)):
        if(1 in idxEd[i]):
            Edev.append(Ed[i])

    ## Search for extra information for each event in EEG
    count = 0
    typeev = [strip(row[0]) for row in Edev]
    latev = [row[id_time] for row in Edev]
    v_diff= []

    for i in range(len(idxEv)):
        ieeg = idxEv[i]
        latieeg = EEGEvent[ieeg].latency
        typeeeg = strip(EEGEvent[ieeg].type)

        #Find the event of the correct type
        typeOK = find([int(typeeeg == i) for i in typeev])
        if(typeOK != []):
            c = [abs(latev[i]-latieeg) for i in typeOK]
            minValue = min(c)
            idx = [i for i, x in enumerate(c) if x == minValue]
            ie = typeOK[idx[0]]
            v_diff.append(v)

            if(v <= latlim):
                #Edit the event
                j = 0
                while j < len(Ename):
                    if(Ename[j] != 'Onset' and Ename[j] != 'Duration'):
                        if(not EnameOK[j] and Edev[ie][j] == []):
                            j = j+2
                        else:
                            thefield = ""
                            if(EnameOK[j]):
                                jj = j
                                thefield = Ename[j]
                                j = j+1
                            elif(not EnameOK[j] and Edev[ie][j] != []):
                                jj=j+1
                                thefield = strip(Edev[ie][j])
                                j = j+2
                            if(not hasattr(EEGEvent[0],thefield)):
                                for iiev in range(len(EEGEvent)):
                                    setattr(EEGEvent[iiev],thefield,[])
                                if(hasattr(EEG,'epoch')):
                                    for iiep in range(len(EEG.epoch)):
                                        setattr(EEG.epoch[iiep].event,thefield,'')
                            setattr(EEGEvent[ieeg],thefield,strip(Edev[ie][jj]))
                            if(hasattr(EEG,'epoch')):
                                for iiep in range(len(EEG.epoch)):
                                    idxEpEv = EEG.epoch[iiep].event == ieeg
                                    if(idxEpEv):
                                        setattr(EEG.epoch[iiep].event,thefield,strip(Edev[ie][jj]))
                    else:
                        j = j+1
                count = count +1
            else:
                print('WARNING!!! %d samples difference for the event %s - %d - urevent %d \n no information was added \n' %(v, EEG.event(ieeg).type, ieeg, EEG.event(ieeg).urevent))
    EEG.event = EEGEvent
    print('\nNew information added to %d events \n\n'%count)
    return EEG