__authors__ = ["T. Vincent"]
__license__ = "MIT"
__date__ = "07/01/2019"

import os
import logging
import weakref
from . import qt
import silx.resources
from silx.utils import weakref as silxweakref

_logger = logging.getLogger(__name__)
"""Module logger"""

_cached_icons = None
"""Cache loaded icons in a weak structure"""

def getIconCache():
    """Get access to all cached icons

    :rtype: dict
    """
    global _cached_icons
    if _cached_icons is None:
        _cached_icons = weakref.WeakValueDictionary()
        # Clean up the cache before leaving the application
        # See https://github.com/silx-kit/silx/issues/1771
        qt.QApplication.instance().aboutToQuit.connect(cleanIconCache)
    return _cached_icons

def cleanIconCache():
    """Clean up the icon cache"""
    _logger.debug("Clean up icon cache")
    _cached_icons.clear()

_supported_formats = None
"""Order of file format extension to check"""

class AbstractAnimatedIcon(qt.QObject):
    """Store an animated icon.

    It provides an event containing the new icon everytime it is updated."""

    def __init__(self, parent=None):
        """Constructor

        :param qt.QObject parent: Parent of the QObject
        :raises: ValueError when name is not known
        """
        qt.QObject.__init__(self, parent)

        self.__targets = silxweakref.WeakList()
        self.__currentIcon = None

    iconChanged = qt.Signal(qt.QIcon)
    """Signal sent with a QIcon everytime the animation changed."""

    def register(self, obj):
        """Register an object to the AbstractAnimatedIcon.
        If no object are registred, the animation is paused.
        Object are stored in a weaked list.

        :param object obj: An object
        """
        if obj not in self.__targets:
            self.__targets.append(obj)
        self._updateState()

    def unregister(self, obj):
        """Remove the object from the registration.
        If no object are registred the animation is paused.

        :param object obj: A registered object
        """
        if obj in self.__targets:
            self.__targets.remove(obj)
        self._updateState()

    def hasRegistredObjects(self):
        """Returns true if any object is registred.

        :rtype: bool
        """
        return len(self.__targets)

    def isRegistered(self, obj):
        """Returns true if the object is registred in the AbstractAnimatedIcon.

        :param object obj: An object
        :rtype: bool
        """
        return obj in self.__targets

    def currentIcon(self):
        """Returns the icon of the current frame.

        :rtype: qt.QIcon
        """
        return self.__currentIcon

    def _updateState(self):
        """Update the object according to the connected objects."""
        pass

    def _setCurrentIcon(self, icon):
        """Store the current icon and emit a `iconChanged` event.

        :param qt.QIcon icon: The current icon
        """
        self.__currentIcon = icon
        self.iconChanged.emit(self.__currentIcon)

class MovieAnimatedIcon(AbstractAnimatedIcon):
    """Store a looping QMovie to provide icons for each frames.
    Provides an event with the new icon everytime the movie frame
    is updated."""

    def __init__(self, filename, parent=None):
        """Constructor

        :param str filename: An icon name to an animated format
        :param qt.QObject parent: Parent of the QObject
        :raises: ValueError when name is not known
        """
        AbstractAnimatedIcon.__init__(self, parent)

        qfile = getQFile(filename)
        self.__movie = qt.QMovie(qfile.fileName(), qt.QByteArray(), parent)
        self.__movie.setCacheMode(qt.QMovie.CacheAll)
        self.__movie.frameChanged.connect(self.__frameChanged)
        self.__cacheIcons = {}

        self.__movie.jumpToFrame(0)
        self.__updateIconAtFrame(0)

    def __frameChanged(self, frameId):
        """Callback everytime the QMovie frame change
        :param int frameId: Current frame id
        """
        self.__updateIconAtFrame(frameId)

    def __updateIconAtFrame(self, frameId):
        """
        Update the current stored QIcon

        :param int frameId: Current frame id
        """
        if frameId in self.__cacheIcons:
            icon = self.__cacheIcons[frameId]
        else:
            icon = qt.QIcon(self.__movie.currentPixmap())
            self.__cacheIcons[frameId] = icon
        self._setCurrentIcon(icon)

    def _updateState(self):
        """Update the movie play according to internal stat of the
        MovieAnimatedIcon."""
        self.__movie.setPaused(not self.hasRegistredObjects())

class MultiImageAnimatedIcon(AbstractAnimatedIcon):
    """Store a looping QMovie to provide icons for each frames.
    Provides an event with the new icon everytime the movie frame
    is updated."""

    def __init__(self, filename, parent=None):
        """Constructor

        :param str filename: An icon name to an animated format
        :param qt.QObject parent: Parent of the QObject
        :raises: ValueError when name is not known
        """
        AbstractAnimatedIcon.__init__(self, parent)

        self.__frames = []
        for i in range(100):
            try:
                frame_filename = os.sep.join((filename, ("%02d" %i)))
                frame_file = getQFile(frame_filename)
            except ValueError:
                break
            try:
                icon = qt.QIcon(frame_file.fileName())
            except ValueError:
                break
            self.__frames.append(icon)

        if len(self.__frames) == 0:
            raise ValueError("Animated icon '%s' do not exists" % filename)

        self.__frameId = -1
        self.__timer = qt.QTimer(self)
        self.__timer.timeout.connect(self.__increaseFrame)
        self.__updateIconAtFrame(0)

    def __increaseFrame(self):
        """Callback called every timer timeout to change the current frame of
        the animation
        """
        frameId = (self.__frameId + 1) % len(self.__frames)
        self.__updateIconAtFrame(frameId)

    def __updateIconAtFrame(self, frameId):
        """
        Update the current stored QIcon

        :param int frameId: Current frame id
        """
        self.__frameId = frameId
        icon = self.__frames[frameId]
        self._setCurrentIcon(icon)

    def _updateState(self):
        """Update the object to wake up or sleep it according to its use."""
        if self.hasRegistredObjects():
            if not self.__timer.isActive():
                self.__timer.start(100)
        else:
            if self.__timer.isActive():
                self.__timer.stop()

def getWaitIcon():
    """Returns a cached version of the waiting AbstractAnimatedIcon.

    :rtype: AbstractAnimatedIcon
    """
    return getAnimatedIcon("process-working")

def getAnimatedIcon(name):
    """Create an AbstractAnimatedIcon from a resource name.

    The resource name can be prefixed by the name of a resource directory. For
    example "silx:foo.png" identify the resource "foo.png" from the resource
    directory "silx".

    If no prefix are specified, the file with be returned from the silx
    resource directory with a specific path "gui/icons".

    See also :func:`silx.resources.register_resource_directory`.

    Try to load a mng or a gif file, then try to load a multi-image animated
    icon.

    In Qt5 mng or gif are not used, because the transparency is not very well
    managed.

    :param str name: Name of the icon, in one of the defined icons
                     in this module.
    :return: Corresponding AbstractAnimatedIcon
    :raises: ValueError when name is not known
    """
    key = name + "__anim"
    cached_icons = getIconCache()
    if key not in cached_icons:

        qtMajorVersion = int(qt.qVersion().split(".")[0])
        icon = None

        # ignore mng and gif in Qt5
        if qtMajorVersion != 5:
            try:
                icon = MovieAnimatedIcon(name)
            except ValueError:
                icon = None

        if icon is None:
            try:
                icon = MultiImageAnimatedIcon(name)
            except ValueError:
                icon = None

        if icon is None:
            raise ValueError("Not an animated icon name: %s", name)

        cached_icons[key] = icon
    else:
        icon = cached_icons[key]
    return icon

def getQIcon(name):
    """Create a QIcon from its name.

    The resource name can be prefixed by the name of a resource directory. For
    example "silx:foo.png" identify the resource "foo.png" from the resource
    directory "silx".

    If no prefix are specified, the file with be returned from the silx
    resource directory with a specific path "gui/icons".

    See also :func:`silx.resources.register_resource_directory`.

    :param str name: Name of the icon, in one of the defined icons
                     in this module.
    :return: Corresponding QIcon
    :raises: ValueError when name is not known
    """
    cached_icons = getIconCache()
    if name not in cached_icons:
        qfile = getQFile(name)
        icon = qt.QIcon(qfile.fileName())
        cached_icons[name] = icon
    else:
        icon = cached_icons[name]
    return icon

def getQPixmap(name):
    """Create a QPixmap from its name.

    The resource name can be prefixed by the name of a resource directory. For
    example "silx:foo.png" identify the resource "foo.png" from the resource
    directory "silx".

    If no prefix are specified, the file with be returned from the silx
    resource directory with a specific path "gui/icons".

    See also :func:`silx.resources.register_resource_directory`.

    :param str name: Name of the icon, in one of the defined icons
                     in this module.
    :return: Corresponding QPixmap
    :raises: ValueError when name is not known
    """
    qfile = getQFile(name)
    return qt.QPixmap(qfile.fileName())

def getQFile(name):
    """Create a QFile from an icon name. Filename is found
    according to supported Qt formats.

    The resource name can be prefixed by the name of a resource directory. For
    example "silx:foo.png" identify the resource "foo.png" from the resource
    directory "silx".

    If no prefix are specified, the file with be returned from the silx
    resource directory with a specific path "gui/icons".

    See also :func:`silx.resources.register_resource_directory`.

    :param str name: Name of the icon, in one of the defined icons
                     in this module.
    :return: Corresponding QFile
    :rtype: qt.QFile
    :raises: ValueError when name is not known
    """
    global _supported_formats
    if _supported_formats is None:
        _supported_formats = []
        supported_formats = qt.supportedImageFormats()
        order = ["mng", "gif", "svg", "png", "jpg"]
        for format_ in order:
            if format_ in supported_formats:
                _supported_formats.append(format_)
        if len(_supported_formats) == 0:
            _logger.error("No format supported for icons")
        else:
            _logger.debug("Format %s supported", ", ".join(_supported_formats))

    for format_ in _supported_formats:
        format_ = str(format_)
        filename = silx.resources._resource_filename('%s.%s' % (name, format_),
                                                     default_directory='gui/icons')
        qfile = qt.QFile(filename)
        if qfile.exists():
            return qfile
        _logger.debug("File '%s' not found.", filename)
    raise ValueError('Not an icon name: %s' % name)


import os
from pathlib import Path
from tempfile import NamedTemporaryFile

import pytest
import pytest_mock
from werkzeug.exceptions import NotFound

from iceart.models import Artist, ArtistDto, ArtistViewModel

def test_artist_vm_init():
    with pytest.raises(NotFound):
        ArtistViewModel(-1)

def test_artist_vm_search_key():
    assert ArtistViewModel(44).search_key() == {"_id": 44}

def test_artist_init():
    # Arrange
    data = {"_id": 44, "title": "t", "info": "i", "file": "f", "paintings": [5, 3, 77]}

    # Act
    model = Artist(data)

    # Assert
    assert model.identity == 44
    assert model.title == "t"
    assert model.info == "i"
    assert model.file == "f"
    assert model.paintings == [5, 3, 77]

def test_artist_dto_init():
    # Arrange
    data = {"_id": 44, "title": "t", "info": "i", "file": "f", "paintings": [5, 3, 77]}
    model = Artist(data)
    with NamedTemporaryFile("w+b", delete=False) as tmp_file:
        tmp_file.write(b"\xab\xef")
        p = Path(tmp_file.name)

    # Act
    with pytest_mock.mock.patch("pathlib.Path.joinpath", return_value=p):
        dto = ArtistDto(model, {1: "img1", 2: "img2"})

    # Assert
    assert dto.image == "q+8="
    assert dto.id == 44
    assert dto.title == "t"
    assert dto.info == "i"
    assert dto.as_json() == {
        "id": 44,
        "title": "t",
        "info": "i",
        "image": "q+8=",
        "paintings": {1: "img1", 2: "img2"},
    }
    assert dto.paintings == {1: "img1", 2: "img2"}

    # Cleanup
    os.remove(p)


