from sys import exit

# Make the start of the game
def start():
    print("You wake up half naked on the ground.")
    print("Around you are massive trees surrounded by magical blue mist.")
    print("Far down the hill in front, you see a little village filled with blue skinned people.")
    print("You see a guard post with two armed guards a little bit to the right.")
    print("On a clearence to the left is a strange rift in space, a portal.")
    print("You can't see clearly what's behind you because of all the mist.")

    choice = input("> ")

    if choice == "front":
        village()
    if choice == "back":
        wolf()
    if choice == "right":
        guard_post()
    if choice == "left":
        rift()
    else:
        dead("You fall over a a rock and die.")

# Make the village part
def village():
    print("After getting through some murmur in the center you approach a cloacked old lady.")
    print("She asks you: 'Left or Right?'")

    choice = input("> ")

    if choice == "left":
        print("The lady reveals herself as a witch and shoots a death spell out of her left hand.")
        dead("You turn into dust.")
    if choice == "right":
        print("The lady summons a rift from her right hand and pushes you through with a magic blast.")
        abyss()
    else:
        print("She turns into a witch screaming 'YOU FOOL!' and throws a volcano spell over you.")
        dead("You turned into fumes.")

# Make the wolf part
def wolf():
    print("You stumble through the thick fog and see two eyes shine through.")
    print("Do you go towards them or run?")

    choice = input("> ")

    if choice == "go" or "towards":
        print("A massive black wolf reveals himself and his fangs.")
        dead("You're dog food now.")
    if choice == "run":
        start()
    else:
        wolf()

# Make the rift part
def rift():
    print("1")

    choice = input("> ")

# Make the guard post part
def guard_post():
    print("1")

    choice = input("> ")

# Second Phase: The Abyss

def dead(why):
    print(why, "Good job!")
    exit(0)

start()


import cv2
import numpy as np

'''
import numpy as np
from scipy.signal import cwt
from skimage.io import imread

# Read the input image
img = imread('input_image.png')

# Perform the continuous wavelet transform (CWT) on the image
# using the 'poisson' wavelet
cwt_result = cwt(img, 'poisson')

# The CWT returns a 2D array, with the first dimension representing the time
# (or in this case, the rows of the image) and the second dimension representing
# the scale (or columns of the image)
# We will use the absolute value of the CWT to identify noisy pixels
cwt_result = np.abs(cwt_result)

# Now we will threshold the CWT result to identify noisy pixels
# First, we need to determine a suitable threshold value
# We can use the median absolute deviation (MAD) to find this value
threshold = np.median(cwt_result) + 0.6745 * np.median(np.abs(cwt_result - np.median(cwt_result)))

# Now we can threshold the CWT result to identify the noisy pixels
noisy_pixels = cwt_result > threshold

# The 'noisy_pixels' array will be a boolean array, with 'True'
# values indicating the presence of noisy pixels in the image
'''

def poisson_noise(img):
    from skimage.io import imread
    import matplotlib.pyplot as plt
    import numpy as np
    import scipy.signal as sig
    from skimage import data

    import numpy as np
    from functools import lru_cache

    def poisson2d_wavelet(omega_x, omega_y, sigma):
        r = np.sqrt(omega_x ** 2 + omega_y ** 2)
        return -sigma ** 2 * np.exp(-sigma ** 2 * r ** 2) * (1 - 2 * sigma ** 2 * r ** 2)

    wavelets = {}
    wavelets['poisson'] = poisson2d_wavelet

    def _get_wavelet_mask(wavelet: str, omega_x: np.array, omega_y: np.array, **kwargs):
        assert omega_x.shape == omega_y.shape
        return wavelets[wavelet](omega_x, omega_y, **kwargs)

    @lru_cache(5)
    def _create_frequency_plane(image_shape: tuple):
        assert len(image_shape) == 2

        h, w = image_shape
        w_2 = (w - 1) // 2
        h_2 = (h - 1) // 2

        w_pulse = 2 * np.pi / w * np.hstack((np.arange(0, w_2 + 1), np.arange(w_2 - w + 1, 0)))
        h_pulse = 2 * np.pi / h * np.hstack((np.arange(0, h_2 + 1), np.arange(h_2 - h + 1, 0)))

        xx, yy = np.meshgrid(w_pulse, h_pulse, indexing='xy')
        dxx_dyy = abs((xx[0, 1] - xx[0, 0]) * (yy[1, 0] - yy[0, 0]))

        return xx, yy, dxx_dyy

    def cwt_2d(x, scales, wavelet, **wavelet_args):
        assert isinstance(x, np.ndarray) and len(x.shape) == 2, 'x should be 2D numpy array'

        x_image = np.fft.fft2(x)
        xx, yy, dxx_dyy = _create_frequency_plane(x_image.shape)

        cwt = []
        wav_norm = []

        for scale_val in scales:
            mask = scale_val * _get_wavelet_mask(wavelet, scale_val * xx, scale_val * yy, **wavelet_args)
            mask = mask.T
            cwt.append(np.fft.ifft2(x_image * mask.T))
            wav_norm.append((np.sum(abs(mask)**2)*dxx_dyy)**(0.5 / (2 * np.pi)))

        cwt = np.stack(cwt, axis=2)
        wav_norm = np.array(wav_norm)

        return cwt, wav_norm

    scales = np.arange(1, 10)
    # img = cv2.imread(img_path,0)
    # img = img_path.copy()
    # print(img.shape)
    # cwtmatr, freqs = sig.cwt2d(image, erlang2d_wavelet, scales, theta=5, scale=2)
    cwtmatr, freqs = cwt_2d(img,scales,'poisson',sigma=1)
    cwt_result = np.abs(cwtmatr)

    # Now we will threshold the CWT result to identify noisy pixels
    # First, we need to determine a suitable threshold value
    # We can use the median absolute deviation (MAD) to find this value
    threshold = np.median(cwt_result) + 0.6745 * np.median(np.abs(cwt_result - np.median(cwt_result)))

    # Now we can threshold the CWT result to identify the noisy pixels
    noisy_pixels_orig = cwt_result > threshold

    img_with_noises = []
    for i in range(9):
        noisy_pixels = noisy_pixels_orig[:img.shape[0],:img.shape[1],i]
        # The 'noisy_pixels' array will be a boolean array, with 'True'
        # values indicating the presence of noisy pixels in the image
        # img = cv2.imread(img_path,1)
        img_with_noise = np.zeros(img.shape)
        img_with_noise[noisy_pixels] = 255
        img_with_noises.append(img_with_noise)
        # cv2.imwrite(f'img_with_noise-{i}.jpg',img_with_noise)
        # print("reached here!")
    # return img_with_noise
    # return cwtmatr
    return img_with_noises

# img_path = r"C:\Users\gprak\Downloads\Github Repos\watermark.png"
# img_path = r"C:\Users\gprak\Downloads\Research Papers\dog\images.jpg"
# img_path = r"C:\Users\gprak\Downloads\Research Papers\label_poisoned_dataset - Copy\aadhar\Aadhaar_letter_large.png"
# img_path = r"C:\Users\gprak\Downloads\Research Papers\label_poisoned_dataset - Copy\invoice\Screenshot 2023-03-19 223303.png"
# poisson_noise(img_path)
# cv2.imwrite('img_with_noise.jpg',img_with_noise)


""" Add Atlas WFS layer to QGIS Project """
import logging
from qgis.core import (QgsProject,  # pylint: disable=import-error
                       QgsVectorLayer, QgsDataSourceUri)

from ..logger import Logger
from ..logger import log
from ..settings import Settings
from ..street_smart import AbstractCommand

RECORDING_LAYER_NAME = Settings.getInstance().getRecordingLayerName()

class AddAtlasWFSLayerCommand(AbstractCommand):
    '''
    Class for Add WFS Layer Command
    '''
    def __init__(self, iface, streetsmart):
        '''
        Constructor
        '''
        super().__init__(iface, streetsmart)
        port = streetsmart.log_port
        self.logger = Logger(__name__, port).get()

    @staticmethod
    def icon_path():
        '''
        Path for the icon
        '''
        return ':/plugins/street_smart/resources/mActionAdd.svg'

    def text(self):
        '''
        Text for the command to show
        '''
        return super().tr(u'Add Atlas Recording WFS')

    def parent(self):
        '''
        Parent
        '''
        return self.iface.mainWindow()

    def callback(self):
        '''
        Code to execute when command is clicked
        '''
        if self.are_usersettings_available():
            self.add_wfs_layer()
            self.streetsmart.buttonstate.atlas_added = True
        else:
            self.show_set_settings_message_box()

    @log()
    def add_wfs_layer(self):
        '''add'''
        recording_uri = self.create_wfs_definition()

        self._add_layer_to_legend(recording_uri)

    @staticmethod
    def _add_layer_to_legend(recording_uri):
        '''add'''

        for lyr in QgsProject.instance().mapLayers().values():
            if lyr.name() == "CycloMedia Recording":
                QgsProject.instance().removeMapLayers([lyr.id()])

        root = QgsProject.instance().layerTreeRoot()
        rec_layer = QgsVectorLayer(recording_uri.uri(),
                                   RECORDING_LAYER_NAME, "WFS")
        rec_layer.setScaleBasedVisibility(True)
        rec_layer.setMinimumScale(5000)
        QgsProject.instance().addMapLayer(rec_layer, False)
        root.insertLayer(0, rec_layer)

    @staticmethod
    @log(logging.DEBUG, print_return=True)
    def __get_settings():
        """Returns the plugin settings."""
        return_value = Settings.getInstance().settings
        return return_value

    @log(logging.DEBUG, print_return=True)
    def create_wfs_definition(self):
        ''' Create definition for the Atlas Recording WFS '''
        settings = self.__get_settings()
        uri = settings[Settings.RECORDING_WFS_LOCATION].value
        get_filter_parameters = Settings.getInstance().getAtlasWFSFilter()
        if not get_filter_parameters:
            get_filter_parameters = "expiredAt is null"
        ds_uri = QgsDataSourceUri(uri)
        ds_uri.setParam('url', uri)
        ds_uri.setParam('typename', 'atlas:Recording')
        ds_uri.setParam('srsname', Settings.getInstance().getAtlasSRSName())
        ds_uri.setParam("username",
                        settings[Settings.USERNAME].value)
        ds_uri.setParam("password",
                        settings[Settings.PASSWORD].value)
        # ds_uri.setParam("authcfg", Settings.getInstance().getAuthcfg())
        ds_uri.setParam("filter", get_filter_parameters)
        ds_uri.setParam('restrictToRequestBBOX', '1')
        ds_uri.setParam('InvertAxisOrientation', '1')
        ds_uri.setParam('version', '1.1.0')

        return ds_uri


import heapq
from puzzle_tree import Node

def heuristic_mismatch(state, goal_state):
    # Heurística: Número de peças fora do lugar
    return sum(state[i][j] != goal_state[i][j] for i in range(3) for j in range(3))

def heuristic_manhattan(state, goal_state):
    # Heurística: Distância de Manhattan
    goal_positions = {goal_state[i][j]: (i, j) for i in range(3) for j in range(3)}
    total_distance = 0
    for i in range(3):
        for j in range(3):
            if state[i][j] != 0:
                goal_row, goal_col = goal_positions[state[i][j]]
                total_distance += abs(i - goal_row) + abs(j - goal_col)
    return total_distance