import requests
from time import sleep

timeToWait = 300 # Time to wait between callouts (in seconds)

while (True):
    # Get list of commands to run this callout
    URL = "https://slack.flemingcaleb.com:5000/api/agent/4/command/"
    r = requests.get(url=URL)

    if r.status_code == requests.codes.ok:
        # Process the list of requests
        print(r)
    elif r.status_code == requests.codes.not_found:
        # No list this time
        print("No list this time")
    else:
        #Handle Unintended Error
        print("ERROR")

    sleep(timeToWait)


# TEE RATKAISUSI TÄHÄN:
def summa(luku: int):
    # kun luku on 1, ei ole muita summattavia...
    if luku <= 1:
        return luku

    return luku + summa(luku - 1)

if __name__ == "__main__":
    tulos = summa(3)

    print(tulos)
    print(summa(5))
    print(summa(10))


"""
Plot a grid on H2
with Poincare Disk visualization.
"""

import logging
import os

import matplotlib.pyplot as plt
import numpy as np

import geomstats.visualization as visualization
from geomstats.geometry.hyperbolic import Hyperbolic

H2 = Hyperbolic(dimension=2)
METRIC = H2.metric

def main(left=-128,
         right=128,
         bottom=-128,
         top=128,
         grid_size=32,
         n_steps=512):
    starts = []
    ends = []
    for p in np.linspace(left, right, grid_size):
        starts.append(np.array([top, p]))
        ends.append(np.array([bottom, p]))
    for p in np.linspace(top, bottom, grid_size):
        starts.append(np.array([p, left]))
        ends.append(np.array([p, right]))
    starts = [H2.intrinsic_to_extrinsic_coords(s) for s in starts]
    ends = [H2.intrinsic_to_extrinsic_coords(e) for e in ends]
    ax = plt.gca()
    for start, end in zip(starts, ends):
        geodesic = METRIC.geodesic(initial_point=start,
                                   end_point=end)

        t = np.linspace(0, 1, n_steps)
        points_to_plot = geodesic(t)
        visualization.plot(
            points_to_plot, ax=ax, space='H2_poincare_disk', marker='.', s=1)
    plt.show()

if __name__ == "__main__":
    if os.environ['GEOMSTATS_BACKEND'] == 'tensorflow':
        logging.info('Examples with visualizations are only implemented '
                     'with numpy backend.\n'
                     'To change backend, write: '
                     'export GEOMSTATS_BACKEND = \'numpy\'.')
    else:
        main()


"""
DESKRIPSI SOAL

Buatlah program yang menerima 3 buah input nilai dan outputkan jumlah maksimal
dari 2 bilangannya ! diantara ketiga input tersebut.

PETUNJUK MASUKAN

Input terdiri atas 3 angka dalam 1 baris

PETUNJUK KELUARAN

Outputkan angka jumlah terbesar dari 2 angka

"""

a, b, c = list(map(int, input().split()))

sum_values = 0

if a >= b:
    if b >= c:  # a > b > c
        sum_values = a + b
    else:  # a, c, b
        sum_values = a + c
else:  # b > a
    if a >= c:  # b > a > c
        sum_values = a + b
    else:  # b > c > a
        sum_values = b + c

print(sum_values)


import torch
import torch.nn as nn
import torch.nn.functional as F

from .activations import ACTIVATIONS

class Embedding(nn.Module):
    '''
    Abstract base class for any module that embeds a collection of N vertices into
    N hidden states
    '''
    def __init__(self, features, hidden, **kwargs):
        super().__init__()
        self.features = features
        self.hidden = hidden

    def forward(self, x):
        pass

class Constant(Embedding):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

    def forward(self, x):
        return x

class OneLayer(Embedding):
    def __init__(self, features, hidden, act=None, wn=False, **kwargs):
        super().__init__(features, hidden)
        self.fc = nn.Linear(features, hidden)
        if wn:
            self.fc = nn.utils.weight_norm(self.fc, name='weight')
        self.activation = ACTIVATIONS[act]()

    def forward(self, x):
        return self.activation(self.fc(x))

class TwoLayer(Embedding):
    def __init__(self, features, hidden, act=None, wn=False, **kwargs):
        super().__init__(features, hidden)
        self.e1 = OneLayer(features, hidden, act, wn)
        self.e2 = OneLayer(hidden, hidden, act, wn)

    def forward(self, x):
        return self.e1(self.e2(x))

class NLayer(nn.Module):
    def __init__(self, dim_in=None, dim_out=None, n_layers=None, dim_hidden=None, act=None, wn=False, **kwargs):
        super().__init__()
        self.activation = ACTIVATIONS[act]()

        if dim_hidden is None:
            dim_hidden = dim_out
        dims = [dim_in] + [dim_hidden] * (n_layers-1) + [dim_out]

        self.fcs = nn.ModuleList()
        for i in range(len(dims)-1):
            fc = nn.Linear(dims[i], dims[i+1])
            if wn:
                fc = nn.utils.weight_norm(fc, name='weight')
            self.fcs.append(fc)

    def forward(self, x):
        for fc in self.fcs:
            x = fc(x)
            x = self.activation(x)
        return x

EMBEDDINGS = dict(
    n=NLayer,
    one=OneLayer,
    two=TwoLayer,
    const=Constant,
)


import tensorflow as tf
import keras.backend as K

def huber_loss(y_true, y_pred):
    return tf.losses.huber_loss(y_true, y_pred)

def adjust_binary_cross_entropy(y_true, y_pred):
    return K.binary_crossentropy(y_true, K.pow(y_pred, 2))

def MMD_Loss_func(num_source, sigmas=None):
    if sigmas is None:
        sigmas = [1, 5, 10]

    def loss(y_true, y_pred):
        cost = []

        for i in range(num_source):
            for j in range(num_source):
                domain_i = tf.where(tf.equal(y_true, i))[:, 0]
                domain_j = tf.where(tf.equal(y_true, j))[:, 0]
                single_res = mmd_two_distribution(K.gather(y_pred, domain_i),
                                                  K.gather(y_pred, domain_j),
                                                  sigmas=sigmas)
                cost.append(single_res)
        #print("wtf")
        cost = K.concatenate(cost)
        return K.mean(cost)
    return loss

def mmd_two_distribution(source, target, sigmas):

    sigmas = K.constant(sigmas)
    xy = rbf_kernel(source, target, sigmas)
    xx = rbf_kernel(source, source, sigmas)
    yy = rbf_kernel(target, target, sigmas)
    return xx + yy - 2 * xy

def rbf_kernel(x, y, sigmas):
    beta = 1. / (2. * (tf.expand_dims(sigmas, 1)))
    dist = compute_pairwise_distances(x, y)
    dot = -K.dot(beta, K.reshape(dist, (1, -1)))
    exp = K.exp(dot)
    return K.mean(exp, keepdims=True)

def compute_pairwise_distances(x, y):
    norm = lambda x: K.sum(K.square(x), axis=1)
    return norm(K.expand_dims(x, 2) - K.transpose(y))


from selenium import webdriver
import time, re
from bs4 import BeautifulSoup
import pyautogui
from selenium.webdriver.support.ui import WebDriverWait
from selenium.common.exceptions import TimeoutException
import pyperclip
import os

# 主要功能就是访问300mium所有影片详情页，然后挨个下载封面
class Crawl_51luxu:
    def main(self, Dir='F:\\pic\\', page=1, category='300MIUM'):
        current_path = os.getcwd().replace('\\', '/') + '/'
        # custom_path = 'F:\\pic\\300MIUM\\'
        custom_path = Dir + category + "\\"
        chrome_opts = webdriver.ChromeOptions()
        chrome_opts.add_argument("--headless")
        chrome_opts.add_experimental_option(
            'excludeSwitches', ['enable-logging'])
        url = 'https://www.51luxu.com/category/sresource/' + category + '/page/' + str(page)
        def open_browser(url):
            driver = webdriver.Chrome(options=chrome_opts)
            driver.get(url)
            return driver

        def scrapy(driver):
            if not os.path.exists(Dir):
                os.mkdir(Dir)
            if not os.path.exists(custom_path):
                os.mkdir(custom_path)
            Exist = []
            if os.path.exists(custom_path + 'history.txt'):
                with open(custom_path + 'history.txt','r+') as f:
                    lines = f.readlines()
                    for line in lines:
                        Exist.append(line.replace("\n",""))
                    f.close()
            # 从history中读入历史的所下载的图片的名字，以免重复下载
            # 这一步主要是为了，当我筛选图片时，看到好看的要保留，看到不好看的要删除
            # 那么读取文件列表就乱了套了，所以把历史下载保存在txt文件中，就知道之前有没有下过这个番号了
            for page in range(1,100):
                try:
                    content = driver.page_source.encode('utf-8')
                    soup = BeautifulSoup(content, 'lxml')
                    img = soup.find_all('img')
                    src1 = re.findall(r'src=".*?"', str(img))
                    name1 = re.findall(r'alt=".*?"', str(img))
                    src2 = []
                    name2 = []
                    for i in src1:
                        src2.append(i.split('=')[1].replace("\"",""))
                    for i in name1:
                        name2.append(i.split('=')[1].replace("\"", ""))
                    if category == "Scute":
                        pattern = "S-cute"
                    else:
                        pattern = category
                    try:
                        temp = [x.replace("inggo.info", "paypp.xyz") for x in src2]
                        src3 = [x for x in temp if 'images.paypp.xyz/wp-content/uploads' in x]
                    except:
                        src3 = [x for x in src2 if 'images.paypp.xyz/wp-content/uploads' in x]
                    name3 = [x for x in name2 if pattern in x]
                    if len(name3) < 12:
                        name3 = name2
                    # 上面是name3和src3 保存了主页面的番号和相应的详情页的链接
                    # 接下来启动第二个浏览器对各个详情页的视频截图进行抓取
                    driver1 = webdriver.Chrome(options=chrome_opts)
                    for i in range(len(src3)):
                        try:
                            if '[' and '【' not in name3[i]:
                                title = name3[i]
                            else:
                                title = name3[i].split('【')[1].split('】')[0] # 简化一下番号的名字
                        except:
                            title = name3[i].split('[')[1].split(']')[0]
                        if i >= 1:
                            try:
                                if name3[i].split('[')[1].split(']')[0] == name3[i-1].split('[')[1].split(']')[0]:
                                    title = name3[i].split(']')[1].replace("[","")
                            except:
                                pass
                        if i >= 1:
                            try:
                                if name3[i].split('【')[1].split('】')[0] == name3[i-1].split('【')[1].split('】')[0]:
                                    title = name3[i].split('】')[1].replace("【","")
                            except:
                                pass
                        if title in Exist:
                            print("%s 已经下载！" % (title))
                            continue
                        # 前文提到的判断是否下过，如果是，后面就不用进行了
                        # 进入相应链接的详情页
                        driver1.get(src3[i])
                        img = driver1.find_element_by_xpath("//html/body/img")
                        img.screenshot(custom_path + title + '.jpg')
                        # wait = WebDriverWait(driver1, 10) # 等待浏览器相应，删除也可以
                        # pyautogui.rightClick(x=500, y=500) # 右击图片，位置可根据自己的屏幕调整
                        # pyautogui.typewrite(['V']) # 另存为的快捷键为 V
                        # time.sleep(2) # 等待电脑响应
                        # pyperclip.copy(custom_path + title + '.jpg')  # 复制文件名加路径到粘贴板
                        # time.sleep(1)
                        # pyautogui.hotkey('ctrlleft', 'V') # 粘贴
                        # time.sleep(1)
                        # pyautogui.press('enter') # 确认
                        # time.sleep(1)
                        while True:
                            filelist = os.listdir(custom_path)
                            if title + '.jpg' in filelist:
                                with open(custom_path + 'history.txt', 'a+') as f:
                                    f.writelines(title)
                                    f.writelines('\n')
                                    f.close()
                                print("%s 下载完成！" % (title))
                                break
                            else:
                                print("等待响应")
                                time.sleep(2)
                                # pyautogui.hotkey('ctrlleft', 'V')  # 粘贴
                                # time.sleep(1)
                                # pyautogui.press('enter')  # 确认
                                # time.sleep(1)
                        # 在txt中加入当前下载的图片名字
                        print("%s 下载完成！"%(title))
                    time.sleep(0.5)
                    driver1.quit()
                    print("第 %d 页爬完"%(page))
                    button =  "//*[@class='next page-numbers']"  #翻页按钮
                    driver.find_elements_by_xpath(button)[0].click()
                except:
                    print("第 %d 页出错！"%(page))
                    driver1.quit()
                    try:
                        button =  "//*[@class='next page-numbers']"  #翻页按钮
                        driver.find_elements_by_xpath(button)[0].click()
                    except:
                        print("爬取完毕！")
                        break
                    continue

        driver = open_browser(url)
        time.sleep(2)
        scrapy(driver)