def gbf(puzzle):
    initial_node = Node(puzzle.initial_state)
    goal_state = puzzle.goal_state

    fila = []
    # fila de prioridade!
    heapq.heappush(fila, (heuristic_mismatch(initial_node.state, goal_state), initial_node))
    visited = set()

    while fila:
        _, current_node = heapq.heappop(fila) # remove nó da fila com menor estimativa heurística

        if puzzle.is_goal_state(current_node.state):
            return current_node.get_solution_path()

        visited.add(tuple(map(tuple, current_node.state)))

        for child in current_node.generate_children(): # gera filhos do nó atual
            if tuple(map(tuple, child.state)) not in visited:
                heapq.heappush(fila, (heuristic_mismatch(child.state, goal_state), child))

    return None


#!/usr/bin/python
# -*- coding: utf-8 -*-
# __author__ = 'gaojun'

# 定义消息属性对象
# FieldBean
class FieldBean(object):
    def __init__(self, type, name, comment, fields, isList):
        self.type = type
        self.name = name
        self.comment = comment
        self.fields = fields
        self.isList = isList


import numpy as np
import open3d as o3d
import sys
import math
import pandas as pd
import cv2
import os

def main():
    args=sys.argv
    dir1=args[1]
    dir2=args[2]
    outdir=args[3]
    over=float(args[4])
    files1=os.listdir("./"+dir1)
    files2=os.listdir("./"+dir2)

    for file in files1:
        #print(file)
        imagename1="./"+dir1+"/"+file
        imagename2="./"+dir2+"/"+file
        image1=cv2.imread(imagename1)
        image2=cv2.imread(imagename2)
        blend_image=cv2.addWeighted(image1,over,image2,(1-over),0)
        #outputname="./"+outdir+"/"+file
        print(outputname)
        cv2.imwrite(outputname,blend_image)
        print("end:",file)

if __name__=="__main__":
    main()


"""
This module mainly provides validation and correction for urls. This class
provides a method for HTTP GET requests as well as a function to translate peers into health.
Author(s): Jie Yang
"""
from __future__ import absolute_import

import binascii
import logging
import re
from base64 import b32decode

import libtorrent
from libtorrent import bdecode, bencode

import six
from six.moves.urllib.parse import parse_qsl, urlsplit

from twisted.internet import reactor
from twisted.internet.defer import fail, succeed
from twisted.internet.ssl import ClientContextFactory
from twisted.python.failure import Failure
from twisted.web import http
from twisted.web.client import Agent, readBody
from twisted.web.http_headers import Headers

from Tribler.Core.exceptions import HttpError
from Tribler.Core.version import version_id

logger = logging.getLogger(__name__)

def is_valid_url(url):
    """
    Checks whether the given URL is a valid URL.

    Both UDP and HTTP URLs will be validated correctly.

    :param url: an object representing the URL
    :return: Boolean specifying whether the URL is valid
    """
    if ' ' in url.strip():
        return
    if url.lower().startswith('udp'):
        url = url.lower().replace('udp', 'http', 1)
    split_url = urlsplit(url)

    return not(split_url[0] == '' or split_url[1] == '')

class WebClientContextFactory(ClientContextFactory):
    def getContext(self, hostname, port):
        return ClientContextFactory.getContext(self)

def http_get(uri):
    """
    Performs a GET request
    :param uri: The URL to perform a GET request to
    :return: A deferred firing the body of the response.
    :raises HttpError: When the HTTP response code is not OK (i.e. not the HTTP Code 200)
    """
    def _on_response(response):
        if response.code == http.OK:
            return readBody(response)
        if response.code == http.FOUND:
            # Check if location header contains magnet link
            location_headers = response.headers.getRawHeaders("location")
            if not location_headers:
                return fail(Failure(RuntimeError("HTTP redirect response does not contain location header")))
            new_uri = location_headers[0]
            if new_uri.startswith('magnet'):
                _, infohash, _ = parse_magnetlink(new_uri)
                if infohash:
                    return succeed(new_uri)
            return http_get(new_uri)
        raise HttpError(response)

    try:
        uri = uri.encode('utf-8')  # Try converting uri to bytes
    except AttributeError:
        pass
    try:
        contextFactory = WebClientContextFactory()
        agent = Agent(reactor, contextFactory)
        headers = Headers({'User-Agent': ['Tribler ' + version_id]})
        deferred = agent.request(b'GET', uri, headers, None)
        deferred.addCallback(_on_response)
        return deferred
    except:
        return fail()

def parse_magnetlink(url):
    """
    Parses the magnet link provided by the given URL.

    The output of this file consists of:
        -   dn: The display name of the magnet link
        -   xt: The URI containing the file hash of the magnet link
        -   trs: The list of Tracker URLs
    :param url: the URL at which the magnet link can be found
    :return: (dn, xt, trs) tuple, which will be left (None, None, []) if the
    given URL does not lead to a magnet link
    """
    dn = None
    xt = None
    trs = []

    logger.debug("parse_magnetlink() %s", url)

    schema, netloc, path, query, fragment = urlsplit(url)
    if schema == "magnet":
        # magnet url's do not conform to regular url syntax (they
        # do not have a netloc.)  This causes path to contain the
        # query part.
        if "?" in path:
            pre, post = path.split("?", 1)
            if query:
                query = "&".join((post, query))
            else:
                query = post

        for key, value in parse_qsl(query):
            if key == "dn":
                # convert to Unicode
                dn = value.decode() if not isinstance(value, six.text_type) else value

            elif key == "xt" and value.startswith("urn:btih:"):
                # vliegendhart: Adding support for base32 in magnet links (BEP 0009)
                encoded_infohash = value[9:49]
                if len(encoded_infohash) == 32:
                    xt = b32decode(encoded_infohash.upper())
                else:
                    xt = binascii.unhexlify(encoded_infohash)

            elif key == "tr":
                trs.append(value)

        logger.debug("parse_magnetlink() NAME: %s", dn)
        logger.debug("parse_magnetlink() HASH: %s", xt)
        logger.debug("parse_magnetlink() TRACS: %s", trs)

    return dn, xt, trs

def fix_torrent(file_path):
    """
    Reads and checks if a torrent file is valid and tries to overwrite the torrent file with a non-sloppy version.
    :param file_path: The torrent file path
    :return: True if the torrent file is now overwritten with valid information, otherwise False
    """
    f = open(file_path, 'rb')
    bdata = f.read()
    f.close()

    # Check if correct bdata
    fixed_data = bdecode(bdata)
    if fixed_data is not None:
        fixed_data = bencode(fixed_data)

    return fixed_data

def translate_peers_into_health(peer_info_dicts):
    """
    peer_info_dicts is a peer_info dictionary from LibTorrentDownloadImpl.create_peerlist_data.
    purpose : where we want to measure a swarm's health but no tracker can be contacted
    """
    upload_only = 0
    finished = 0
    unfinished_able_dl = 0
    interest_in_us = 0

    # collecting some statistics
    for p_info in peer_info_dicts:
        upload_only_b = False

        if p_info['upload_only']:
            upload_only += 1
            upload_only_b = True
        if p_info['uinterested']:
            interest_in_us += 1
        if p_info['completed'] == 1:
            finished += 1
        else:
            unfinished_able_dl += 1 if upload_only_b else 0

    # seeders potentials:
    # 1. it's only want uploading right now (upload only)
    # 2. it's finished (we don't know whether it want to upload or not)
    # leecher potentials:
    # 1. it's interested in our piece
    # 2. it's unfinished but it's not 'upload only' (it can't leech for some reason)
    # 3. it's unfinished (less restrictive)

    # make sure to change those description when changing the algorithm

    num_seeders = max(upload_only, finished)
    num_leech = max(interest_in_us, min(unfinished_able_dl, len(peer_info_dicts) - finished))
    return num_seeders, num_leech

def unichar_string(text):
    """ Unicode character interpretation of text for Python 2.7 """
    return u''.join(six.unichr(ord(t)) for t in text)

def is_simple_match_query(query):
    """
    Check if the query is a simple match query with AND operators only.
    Supports unicode characters.
    """
    pattern = re.compile(r"\"[\\\w]+\"\*", flags=re.UNICODE)
    splits = pattern.split(query)
    for connector in splits:
        if connector and connector != " AND ":
            return False
    return True

def has_bep33_support():
    """
    Return whether our libtorrent version has support for BEP33 (DHT health lookups).
    Also see https://github.com/devos50/libtorrent/tree/bep33_support
    """
    return 'dht_pkt_alert' in dir(libtorrent)

def is_infohash(infohash):
    return infohash and len(infohash) == 40 and is_hex_string(infohash)

def is_channel_public_key(key):
    return key and len(key) == 128 and is_hex_string(key)

def is_hex_string(text):
    try:
        int(text, 16)
        return True
    except ValueError:
        return False


'''
Test the handling & generation of missing values
'''

# Standard library imports
import unittest
from collections import namedtuple
from unittest.mock import Mock, patch

# External library imports
import pandas as pd
import numpy as np
from pandas.testing import assert_frame_equal, assert_series_equal

# Exhibit imports
from exhibit.db import db_util
from exhibit.core.constants import MISSING_DATA_STR, ORIGINAL_VALUES_PAIRED
from exhibit.core.tests.test_reference import temp_exhibit

# Module under test
from exhibit.core.generate import missing as tm

class missingDataTests(unittest.TestCase):
    '''
    Doc string
    '''

    @classmethod
    def tearDownClass(cls):
        '''
        Clean up local exhibit.db from temp tables
        '''

        db_util.purge_temp_tables()

    def test_feeding_data_to_missing_generator(self):
        '''
        Doc string
        '''

        test_df = pd.DataFrame()

        path = "exhibit.core.generate.missing.MissingDataGenerator.__init__"
        with patch(path) as mock_init:
            mock_init.return_value = None
            generatorMock = tm.MissingDataGenerator(Mock(), Mock())

        setattr(generatorMock, "data", test_df)

        self.assertTrue(
            isinstance(generatorMock.data,
            pd.DataFrame))

    def test_never_null_indices_are_identified(self):
        '''
        Some cells can't ever have nulls due to custom constraints.
        Filter and Partition fields are optional when defining custom
        constraints.
        '''

        test_dict = {
            "constraints" : {
                "custom_constraints": {
                    "cc1" : {
                        "filter"  : "~Test.isna()",
                        "targets" : {
                            "Num" : "make_not_null"
                        }
                    },
                }
            }
        }

        test_data = pd.DataFrame(data={
            "Test" : [1, 2, 3, pd.NA, 5],
            "Num"  : [1, 2, 3, 4, 5]
        })

        test_gen = tm.MissingDataGenerator(test_dict, test_data)

        not_null_idx = test_gen._find_not_null_idx()

        result = not_null_idx[0]

        assert_series_equal(
            test_data.loc[result],
            test_data.loc[[0, 1, 2, 4], "Num"])

    def test_paired_columns_with_missing_data_identified(self):
        '''
        Doc string
        '''

        test_dict = {
            "columns" : {
                "A" : {
                    "type"            : "categorical",
                    "paired_columns"  : ["B"],
                    "miss_probability": 0.5,
                    "original_values" : ORIGINAL_VALUES_PAIRED
                },
                "B" : {
                    "type"            : "categorical",
                    "paired_columns" : ["A"],
                    "miss_probability" : 0.5,
                    "original_values" : pd.DataFrame()
                },
                "C" : {
                    "type"            : "categorical",
                    "paired_columns" : ["D"],
                    "miss_probability" : 0.6,
                    "original_values" : pd.DataFrame()
                },
                "D" : {
                    "type"            : "categorical",
                    "paired_columns" : ["C"],
                    "miss_probability" : 0.7,
                    "original_values" : ORIGINAL_VALUES_PAIRED
                }
            },
            "constraints" : {
                "custom_constraints" : {},

                },
            "linked_columns" : []
        }

        expected = [
            {"A", "B"},
        ]

        test_gen = tm.MissingDataGenerator(test_dict, Mock())
        result = test_gen._find_columns_with_linked_missing_data()

        self.assertCountEqual(expected, result)

    def test_linked_columns_with_missing_data_identified(self):
        '''
        Doc string
        '''

        test_dict = {
            "columns" : {
                "A" : {
                    "type"            : "categorical",
                    "paired_columns"  : [],
                    "miss_probability": 0.5,
                    "original_values" : pd.DataFrame()
                    },
                "B" : {
                    "type"            : "categorical",
                    "paired_columns" : [],
                    "miss_probability" : 0.5,
                    "original_values" : pd.DataFrame()
                    },
                "C" : {
                    "type"            : "categorical",
                    "paired_columns" : [],
                    "miss_probability" : 0.6,
                    "original_values" : pd.DataFrame()
                    },
                "D" : {
                    "type"            : "categorical",
                    "paired_columns" : [],
                    "miss_probability" : 0.5,
                    "original_values" : pd.DataFrame()
                    }
            },
            "constraints" : {
                "custom_constraints" : {},
                },
            "linked_columns" : [
                (1, ["A", "B"]),
                (2, ["C", "D"])
                ]
        }

        expected = [
            {"A", "B"},
        ]

        test_gen = tm.MissingDataGenerator(test_dict, Mock())
        result = test_gen._find_columns_with_linked_missing_data()

        self.assertCountEqual(expected, result)

    def test_linked_and_paired_columns_with_missing_data_identified(self):
        '''
        Doc string
        '''

        test_dict = {
            "columns" : {
                "A" : {
                    "type"            : "categorical",
                    "paired_columns"  : ["B"],
                    "miss_probability": 0.5,
                    "original_values" : pd.DataFrame()
                    },
                "B" : {
                    "type"            : "categorical",
                    "paired_columns" : ["A"],
                    "miss_probability" : 0.5,
                    "original_values" : ORIGINAL_VALUES_PAIRED
                    },
                "C" : {
                    "type"            : "categorical",
                    "paired_columns" : [],
                    "miss_probability" : 0.5,
                    "original_values" : pd.DataFrame()
                    }
            },
            "constraints" : {
                "custom_constraints" : {},
                },
            "linked_columns" : [
                (0, ["A", "C"]),
                ]
        }

        expected = [
            {"A", "B", "C"},
        ]

        test_gen = tm.MissingDataGenerator(test_dict, Mock())
        result = test_gen._find_columns_with_linked_missing_data()

        self.assertTrue(expected[0], result[0])

    def test_make_null_constraint_in_columns(self):
        '''
        When we're adding nulls to categorical columns, the non-null
        numerical values must be re-calulcated and re-scaled because
        Missing data (null identifier in categorical columns) can have
        vastly different weights compared to the old values. However,
        we shouldn't rescaled the whole column anew, just the added values.
        '''

        Weights = namedtuple("Weights", ["weight", "equal_weight"])

        #demo weights table
        weights_df = pd.DataFrame(
            data=[
                ("C", "A", "spam", Weights(0.5, 0.5)),
                ("C", "A", "eggs", Weights(0.5, 0.5)),
                ("C", "B", "bacon", Weights(0.5, 0.5)),
                ("C", "A", MISSING_DATA_STR, Weights(0.5, 0.5)),
                ("C", "B", MISSING_DATA_STR, Weights(0.5, 0.5)),
            ],
            columns=["num_col", "cat_col", "cat_value", "weights"])

        #reformat into dictionary
        weights = (
            weights_df
                .set_index(["num_col", "cat_col", "cat_value"])
                .to_dict(orient="index")
        )

        test_dict = {
            "_rng" : np.random.default_rng(seed=0),
            "metadata" : {
                "categorical_columns": ["A", "B"],
                "numerical_columns" : ["C"]
            },
            "columns": {
                "A": {
                    "type"            : "categorical",
                    "paired_columns"  : [],
                    "miss_probability": 0,
                    "original_values" : pd.DataFrame()

                },
                "B": {
                    "type"            : "categorical",
                    "paired_columns"  : [],
                    "miss_probability": 0,
                    "original_values" : pd.DataFrame()

                },
                "C": {
                    "type"            : "continuous",
                    "precision"       : "integer",
                    "distribution"    : "weighted_uniform",
                    "distribution_parameters": {
                        "dispersion": 0,
                        "target_sum" : 10,
                    },
                    "miss_probability": 0
                },

            },
            "constraints" : {
                "custom_constraints": {
                    "cc1" : {
                        "filter"  : "A == 'spam'",
                        "targets" : {
                            "B" : "make_null"
                        }
                    }
                }
            },
            "linked_columns" : [],
            "weights_table" : weights,
            "weights_table_target_cols": ["A", "B"]
        }

        test_data = pd.DataFrame(data={
            "A" : ["spam", "spam", "eggs", "eggs"],
            "B" : ["bacon"] * 4,
            "C" : [10, 20, 4, 4],
        })

        expected = pd.DataFrame(data={
            "A" : ["spam", "spam", "eggs", "eggs"],
            "B" : [pd.NA, pd.NA, "bacon", "bacon"],
            "C" : [1, 1, 4, 4],
        })

        test_gen = tm.MissingDataGenerator(test_dict, test_data)
        result = test_gen.add_missing_data()

        assert_frame_equal(result, expected, check_dtype=False)

    def test_not_null_constraint_in_columns(self):
        '''
        Doc string
        '''

        test_dict = {
            "_rng" : np.random.default_rng(seed=0),
            "metadata" : {
                "categorical_columns": ["C", "D"],
                "numerical_columns" : []
            },
            "columns": {
                "C": {
                    "type"            : "categorical",
                    "paired_columns"  : [],
                    "miss_probability": 0.2,
                    "original_values" : pd.DataFrame()

                },
                "D": {
                    "type"            : "categorical",
                    "paired_columns"  : [],
                    "miss_probability": 0.5,
                    "original_values" : pd.DataFrame()

                }
            },
            "constraints" : {
                "custom_constraints": {
                    "cc1" : {
                        "filter"  : "~C.isna()",
                        "targets" : {
                            "D" : "make_not_null"
                        }
                    }
                }
            },
            "linked_columns" : []
        }

        test_data = pd.DataFrame(data={
            "C" : np.random.random(1000), #pylint: disable=no-member
            "D" : np.random.random(1000), #pylint: disable=no-member

        })

        test_gen = tm.MissingDataGenerator(test_dict, test_data)
        result = test_gen.add_missing_data()

        self.assertTrue(result["C"].isna().any())
        self.assertTrue(result["D"].isna().any())
        self.assertFalse(result.loc[~result["C"].isna(), "D"].isna().any())

    def test_paired_columns_are_respected_for_missing_data(self):
        '''
        Doc string
        '''

        test_dict = {
            "_rng" : np.random.default_rng(seed=0),
            "metadata" : {
                "categorical_columns": ["A", "B"],
                "numerical_columns" : []
            },
            "columns": {
                "A": {
                    "type"            : "categorical",
                    "paired_columns"  : ["B"],
                    "miss_probability": 0.5,
                    "original_values" : pd.DataFrame()
                },
                "B": {
                    "type"            : "categorical",
                    "paired_columns"  : ["A"],
                    "miss_probability": 0.5,
                    "original_values" : ORIGINAL_VALUES_PAIRED

                },
            },
            "constraints" : {
                "custom_constraints" : {},
            },
            "linked_columns" : [],
        }

        test_data = pd.DataFrame(data={
            "A" : np.random.random(1000), #pylint: disable=no-member
            "B" : np.random.random(1000), #pylint: disable=no-member
        })

        test_gen = tm.MissingDataGenerator(test_dict, test_data)
        result = test_gen.add_missing_data()

        self.assertTrue(result["A"].isna().any())
        self.assertTrue(result["B"].isna().any())
        assert_series_equal(result["B"].isna(), result["A"].isna(), check_names=False)

    def test_missing_data_added_to_standalone_categorical_column(self):
        '''
        Doc string
        '''

        test_dict = {
            "_rng" : np.random.default_rng(seed=0),
            "metadata" : {
                "categorical_columns": ["A", "B"],
                "numerical_columns" : []
            },
            "columns": {
                "A": {
                    "type"            : "categorical",
                    "paired_columns"  : [],
                    "miss_probability": 1,
                    "original_values" : pd.DataFrame()
                },
                "B": {
                    "type"            : "categorical",
                    "paired_columns"  : [],
                    "miss_probability": 0,
                    "original_values" : pd.DataFrame()

                },
            },
            "constraints" : {
                "custom_constraints" : {}
            },
            "linked_columns" : [],
        }

        test_data = pd.DataFrame(data={
            "A" : list("ABCDE"),
            "B" : list("ABCDE")
        })

        expected = pd.DataFrame(data={
            "A" : [pd.NA] * 5,
            "B" : list("ABCDE")
        })

        test_gen = tm.MissingDataGenerator(test_dict, test_data)
        result = test_gen.add_missing_data()

        assert_frame_equal(expected, result, check_dtype=False)

    def test_continuous_column_adjusted_to_categorical_missing_data(self):
        '''
        Remember that continuous columns depend on values in categorical columns
        in the same row for their weights, including for Missing data values.
        Adding Missing data also changes the target_sum of the continuous column
        so we need to re-scale the whole column after adding missing data either
        to it or to the categorical columns.

        We rely on np.random to generate reasonable number of NAs with 0.5 prob,
        but that can sometimes fail so we ensure that the seed is constant.
        '''

        Weights = namedtuple("Weights", ["weight", "equal_weight"])

        #demo weights table
        weights_df = pd.DataFrame(
            data=[
                ("C2", "C1", "A", Weights(0.1, 0.5)),
                ("C2", "C1", "B", Weights(0.9, 0.5)),
                ("C2", "C1", MISSING_DATA_STR, Weights(0.2, 0.5)),
            ],
            columns=["num_col", "cat_col", "cat_value", "weights"])

        #reformat into dictionary
        weights = (
            weights_df
                .set_index(["num_col", "cat_col", "cat_value"])
                .to_dict(orient="index")
        )

        test_dict = {
            "_rng" : np.random.default_rng(seed=0),
            "metadata": {
                "categorical_columns": [
                    "C1"
                ],
                "numerical_columns" : [
                    "C2"
                ]
            },
            "columns": {
                "C1": {
                    "type"            : "categorical",
                    "paired_columns"  : [],
                    "miss_probability": 0.5,
                    "original_values" : pd.DataFrame()
                },
                "C2": {
                    "type"            : "continuous",
                    "precision"       : "integer",
                    "distribution"    : "weighted_uniform",
                    "distribution_parameters": {
                        "uniform_base_value" : 100,
                        "dispersion": 0,
                        "target_sum" : 200, # factor of two
                    },
                    "miss_probability": 0
                },
            },
            "constraints" : {
                "custom_constraints" : {}
            },
            "linked_columns" : [],
            "weights_table" : weights,
            "weights_table_target_cols": ["C1"]
        }

        test_data = pd.DataFrame(data={
            "C1" : ["A", "A", "A", "B", "B"] * 20,
            "C2" : [1] * 100
        })

        test_gen = tm.MissingDataGenerator(test_dict, test_data)
        result = test_gen.add_missing_data()

        self.assertTrue(result["C1"].isna().any())
        self.assertEqual(result["C2"].sum(), 200)

    def test_user_linked_columns_having_missing_data(self):
        '''
        Because user linked columns can have complex relationships, we
        need to make sure missing data is handled correctly.
        '''

        test_df = pd.DataFrame(data={
            "A": ["spam", "spam", "eggs", "eggs", "spam"],
            "B": ["bacon", "spamspam", np.nan, "parrot", "bacon"],
            "C": range(5)
        })

        test_dict = {
            "metadata" : {
                "number_of_rows" : 1000
            }
        }

        fromdata_test = {
            "linked_columns" : ["A", "B"]
        }

        _, df = temp_exhibit(
            filename=test_df, fromdata_namespace=fromdata_test,
            test_spec_dict=test_dict, return_spec=False)

        self.assertTrue(df.query("A == 'eggs'")["B"].isna().any())