from models.resnet import ResNet
from models.unet import UNet, UNet_dualHeads

model_zoo = {
    'UNet': UNet,
    'UNet_dualHeads': UNet_dualHeads
}

def get_model(cfg):

    ########################### COMPUTE INPUT & OUTPUT CHANNELS ############################
    print("Satellites: ", cfg.DATA.satellites)
    print("num_classes:", cfg.MODEL.NUM_CLASS)

    # cfg.MODEL.NUM_CLASS = cfg.MODEL.cfg.MODEL.NUM_CLASS

    INPUT_CHANNELS_DICT = {}
    INPUT_CHANNELS_LIST = []
    for sat in cfg.DATA.satellites:
        INPUT_CHANNELS_DICT[sat] = len(list(cfg.DATA.input_bands[sat]))
        if cfg.DATA.stacking: INPUT_CHANNELS_DICT[sat] = len(cfg.DATA.prepost) * INPUT_CHANNELS_DICT[sat]
        INPUT_CHANNELS_LIST.append(INPUT_CHANNELS_DICT[sat])

    ########################### MODEL SELECTION ############################
    if cfg.MODEL.ARCH in model_zoo.keys():
        INPUT_CHANNELS = sum(INPUT_CHANNELS_LIST)
        MODEL = model_zoo[cfg.MODEL.ARCH]
        return MODEL(INPUT_CHANNELS,
                    num_classes=cfg.MODEL.NUM_CLASS,
                    topo=cfg.MODEL.TOPO,
                    use_deconv=cfg.MODEL.USE_DECONV) #'FC-EF'


#Stack using Linked List
class StackNode:
    def __init__(self,data):
        self.data=data
        self.next=None
class Stack:
    def __init__(self):
        self.root=None
    def isempty(self):
        return True if self.root is None else False
    def push(self,data):
        new_node=StackNode(data)
        new_node.next=self.root
        self.root=new_node
        print("pushed")
    def pop(self):
        curr=self.root
        if curr is None:
            return
        else:
            self.root=curr.next
            curr=None
            return
    def prints(self):
        curr=self.root
        while curr:
            print(curr.data,end='-->')
            curr=curr.next

    def top(self):
        return self.root.data
    def rev(self):
        while not self.isempty():

            x=self.top()
            print(x,end='')
            x=self.pop()
s=Stack()
print(s.isempty())
s.push('h')
s.push('e')
s.push('m')
s.push('a')
#s.pop()
#s.prints()
s.top()
s.rev()


#!/bin/python

import csv
import urllib
import sys

if __name__ == "__main__":

	with open('payphone_set.csv', 'rb') as csvfile:
		csvreader = csv.reader(csvfile)
		for row in csvreader:
			if row[0] == 'ID':
				continue
			number = "+" + row[0]
			neighborhood = row[7]
			lat = row[5]
			lon = row[6]
			params = urllib.urlencode({'pay_phone[number]': number,
					 	   'pay_phone[neighborhood]': neighborhood,
					 	   'pay_phone[lat]': lat,
						   'pay_phone[lon]': lon})
			urllib.urlopen("http://sfpayphones.urbansmore.com/pay_phones", params)
			#sys.exit(0)


from django.urls import path

from .views import (get_user, add_user, get_categories, get_recipe,
                    add_to_favourite, get_user_favourites,
                    get_recipes_in_category, get_random_recipe,
                    add_to_dislikes)

urlpatterns = [
    path('users/<int:telegram_id>', get_user),
    path('users/add/', add_user),

    path('categories/', get_categories),
    path('category/recipes/', get_recipes_in_category),

    path('recipe/random/', get_random_recipe),

    path('favourites/recipe/', get_recipe),
    path('favourites/', get_user_favourites),
    path('favourites/add', add_to_favourite),

    path('dislikes/add', add_to_dislikes)
]


def main():
    for cont in range(0, 44):
        with open("C:\\Users\\p22.ribeiro\\OneDrive\\repocode\\challenge-python\\dataset\\{}".format(cont), "r", encoding="cp1252") as arquivo:
            frase = arquivo.read()

    for remove in '!@#$%&*()<>:;,./?\|][}{=+-"~£':
        frase = frase.replace(remove, ' ').lower()

    lista_frase = frase.split()
    clear_list = set(lista_frase)
    clear_list = sorted(clear_list)
    comprimento = len(clear_list)

    # print(lista_frase)
    # print(comprimento)

    indice = 0
    dicionario_palavra = dict()
    while indice < comprimento:
        for palavra in clear_list:
            dicionario_palavra = [indice, palavra]

            print(dicionario_palavra) # Tirar este print
            indice += 1
main()


import webapp2
import jinja2
import os
from google.appengine.ext import db

template_dir = os.path.join(os.path.dirname(__file__), 'templates')
template_env = jinja2.Environment(loader=jinja2.FileSystemLoader(template_dir), autoescape=True)

def to_render(template, **para):
    t = template_env.get_template(template)
    return t.render(para)

def blog_key(name='default'):
        return db.Key.from_path('blog', name)

class Art(db.Model):
    title = db.StringProperty(required = True)
    arc = db.TextProperty(required = True)
    created = db.DateTimeProperty(auto_now_add = True)

    def render(self):
        self._render_text = self.arc.replace('\n', '<br>')
        return to_render('post.html', p = self)

class BaseHandler(webapp2.RequestHandler):
    def render(self, template, **para):
        self.response.out.write(to_render(template, **para))

class FrontPage(BaseHandler):
     def get(self):
        arts = []
        arts = db.GqlQuery("select * from Art order by created DESC")
        self.render("frontPage.html", arts = arts)

class ShowPost(BaseHandler):
     def get(self, post_id):
         key = db.Key.from_path('Art', int(post_id), parent=blog_key())
         post = db.get(key)

         self.render('permanlink.html', post = post)

"""Problem:
        1. redirect('/blog') don't refresh the page
        2. how  add id colum to db automatiaclly increase
        3. miss click on the title jump to a new page
"""
class NewPost(BaseHandler):
     def get(self):
        self.render("newPost.html")

     def post(self):
         title = self.request.get('title')
         arc = self.request.get('arc')
         if title and arc.strip():
             a = Art(parent=blog_key(), title = title, arc = arc)
             a.put()

             self.redirect('/blog/%s' % str(a.key().id()))
         else:
             self.render("newPost.html", title=title, arc = arc, error="Content insufficiency")

app = webapp2.WSGIApplication([('/blog/?', FrontPage), ('/blog/newpost', NewPost), ('/blog/([0-9]+)', ShowPost)],
        debug=True)


from datetime import datetime, timezone

from config import Config
from logger import logger
from model.coordinates import Coordinates
from model.media_type import MediaType
from model.ts_source import TsSource

class MediaFile:
    original_path: str
    original_filename: str
    filename: str
    media_type: MediaType
    dir_path: list[str]

    unix_time_sec: int = None
    timestamp: datetime = None
    ts_source: TsSource = None
    mtime: datetime = None
    index: int = None

    coordinates: Coordinates = None

    md5: str = None

    target_dir = None
    target_filename = None
    target = None

    def __init__(self, original_path: str, original_filename: str, filename: str, media_type: MediaType,
                 dir_path: list[str]):
        self.original_path = original_path
        self.original_filename = original_filename
        self.filename = filename
        self.media_type = media_type
        self.dir_path = dir_path

    def __repr__(self):
        if self.ts_source == TsSource.EXIF:
            sym = Config.SYM_CHECK
        else:
            sym = Config.SYM_MULTIPLICATION
        return f'{sym} {self.ts_source} {self.dir_path}/{self.original_filename}, ts={self.timestamp}'

    def __lt__(self, other):
        return self.original_filename.lower() < other.original_filename.lower()

    def has_timestamp(self) -> bool:
        return self.timestamp is not None

    def update_time(self, ts: datetime, source: TsSource, force: bool = False):
        if ts is not None and (force or self.timestamp is None or ts < self.timestamp):
            self.timestamp = ts.astimezone(timezone.utc)
            self.unix_time_sec = int(self.timestamp.timestamp())
            self.ts_source = source
            if self.ts_source == TsSource.MTIME:
                self.mtime = ts

    def update_coordinates(self, coordinates: Coordinates):
        if coordinates is not None:
            self.coordinates = coordinates

    @staticmethod
    def create(source_dir: str, file_dir: str) -> 'MediaFile':
        original_filename, filename, media_type, split_path = MediaFile.retrieve_filename_data(source_dir, file_dir)
        return MediaFile(
            original_path=file_dir,
            original_filename=original_filename,
            filename=filename,
            media_type=media_type,
            dir_path=split_path
        )

    @staticmethod
    def retrieve_filename_data(source_dir: str, file_dir: str):
        if not source_dir.endswith('/'):
            source_dir += '/'

        split_path = file_dir.replace(source_dir, '').split('/')
        original_filename = split_path.pop()
        fixed_filename = MediaFile.replace_dots(original_filename)
        filename, extension = fixed_filename.split('.')
        media_type = MediaType.from_string(extension)

        return original_filename, filename, media_type, split_path

    @staticmethod
    def replace_dots(original_filename: str) -> str:
        result = original_filename
        while result.count('.') > 1:
            result = result.replace('.', ' ', 1)
        return result


import math
import random

import numba as nb
import numpy as np

@nb.jit(nopython=True)
def dimension_selector_uniform(n_dimensions):
    return random.randrange(n_dimensions)

def get_dimension_selector_expovariate(
    lambd=None,
    rel_lambd=None,
):
    if lambd is not None and rel_lambd is not None:
        raise ValueError("Cannot set both lambd and rel_lambd")

    if lambd is None and rel_lambd is None:
        # the default, using a rel_lambd of 4.0, placing the pseudo-mean
        # 1/4 of the way into the dimensions
        rel_lambd = 4.

    @nb.jit(nopython=True)
    def dimension_selector_expovariate(n_dimensions):
        nonlocal lambd, rel_lambd

        value = math.inf
        while value >= n_dimensions:
            value = random.expovariate(
                lambd if lambd is not None else rel_lambd/n_dimensions
            )
        return int(value)

    return dimension_selector_expovariate