if __name__ == "__main__" and __package__ is None:
    #overwrite __package__ builtin as per PEP 366
    __package__ = "exhibit"
    unittest.main(warnings="ignore")


from utils.introspection import wrap_and_override_class_defaults

def get_optimizer(optim_cfg, model, optim_state=None):
    """
    Get the optimizer to be used.
    Parameters
    ----------
    optim_cfg : dict
        Dictionary containing the config of the optimizer.
    model : nn.Module
        The model to optimize.
    optim_state : dict
        The state of the optimizer to be load. Default: None.
    Returns
    -------
    optimizer : obj
        The optimizer object.
    """
    optim_class_cfg = optim_cfg.copy()
    if 'weight_decay' in optim_cfg:
        optim_class_cfg['weight_decay'] = optim_class_cfg['weight_decay']['rate']
        if optim_cfg['weight_decay']['type'] == 'Weights':
            decay = []
            no_decay = []
            for name, param in model.named_parameters():
                if param.requires_grad and not any(i in name for i in ['bias', 'bn']):
                    decay.append(param)
                else:
                    no_decay.append(param)
            params = [{'params': decay},
                      {'params': no_decay, 'weight_decay': 0.}]
        else:
            params = model.parameters()

    else:
        params = model.parameters()

    optimizer_class = wrap_and_override_class_defaults(optim_class_cfg, 'torch.optim')
    optimizer = optimizer_class(params)

    if optim_state:
        optimizer.load_state_dict(optim_state)

    return optimizer


import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import GridSearchCV

class model_class:
    def model_build(self):
        df = pd.read_excel("customer_churn_large_dataset.xlsx")

        #handling Categorical featurews
        dummy_cols = pd.get_dummies(df[['Gender','Location']],drop_first=True)

        df = pd.concat([df, dummy_cols], axis=1)
        df.drop(["Gender",'Location'], axis=1, inplace=True)

        # Customerid and name features are not required because all the records are unique
        df.drop(["CustomerID","Name"], axis=1,inplace=True)

        #spliting the data
        X = df.drop(['Churn'],axis=1)
        Y = df.loc[:,["Churn"]]
        X_train, X_test, y_train, y_test = train_test_split(X, Y, test_size=0.3, random_state=0)

        # Hyperparameter tuning

        '''param_grid = {"n_estimators": [10, 50, 100, 130], "criterion": ['gini', 'entropy'],
                               "max_depth": range(2, 4, 1), "max_features": ['auto', 'log2']}

        grid = GridSearchCV(estimator=RandomForestClassifier(), param_grid=param_grid, cv=2,  verbose=3)
        grid.fit(X_train, y_train)'''

        model_rf=RandomForestClassifier()
        model_rf.fit(X_train,y_train)

        return model_rf


# from airflow.hooks.http_hook import HttpHook
from airflow.providers.http.hooks.http import HttpHook
from datetime import datetime, timedelta
import requests
import json

class TwitterHook(HttpHook):

    def __init__(self, query, conn_id = None, start_time = None, end_time = None):
        self.query = query
        self.conn_id = conn_id or "twitter_default"
        self.start_time = start_time
        self.end_time = end_time
        super().__init__(http_conn_id=self.conn_id)

    # Montando URL - create_url
    def create_url(self):
        query = self.query
        tweet_fields = "tweet.fields=author_id,conversation_id,created_at,id,in_reply_to_user_id,public_metrics,text"
        user_fields = "expansions=author_id&user.fields=id,name,username,created_at"
        start_time = (f"&start_time={self.start_time}" if self.start_time else "")
        end_time = (f"&end_time={self.end_time}" if self.end_time else "")
        url = "{}/2/tweets/search/recent?query={}&{}&{}{}{}".format(self.base_url, query, tweet_fields, user_fields, start_time, end_time)

        return url

    # Montando Headers - connect_to_endpoint
    def connect_to_endpoint(self, url, session):
        response = requests.Request("GET", url)
        prep = session.prepare_request(response)
        self.log.info(f"URL: {url}")
        return self.run_and_check(session, prep, {})

    # recriando a URL com o Token - paginate
    def paginate(self, url_raw, session):
        list_json_response = []

        response = self.connect_to_endpoint(url_raw, session)

        # leitura do json
        json_response = response.json()
        list_json_response.append(json_response)

        while "next_token" in json_response.get("meta", {}):
            next_token = json_response['meta']['next_token']
            nova_url = f"{url_raw}&next_token={next_token}"
            response = self.connect_to_endpoint(nova_url, session)
            json_response = response.json()
            list_json_response.append(json_response)

        return list_json_response

    def run(self):
        session = self.get_conn()
        url_raw = self.create_url()

        return self.paginate(url_raw, session)

if __name__ == "__main__":

    TIMESTAMP_FORMAT = "%Y-%m-%dT%H:%M:%S.00Z"
    end_time = datetime.now().strftime(TIMESTAMP_FORMAT)
    start_time = (datetime.now() + timedelta(-1)).date().strftime(TIMESTAMP_FORMAT)

    for pg in TwitterHook(query="NBABrasil", start_time=start_time, end_time=end_time).run():
        print(json.dumps(pg, indent=4, sort_keys=True))


from typing import Dict, List
from datamodel import OrderDepth, TradingState, Order
import math

class Trader:
    def run(self, state: TradingState) -> Dict[str, List[Order]]:
        result = {}

        for product in state.order_depths.keys():
            if product == "BANANAS":
                order_depth: OrderDepth = state.order_depths[product]
                pearl_orders: list[Order] = []

            elif product == "PEARLS":
                # init lists

                order_depth: OrderDepth = state.order_depths[product]
                pearl_orders: list[Order] = []

                # check whether to ask or bid first based on volume
                # to be implemented?

                pearl_orders.append(Order(product, 10001, -40))
                pearl_orders.append(Order(product, 9999, 40))

                result[product] = pearl_orders

        return result


#!/usr/bin/env python3

import yaml
import smtplib
import requests
import urllib.error
import auction.suburb

def main():
    # load config.
    try:
        with open('config.yaml', 'r') as config_file:
            config = yaml.load(config_file)
    except (OSError, IOError):
        print('failed reading config.yaml. :-(')
        exit(1)

    # initialise global settings.
    auction.suburb.Suburb.baseurl = config['baseurl']
    auction.suburb.Suburb.textimageurl = config['textimageurl']

    # load each (geographical) state.
    for config_path, suburbs in config['paths'].items():
        # load html for this (geographical) state.
        try:
            with open('sample.html', 'r') as sample_file:
                auction_data_raw = sample_file.read()
                print('loaded sample.html into auction_data_raw.')
        except (OSError, IOError):
            url = '{base}/{path}'.format(base=config['baseurl'], path=config_path)
            headers = {}
            headers['User-Agent'] = ('Mozilla/5.0 (Macintosh; Intel Mac OS X 10.11;'
                ' rv:47.0) Gecko/20100101 Firefox/47.0')
            headers['DNT'] = '1'
            headers['Accept'] = ('text/html,application/xhtml+xml,application/xml;'
                'q=0.9,*/*;q=0.8')
            headers['Accept-Language'] = 'en-GB,en;q=0.5'
            headers['Accept-Encoding'] = 'gzip, deflate, br'
            req = requests.get(url)
            auction_data_raw = req.text

        # load each suburb.
        for name, suburb_config in suburbs.items():
            sub_emails = suburb_config['emails']
            print('suburb: ' + name)
            print('emails: ' + repr(sub_emails))
            mySuburb = auction.suburb.Suburb(name, config['from'], sub_emails, auction_data_raw)
            msg = mySuburb.render_msg('\n')

            # send out results.
            s = smtplib.SMTP('localhost')
            results = []
            for email in sub_emails:
                if 'To' in msg:
                    del msg['To']
                msg['To'] = email

                if True == config['live']:
                    s.send_message(msg)

                results.append(msg.as_string())
            s.quit()
            print('\n'.join(results))

if __name__ == '__main__':
    main()


"""
This is a simple wrapper for `train_network.py`. The purpose is to
loop over the network training process and use the prediction of each
pass as the target of the following iteration. The first pass uses data
made from only PCAL and DARM and aims to subtract the calibration lines.
"""
import sys
import re
import os
import NonlinearRegression.tools.analyze_run_data as ard

# Start message
iterate = 'Running Multi-Pass Subtraction'
print('\n{0}\n{1}'.format(iterate, '-' * len(iterate)))

# Make sure the data loads when running from any directory
dir_path = os.path.dirname(os.path.realpath(__file__))
os.chdir(dir_path)

# Collect the command line flags
flags = ' '.join(sys.argv[1:])

# Make sure a model is declared
model_type = re.compile(r'[a-zA-Z]+')
model_version = re.compile(r'\d+')
if not "-m" in flags:
    print("ERROR: Must specify a model using the -m flag")
    sys.exit(1)
else:
    flag_list = flags.split(' ')
    for flag in flag_list:
        if "-m" in flag:
            index = flag_list.index(flag)

model = flag_list[index + 1]
basename = model_type.findall(model)[0]
try:
    version = model_version.findall(model)[0]
except IndexError:
    version = '0'

# Delete the old results so we don't append to them
matfile = 'params/{0}/subtraction_results-{1}.mat'.format(basename, version)
if os.path.isfile(matfile):
    os.system('rm {}'.format(matfile))

# Loop three times - Once for calibration lines, once for linear couplings,
# and once more to remove as many nonlinear couplings as possible.
for ii in range(3):
    if ii == 0:
        print('[+] Removing calibration lines...')
        cal_file = ' --datafile Data/L1_calibration.mat'
        os.system('python train_network.py {}'.format(flags + cal_file))

    if ii == 1:
        print('\n[+] Removing first order noise sources...')
        os.system('python train_network.py {}'.format(flags + ' --doLoops'))

    if ii == 2:
        print('\n[+] Removing nonlinear sources...')
        os.system('python train_network.py {}'.format(flags + ' --doLoops'))

fs = 256
for flag in flag_list:
    if "--fs_slow" in flag:
        index = flag_list.index(flag)
        fs = int(flag_list[index + 1])

nperseg = fs * 8
plotDir = 'params/{0}/Figures'.format(basename)
ard.plot_progress(matfile, fs, nperseg, plotDir=plotDir, version=version)


#!/usr/bin/env python3
# (c) https://t.me/TelethonChat/37677
# This Source Code Form is subject to the terms of the GNU
# General Public License, v.3.0. If a copy of the GPL was not distributed with this
# file, You can obtain one at https://www.gnu.org/licenses/gpl-3.0.en.html.

from telethon.sessions import StringSession
from telethon.sync import TelegramClient

print(
    """Please go-to my.telegram.org
Login using your Telegram account
Click on API Development Tools
Create a new application, by entering the required details"""
)
APP_ID = int(input("Enter APP ID here: "))
API_HASH = input("Enter API HASH here: ")

with TelegramClient(StringSession(), APP_ID, API_HASH) as client:
    print(client.session.save())
    client.sendmessage("me", client.session.save())


#!/usr/bin/env python3

import urllib.request
import pprint
nasaurl = "https://api.nasa.gov/planetary/apod?api_key=DEMO_KEY"
apodurlobj = urllib.request.urlopen(nasaurl)
dir(apodurlobj)
apodurlobj.code
apodurlobj.length
apod = apodurlobj.read().decode("utf-8")

pprint.pprint(apod)


"""
This file is part of the TheLMA (THe Laboratory Management Application) project.
See LICENSE.txt for licensing, CONTRIBUTORS.txt for contributor information.

ISO job member table.
"""
from sqlalchemy import Column
from sqlalchemy import ForeignKey
from sqlalchemy import Integer
from sqlalchemy import Table
from sqlalchemy.schema import PrimaryKeyConstraint

__docformat__ = "reStructuredText en"
__all__ = ['create_table']

def create_table(metadata, job_tbl, iso_tbl):
    "Table factory."
    tbl = Table('iso_job_member', metadata,
                Column('job_id', Integer,
                       ForeignKey(job_tbl.c.job_id), nullable=False),
                Column('iso_id', Integer,
                       ForeignKey(iso_tbl.c.iso_id),
                       nullable=False, unique=True)
                )
    PrimaryKeyConstraint(tbl.c.job_id, tbl.c.iso_id)
    return tbl


import math as mt
def cosine(x, n):
    x = x % (2 * mt.pi)
    if x > mt.pi:
        x = abs(x - 2 * mt.pi)
    if x > mt.pi / 2:
        return -cosine(mt.pi - x, n)
    total = 0
    for i in range(0, n + 1):
        total += ((-1) ** i) * (x**(2*i) / mt.factorial(2*i))
    return total

print(cosine(0.785398,69))


import unittest
from Solutions import Lesson04

class FrogRiverOneTests(unittest.TestCase):
    def test_frog_river_one_example_test_01(self):
        x = 5
        a = [1, 3, 1, 4, 2, 3, 5, 4]
        res = Lesson04.frog_river_one(x, a)
        self.assertEqual(6, res)


# -*- coding: utf-8 -*-
from django.urls import path

from . import views

urlpatterns = [
    path('stop/', views.stop_impersonate, name='impersonate-stop'),
    path(
        'list/',
        views.list_users,
        {'template': 'impersonate/list_users.html'},
        name='impersonate-list',
    ),
    path(
        'search/',
        views.search_users,
        {'template': 'impersonate/search_users.html'},
        name='impersonate-search',
    ),
    path('<path:uid>/', views.impersonate, name='impersonate-start'),
]


import os
import re
import sys
import argparse

class Markup(object):
    BOLD_START = "["
    BOLD_END = "]"
    ITALIC_START = "{"
    ITALIC_END = "}"
    START_PLACEHOLDER = "<<PLACEHOLDER>>"
    END_PLACEHOLDER = "<</PLACEHOLDER>>"
    PUNCTUATION_CHARACTERS = '.,;:?!()'

    def __init__(self):
        link_regex = r"(?P<text>[^\"]+)\"_(?P<link>[^\s\t\n]+)"
        self.link_pattern = re.compile(link_regex)
        self.aliases = {}
        self.references = set()

    def convert(self, text):
        text = self.bold(text)
        text = self.italic(text)
        text = self.link(text)
        return text

    def add_link_alias(self, name, href):
        self.aliases[name] = href

    def add_internal_reference(self, name):
        self.references.add(name)

    def bold(self, text):
        text = text.replace("\\" + Markup.BOLD_START, Markup.START_PLACEHOLDER)
        text = text.replace("\\" + Markup.BOLD_END, Markup.END_PLACEHOLDER)
        text = text.replace(Markup.BOLD_START, self.bold_start())
        text = text.replace(Markup.BOLD_END, self.bold_end())
        text = text.replace(Markup.START_PLACEHOLDER, Markup.BOLD_START)
        text = text.replace(Markup.END_PLACEHOLDER, Markup.BOLD_END)
        return text

    def italic(self, text):
        text = text.replace("\\" + Markup.ITALIC_START, Markup.START_PLACEHOLDER)
        text = text.replace("\\" + Markup.ITALIC_END, Markup.END_PLACEHOLDER)
        text = text.replace(Markup.ITALIC_START, self.italic_start())
        text = text.replace(Markup.ITALIC_END, self.italic_end())
        text = text.replace(Markup.START_PLACEHOLDER, Markup.ITALIC_START)
        text = text.replace(Markup.END_PLACEHOLDER, Markup.ITALIC_END)
        return text

    def link(self, text):
        for name, link in self.link_pattern.findall(text):
            link = link.rstrip(Markup.PUNCTUATION_CHARACTERS)
            href = self.create_link(name, link)
            text = text.replace('\"%s\"_%s' % (name, link), href, 1)
        return text

class HTMLMarkup(Markup):
    def __init__(self):
        super().__init__()

    def bold_start(self):
        return ""

    def bold_end(self):
        return ""

    def italic_start(self):
        return ""

    def italic_end(self):
        return ""

    def create_link(self, content, link):
        if link in self.aliases:
            href = self.aliases[link]
        else:
            href = link

        return "" + content + ""

class Formatting(object):
    UNORDERED_LIST_MODE = "unordered-list"
    ORDERED_LIST_MODE = "ordered-list"

    def __init__(self, markup):
        image_regex = r"^image\((?P<file>[^\,]+)(,(?P<link>[^\,]+))?\)"
        named_link_regex = r"^link\((?P<name>[^\,]+)\)"
        define_link_alias_regex = r"^link\((?P<alias>[^\,]+),(?P<value>[^\,]+)\)"
        self.image_pattern = re.compile(image_regex)
        self.named_link_pattern = re.compile(named_link_regex)
        self.define_link_alias_pattern = re.compile(define_link_alias_regex)
        self.markup = markup
        self.first_header = ""
        self.current_list_mode = Formatting.UNORDERED_LIST_MODE
        self.current_command_list = []

    def convert(self, command, paragraph, commands):
        self.current_command_list = commands
        if command == "p":
            return self.paragraph(paragraph)
        elif command == "b":
            return self.linebreak(paragraph)
        elif command == "pre":
            return self.preformat(paragraph)
        elif command == "c":
            return self.center(paragraph)
        elif command == "h1" or command == "h2" or command == "h3" or \
                        command == "h4" or command == "h5" or command == "h6":
            level = int(command[1])
            return self.header(paragraph, level)
        elif command == "ul":
            return self.unordered_list(paragraph)
        elif command == "ol":
            return self.ordered_list(paragraph)
        elif command == "dl":
            return self.definition_list(paragraph)
        elif command == "l":
            if "olb" in commands:
              self.current_list_mode = Formatting.ORDERED_LIST_MODE
            elif "ulb" in commands:
              self.current_list_mode = Formatting.UNORDERED_LIST_MODE

            return self.list_item(paragraph)
        elif command == "dt":
            return self.definition_term(paragraph)
        elif command == "dd":
            return self.definition_description(paragraph)
        elif command == "ulb":
            self.current_list_mode = Formatting.UNORDERED_LIST_MODE
            return self.unordered_list_begin(paragraph)
        elif command == "ule":
            return self.unordered_list_end(paragraph)
        elif command == "olb":
            self.current_list_mode = Formatting.ORDERED_LIST_MODE
            return self.ordered_list_begin(paragraph)
        elif command == "ole":
            self.current_list_mode = Formatting.UNORDERED_LIST_MODE
            return self.ordered_list_end(paragraph)
        elif command == "dlb":
            return self.definition_list_begin(paragraph)
        elif command == "dle":
            return self.definition_list_end(paragraph)
        elif command == "all(p)":
            return self.all_paragraphs(paragraph)
        elif command == "all(c)":
            return self.all_centered(paragraph)
        elif command == "all(b)":
            return self.all_breaks(paragraph)
        elif command == "all(l)":
            return self.all_list_items(paragraph)
        elif command == "line":
            return self.horizontal_rule(paragraph)
        elif command.startswith("image"):
            m = self.image_pattern.match(command)
            return self.image(paragraph, file=m.group('file'), link=m.group('link'))
        elif command.startswith("link"):
            m = self.named_link_pattern.match(command)
            if m:
                return self.named_link(paragraph, name=m.group('name'))
            m2 = self.define_link_alias_pattern.match(command)
            if m2:
                return self.define_link_alias(paragraph, alias=m2.group('alias'), value=m2.group('value'))
        elif command.startswith("tb"):
            configuration = self.get_table_configuration(command)
            return self.table(paragraph, configuration)
        return ""

    def math(self, paragraph):
        return self.paragraph(paragraph) + "\n"

    def paragraph(self, paragraph):
        return "
" + paragraph + "
"

    def linebreak(self, paragraph):
        return paragraph + "
"

    def preformat(self, paragraph):
        return "
" + paragraph + "
"

    def center(self, paragraph):
        return "" + paragraph + ""

    def header(self, paragraph, level):
        if self.first_header == "":
            self.first_header = paragraph.strip()
        return "<H%d>%s</H%d>" % (level, paragraph, level)

    def unordered_list(self, paragraph):
        converted = self.unordered_list_begin("")
        for line in paragraph.splitlines():
            converted += self.unordered_list_item(line) + "\n"
        return self.unordered_list_end(converted)

    def ordered_list(self, paragraph):
        converted = self.ordered_list_begin("")
        for index, line in enumerate(paragraph.splitlines()):
            converted += self.ordered_list_item(line, index+1) + "\n"
        return self.ordered_list_end(converted)

    def definition_list(self, paragraph):
        converted = self.definition_list_begin("")
        is_title = True
        for line in paragraph.splitlines():
            if is_title:
                converted += self.definition_term(line) + "\n"
            else:
                converted += self.definition_description(line) + "\n"

            is_title = not is_title

        return self.definition_list_end(converted)

    def list_item(self, paragraph, index=None):
        if self.current_list_mode == Formatting.ORDERED_LIST_MODE:
            return self.ordered_list_item(paragraph, index)
        return self.unordered_list_item(paragraph)

    def unordered_list_item(self, paragraph):
        return "
" + paragraph

    def ordered_list_item(self, paragraph, index):
        return self.unordered_list_item(paragraph)

    def definition_term(self, paragraph):
        return "
" + paragraph

    def definition_description(self, paragraph):
        return "