def get_finder_for_cluster_obeying(
    check_func,
    min_count=1,
    max_count=-1,
    max_depth=-1,
    dimension_selector=dimension_selector_uniform,
    fixed_dimensional_parameters=-1,
    fixed_non_dimensional_parameters=-1,
    fixed_n=-1,
    verbose=False,
    jit_kwargs={},
):
    @nb.jit(nopython=True, **jit_kwargs)
    def _find_cluster_obeying(
        dimensional_parameters,
        non_dimensional_parameters,
        random_seed=None,
        iterations=-1,
    ):
        if dimensional_parameters.shape[1] != non_dimensional_parameters.shape[0]:
            raise ValueError(
                "Minor dimension of dimensional_parameters must match "
                "major dimension of non_dimensional_parameters"
            )

        if (
            fixed_dimensional_parameters != -1
            and fixed_dimensional_parameters != dimensional_parameters.shape[0]
        ):
            raise ValueError("Number of dimensional parameters not expected value")

        if (
            fixed_non_dimensional_parameters != -1
            and fixed_non_dimensional_parameters != non_dimensional_parameters.shape[1]
        ):
            raise ValueError("Number of non-dimensional parameters not expected value")

        if (
            fixed_n != -1
            and fixed_n != non_dimensional_parameters.shape[0]
        ):
            raise ValueError("Number of candidates not expected value")

        final_max_depth = max_depth if max_depth != -1 else (1 + int(
            math.floor(math.log(dimensional_parameters.shape[-1]) / math.log(2))
        ))

        if final_max_depth < 2:
            raise ValueError("max_depth < 2 makes no sense")

        if random_seed is not None:
            random.seed(random_seed)

        bitmap_stack = np.zeros(
            (final_max_depth, dimensional_parameters.shape[-1]),
            dtype=np.bool_,
        )
        bitmap_stack[0,:] = True
        right_branch_stack = np.zeros((final_max_depth,), dtype=np.int8)

        current_level = 1
        iteration = 0

        while True:
            if right_branch_stack[current_level] == 0:
                chosen_dimension = dimension_selector(dimensional_parameters.shape[0])
                vals_count = 0
                # initialize these to any value of the correct type
                vals_min = vals_max = dimensional_parameters[0,0]
                # scan for range of remaining values in this dimension
                for i in range(dimensional_parameters.shape[1]):
                    if bitmap_stack[current_level-1,i]:
                        v = dimensional_parameters[chosen_dimension,i]

                        if vals_count == 0:
                            vals_min = vals_max = v
                        else:
                            vals_min = min(vals_min, v)
                            vals_max = max(vals_max, v)

                        vals_count+=1

                chosen_split_point = random.uniform(vals_min, vals_max)

                # mark values greater than threshold
                remaining_count = 0
                for i in range(dimensional_parameters.shape[1]):
                    if bitmap_stack[current_level-1,i]:
                        is_chosen = (
                            dimensional_parameters[chosen_dimension,i] >= chosen_split_point
                        )
                        bitmap_stack[current_level,i] = is_chosen
                        if is_chosen:
                            remaining_count+=1
            elif right_branch_stack[current_level] == 1:
                # invert current_level's bitmap, masked by the previous level's
                remaining_count = 0
                for i in range(bitmap_stack.shape[1]):
                    if bitmap_stack[current_level-1,i]:
                        is_chosen = not bitmap_stack[current_level,i]
                        bitmap_stack[current_level,i] = is_chosen
                        if is_chosen:
                            remaining_count+=1
            else:
                # tidy up then unwind
                right_branch_stack[current_level] = 0
                bitmap_stack[current_level,:] = False
                if current_level > 1:
                    current_level-=1
                    # advance branch at underlying level
                    right_branch_stack[current_level]+=1
                else:
                    # we're at the root
                    iteration+=1
                    if iterations != -1 and iteration >= iterations:
                        return None

                    # start again by continuing at the
                    # same current_level

                continue

            if verbose:
                print("current_level = ", current_level, " remaining_count = ", remaining_count)

            if remaining_count < min_count:
                right_branch_stack[current_level]+=1
                continue

            if max_count == -1 or remaining_count <= max_count:
                ndp_subset = np.empty(
                    (remaining_count, non_dimensional_parameters.shape[1],),
                    dtype=non_dimensional_parameters.dtype,
                )

                j = 0
                for i in range(bitmap_stack.shape[1]):
                    if j < remaining_count and bitmap_stack[current_level,i]:
                        for k in range(ndp_subset.shape[1]):
                            ndp_subset[j,k] = non_dimensional_parameters[i,k]
                        j+=1

                check_result = check_func(ndp_subset)
                if check_result:
                    if check_result > 0:
                        return bitmap_stack[current_level,:]
                    else:
                        # negative result signals to stop checking this branch
                        right_branch_stack[current_level]+=1
                        continue

            if remaining_count <= 1:
                # dividing any more makes no sense
                right_branch_stack[current_level]+=1
                continue

            if current_level+1 >= final_max_depth:
                # can't descend any deeper
                right_branch_stack[current_level]+=1
                continue

            current_level+=1

    return _find_cluster_obeying


import requests
import json
url = "https://api.telegram.org/bot5653233459:AAHWejZRnvy4luWTetBSbQY5jTzS11mA35U/sendMessage"

photo_url = "https://api.telegram.org/bot5653233459:AAHWejZRnvy4luWTetBSbQY5jTzS11mA35U/sendPhoto"

document_url = "https://api.telegram.org/bot5653233459:AAHWejZRnvy4luWTetBSbQY5jTzS11mA35U/sendDocument"

def buttons(chat_id):
  payload = {
      "photo": "https://blog.mint.com/wp-content/uploads/2013/02/1.jpg",
      #"caption": caption,
      "chat_id": chat_id,
      "reply_markup": {
          "inline_keyboard": [
              [
                  {
                      "text": "Show Plans",
                      "callback_data": "Insurance Plan"
                  }
              ]
          ]
      }
  }
  headers = {
      "Accept": "application/json",
      "Content-Type": "application/json"
  }

  response = requests.post(photo_url, json=payload)

def button_1(chat_id):
  payload = {
      "photo": "AgACAgUAAxkBAAIGv2Mhrr21NIyhQKZHdVnObrNS0_SdAAIStTEb3U4IVSXi2GZ7s3TqAQADAgADcwADKQQ",
      "chat_id": chat_id,
    #   "text": "Select one option",
      "reply_markup": {
          "inline_keyboard": [
              [
                  {
                      "text": "Term Life",
                      "callback_data": "Term Life"
                  },
                  {
                      "text": "mediclaim",
                      "callback_data": "Mediclaim"
                  },
                  {
                      "text": "Accidental",
                      "callback_data": "Accidental Insurance"
                  },

              ]
          ]
      }
  }
  headers = {
      "Accept": "application/json",
      "Content-Type": "application/json"
  }

  response = requests.post(photo_url, json=payload)
  print(response)

def term_life(chat_id):
  payload = {
      "chat_id": chat_id,
      'document': 'BQACAgUAAxkBAAIClGMIdmbOEsi8xsAic-Bk0UahnIl5AAJCBgACDBJBVBLbNwoHbsUhKQQ',
      #"text": "Choose Your Plan",
      "reply_markup": {
          "inline_keyboard": [
              [
                  {
                      "text": "25Lac",
                      "callback_data": "25Lac"
                  },
                  {
                      "text": "50Lac",
                      "callback_data": "50Lac"
                  },
                  {
                      "text": "75Lac",
                      "callback_data": "75Lac"
                  },
                  {
                      "text": "1Cr",
                      "callback_data": "1r"
                  },

              ]
          ]
      }
  }
  headers = {
      "Accept": "application/json",
      "Content-Type": "application/json"
  }

  response = requests.post(document_url, json=payload)

def mediclaim(chat_id):
  payload = {
      "chat_id": chat_id,
      #"text": "Choose Your Plan",
      "document":"BQACAgUAAxkBAAICmmMIeJtMVL1v2JTsRhsdMb4uSDvCAAJEBgACDBJBVKwG4QUSEWW7KQQ",
      "reply_markup": {
          "inline_keyboard": [
              [
                  {
                      "text": "2Lac",
                      "callback_data": "mediclaim up to 2Lac"
                  },
                  {
                      "text": "5Lac",
                      "callback_data": "mediclaim up to 5Lac"
                  },
                  {
                      "text": "10Lac",
                      "callback_data": "mediclaim up to 10Lac"
                  },
                  {
                      "text": "25Lac",
                      "callback_data": "mediclaim up to 25Lac"
                  },

              ]
          ]
      }
  }
  headers = {
      "Accept": "application/json",
      "Content-Type": "application/json"
  }

  response = requests.post(document_url, json=payload)

def accidental(chat_id):
  payload = {
      "chat_id": chat_id,
      #"text": "Choose Your Plan",
      "document":"BQACAgUAAxkBAAICmGMIeJMERoZF4atIdkk_L-cYGESUAAJDBgACDBJBVCJlGZUyjyGkKQQ",
      "reply_markup": {
          "inline_keyboard": [
              [
                  {
                      "text": "5Lac",
                      "callback_data": "Plan of 5Lac"
                  },
                  {
                      "text": "10Lac",
                      "callback_data": "Plan of 10Lac"
                  },
                  {
                      "text": "25Lac",
                      "callback_data": "Plan of 25Lac"
                  },
                  {
                      "text": "50Lac",
                      "callback_data": "Plan of 50Lac"
                  },

              ]
          ]
      }
  }
  headers = {
      "Accept": "application/json",
      "Content-Type": "application/json"
  }

  response = requests.post(document_url, json=payload)

def existing_user(chat_id):
  payload = {
      "chat_id": chat_id,
      "text": "Seems you are an existing user! To see your details click here ",
      "reply_markup": {
          "inline_keyboard": [
              [
                  {
                      "text": "Show Details",
                      "callback_data": "show details"
                  }
              ]
          ]
      }
  }
  headers = {
      "Accept": "application/json",
      "Content-Type": "application/json"
  }

  response = requests.post(url, json=payload, headers=headers)

#print(response.text)
# import requests

# url = "https://api.telegram.org/bot5340261920:AAF2GGInKosubny7ox-CWeZyl8IMESgQg5o/sendPhoto"

# payload = {
#     "photo": "AgACAgUAAxkBAAMLYvDs4xqN8GzQGUY555yHLr5joacAAjGxMRtMw4hX56puCadfo3cBAAMCAAN5AAMpBA",
#     # "caption": "Optional",
#     # "disable_notification": False,
#     "reply_to_message_id": 0,
#     "chat_id":1091996976
# }
# headers = {
#     "Accept": "application/json",
#     "User-Agent": "Telegram Bot SDK - (https://github.com/irazasyed/telegram-bot-sdk)",
#     "Content-Type": "application/json"
# }

# response = requests.post(url, json=payload)

# print(response.text)


import os
import re
import sys
import glob
import builtins
from contextlib import contextmanager

import setuptools
from setuptools import setup, Extension
from setuptools.command.build_ext import build_ext as _build_ext
from setuptools.command.install import install as _install

with open("README.md", "r") as fh:
    long_description = fh.read()

PACKAGENAME = "aliad"
VERSIONFILE = f"{PACKAGENAME}/_version.py"
verstrline = open(VERSIONFILE, "rt").read()
VSRE = r"^__version__ = ['\"]([^'\"]*)['\"]"
mo = re.search(VSRE, verstrline, re.M)
if mo:
    verstr = mo.group(1)
else:
    raise RuntimeError("Unable to find version string in %s." % (VERSIONFILE,))