" + paragraph

    def unordered_list_begin(self, paragraph):
        return "
" + paragraph

    def unordered_list_end(self, paragraph):
        return paragraph + "
"

    def ordered_list_begin(self, paragraph):
        return "
" + paragraph

    def ordered_list_end(self, paragraph):
        return paragraph + "
"

    def definition_list_begin(self, paragraph):
        return "
" + paragraph

    def definition_list_end(self, paragraph):
        return paragraph + "
"

    def all_paragraphs(self, paragraph):
        converted = ""
        for line in paragraph.splitlines():
            converted += self.paragraph(line) + "\n"
        return converted

    def all_centered(self, paragraph):
        converted = ""
        for line in paragraph.splitlines():
            converted += self.center(line) + "\n"
        return converted

    def all_breaks(self, paragraph):
        return paragraph.replace("\n", "
\n")

    def all_list_items(self, paragraph):
        converted = ""
        for line in paragraph.splitlines():
            converted += self.list_item(line) + "\n"
        return converted

    def horizontal_rule(self, paragraph):
        return "
" + paragraph

    def image(self, paragraph, file, link=None):
        converted = ""
        if link:
            converted = "" + converted + ""
        return converted + paragraph

    def named_link(self, paragraph, name):
        return "" + paragraph

    def define_link_alias(self, paragraph, alias, value):
        self.markup.add_link_alias(alias, value)
        return paragraph

    def get_table_configuration(self, command):
        config = {
            'separator': ',',
            'num_columns': 0,
            'border_width': 1,
            'table_alignment': 'center'
        }

        table_regex = r"^tb\((?P<configuration>.+)\)"
        table_pattern = re.compile(table_regex)

        m = table_pattern.match(command)
        if m:
            entries = m.groups('configuration')[0].split(',')
            alignments = {'l': 'left', 'c': 'center', 'r' : 'right'}
            vertical_alignments = {'t': 'top', 'm': 'middle', 'ba' : 'baseline', 'bo': 'bottom'}

            for entry in entries:
                lhs, rhs = entry.split('=')

                if lhs == 'c':
                    config['num_columns'] = int(rhs)
                elif lhs == 's':
                    config['separator'] = rhs
                elif lhs == 'b':
                    config['border_width'] = int(rhs)
                elif lhs == 'w':
                    if rhs.endswith("%"):
                        config['table_width'] = rhs
                    else:
                        config['cell_width'] = rhs
                elif lhs == "a":
                    config['table_alignment'] = alignments[rhs]
                elif lhs == "ea":
                    config['cell_alignment'] = alignments[rhs]
                elif lhs == "eva":
                    config['cell_vertical_alignment'] = vertical_alignments[rhs]
                elif lhs.startswith("cw") and len(lhs) >= 3:
                    column = int(lhs[2:]) - 1
                    if 'custom_cell_width' not in config:
                        config['custom_cell_width'] = {}
                    config['custom_cell_width'][column] = rhs
                elif lhs.startswith("ca") and len(lhs) >= 3:
                    column = int(lhs[2:]) - 1
                    if 'custom_cell_alignment' not in config:
                        config['custom_cell_alignment'] = {}
                    config['custom_cell_alignment'][column] = alignments[rhs]

        return config

    def table(self, paragraph, configuration):
        if configuration['num_columns'] == 0:
            rows = self.create_table_with_columns_based_on_newlines(paragraph, configuration['separator'])
        else:
            rows = self.create_table_with_fixed_number_of_columns(paragraph, configuration['separator'],
                                                                  configuration['num_columns'])

        tbl = "
" % configuration['table_alignment']
        tbl += "
\n" % configuration['border_width']

        for row_idx in range(len(rows)):
            columns = rows[row_idx]
            tbl += "
"

            for col_idx in range(len(columns)):
                col = columns[col_idx]
                tbl += "<TD "

                if 'custom_cell_width' in configuration:
                    if col_idx in configuration['custom_cell_width']:
                        tbl += "WIDTH=\"%s\"" % configuration['custom_cell_width'][col_idx]
                else:
                    if 'cell_width' in configuration:
                        tbl += "WIDTH=\"%s\"" % configuration['cell_width']

                if 'custom_cell_alignment' in configuration:
                    if col_idx in configuration['custom_cell_alignment']:
                        tbl += " ALIGN =\"%s\"" % configuration['custom_cell_alignment'][col_idx]

                tbl += ">"
                tbl += col

                if row_idx < len(rows) and col_idx < len(columns) - 1:
                    tbl += "	"

            if row_idx < len(rows) - 1:
                tbl += "
\n"

        tbl += "\n"
        tbl += "
"
        tbl += "

\n"
        return tbl

    def create_table_with_columns_based_on_newlines(self, paragraph, separator):
        rows = []
        lines = paragraph.splitlines()
        for line in lines:
            rows.append(line.split(separator))
        return rows

    def create_table_with_fixed_number_of_columns(self, paragraph, separator, num_columns):
        cells = paragraph.split(separator)
        current_row = []
        rows = []

        for cell in cells:
            current_row.append(cell.strip('\n'))

            if len(current_row) == num_columns:
                rows.append(current_row)
                current_row = []

        if len(current_row) > 0:
            rows.append(current_row)

        return rows

class HTMLFormatting(Formatting):
    def __init__(self, markup):
        super().__init__(markup)

    def begin_document(self):
        return "\n"

    def end_document(self):
        return "\n"

    def raw_html(self, content):
        return content

class TxtParser(object):
    def __init__(self):
        self.markup = HTMLMarkup()
        self.format = HTMLFormatting(self.markup)
        self.append_page_break = False
        self.create_title = False
        self.page_title = ""
        self.paragraph_filters = []
        self.document_filters = []

    def convert(self, content):
        converted = self.format.begin_document()

        if len(content) > 0:
            self.parse_link_aliases_and_find_title(content)

            if self.create_title and self.page_title != "":
                converted += "\n"
                converted += "<TITLE>%s</TITLE>\n" % self.page_title
                converted += "\n"

            converted += self.transform_paragraphs(content)

        if self.append_page_break:
            converted += "\n"

        converted += self.format.end_document()

        for doc_filter in self.document_filters:
            converted = doc_filter(converted)

        return converted

    def parse_link_aliases_and_find_title(self, content):
        for paragraph, is_raw in self.paragraphs(content):
            if not is_raw:
                self.convert_paragraph(paragraph)
        self.page_title = self.format.first_header

    def transform_paragraphs(self, content):
        converted = ""
        for paragraph, is_raw in self.paragraphs(content):
            if is_raw:
                converted += paragraph
            else:
                converted_paragraph = self.convert_paragraph(paragraph)
                for paragraph_filter in self.paragraph_filters:
                    converted_paragraph = paragraph_filter(converted_paragraph)
                converted += converted_paragraph
        return converted

    def convert_paragraph(self, paragraph):
        if self.is_raw_html_paragraph(paragraph):
            return self.format.raw_html(paragraph) + '\n'

        if self.is_math_paragraph(paragraph):
            return self.format.math(self.do_markup(paragraph))

        if self.has_formatting(paragraph):
            paragraph = self.do_markup(paragraph)
            return self.do_formatting(paragraph)

        return self.format.paragraph(self.do_markup(paragraph)) + "\n"

    def has_formatting(self, paragraph):
        return self.last_word(paragraph).startswith(":")

    def last_word(self, text):
        return text.split()[-1]

    def order_commands(self, commands):
        return list(reversed(commands))

    def do_formatting(self, paragraph):
        last_word = self.last_word(paragraph)
        format_str = paragraph[paragraph.rfind(last_word):]
        format_str = format_str.strip('\n')
        paragraph = paragraph.replace(format_str, "")
        commands = format_str[1:].strip()
        command_regex = r"(?P<command>[^\(,]+(\([^\)]+\))?),?"
        command_pattern = re.compile(command_regex)

        commands = [x[0] for x in command_pattern.findall(commands)]

        for command in self.order_commands(commands):
            paragraph = self.format.convert(command, paragraph, commands)

        return paragraph + '\n'

    def do_markup(self, paragraph):
        return self.markup.convert(paragraph)

    def paragraphs(self, content):
        paragraph = []
        last_line_had_format = False
        ignore_lines = False
        raw_lines = False

        for line in self.lines(content):
            if self.is_ignored_textblock_begin(line):
                if len(paragraph) > 0:
                    yield ('\n'.join(paragraph) + '\n', False)
                paragraph = []
                last_line_had_format = False
                ignore_lines = True
            elif self.is_ignored_textblock_end(line):
                ignore_lines = False
                continue
            elif self.is_raw_textblock_begin(line):
                if len(paragraph) > 0:
                    yield ('\n'.join(paragraph) + '\n', False)
                paragraph = []
                last_line_had_format = False
                raw_lines = True
                continue
            elif self.is_raw_textblock_end(line):
                if len(paragraph) > 0:
                    yield ('\n'.join(paragraph) + '\n', True)
                paragraph = []
                raw_lines = False
                continue

            if ignore_lines:
                continue
            elif raw_lines:
                paragraph.append(line)
                continue

            if self.is_paragraph_separator(line) or last_line_had_format:
                if len(paragraph) > 0:
                    yield ('\n'.join(paragraph) + '\n', False)

                if self.is_paragraph_separator(line):
                    paragraph = []
                    last_line_had_format = False
                else:
                    paragraph = [line]
                    last_line_had_format = self.has_formatting(line)
            else:
                paragraph.append(line)
                last_line_had_format = self.has_formatting(line)

        if len(paragraph) > 0:
            yield ('\n'.join(paragraph) + '\n', False)

    def is_ignored_textblock_begin(self, line):
        return line.startswith('')

    def is_raw_textblock_begin(self, line):
        return False

    def is_raw_textblock_end(self, line):
        return False

    def is_raw_html_paragraph(self, paragraph):
        return paragraph.startswith('<') and paragraph.endswith('>\n')

    def is_math_paragraph(self, paragraph):
        return ('\\begin\{equation\}' in paragraph) and ('\\end\{equation\}' in paragraph)

    def is_paragraph_separator(self, line):
        return len(line) == 0 or line.isspace()

    def lines(self, content):
        lines = content.splitlines()
        current_line = ""
        i = 0

        while i < len(lines):
            current_line += lines[i]

            if current_line.endswith("\\"):
                current_line = current_line[0:-1]
            else:
                yield current_line
                current_line = ""

            i += 1

class Txt2Html(TxtParser):
    def __init__(self):
        super().__init__()
        self.markup = HTMLMarkup()
        self.format = HTMLFormatting(self.markup)

    def is_paragraph_separator(self, line):
        return line.startswith(".. HTML_ONLY") or \
               line.startswith(".. END_HTML_ONLY") or \
               super().is_paragraph_separator(line)

class TxtConverter:
    def get_argument_parser(self):
        return None

    def get_output_filename(self, path):
        return ""

    def create_converter(self, args):
        return None

    def run(self, args=sys.argv[1:], out=sys.stdout, err=sys.stderr):
        parser = self.get_argument_parser()
        parsed_args = parser.parse_args(args)

        write_to_files = parsed_args.output_dir or (len(parsed_args.files) > 1)

        for filename in parsed_args.files:
            if parsed_args.skip_files and filename in parsed_args.skip_files:
                continue

            with open(filename, 'r') as f:
                if parsed_args.verbose:
                    print("Converting", filename, "...", file=err)
                content = f.read()
                converter = self.create_converter(parsed_args)

                try:
                    result = converter.convert(content)
                except Exception as e:
                    msg = "###########################################################################\n" \
                          " ERROR: " + e.args[0] + "\n" \
                          "###########################################################################\n"
                    print(msg, file=err)
                    result = msg

                if write_to_files:
                    if parsed_args.output_dir:
                        output_filename = os.path.join(parsed_args.output_dir, os.path.basename(self.get_output_filename(filename)))
                    else:
                        output_filename = self.get_output_filename(filename)
                    with open(output_filename, "w+t") as outfile:
                        outfile.write(result)
                else:
                    print(result, end='', file=out)

class Txt2HtmlConverter(TxtConverter):
    def get_argument_parser(self):
        parser = argparse.ArgumentParser(description='converts a text file with simple formatting & markup into HTML.\n'
                                                     'formatting & markup specification is given in README')
        parser.add_argument('-b', dest='breakflag', action='store_true', help='add a page-break comment to end of each'
                                                                              'HTML file. useful when set of HTML files'
                                                                              ' will be converted to PDF')
        parser.add_argument('-x', metavar='file-to-skip', dest='skip_files', action='append')
        parser.add_argument('--verbose', '-v', dest='verbose', action='store_true')
        parser.add_argument('--output-directory', '-o', dest='output_dir')
        parser.add_argument('--generate-title', dest='create_title', action='store_true', help='add HTML head page'
                                                                                'title based on first '
                                                                                'h1,h2,h3,h4... element')
        parser.add_argument('files',  metavar='file', nargs='+', help='one or more files to convert')
        return parser

    def create_converter(self, args):
        converter = Txt2Html()
        converter.append_page_break = args.breakflag
        converter.create_title = args.create_title
        return converter

    def get_output_filename(self, path):
        filename, ext = os.path.splitext(path)
        return filename + ".html"

def main():
    app = Txt2HtmlConverter()
    app.run()

if __name__ == "__main__":
    main()


import random

class Solution:
    def arraysIntersection(self, arr1, arr2, arr3):
        if (not arr1) or (not arr2) or (not arr3):
            return None
        ha = {}
        res = []
        for i in arr1:
            if i not in ha:
                ha[i] = 1
            else:
                ha[i] += 1
        for i in arr2:
            if i not in ha:
                ha[i] = 1
            else:
                ha[i] += 1
        for i in arr3:
            if i not in ha:
                ha[i] = 1
            else:
                ha[i] += 1
        for i in ha:
            if ha.get(i) == 3:
                res.append(i)
        res.sort()

        return res

if __name__ == "__main__":
    solution = Solution()
    arr1 = [1, 2, 3, 4, 5]
    arr2 = [1, 2, 5, 7, 9]
    arr3 = [1, 3, 4, 5, 8]
    print(solution.arraysIntersection(arr1, arr2, arr3))

LeetCode Contest/5079. Intersection of Three Sorted Arrays/hashtable.py


from logging import Logger

from web3.datastructures import AttributeDict
from web3.types import LogReceipt

from src.contracts.ethereum.multisig_wallet import MultisigWallet
from src.db.collections.eth_signatures import EthSignatures
from src.db.collections.eth_swap import Swap, Status
from src.db.collections.scrt_retry import ScrtRetry
from src.db.collections.swaptrackerobject import SwapTrackerObject
from src.util.coins import CoinHandler
from src.util.common import swap_retry_address

def build_hash(nonce, token):
    return f'{nonce}|{token}'

class EthConfirmer:

    def __init__(self, multisig_contract: MultisigWallet, logger: Logger):
        self.multisig_contract = multisig_contract
        self.logger = logger
        self.coins = CoinHandler()

    def submit(self, event: LogReceipt):
        self._handle_submit(event)

    def _handle_submit(self, event: LogReceipt):
        data = self.multisig_contract.submission_data(event.args.transactionId)
        nonce, scrt_token = self.get_tx_params_from_data(data)
        swap_id = build_hash(nonce, scrt_token)
        EthSignatures(swap_id=swap_id,
                      tx_id=event.args.transactionId,
                      tx_hash=event['transactionHash'].hex(),
                      signer="leader").save()

    def withdraw(self, event: AttributeDict):
        self._handle(event, True)

    def failed_withdraw(self, event: AttributeDict):
        self._handle(event, False)

    def _handle(self, event: AttributeDict, success: bool):
        transaction_id = event.args.transactionId
        data = self.multisig_contract.submission_data(transaction_id)

        nonce, scrt_token = self.get_tx_params_from_data(data)

        self._set_tx_result(nonce, scrt_token, success=success)

    def get_tx_params_from_data(self, data):
        nonce = data['nonce']
        token = data['token']
        if token.lower() == swap_retry_address:
            self.logger.info(f'Retrieving original ID for {nonce}|{token.lower()}')
            retry = ScrtRetry.objects().get(retry_id=f'{nonce}|{token.lower()}')
            nonce, token = retry.original_id.split('|')
            self.logger.info(f'Got original id: {nonce} for token {token.lower()}')
        if token == '0x0000000000000000000000000000000000000000':
            scrt_token = self.coins.scrt_address('native')
        else:
            scrt_token = self.coins.scrt_address(token)
        return nonce, scrt_token

    @staticmethod
    def _confirmer_id(token: str):
        return f'confirmer-{token}'

    @staticmethod
    def get_swap(nonce, token):
        return Swap.objects().get(src_tx_hash=build_hash(nonce, token))

    def _set_tx_result(self, nonce, token, success=True):
        try:
            swap = self.get_swap(nonce, token)
        except Exception as e:  # pylint: disable=broad-except
            self.logger.error(
                f'Error handling swap {build_hash(nonce, token)}: {e}')
            return

        if swap.status != Status.SWAP_SUBMITTED:
            return
        if success:
            swap.update(status=Status.SWAP_CONFIRMED)
        else:
            swap.update(status=Status.SWAP_FAILED)

        obj = SwapTrackerObject.get_or_create(self._confirmer_id(token))
        obj.update(nonce=nonce)


import cv2 as cv
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.utils.data
import torchvision.transforms as transforms
import torchvision.utils
import os
from PIL import Image
from torch.autograd import Variable
from TextureTrain import texture
from Net import ContentNet
from Net import CoderGan

overlap_pred = 4
device = torch.device("cuda:0")
n_epoches = 25
image_size = 128
image_size_raw = 512
batch_size = 1
beta_1 = 0.5
lr = 0.0002
wtl2 = 0.998
wtlD = 0.001
niter = 25
overlapL2Weight = 10
dir = 'result/'
content_path = 'test/3.jpg'
transform = transforms.Compose([transforms.Scale(image_size),

                                transforms.CenterCrop(image_size),
                                transforms.ToTensor(),
                                transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))])