setup(
    name=PACKAGENAME, # Replace with your own username
    version=verstr,
    author="Alkaid Cheng",
    author_email="chi.lung.cheng@cern.ch",
    description="A library for anomaly detection.",
    long_description=long_description,
    long_description_content_type="text/markdown",
    packages=setuptools.find_packages(),
    package_data={PACKAGENAME: []},
    exclude_package_data={PACKAGENAME: []},
    classifiers=[
        'Programming Language :: Python',
        'Programming Language :: Python :: 3',
        'Programming Language :: Python :: 3.8',
        'Programming Language :: Python :: 3.9',
        'Programming Language :: Python :: 3.10',
        "License :: OSI Approved :: Apache Software License",
        "Operating System :: OS Independent",
    ],
    install_requires=[
          'numpy',
          'pandas',
          'matplotlib',
          'click',
          'quickstats'
      ],
    scripts=[f'bin/{PACKAGENAME}'],
    python_requires='>=3.8',
)


import numpy as np
import matplotlib.pyplot as plot
import math

def jacobi(x):
    x1, x2 = x

    return np.array([[1, math.sin(x2)], [-math.cos(x1), 1]])

def func(x):
    x1, x2 = x

    return np.array([x1 - math.cos(x2) - 1, x2 - math.sin(x1) - 1])

def find_delta_x(f, J):
    return np.linalg.solve(J, -1 * f)

def newthon(x_start, eps):
    x_curr = x_start
    x_next = []
    iters = 0
    is_close = False

    while True:
        print(f'x_{iters} = \n{x_curr}')

        f_x = func(x_curr)
        J_x = jacobi(x_curr)
        print(f'f(x_{iters}) = \n {f_x}')
        print(f'J(x_{iters}) = \n {J_x}')

        x_next = x_curr + find_delta_x(f_x, J_x)

        print(f'x_{iters + 1} = \n{x_next}')

        diff = np.linalg.norm(x_next - x_curr, ord=np.inf)
        print(f'||x_{iters + 1} - x_{iters}|| = {diff}')

        if diff <= eps:
            print(f'Found solution in {iters} steps')
            break

        x_curr = x_next
        iters += 1

    return x_next, iters

def ph(x):
    x1, x2 = x

    return np.array([[1 + math.cos(x2)], [1 + math.sin(x1)]])

def ph_der(x):
    x1, x2 = x

    return np.array([[0, -math.sin(x2)], [math.cos(x1), 0]])

def simple_iters(x_range, phi, phi_deriv, eps):
    x_curr = np.array([[np.mean(x)] for x in x_range])
    x_next = []
    iters = 0
    print(f'x is = {x_range}')
    x_series = [np.linspace(x[0], x[1]) for x in x_range]

    q = max(map(lambda x: np.linalg.norm(phi_deriv(x), ord=np.inf), zip(*x_series)))
    print(f'q = {q}')
    if q >= 1:
        print("q should be < 1")
        exit()

    coeff = q / (1 - q)
    print(f'coeff = {coeff}')
    while True:
        print(f'x_{iters} = \n{x_curr}')

        x_next = phi(x_curr)

        print(f'x_{iters + 1} = \n{x_next}')

        diff = np.linalg.norm(x_next - x_curr, ord=np.inf) * coeff
        print(f'||x_{iters + 1} - x_{iters}|| * coeff = {diff}')

        if diff <= eps:
            print(f'Found solution in {iters} steps')
            break

        x_curr = x_next
        iters += 1

    return x_next, iters

def main():
    # x_series = np.arange(-3.0, 3.1, 0.1)
    # f1_series = [(lambda x2: math.cos(x2) + 1)(x) for x in x_series]
    # f2_series = [(lambda x1: math.sin(x1) + 1)(x) for x in x_series]

    # plot.figure()
    # plot.xlabel('x1')
    # plot.ylabel('x2')
    # plot.plot(x_series, f1_series, 'r')
    # plot.plot(f2_series, x_series,'g')
    # plot.axis('equal')
    # plot.grid(True)
    # plot.show()

    # 1.5 <= x1 <= 2
    # 0.7 <= x2 <= 0.92
#    (1.73, 0.83)
    eps = float(input())
    x_start = np.array([[1.7], [0.75]])

    root_n, iters_n = newthon(x_start, eps)

    x_range = [(1.7, 1.8), (0.75, 0.85)]
    root_si, iters_si = simple_iters(x_range, ph, ph_der, eps)

    print(f'Newthon: root is:\n{root_n}\nfound in {iters_n} iterations')
    print(f'Simple iterations: root is:\n{root_si}\nfound in {iters_si} iterations')

    print(f'Are roots close? {np.allclose(root_n, root_si, atol=eps)}')

main()


import os
import subprocess

import sphinx_autobuild.build
from sphinx_autobuild.build import show

def get_builder(watcher, sphinx_args, *, host, port, pre_build_commands):
    """Prepare the function that calls sphinx."""

    def build():
        """Generate the documentation using ``sphinx``."""
        if not watcher.filepath:
            return
        show(context=f"Detected change: {watcher.filepath}")

        show(context="python3 -m invoke doc")
        subprocess.run("python3 -m invoke doc".split(), check=False)

        for locale in "zh_CN", "de_DE":
            if os.path.isdir(f"output/{locale}"):
                show(context=f"python3 -m invoke intl -l {locale}")
                subprocess.run(
                    f"python3 -m invoke intl -l {locale}".split(), check=False
                )

        show(context="python3 -m invoke run -t post-process")
        subprocess.run("python3 -m invoke run -t post-process".split(), check=False)

        show(context=f"Serving on http://{host}:{port}")

    return build

sphinx_autobuild.build.get_builder = get_builder

if __name__ == "__main__":
    from sphinx_autobuild.cli import main

    main()


import cv2
import numpy as np

img = cv2.imread('bookpage.jpg')

grayscaled = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
#retval, threshold = cv2.threshold(grayscaled, 11, 255 , cv2.THRESH_BINARY)
threshold = cv2.adaptiveThreshold(grayscaled, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 115, 1)

median = cv2.medianBlur(threshold,3)
gaus = cv2.GaussianBlur(threshold,(5,5),0)

cv2.imshow('original',img)
cv2.imshow('gray',grayscaled)
cv2.imshow('threshold',threshold)
cv2.imshow('gaus',gaus)

cv2.waitKey(0)
cv2.destroyAllWindows()


import logging
import numpy as np
import tensorflow as tf
import tensorflow.keras as keras
from tensorflow.keras import backend as K
from tensorflow.keras import Sequential
from tensorflow.keras.layers import Conv2D, Flatten, Dense
from openfl.models.tensorflow import KerasFLModel

class KerasCNN(KerasFLModel):
    """A basic convolutional neural network model.

    """
    def __init__(self, **kwargs):
        """Initializer

        Args:
            **kwargs: Additional parameters to pass to the function

        """
        super().__init__(**kwargs)

        self.model = self.build_model(self.feature_shape, self.data.num_classes, **kwargs)

        self.set_logger()

        print(self.model.summary())
        if self.data is not None:
            print("Training set size: %d; Validation set size: %d" % (self.get_training_data_size(), self.get_validation_data_size()))

    def build_model(self,
                    input_shape,
                    num_classes,
                    conv_kernel_size=(4, 4),
                    conv_strides = (2, 2),
                    conv1_channels_out=16,
                    conv2_channels_out=32,
                    final_dense_inputsize=100,
                    **kwargs):
        """Define the model architecture.

        Args:
            input_shape (numpy.ndarray): The shape of the data
            num_classes (int): The number of classes of the dataset

        Returns:
            tensorflow.python.keras.engine.sequential.Sequential: The model defined in Keras

        """
        model = Sequential()
        model.add(Conv2D(conv1_channels_out,
                        kernel_size=conv_kernel_size,
                        strides=conv_strides,
                        activation='relu',
                        input_shape=input_shape))
        model.add(Conv2D(conv2_channels_out,
                        kernel_size=conv_kernel_size,
                        strides=conv_strides,
                        activation='relu'))
        model.add(Flatten())
        model.add(Dense(final_dense_inputsize, activation='relu'))
        model.add(Dense(num_classes, activation='softmax'))

        model.compile(loss=keras.losses.categorical_crossentropy,
                        optimizer=keras.optimizers.Adam(),
                        metrics=['accuracy'])

        # initialize the optimizer variables
        opt_vars = model.optimizer.variables()
        for v in opt_vars:
            v.initializer.run(session=self.sess)

        return model


import requests
import pandas
from bs4 import BeautifulSoup
import json

url = 'https://www.imdb.com/chart/top/'

response = requests.get(url).content

soup = BeautifulSoup(response,'html.parser')

title = soup.find_all('td', class_='titleColumn')

rating = soup.find_all('strong')

images = soup.find_all('img')

movie_name = []
movie_year =[]
movie_href =[]
movie_image = []
movie_rating = []

for t in title:
    imdb_title_num = t.a.get('href').split('/')[2]
    href = 'https://www.imdb.com/title/'+imdb_title_num
    movie_href.append(href)
    imdb_title = t.a.text
    movie_name.append(imdb_title)
    year = t.span.text
    movie_year.append(year)

for rate in rating:
    r = rate.text
    movie_rating.append(r)

for img in images:
    i = img.get('src')
    movie_image.append(i)

model = pandas.DataFrame({'title': movie_name, 'year': movie_year, 'rating': movie_rating, 'image': movie_image, 'href': movie_href})
model.to_json('movies_data.json', orient="records")


import sqlite3
import json
from datetime import datetime
from traceback import print_tb

from helpers import create_table_if_not_exists, get_db_path, get_timeframe_path, format_data, \
    acceptable, get_timeframes

timeframes = get_timeframes()
sql_transaction = []
start_row = 0
# start_row = 8400000  # that is where I stopped it last time

print(timeframes)

def find_parent(pid):
    try:
        sql = "SELECT comment FROM parent_reply WHERE comment_id = '{}' LIMIT 1".format(pid)
        c.execute(sql)
        result = c.fetchone()
        if result is not None:
            res = result[0]
            if res is None or res == 'False' or res == '0':
                return False
            return res
        else:
            return False
    except Exception as e:
        print('find_parent', e)
        print_tb(e)
        return False

def find_existing_score(pid):
    if pid is False:
        return False

    try:
        sql = "SELECT score FROM parent_reply WHERE parent_id = '{}' LIMIT 1".format(pid)
        c.execute(sql)
        result = c.fetchone()
        if result is not None:
            return result[0]
        else:
            return False
    except Exception as e:
        print('find_existing_score', e)
        print_tb(e)
        return False

def transaction_bldr(sql, bindings = None):
    global sql_transaction
    sql_transaction.append([sql, bindings])
    if len(sql_transaction) > 2000:
        c.execute('BEGIN TRANSACTION')
        for s, b in sql_transaction:
            try:
                if b is not None:
                    c.execute(s, b)
                else:
                    c.execute(s)
            # except Exception as e:
            #     print(str(datetime.now()), s, e)
            except:
                pass
        connection.commit()
        sql_transaction = []

def sql_insert_replace_comment(commentid, parentid, parent, comment, subreddit, time, score):
    try:
        sql = """UPDATE parent_reply
        SET parent_id = ?,
        comment_id = ?,
        parent = ?,
        comment = ?,
        subreddit = ?,
        unix = ?,
        score = ?
        WHERE parent_id = ?;"""

        b = [parentid, commentid, parent, comment, subreddit, int(time), score, parentid]

        transaction_bldr(sql, b)
    except Exception as e:
        print('sql_insert_replace_comment', e)
        print_tb(e)

def sql_insert_has_parent(commentid, parentid, parent, comment, subreddit, time, score):
    try:
        sql = """INSERT INTO parent_reply (parent_id, comment_id, parent, comment, subreddit, unix, score)
        VALUES (?, ?, ?, ?, ?, ?, ?);
        """

        b = [parentid, commentid, parent, comment, subreddit, int(time), score]

        transaction_bldr(sql, b)
    except Exception as e:
        print('sql_insert_has_parent', e)
        print_tb(e)