transform1 = transforms.Compose([transforms.Scale(image_size_raw),
                                 transforms.CenterCrop(image_size_raw),
                                 transforms.ToTensor(),
                                 transforms.Normalize(mean=(0.485, 0.456, 0.406), std=(0.229, 0.224, 0.225))])
denorm_transform = transforms.Normalize(mean=(-1, -1, -1), std=(2, 2, 2))
denorm_transform1 = transforms.Normalize(mean=(-2.12, -2.04, -1.80), std=(4.37, 4.46, 4.44))
transform3 = transforms.Normalize(mean=(0.485, 0.456, 0.406), std=(0.229, 0.224, 0.225))
pic = content_path
if not os.path.exists(dir):
    os.mkdir(dir)

content_image_ori = cv.imread(pic)
print(pic)
# print(content_image_ori)
content_image_ori = cv.cvtColor(content_image_ori, cv.COLOR_BGR2RGB)
content_image_ori_PIL = Image.fromarray(content_image_ori)
content_image = transform(content_image_ori_PIL).unsqueeze(0)
content_images = content_image
device = torch.device("cuda:0")
content_raw = transform1(content_image_ori_PIL).unsqueeze(0).to(device)

torchvision.utils.save_image(denorm_transform1(content_raw[0]), dir + '/real.jpg')

content_raw[:, :, int(image_size_raw / 4):int(image_size_raw / 4 + image_size_raw / 2),
int(image_size_raw / 4):int(image_size_raw / 4 + image_size_raw / 2)] = 0.0
content_raw[:, :, int(image_size_raw / 4):int(image_size_raw / 4 + image_size_raw / 2),
int(image_size_raw / 4):int(image_size_raw / 4 + image_size_raw / 2)] = torch.mean(content_raw)

torchvision.utils.save_image(denorm_transform1(content_raw[0]), dir + '/cropped.jpg')

photos = ["test/2.jpg", "test/3.jpg"]
for path in photos:
    content_image_ori1 = cv.imread(path)
    content_image_ori1 = cv.cvtColor(content_image_ori1, cv.COLOR_BGR2RGB)
    content_image_ori_PIL1 = Image.fromarray(content_image_ori1)
    content_image1 = transform(content_image_ori_PIL1).unsqueeze(0)
    content_images = torch.cat((content_images, content_image1), 0)

input_cropped = torch.FloatTensor(batch_size, 3, image_size, image_size)

input_cropped = Variable(input_cropped).to(device)

input_cropped.resize_(content_images.size()).copy_(content_images)

input_cropped.data[:, 0,

int(image_size / 4 + overlap_pred):int(image_size / 4 + image_size / 2 - overlap_pred),
int(image_size / 4 + overlap_pred):int(
    image_size / 4 + image_size / 2 - overlap_pred)] = 2 * 117.0 / 255.0 - 1.0
input_cropped.data[:, 1,
int(image_size / 4 + overlap_pred):int(image_size / 4 + image_size / 2 - overlap_pred),
int(image_size / 4 + overlap_pred):int(
    image_size / 4 + image_size / 2 - overlap_pred)] = 2 * 104.0 / 255.0 - 1.0
input_cropped.data[:, 2,
int(image_size / 4 + overlap_pred):int(image_size / 4 + image_size / 2 - overlap_pred),
int(image_size / 4 + overlap_pred):int(
    image_size / 4 + image_size / 2 - overlap_pred)] = 2 * 123.0 / 255.0 - 1.0

content_net = CoderGan().to(device)
content_net.load_state_dict(torch.load("GAN_cifar10.pth", map_location=lambda storage, location: storage)['state_dict'])
resume_epoch = torch.load("GAN_cifar10.pth")['epoch']
print(content_net)
synthesis = content_net(input_cropped)
recon_image = input_cropped.clone()
recon_image.data[:, :, int(image_size / 4):int(image_size / 4 + image_size / 2),
int(image_size / 4):int(image_size / 4 + image_size / 2)] = synthesis.data
torchvision.utils.save_image(denorm_transform(recon_image.data[0]), dir + '/input.jpg')
torchvision.utils.save_image(denorm_transform(synthesis.data[0]), dir + '/output.jpg')
content_result = denorm_transform(synthesis.data[0])
content_result = transform3(content_result)
content_result = content_result.unsqueeze(0)
content_result = F.interpolate(content_result, [int(image_size_raw / 2), int(image_size_raw / 2)],
                               mode="bilinear")