def sql_insert_no_parent(commentid, parentid, comment, subreddit, time, score):
    try:
        sql = """INSERT INTO parent_reply (parent_id, comment_id, comment, subreddit, unix, score)
        VALUES (?, ?, ?, ?, ?, ?);"""

        b = [parentid, commentid, comment, subreddit, int(time), score]

        transaction_bldr(sql, b)
    except Exception as e:
        print('sql_insert_no_parent', e)
        print_tb(e)

for timeframe in timeframes:
    with sqlite3.connect(get_db_path(timeframe)) as connection:
        c = connection.cursor()
        create_table_if_not_exists(c)

        row_counter = 0
        paired_rows = 0

        # with open(get_timeframe_path(timeframe), buffering=1000) as f:
        with open(get_timeframe_path(timeframe)) as f:
            for row in f:
                row_counter += 1

                if row_counter >= start_row:
                    try:
                        row = json.loads(row)
                        parent_id = row['parent_id'].split('_')[1]
                        body = format_data(row['body'])
                        created_utc = row['created_utc']
                        score = row['score']

                        comment_id = row['id']

                        subreddit = row['subreddit']
                        parent_data = find_parent(parent_id)

                        existing_comment_score = find_existing_score(parent_id)
                        if existing_comment_score:
                            if score > existing_comment_score:
                                if acceptable(body):
                                    sql_insert_replace_comment(comment_id, parent_id, parent_data, body, subreddit,
                                                               created_utc, score)

                        else:
                            if acceptable(body):
                                if parent_data:
                                    if score >= 2:
                                        sql_insert_has_parent(comment_id, parent_id, parent_data, body, subreddit,
                                                              created_utc, score)
                                        paired_rows += 1
                                else:
                                    sql_insert_no_parent(comment_id, parent_id, body, subreddit, created_utc, score)
                    except Exception as e:
                        print(e)

                if row_counter % 100000 == 0:
                    print('Total Rows Read: {}, Paired Rows: {}, Time: {}'.format(row_counter, paired_rows,
                                                                                str(datetime.now())))

    # start from 0
    start_row = 0

print('Done')


# -*- coding: utf-8 -*-
import scrapy
from LaGou.items import LagouItem
import LaGou.settings as settings

class LagouSpider(scrapy.Spider):
    name = 'lagou'
    allowed_domains = ['https://www.lagou.com']
    start_urls = ['http://https://www.lagou.com/']

    def parse(self, response):
        if response.status==200:
            items=response.css('ul .con_list_item')
            data=LagouItem()
            for item in items:
                data['position']=item.css('.p_top .position_link h3::text').extract_first()
                data['company']=item.css('.company_name a::text').extract_first()
                data['sadd']=item.css('.p_top .add em::text').extract_first()
                data['salary']=item.css('.li_b_l .money::text').extract_first()
                data['claim']=item.css('.p_bot .li_b_l::text').extract()[-1].strip()
                # data['tags']=item.css('.list_item_bot .li_b_l span::text').extract()
                data['joburl']=item.css('.p_top .position_link::attr(href)').extract_first()
                yield data

    def start_requests(self):
        for page in range(3,settings.MAX_PAGE+1):
            url='https://www.lagou.com/jobs/list_%s?city=%s&cl=false&fromSearch=true'%(settings.KEY,settings.CITY)   #输入uid
            yield scrapy.Request(url=url,callback=self.parse,meta={'page':page},dont_filter=True)


import curses
import curses.ascii
from curses.textpad import Textbox

class MyTextPad(Textbox):
    ignored_keys = {
        curses.KEY_PPAGE,  # Page Up
        curses.KEY_NPAGE,  # Page Down
    }

    def __init__(self, win, default):
        super().__init__(win)

        self.default = default
        self.line = default
        self._pos = len(default)
        self.refresh()

    @property
    def pos(self):
        return self._pos

    @pos.setter
    def pos(self, val):
        self._pos = val
        if self._pos < 0:
            self._pos = 0
        if self._pos > len(self.line):
            self._pos = len(self.line)

    @property
    def cursor_pos(self):
        y = self.pos // self.maxx
        x = self.pos % self.maxx

        return y, x

    def refresh(self):
        self.win.clear()
        for y in range(self.maxy):
            self.win.addstr(y, 0, self.line[self.maxx * y:self.maxx * (y + 1)])
        self.win.move(*self.cursor_pos)
        self.win.refresh()

    def do_command(self, ch):
        ordch = ord(ch) if isinstance(ch, str) else ch
        ch = chr(ch) if isinstance(ch, int) else ch

        if curses.KEY_BACKSPACE == ordch:
            self.line = self.line[:self.pos -1] + self.line[self.pos:]
            self.pos -= 1
        elif curses.KEY_LEFT == ordch:
            self.pos -= 1
        elif curses.KEY_RIGHT == ordch:
            self.pos += 1
        elif curses.KEY_DOWN == ordch:
            self.pos += self.maxx
        elif curses.KEY_DC == ordch:
            self.line = self.line[:self.pos] + self.line[self.pos + 1:]
        elif curses.KEY_UP == ordch:
            self.pos -= self.maxx
        elif curses.KEY_HOME == ordch:
            self.pos = 0
        elif curses.KEY_END == ordch:
            self.pos = len(self.line)
        elif ordch in self.ignored_keys:
            pass
        elif '\n' == ch:
                return 0
        elif 27 == ordch:
            return -1
        elif ch.isprintable():
            self.line = self.line[:self.pos] + ch + self.line[self.pos:]
            self.pos += 1

        return True

    def gather(self):
        return self.line.strip()

    def edit(self, validate=None):
        while 1:
            ch = self.win.get_wch()

            if validate:
                ch = validate(ch)

            if not ch:
                continue

            code = self.do_command(ch)

            if code == -1:
                return self.default

            if not code:
                break

            self.refresh()
        return self.gather()


# coding: utf-8

import json
import os

import click
import gql
import graphql
import requests

from gql.transport.requests import RequestsHTTPTransport

try:
    # python2
    from urlparse import urlparse
except ImportError:
    # python3
    from urllib.parse import urlparse

class SchemaSourceType(click.ParamType):
    name = 'schema_source'

    def __init__(self, authenvvar=None, **kwargs):
        self.authenvvar = authenvvar
        return super().__init__(**kwargs)

    def convert_from_url(self, value, param, ctx):

        headers = {}
        if self.authenvvar is not None:
            headers['Authorization'] = os.environ.get(self.authenvvar)

        try:
            client = gql.Client(
                transport=RequestsHTTPTransport(
                    url=value, headers=headers, use_json=True,
                ),
                fetch_schema_from_transport=True,
            )
        except requests.exceptions.HTTPError as e:
            m = str(e)
            if self.authenvvar is not None and e.response.status_code == 401:
                m += ' : Try setting %s in the environment.' % self.authenvvar
            self.fail(m, param=param, ctx=ctx)
        except (
                requests.exceptions.ConnectionError,
                requests.exceptions.Timeout,
                requests.exceptions.RequestException
        ) as e:
            self.fail(e, param=param, ctx=ctx)

        return client.schema

    def convert_from_file(self, value, param, ctx):
        f = click.File('r').convert(value, param, ctx)

        try:
            introspection = json.load(f)['data']
            schema = graphql.build_client_schema(introspection)
        except (ValueError, KeyError) as e:
            self.fail(
                'File content is not valid a graphql schema %s.' % e,
                param=param, ctx=ctx
            )

        return schema

    def convert(self, value, param, ctx):

        parsedurl = urlparse(value)

        if parsedurl.scheme and parsedurl.netloc:
            schema = self.convert_from_url(value, param, ctx)
        else:
            schema = self.convert_from_file(value, param, ctx)

        return schema

SCHEMA_SOURCE = SchemaSourceType()


a = []
sum = 0

for i in range(9):
    a.append(int(input()))
    sum += a[i]

a = sorted(a)
i = 0

while i < 9:
    sum -= a[i]
    j = 0

    while j < 9:
        if i != j and sum - a[j] == 100:
            break
        j += 1

    if j < 9:
        break

    sum += a[i]
    i += 1

for k in range(9):
    if k != i and k != j:
        print(a[k])


'''
Arbitrary parameters that matter a surprising amount for making photometry
reasonably good.
'''

__all__ = ['thresh', 'fwhm', 'radius', 'annuli_r']

# Thresholds for source identification after bias & flat fielding.
# These must be low enough to catch good comparison stars. Too high, and
# astrometry gets confused.
thresh = {'g':600, 'r':1700, 'i':2200, 'z':1100}

# FWHM for star finder. Set by coarsely measuring off ds9 images.
fwhm =   {'g':14, 'r':14, 'i':14, 'z':12}

# Radii for aperture photometry. Hand-measured.
radius = {'g':18, 'r':15, 'i':15, 'z':17}
annuli_r = {'g':[21,24], 'r':[20,24], 'i':[20,24], 'z':[20,23]}

# MANUAL CHOOSING: best for r: 8, i: (5 or 8, not sure)
N_comp_stars = {'r':8, 'i':5, 'g':6, 'z':6}


#!/usr/bin/env python3

DEBUG = False
def debug_print(s):
    print(s)

def check(s):
    """Returns two booleans, the first is whether there are character twins.  The second is whether there are character triplets."""
    t = sorted(s)
    t.append("\n")
    has_twins = False
    has_triplets = False
    run_count = 1
    prev = None
    for x in t:
        if x == prev:
            run_count = run_count + 1
        else:
            if run_count == 2:
                has_twins = True
            elif run_count == 3:
                has_triplets = True
            run_count = 1
            prev = x
        prev = x

    debug_print("{}:    {} {}".format(s, has_twins, has_triplets))
    return has_twins, has_triplets

twins_count = 0
triplets_count = 0
with open("input.txt") as the_file:
    for line in the_file:
        s = line.strip()
        has_twins, has_triplets = check(s)
        if has_twins: twins_count = twins_count + 1
        if has_triplets: triplets_count = triplets_count + 1

print(twins_count * triplets_count)


import datetime
import os
import re
import urllib.parse

from itertools import groupby

from django import forms as django_forms

from django.conf import settings
from django.core.paginator import Paginator, InvalidPage
from django import urls
from django.forms import fields
from django.http import HttpResponse, HttpResponseNotFound, Http404, \
    HttpResponseRedirect, HttpResponsePermanentRedirect
from django.shortcuts import render
from django.shortcuts import get_object_or_404
from django.template import RequestContext
from django.template.defaultfilters import filesizeformat
from django.utils import html
from django.views.decorators.vary import vary_on_headers

from core.utils.url import unpack_url_path
from core import models
from core import solr_index
from core.rdf import title_to_graph, issue_to_graph, page_to_graph

from core.utils.utils import HTMLCalendar, _get_tip, _stream_file, \
    _page_range_short, _rdf_base, get_page, label, create_crumbs
from core.decorator import cache_page, rdf_view

@cache_page(settings.DEFAULT_TTL_SECONDS)
def issues(request, year=None):
    issues = models.Issue.objects.all().order_by('date_issued')
    year_view, select_year_form = _create_year_form(issues, year, True)
    page_title = "Browse All Issues"
    page_name = "issues"
    crumbs = list(settings.BASE_CRUMBS)
    return render(request, 'issues.html', locals())

@cache_page(settings.DEFAULT_TTL_SECONDS)
def issues_title(request, lccn, year=None):
    title = get_object_or_404(models.Title, lccn=lccn)
    issues = title.issues.all()
    year_view, select_year_form = _create_year_form(issues, year, False)
    page_title = "Browse Issues: %s" % title.display_name
    page_name = "issues_title"
    crumbs = create_crumbs(title)
    return render(request, 'issues_title.html', locals())