content_result.cuda()
result = texture(content_raw, content_result, dir)
content_raw = denorm_transform1(content_raw.data[0])
for i in range(3):
    content_raw.data[i, int(image_size_raw / 4):int(image_size_raw / 4 + image_size_raw / 2), \
    int(image_size_raw / 4):int(image_size_raw / 4 + image_size_raw / 2)] = result.data[0][i]
torchvision.utils.save_image(content_raw, dir + '/result.jpg')


from collections import defaultdict

t = int(input())
for _ in range(t):
	n, m, k = map(int, input().split())
	arr = [int(j) for j in input().split()]

	d = defaultdict(int)

	for i in range(m):
		u, v, val = map(int, input().split())
		d[(u-1, v-1)] = val

	res = []
	for i in range(2**n):
		val = 0
		for j in range(n-1, -1, -1):
			if ((1<<j)&i) > 0:
				val += arr[n-1-j]

		b = bin(i)[2:]
		b = '0'*(n-len(b)) + b
		for x in range(len(b)):
			for y in range(x, len(b)):
				if b[x:y+1].count('1') == len(b[x:y+1]):
					val += d[(x, y)]

		res += [val]

	res.sort(reverse=True)
	print(*res[:k])


def sortedListToBST(head):
        """
        :type head: ListNode
        :rtype: TreeNode
        """
        def mySort(head,tail):
                slow = head
                fast = head
                if head==tail:
                        return None
                while fast!=tail and fast.next!=tail:
                        slow = slow.next
                        fast = fast.next.next
                # print(slow.val,fast.val)
                root = TreeNode(slow.val)
                left = mySort(head,slow)
                right = mySort(slow.next,tail)
                root.left = left
                root.right = right
                return root
        return mySort(head,None)

execise2/109Convert Sorted List to Binary Search Tree.py


# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> ListNode:
        cntA = cntB = 0
        itrA, itrB = headA, headB
        while itrA or itrB:
            if itrA:
                cntA += 1
                itrA = itrA.next
            if itrB:
                cntB += 1
                itrB = itrB.next

        large, small = max(cntA, cntB), 0
        if large == cntA:
            itrL, itrS, small = headA, headB, cntB
        else:
            itrL, itrS, small = headB, headA, cntA
        for i in range(large - small):
            itrL = itrL.next
        while itrL and itrS:
            if itrL == itrS:
                return itrL
            itrL = itrL.next
            itrS = itrS.next
        return None


import requests
import logging
import jwt
import secrets
import os
import configparser

LEONID_AUTH_TOKEN = "%Leonid_Test_Token%"

if os.getenv("SQL_USER") is None:
    LEONID_BASE_URL = "http://localhost:5001"

else:
    LEONID_BASE_URL = "http://iseecubes_leonid_the_chat_bot_1:5001"

LEONID_TEMPORARY_UNAVAILABLE_MESSAGE = "<Leonid is asleep right now, we can't wake him up - " \
                                       "please try to write him later>"

class LocalChatBotIntegration:

    def check_if_bot_available(self, config_file_path, bot_name: str):
        """
        This method fetches configuration from environmental variables in order to check if given
        chat bot is available.
        :param bot_name: str
        :return: bool
        """
        try:
            if bot_name == 'Leonid':
                # Running on local machine - fetching config from the config file
                if os.getenv("SQL_USER") is None:
                    # Reading DB name, host and credentials from config
                    config = configparser.ConfigParser()
                    config.read(config_file_path)
                    bot_status = config.get("CHAT_SERVER_CONFIG", "enable_leonid_chat_bot")

                    if bot_status == 'Enabled':
                        return True

                # Running in a Docker container - fetching config from env. variable
                flag = os.getenv("LEONID_THE_CHAT_BOT")
                if flag == 'Enabled':
                    return True
                else:
                    return False

        except Exception:
            return False

    def route_incoming_message(self, bot_name, user_name, message_content):
        """
        This method redirects user's message and name to the selected local chat bot
        and returns the response that comes from the bot back to the calling method.
        :param bot_name: str (must be on the chat bots list)
        :param user_name: str
        :param message_content: str
        :return: str
        """
        if bot_name == 'Leonid':
            return self.send_message_to_leonid(user_name, message_content)

        else:
            return {"Error": f"No chat bot with ID {bot_name}"}

    def send_message_to_leonid(self, user_name, message_content):
        """
        This method redirects user's message and name to Leonid the chat bot
        and returns the response that comes from the bot back to the calling method
        :param user_name: str
        :param message_content: str
        :return: str
        """

        secret_key = secrets.token_hex(16)

        token_content = {"user_name": user_name, "user_token": LEONID_AUTH_TOKEN}
        encoded_jwt = jwt.encode(token_content, secret_key, algorithm="HS256")

        payload = {"user_data":   encoded_jwt,
                   "user_prompt": message_content}

        try:
            bot_prompt_url = LEONID_BASE_URL + '/receive_prompt'
            response = requests.post(url=bot_prompt_url,json=payload)

            return response.text

        except requests.exceptions.ConnectionError as e:
            logging.error(f"Can't contact Leonid the chat bot, please verify the service is available - {e}")
            return LEONID_TEMPORARY_UNAVAILABLE_MESSAGE

    def notify_all_bots_on_user_disconnection(self, user_name, bot_name="Leonid"):
        """
        This method notifies the selected chat bot on user disconnection.
        Each bot may have a different procedure for this, so the method contains a separate
        section for each chat bot.
        :param user_name: str
        :param bot_name: str  (must be on the chat bots list)
        :return: str
        """
        secret_key = secrets.token_hex(16)

        # Each bot might have a different procedure for conversation termination
        # Right now we have only one local chat bot. If more chat bots are to be integrated with
        # the application more procedures will be added to this method.
        if bot_name == "Leonid":

            token_content = {"user_name": user_name, "user_token": LEONID_AUTH_TOKEN}
            encoded_jwt = jwt.encode(token_content, secret_key, algorithm="HS256")

            payload = {"user_data": encoded_jwt}

            bot_prompt_url = LEONID_BASE_URL + '/user_disconnection'
            logging.info(f"Chat Server: notifying Leonid the chatbot that user {user_name} "
                         f"has disconnected and left the chat")

            response = requests.post(url=bot_prompt_url, json=payload)
            logging.info(f"Chat Server: response received from Leonid: {response.text}")

            return response.text

        else:
            return {"error": f"The bot {bot_name} is not on the list."}


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

import os
import pickle

top_dir = "/path/to/raw"

etna_counter = 0
data = []
for dir_, folders, files in os.walk(top_dir):
    for f in files:
        f_lower = f.lower()
        if f_lower.endswith(".jpg"):
            cls = os.path.basename(dir_)
            if 'Cirneco' in cls:
                etna_counter += 1
                cls = 'Etna Cirneco'
            data.append([cls, os.path.join(dir_, f)])

target_file = "/path/to/pickle.pkl"
with open(target_file, 'wb') as target:
    pickle.dump(data, target)

print("Done")
print(etna_counter)


import json, random

from flask import render_template, Blueprint, request
from words import WordProbability, load_letter_frequencies, load_word_list
from constraint import Constraints, LengthConstraint

wordle = Blueprint('wordle', __name__, template_folder="templates")
wp = WordProbability([load_letter_frequencies('english_monograms.txt'),
                      load_letter_frequencies('english_bigrams.txt'),
                      load_letter_frequencies('english_trigrams.txt')])
word_list = load_word_list('wordlist.txt')

@wordle.route('/')
def home():
    """Landing page."""
    return render_template(
        'home.html',
        title="Jinja Demo Site",
        description="Smarter page templates with Flask & Jinja."
    )

@wordle.route('/guess', methods=['POST'])
def optimal_guess():
    json_data = request.get_json(force=True)
    print(json_data)
    constraints = Constraints.from_wordle(json_data)
    constraints.prepend(LengthConstraint(5))
    valid_words = list(filter(constraints.apply, word_list))
    print(valid_words)
    best_words = wp.best_words_by_score(valid_words, 5)
    print(best_words)
    return json.dumps(best_words)

@wordle.route('/word', methods=['GET'])
@wordle.route('/word/<seed>', methods=['GET'])
def word(seed=None):
    subwords = [w for w in word_list if len(w) == 5]
    if seed is not None:
        random.seed(seed)
    ix = random.randint(0, len(subwords))
    return subwords[ix]


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

import os
import logging
import subprocess

from boto3.s3.transfer import TransferConfig
from libs.fs.s3 import s3

from .consts import (DIR_MCLUSTER, S3_DUMP_FILE_PATH,
                     DUMP_DB_COMMAND, DUMP_TABLE_COMMAND)

class Dump(object):
    def __init__(self, user_id, db_id):
        self.user_id = user_id
        self.db_id = db_id

    def __repr__(self):
        return '<Dump user:{0} db:{1}>'.format(self.user_id, self.db_id)

    def execute(self, db_name, tb_name=None):
        file_name = self.generate_file_name(db_name, tb_name=tb_name)
        local_path = self.get_local_path(file_name)
        s3_path = self.get_s3_path(file_name)

        # 先删除已存在的文件
        self.delete_s3(s3_path)
        self.delete_local(local_path)

        # 再执行dump
        if tb_name:
            command = DUMP_TABLE_COMMAND.format(db_name=db_name,
                                                tb_name=tb_name,
                                                local_path=local_path)
        else:
            command = DUMP_DB_COMMAND.format(db_name=db_name,
                                             local_path=local_path)
        logging.info("[dump] command:{0}".format(command))

        p = subprocess.Popen(command, shell=True,
                             stdout=subprocess.PIPE,
                             stderr=subprocess.STDOUT)
        p.wait()

        # 上传到S3
        if os.path.exists(local_path):
            # 针对大文件上传，并发上传线程数设置为1
            config = TransferConfig(max_concurrency=1)
            s3.upload_file(local_path, s3_path, config=config)
            logging.info("[dump] upload file [{0}] to [matrix/{1}]".format(local_path, s3_path))

        # 再次删除本地dump文件
        self.delete_local(local_path)
        return file_name

    def generate_file_name(self, db_name, tb_name=None):
        """
        文件名称格式：
        库：userid_dbid_dbname.sql
        表：userid_dbid_dbname_tbname.sql
        """
        return ("{0}_{1}_{2}_{3}.sql".format(self.user_id, self.db_id, db_name, tb_name) if
                tb_name else "{0}_{1}_{2}.sql".format(self.user_id, self.db_id, db_name))

    @classmethod
    def url(cls, file_name):
        key = cls.get_s3_path(file_name)
        return s3.get_url(key)

    @classmethod
    def is_upload_s3(cls, file_name):
        """是否上传到S3"""
        key = cls.get_s3_path(file_name)
        return s3.is_file_exists(key)

    @classmethod
    def get_local_path(cls, file_name):
        """本地路径
        /srv/mcluster/userid_dbid_dbname.sql
        """
        return "/".join((DIR_MCLUSTER, file_name))

    @classmethod
    def get_s3_path(cls, file_name):
        """S3上路径
        mcluster/dump/userid_dbid_dbname.sql
        """
        return "/".join((S3_DUMP_FILE_PATH, file_name))

    def delete_local(self, path):
        """删除本地"""
        if os.path.exists(path):
            os.remove(path)
            logging.info("[dump] delete local file:{0}".format(path))

    def delete_s3(self, path):
        """删除远端"""
        if s3.is_file_exists(path):
            s3.delete_file(path)
            logging.info("[dump] delete s3 file:{0}".format(path))