@cache_page(settings.DEFAULT_TTL_SECONDS)
def title_holdings(request, lccn):
    title = get_object_or_404(models.Title, lccn=lccn)
    page_title = "Libraries that Have It: %s" % label(title)
    page_name = "holdings"
    crumbs = create_crumbs(title)

    holdings = title.holdings.select_related('institution').order_by('institution__name')

    return render(request, 'holdings.html', locals())

@cache_page(settings.DEFAULT_TTL_SECONDS)
def title_marc(request, lccn):
    title = get_object_or_404(models.Title, lccn=lccn)
    page_title = "MARC Bibliographic Record: %s" % label(title)
    page_name = "marc"
    crumbs = create_crumbs(title)
    return render(request, 'marc.html', locals())

@cache_page(settings.DEFAULT_TTL_SECONDS)
@rdf_view
def title_rdf(request, lccn):
    title = get_object_or_404(models.Title, lccn=lccn)
    graph = title_to_graph(title)
    response = HttpResponse(graph.serialize(base=_rdf_base(request),
                                            include_base=True),
                            content_type='application/rdf+xml')
    return response

@cache_page(settings.DEFAULT_TTL_SECONDS)
def title_atom(request, lccn, page_number=1):
    title = get_object_or_404(models.Title, lccn=lccn)
    issues = title.issues.all().order_by('-batch__created', '-date_issued')
    paginator = Paginator(issues, 100)
    try:
        page = paginator.page(page_number)
    except InvalidPage:
        raise Http404("No such page %s for title feed" % page_number)

    # figure out the time the title was most recently updated
    # via the create date of the batch
    issues = page.object_list
    num_issues = issues.count()
    if num_issues > 0:
        feed_updated = issues[0].batch.created
    else:
        feed_updated = title.created

    host = request.get_host()
    return render(request, 'title.xml', locals(),
                  content_type='application/atom+xml')

@cache_page(settings.DEFAULT_TTL_SECONDS)
def title_marcxml(request, lccn):
    title = get_object_or_404(models.Title, lccn=lccn)
    return HttpResponse(title.marc.xml, content_type='application/marc+xml')

@cache_page(settings.DEFAULT_TTL_SECONDS)
def issue_pages(request, lccn, date, edition, page_number=1):
    title = get_object_or_404(models.Title, lccn=lccn)
    _year, _month, _day = date.split("-")
    try:
        _date = datetime.date(int(_year), int(_month), int(_day))
    except ValueError as e:
        raise Http404
    try:
        issue = title.issues.filter(date_issued=_date,
                                    edition=edition).order_by("-created")[0]
    except IndexError as e:
        raise Http404
    issue_pages = []
    for page in issue.pages.all():
        # include both issue and page because of how metadata
        # is being pulled in the template
        issue_pages.append({'issue': issue, 'page': page})
    paginator = Paginator(issue_pages, 20)
    try:
        page = paginator.page(page_number)
    except InvalidPage:
        page = paginator.page(1)
    page_range_short = list(_page_range_short(paginator, page))

    # set page number variables
    if page.has_previous():
        previous_page_number = int(page_number) - 1
    if page.has_next():
        next_page_number = int(page_number) + 1

    if not page.object_list:
        notes = issue.notes.filter(type="noteAboutReproduction")
        num_notes = notes.count()
        if num_notes >= 1:
            display_label = notes[0].label
            explanation = notes[0].text
    page_title = 'All Pages: %s, %s' % (label(title), label(issue))
    page_head_heading = "All Pages: %s, %s" % (title.display_name, label(issue))
    page_head_subheading = label(title)
    crumbs = create_crumbs(title, issue, date, edition)
    response = render(request, 'issue_pages.html', locals())
    return response

@cache_page(settings.DEFAULT_TTL_SECONDS)
@rdf_view
def issue_pages_rdf(request, lccn, date, edition):
    title, issue, page = _get_tip(lccn, date, edition)
    graph = issue_to_graph(issue)
    response = HttpResponse(graph.serialize(base=_rdf_base(request),
                                            include_base=True),
                            content_type='application/rdf+xml')
    return response

@cache_page(settings.DEFAULT_TTL_SECONDS)
@vary_on_headers('Referer')
def page(request, lccn, date, edition, sequence, words=None):
    fragments = []
    if words:
        fragments.append("words=" + words)
    qs = request.META.get('QUERY_STRING')
    if qs:
        fragments.append(qs)
    if fragments:
        path_parts = dict(lccn=lccn, date=date, edition=edition,
                          sequence=sequence)
        url = urls.reverse('openoni_page',
                                   kwargs=path_parts)

        return HttpResponseRedirect(url + "#" + "&".join(fragments))

    title, issue, page = _get_tip(lccn, date, edition, sequence)

    if not page.jp2_filename:
        notes = page.notes.filter(type="noteAboutReproduction")
        num_notes = notes.count()
        if num_notes >= 1:
            explanation = notes[0].text
        else:
            explanation = ""

    # if no word highlights were requests, see if the user came
    # from search engine results and attempt to highlight words from their
    # query by redirecting to a url that has the highlighted words in it
    if not words:
        try:
            words = _search_engine_words(request)
            words = '+'.join(words)
            if len(words) > 0:
                path_parts = dict(lccn=lccn, date=date, edition=edition,
                                  sequence=sequence, words=words)
                url = urls.reverse('openoni_page_words',
                                           kwargs=path_parts)
                return HttpResponseRedirect(url)
        except Exception as e:
            if settings.DEBUG:
                raise e
            # else squish the exception so the page will still get
            # served up minus the highlights

    # Calculate the previous_issue_first_page. Note: it was decided
    # that we want to skip over issues with missing pages. See ticket
    # #383.
    _issue = issue
    while True:
        previous_issue_first_page = None
        _issue = _issue.previous
        if not _issue:
            break
        previous_issue_first_page = _issue.first_page
        if previous_issue_first_page:
            break

    # do the same as above but for next_issue this time.
    _issue = issue
    while True:
        next_issue_first_page = None
        _issue = _issue.next
        if not _issue:
            break
        next_issue_first_page = _issue.first_page
        if next_issue_first_page:
            break

    page_title = "%s, %s, %s" % (label(title), label(issue), label(page))
    page_head_heading = "%s, %s, %s" % (title.display_name, label(issue), label(page))
    page_head_subheading = label(title)
    crumbs = create_crumbs(title, issue, date, edition, page)

    filename = page.jp2_abs_filename
    if filename:
        try:
            im = os.path.getsize(filename)
            image_size = filesizeformat(im)
        except OSError:
            image_size = "Unknown"

    image_credit = issue.batch.awardee.name
    host = request.get_host()
    static_url = settings.STATIC_URL

    template = "page.html"
    response = render(request, template, locals())
    return response

@cache_page(settings.DEFAULT_TTL_SECONDS)
def titles(request, start=None, page_number=1):
    page_title = 'Newspaper Titles'
    if start:
        page_title += ' Starting With %s' % start
        titles = models.Title.objects.order_by('name_normal')
        titles = titles.filter(name_normal__istartswith=start.upper())
    else:
        titles = models.Title.objects.all().order_by('name_normal')
    paginator = Paginator(titles, 50)
    try:
        page = paginator.page(page_number)
    except InvalidPage:
        page = paginator.page(1)
    page_start = page.start_index()
    page_end = page.end_index()
    page_range_short = list(_page_range_short(paginator, page))
    browse_val = [chr(n) for n in range(65, 91)]
    browse_val.extend([str(i) for i in range(10)])
    collapse_search_tab = True
    crumbs = list(settings.BASE_CRUMBS)
    return render(request, 'titles.html', locals())

@cache_page(settings.DEFAULT_TTL_SECONDS)
def title(request, lccn):
    title = get_object_or_404(models.Title, lccn=lccn)
    page_title = label(title)
    page_name = "title"
    # we call these here, because the query the db, they are not
    # cached by django's ORM, and we have some conditional logic
    # in the template that would result in them getting called more
    # than once. Short story: minimize database hits...
    related_titles = title.related_titles()
    succeeding_titles = title.succeeding_titles()
    preceeding_titles = title.preceeding_titles()
    notes = []
    has_external_link = False
    for note in title.notes.all():
        org_text = html.escape(note.text)
        text = re.sub('(http(s)?://[^\s]+[^\.])',
                      r'\1', org_text)
        if text != org_text:
            has_external_link = True
        notes.append(text)

    if title.has_issues:
        rep_notes = title.first_issue.notes.filter(type="noteAboutReproduction")
        num_notes = rep_notes.count()
        if num_notes >= 1:
            explanation = rep_notes[0].text

    first_issue = title.first_issue
    if first_issue:
        issue_date = first_issue.date_issued

    # add essay info on this page from either the database or from a template
    first_essay = title.first_essay
    essay_template = os.path.join(settings.ESSAY_TEMPLATES, title.lccn+".html")

    crumbs = create_crumbs(title)
    response = render(request, 'title.html', locals())
    return response

@cache_page(settings.DEFAULT_TTL_SECONDS)
def titles_in_city(request, state, county, city,
                   page_number=1, order='name_normal'):
    state, county, city = list(map(unpack_url_path, (state, county, city)))
    page_title = "Titles in City: %s, %s" % (city, state)
    titles = models.Title.objects.all()
    if city:
        titles = titles.filter(places__city__iexact=city)
    if county:
        titles = titles.filter(places__county__iexact=county)
    if state:
        titles = titles.filter(places__state__iexact=state)
    titles = titles.order_by(order)
    titles.distinct()

    if titles.count() == 0:
        raise Http404

    paginator = Paginator(titles, 50)
    try:
        page = paginator.page(page_number)
    except InvalidPage:
        page = paginator.page(1)
    page_range_short = list(_page_range_short(paginator, page))

    return render(request, 'reports/city.html', locals())

@cache_page(settings.DEFAULT_TTL_SECONDS)
def titles_in_county(request, state, county,
                     page_number=1, order='name_normal'):
    state, county = list(map(unpack_url_path, (state, county)))
    page_title = "Titles in County: %s, %s" % (county, state)
    titles = models.Title.objects.all()
    if county:
        titles = titles.filter(places__county__iexact=county)
    if state:
        titles = titles.filter(places__state__iexact=state)
    titles = titles.order_by(order)
    titles = titles.distinct()

    if titles.count() == 0:
        raise Http404

    paginator = Paginator(titles, 50)
    try:
        page = paginator.page(page_number)
    except InvalidPage:
        page = paginator.page(1)
    page_range_short = list(_page_range_short(paginator, page))

    return render(request, 'reports/county.html', locals())

@cache_page(settings.DEFAULT_TTL_SECONDS)
def titles_in_state(request, state, page_number=1, order='name_normal'):
    state = unpack_url_path(state)
    page_title = "Titles in State: %s" % state
    titles = models.Title.objects.all()
    if state:
        titles = titles.filter(places__state__iexact=state)
    titles = titles.order_by(order)
    titles = titles.distinct()

    if titles.count() == 0:
        raise Http404

    paginator = Paginator(titles, 50)
    try:
        page = paginator.page(page_number)
    except InvalidPage:
        page = paginator.page(1)
    page_range_short = list(_page_range_short(paginator, page))

    return render(request, 'reports/state.html', locals())

# TODO: this redirect can go away some suitable time after 08/2010
# it predates having explicit essay ids
@cache_page(settings.DEFAULT_TTL_SECONDS)
def title_essays(request, lccn):
    title = get_object_or_404(models.Title, lccn=lccn)
    # if there's only one essay might as well redirect to it
    if len(title.essays.all()) >= 1:
        url = title.essays.all()[0].url
        return HttpResponsePermanentRedirect(url)
    else:
        return HttpResponseNotFound()

def _create_year_form(issues, year, all_issues):
    if issues.count() > 0:
        if year is None:
            _year = issues[0].date_issued.year
        else:
            _year = int(year)
    else:
        _year = 1900 # no issues available
    year_view = HTMLCalendar(firstweekday=6, issues=issues, all_issues=all_issues).formatyear(_year)
    dates = issues.dates('date_issued', 'year')

    class SelectYearForm(django_forms.Form):
        year = fields.ChoiceField(choices=((d.year, d.year) for d in dates), initial=_year)
        year.widget.attrs["class"] = "form-select w-auto d-inline-block"

    return year_view, SelectYearForm()

def _search_engine_words(request):
    """
    Inspects the http request and returns a list of words from the OCR
    text relevant to a particular search engine query. If the
    request didn't come via a search engine result an empty list is
    returned.
    """
    # get the refering url
    referer = request.META.get('HTTP_REFERER')
    if not referer:
        return []
    uri = urllib.parse.urlparse(referer)
    qs = urllib.parse.parse_qs(uri.query)

    # extract a potential search query from refering url
    if 'q' in qs:
        words = qs['q'][0]
    elif 'p' in qs:
        words = qs['p'][0]
    else:
        return []

    # ask solr for the pre-analysis words that could potentially
    # match on the page. For example if we feed in 'buildings' we could get
    # ['building', 'buildings', 'BUILDING', 'Buildings'] depending
    # on the actual OCR for the page id that is passed in
    words = words.split(' ')
    words = solr_index.word_matches_for_page(request.path, words)
    return words

@cache_page(settings.DEFAULT_TTL_SECONDS)
def page_ocr(request, lccn, date, edition, sequence):
    title, issue, page = _get_tip(lccn, date, edition, sequence)
    page_title = "%s, %s, %s" % (label(title), label(issue), label(page))
    crumbs = create_crumbs(title, issue, date, edition, page)
    host = request.get_host()
    return render(request, 'page_text.html', locals())

def page_pdf(request, lccn, date, edition, sequence):
    title, issue, page = _get_tip(lccn, date, edition, sequence)
    return _stream_file(page.pdf_abs_filename, 'application/pdf')

def page_jp2(request, lccn, date, edition, sequence):
    title, issue, page = _get_tip(lccn, date, edition, sequence)
    return _stream_file(page.jp2_abs_filename, 'image/jp2')

def page_ocr_xml(request, lccn, date, edition, sequence):
    title, issue, page = _get_tip(lccn, date, edition, sequence)
    return _stream_file(page.ocr_abs_filename, 'application/xml')

def page_ocr_txt(request, lccn, date, edition, sequence):
    title, issue, page = _get_tip(lccn, date, edition, sequence)
    try:
        text = page.ocr.text
        return HttpResponse(text, content_type='text/plain')
    except models.OCR.DoesNotExist:
        raise Http404("No OCR for %s" % page)

@cache_page(settings.DEFAULT_TTL_SECONDS)
@rdf_view
def page_rdf(request, lccn, date, edition, sequence):
    page = get_page(lccn, date, edition, sequence)
    graph = page_to_graph(page)
    response = HttpResponse(graph.serialize(base=_rdf_base(request),
                                            include_base=True),
                            content_type='application/rdf+xml')
    return response

@cache_page(settings.DEFAULT_TTL_SECONDS)
def page_print(request, lccn, date, edition, sequence,
               width, height, x1, y1, x2, y2):
    page = get_page(lccn, date, edition, sequence)
    title = get_object_or_404(models.Title, lccn=lccn)
    issue = page.issue
    page_title = "%s, %s, %s" % (label(title), label(issue), label(page))
    crumbs = create_crumbs(title, issue, date, edition, page)
    host = request.get_host()
    image_credit = page.issue.batch.awardee.name
    path_parts = dict(lccn=lccn, date=date, edition=edition,
                      sequence=sequence,
                      width=width, height=height,
                      x1=x1, y1=y1, x2=x2, y2=y2)
    url = urls.reverse('openoni_page_print',
                               kwargs=path_parts)

    return render(request, 'page_print.html', locals())

@cache_page(settings.DEFAULT_TTL_SECONDS)
def issues_first_pages(request, lccn, page_number=1):
    title = get_object_or_404(models.Title, lccn=lccn)
    issues = title.issues.all()
    if not issues.count() > 0:
        raise Http404("No issues for %s" % title.display_name)

    first_pages = []
    for issue in issues:
        # include both issue and page because in some cases
        # an issue exists which has no associated pages
        first_pages.append({'issue': issue, 'page': issue.first_page})

    paginator = Paginator(first_pages, 20)
    try:
        page = paginator.page(page_number)
    except InvalidPage:
        page = paginator.page(1)
    page_range_short = list(_page_range_short(paginator, page))

    # set page number variables
    if page.has_previous():
        previous_page_number = int(page_number) - 1
    if page.has_next():
        next_page_number = int(page_number) + 1

    page_title = 'Browse Issues: %s' % label(title)
    page_head_heading = "Browse Issues: %s" % title.display_name
    page_head_subheading = label(title)
    crumbs = create_crumbs(title)
    return render(request, 'issue_pages.html', locals())


__author__ = 'ravi'
from pprint import pprint

def get_word_count(file_name):
    content = {}

    for line in open(file_name):
        for word in line.rstrip().split(' '):
            content[word] = content.get(word, 0) + 1

    return content

words = get_word_count('mesg')
pprint(words)


# https://www.codewars.com/kata/558d5c71c68d1e86b000010f

from itertools import product as P
from collections import Counter
# precompute
vampires = []

for L in (2,3):
    G = [range(0,10) for _ in range(L)]
    limit1 = 10**(2*L-1)
    limit2 = 10**L**2-1
    for a,b in P(P(*G), P(*G)):
        p = int(''.join(map(str,a))) * int(''.join(map(str,b)))
        if limit1 < p < limit2 and Counter(str(p)) == Counter(map(str,a+b)) and a[-1]+b[-1] != 0:
            vampires.append(p)
vampires = sorted(list(set(vampires)))

def vampire_number(k):
    return vampires[k-1]

# clever
is_vampire = lambda x, y: sorted(f"{x}{y}") == sorted(f"{x*y}") and x%10 + y%10 > 0
vampires = sorted({x*y for p in (1, 2) for x in range(10**p, 10**(p+1)) for y in range(x, 10**(p+1)) if is_vampire(x, y)})

# ya clever
vampires = set()
for i in [1, 2]:
    for x, y in combinations(range(10**i, 10**(i+1)), 2):
        if x % 10 == 0 == y % 10:
            continue
        z = x * y
        if sorted(str(z)) == sorted(f'{x}{y}'):
            vampires.add(z)
xs = sorted(vampires)


# -*- coding:utf-8 -*-
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None
class Solution:
    def FindFirstCommonNode(self, pHead1, pHead2):
        # write code here
        stck1 = []
        stck2 = []
        h1,h2 = pHead1,pHead2
        while h1:
            stck1.append(h1)
            h1 = h1.next
        while h2:
            stck2.append(h2)
            h2 = h2.next
        cur = None
        while stck1 and stck2:
            if stck1.pop() == stck2[-1]:
                cur = stck2.pop()
            else:
                return cur
        return cur


import unittest
from KPIAlgebras.response_objects import response_objects
from KPIAlgebras.request_objects import request_objects

class TestResponseObjects(unittest.TestCase):
    def test_response_sucess_is_true(self):
        value = "test"
        response_sucess = response_objects.ResponseSuccess(value)
        self.assertTrue(bool(response_sucess))

    def test_response_success_has_type_and_value(self):
        value = "test"
        response_success = response_objects.ResponseSuccess(value)
        self.assertEquals(response_success.value, value)
        self.assertEquals(response_success.type, response_objects.ResponseSuccess.SUCCESS)

    def test_response_failure_is_false(self):
        type = 'test)type'
        message = 'test_message'
        response_failure = response_objects.ResponseFailure(type, message)
        self.assertFalse(bool(response_failure))

    def test_response_failure_has_type_and_message(self):
        type = 'parameterserror'
        message = 'test_message'
        response_failure = response_objects.ResponseFailure(type, message)
        self.assertEquals(response_failure.type, type)
        self.assertEquals(response_failure.message, message)

    def test_response_failure_has_value(self):
        type = 'parameterserror'
        message = 'test_message'
        response_failure = response_objects.ResponseFailure(type, message)
        self.assertDictEqual(response_failure.value, {'type': type, 'message':message})

    def test_response_failure_build_from_invalid_request(self):
        invalid_request = request_objects.InvalidRequestObject()
        response_failure = response_objects.ResponseFailure.build_from_invalid_request(invalid_request)
        self.assertFalse(bool(response_failure))
        self.assertEquals(response_failure.type, response_objects.ResponseFailure.PARAMETERS_ERROR)

    def test_response_failure_build_from_invalid_request_with_errors(self):
        invalid_request = request_objects.InvalidRequestObject()
        invalid_request.add_error("Target Node", 'is missing')
        invalid_request.add_error("Delta", 'is missing')
        response_failure = response_objects.ResponseFailure.build_from_invalid_request(invalid_request)
        self.assertFalse(bool(response_failure))
        self.assertEquals(response_failure.type, response_objects.ResponseFailure.PARAMETERS_ERROR)
        self.assertEquals(response_failure.message, "Target Node: is missing\nDelta: is missing")


# Import libraries
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
import missingno as msno
from _datetime import date
from sklearn.metrics import accuracy_score
from sklearn.model_selection import train_test_split
from sklearn.neighbors import LocalOutlierFactor
from sklearn.preprocessing import MinMaxScaler, LabelEncoder, StandardScaler, RobustScaler

pd.set_option('display.max_columns', None)
pd.set_option('display.max_rows', None)
pd.set_option('display.float_format', lambda x: '%.3f' % x)
pd.set_option('display.width', 500)

# Import the dataset for the small-scale applications
def load():
    data = pd.read_csv('01_miuul_machine_learning_summercamp/00_datasets/titanic.csv')
    data.columns = [col.lower() for col in data.columns]
    return data

df = load()
df.head()

##############################
# Standard scaler
##############################
ss = StandardScaler()
df['age_standard_scaler'] = ss.fit_transform(df[['age']])
df.head()

##############################
# Robust scaler
##############################
rs = RobustScaler()
df['age_robust_scaler'] = rs.fit_transform(df[['age']])
df.head()

##############################
# MinMax scaler
##############################
mms = MinMaxScaler()
df['age_min_max_scaler'] = mms.fit_transform(df[['age']])
df.head()
df.describe().T

##############################
# Getting num_summary function
##############################
def num_summary(dataframe, col_name, plot=False):
    """
    for col in num_cols:
        print(f'\n***************-{col.upper()}-***************')
        num_summary(df, col, plot=False)
    """
    quantiles = [0.05, 0.25, 0.50, 0.75, 0.90, 0.95, 0.99]
    print(dataframe[col_name].describe(quantiles).T)

    if plot:
        plt.figure(figsize=(12, 6))
        plt.subplot(1, 2, 1)
        sns.boxplot(y=dataframe[col_name], data=dataframe)
        plt.subplot(1, 2, 2)
        sns.histplot(x=dataframe[col_name], data=dataframe)
        plt.show(block=True)

age_cols = [col for col in df.columns if 'age' in col]
for col in age_cols:
    print(f'\n***************-{col.upper()}-***************')
    num_summary(df, col, plot=True)

##############################
# Converting numerical variables to categorical variables
##############################
df['age_qcut'] = pd.qcut(df.age, 5)
df.head()

df['age_cut'] = pd.cut(df.age, bins=[0, 18, 25, 45, 60, 100], labels=['0_18', '19_25', '26_45', '46_60', '61_100'])
df.head()