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

MIN_SIZE = 1000
MIN_THOLD = 60

class Camera:
    def __init__(self, camera):
        self._cam = cv.CaptureFromCAM(camera)

    def calibrate(self):
        cv.NamedWindow('calibration')
        while True:
            f = cv.QueryFrame(self._cam)
            red = self.getRedChannel(f)
            seq = cv.FindContours(red,
                cv.CreateMemStorage(0),
                cv.CV_RETR_EXTERNAL,
                cv.CV_CHAIN_APPROX_SIMPLE)
            while seq:
                size = abs(cv.ContourArea(seq))
                if size > MIN_SIZE:
                    bb = cv.BoundingRect(seq, 0)
                    center = (bb[0]+bb[2]/2, bb[1]+bb[3]/2)
                    cv.Circle(f, center, 10, cv.Scalar(0,255,0))
                seq = seq.h_next()
            cv.ShowImage('calibration', f)
            cv.WaitKey(33)

    def getRedChannel(self, image):
        chR = cv.CreateImage(cv.GetSize(image), 8, 1)
        chG = cv.CreateImage(cv.GetSize(image), 8, 1)
        chB = cv.CreateImage(cv.GetSize(image), 8, 1)
        cv.Split(image, chB, chG, chR, None)
        cv.Add(chB, chG, chG);
        cv.Sub(chR, chG, chR);
        cv.Threshold(chR, chR, MIN_THOLD, 255, cv.CV_THRESH_BINARY)
        return chR

    def getCoords(self):
        f = cv.QueryFrame(self._cam)
        seq = cv.FindContours(red,
            cv.CreateMemStorage(0),
            cv.CV_RETR_EXTERNAL,
            cv.CV_CHAIN_APPROX_SIMPLE)
        while seq:
            size = abs(cv.ContourArea(seq))
            if size > MIN_SIZE:
                bb = cv.BoundingRect(seq, 0)
                center = (bb[0]+bb[2]/2, bb[1]+bb[3]/2)
                yield center
            seq = seq.h_next()

    def getSize(self):
        height = cv.GetCaptureProperty(self._cam, cv.CV_CAP_PROP_FRAME_HEIGHT)
        width = cv.GetCaptureProperty(self._cam, cv.CV_CAP_PROP_FRAME_WIDTH)
        return (width, height)

class Disposition:
    def __init__(self, camera):
        self._cam = Camera(camera)
        self._size = self._cam.getSize()

    def getRelativeCoords(self):
        coords = []
        for pos in self._c.getCoords():
            Rx = pos[0] / self._size[0]
            Ry = pos[1] / self._size[1]
            coords.append((Rx, Ry))
        return coords

    def test(self):
        if len(self.getRelativeCoords()) != 3:
            return True
        return False


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

import os
import sys

try:
    from setuptools import setup
except ImportError:
    from distutils.core import setup

if sys.argv[-1] == 'publish':
    os.system('python setup.py sdist upload')
    sys.exit()

readme = open('README.rst').read()

setup(
    name='spectral',
    version='0.2.0',
    description=('Python package for extracing spectral features from speech.'),
    long_description=readme,
    author='Maarten Versteegh',
    author_email='maartenversteegh@gmail.com',
    url='https://github.com/mwv/spectral',
    packages=[
        'spectral',
    ],
    package_dir={'spectral': 'spectral'},
    include_package_data=True,
    install_requires=['numpy>=1.6.2', 'scipy'],
    license="GPL",
    zip_safe=False,
    keywords='spectral',
    classifiers=[
        'Development Status :: 2 - Pre-Alpha',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: BSD License',
        'Natural Language :: English',
        "Programming Language :: Python :: 2",
        'Programming Language :: Python :: 2.6',
        'Programming Language :: Python :: 2.7',
        'Programming Language :: Python :: 3',
        'Programming Language :: Python :: 3.3',
    ],
)


import cv2
import base64
import tensorflow as tf
import numpy as np

def prep_points(boxes):
    all_points_boxes = []
    for box in boxes:
        curr_box = []
        box_list =  list(box.items());
        for i in range(4):
            label_x, point_x = box_list[i * 2]
            label_y, point_y = box_list[(i * 2) + 1]
            point = (int(point_x), int(point_y))
            curr_box.append(point)

        all_points_boxes.append(curr_box)

    return (all_points_boxes)

def bb_intersection_over_union(boxA, boxB):
    _, boxA_top_left_y = boxA[0];
    _, boxA_bottom_right_y = boxA[1];

    _, boxB_top_left_y = boxB[0];
    _, boxB_bottom_right_y = boxB[1];

    inter_top_left_y = max(boxA_top_left_y, boxB_top_left_y)
    inter_bottom_right_y = min(boxA_bottom_right_y, boxB_bottom_right_y)
    interArea = max(0, inter_bottom_right_y - inter_top_left_y)

    boxAArea = (boxA_bottom_right_y - boxA_top_left_y)
    boxBArea = (boxB_bottom_right_y - boxB_top_left_y)

    # compute the intersection over union by taking the intersection
    # area and dividing it by the sum of prediction + ground-truth
    # areas - the interesection area
    iou = interArea / float(boxAArea + boxBArea - interArea)

    # return the intersection over union value
    return iou

def foramt_4_points_bb_to_2_points_bb(bounding_box):
    aX, aY = bounding_box[0];
    bX, bY = bounding_box[1];
    cX, cY = bounding_box[2];
    dX, dY = bounding_box[3];

    top_left_x = min(aX, bX, cX, dX)
    top_left_y = min(aY, bY, cY, dY)

    bottom_right_x = max(aX, bX, cX, dX)
    bottom_right_y = max(aY, bY, cY, dY)

    return ([(top_left_x, top_left_y), (bottom_right_x, bottom_right_y)])

def IoU_by_y(dishes_list, prices_list):
    l = list();
    for dish in dishes_list:
        best_iou_value = 0;
        best_iou_price = ();

        dish_box = foramt_4_points_bb_to_2_points_bb(dish)

        for price in prices_list:
            price_box = foramt_4_points_bb_to_2_points_bb(price)

            curr_iou = bb_intersection_over_union(dish_box, price_box)

            if (curr_iou > best_iou_value):
                best_iou_value = curr_iou
                best_iou_price = price

        if (best_iou_value > 0):
            l.append({"price": best_iou_price, "dish": dish})

    return l

def IoU_by_y_with_threshold(dishes_list, prices_list):
    l = list();
    for dish in dishes_list:
        all_prices_in_same_row = list()
        best_iou_value = 0;
        best_iou_price = ();

        dish_box = foramt_4_points_bb_to_2_points_bb(dish)

        for price in prices_list:
            price_box = foramt_4_points_bb_to_2_points_bb(price)

            curr_iou = bb_intersection_over_union(dish_box, price_box)

            if (curr_iou >= 0.5):
                all_prices_in_same_row.append(price)

        if (len(all_prices_in_same_row) > 0):
            all_prices_in_same_row = sorted(all_prices_in_same_row, key=lambda curr_price: curr_price[0][0])

            l.append({"price": all_prices_in_same_row[0], "dish": dish})

    return l

def crop_image(img, bounding_box):
    bb_2_points = foramt_4_points_bb_to_2_points_bb(bounding_box)
    Ax, Ay = bb_2_points[0]
    Bx, By = bb_2_points[1]
    cropped_img = img[Ay:By, Ax:Bx]
    return (cropped_img)

def bb_2_points_intersection_over_union(boxA, boxB):
    # determine the (x, y)-coordinates of the intersection rectangle
    xA = max(boxA[0], boxB[0])
    yA = max(boxA[1], boxB[1])
    xB = min(boxA[2], boxB[2])
    yB = min(boxA[3], boxB[3])

    # compute the area of intersection rectangle
    interArea = max(0, xB - xA + 1) * max(0, yB - yA + 1)

    # compute the area of both the prediction and ground-truth
    # rectangles
    boxAArea = (boxA[2] - boxA[0] + 1) * (boxA[3] - boxA[1] + 1)
    boxBArea = (boxB[2] - boxB[0] + 1) * (boxB[3] - boxB[1] + 1)

    # compute the intersection over union by taking the intersection
    # area and dividing it by the sum of prediction + ground-truth
    # areas - the interesection area
    iou = interArea / float(boxAArea + boxBArea - interArea)

    # return the intersection over union value
    return iou

def find_best_contours(img):
    (original_h, original_w, original_z) = img.shape
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    blur = cv2.GaussianBlur(gray, (5, 5), 1)

    if (original_h <= 35):
        th = cv2.adaptiveThreshold(blur, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY_INV, 5, 2)
    else:
        th = cv2.adaptiveThreshold(blur, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY_INV, 15, 3)

    rect_kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (1, original_h))
    th = cv2.morphologyEx(th, cv2.MORPH_CLOSE, rect_kernel)

    contours, hierarchy = cv2.findContours(th, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
    filtered_contours = [];

    for i, cnt in enumerate(contours):
        is_found_bigger = False
        [x_i, y_i, w_i, h_i] = cv2.boundingRect(cnt)

        for j, _ in enumerate(contours):
            [x_j, y_j, w_j, h_j] = cv2.boundingRect(contours[j])
            iou = bb_2_points_intersection_over_union([x_i, y_i, x_i + w_i, y_i + h_i],
                                                      [x_j, y_j, x_j + w_j, h_j + y_j])

            if (iou > 0):
                if (w_i * h_i < w_j * h_j):
                    is_found_bigger = True
                    break

        if not (is_found_bigger):
            filtered_contours.append(contours[i])

    filtered_contours = sorted(filtered_contours, key=lambda cnt: cv2.boundingRect(cnt)[0])
    return filtered_contours

def predict_price_contours(filtered_contours, img, digits_model, graph):
    (original_h, original_w, original_z) = img.shape
    predicted_price = ""
    for cnt in filtered_contours:
        [x, y, w, h] = cv2.boundingRect(cnt)

        if (h < 0.2 * original_h and w < 0.2 * original_w):
            h = int(0.2 * original_h)
            w = int(0.2 * original_w)

        current_digit = img[y:y + h, x:x + w]
        current_digit = cv2.cvtColor(current_digit, cv2.COLOR_BGR2GRAY)
        row, col = current_digit.shape[:2]
        bottom = current_digit[row - 2:row, 0:col]
        mean = cv2.mean(bottom)[0]

        if (original_h <= 35):
            bordersize = 5
        else:
            bordersize = 10

        th = cv2.resize(current_digit, None, fx=2, fy=2)
        th = cv2.adaptiveThreshold(th, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY_INV, 29, 15)

        th = cv2.resize(th, None, fx=0.5, fy=0.5)
        th = cv2.copyMakeBorder(th, top=bordersize, bottom=bordersize, left=bordersize, right=bordersize,
                                borderType=cv2.BORDER_CONSTANT, value=[0, 0, 0])
        th = cv2.resize(th, dsize=(28, 28), interpolation=cv2.INTER_CUBIC)

        colors, counts = np.unique(th.reshape(-1), axis=0, return_counts=True)

        black_ratio = counts[0] / float(28 * 28)
        if (black_ratio >= 0.99):
            continue

        if (h / float(original_h) < 0.5 or black_ratio > 0.90):
            if (predicted_price == "" or "." in predicted_price):
                continue

            predicted_price = predicted_price + "."
            continue

        th = np.reshape(th, newshape=(28, 28, 1))
        img_for_prediction = np.expand_dims(th, axis=0)

        with graph.as_default():
            pred = digits_model.predict(img_for_prediction)[0]

        maximum = np.max(pred)
        predicted_digit = np.where(pred == maximum)[0][0]
        predicted_price = predicted_price + str(predicted_digit)

    return predicted_price

def convert_points_to_images(img, prices_dishes_matches, digits_model, graph):
    ret = list()
    for x in prices_dishes_matches:
        cropped_dish = crop_image(img, x["dish"])
        cropped_price = crop_image(img, x["price"])
        price_contours = find_best_contours(cropped_price)
        price_string = predict_price_contours(price_contours, cropped_price, digits_model, graph)
        _, binframe = cv2.imencode('.jpg', cropped_dish)
        dish_base64 = base64.b64encode(binframe).decode('UTF-8')

        try:
            price_float = float(price_string)
        except ValueError:
            continue

        ret.append({"dish": dish_base64, "price": price_float})
    return ret;

def extract_items(img, dishes, prices, digits_model, graph):
    dishes_points = prep_points(dishes)
    prices_points = prep_points(prices)

    prices_dishes_matches = IoU_by_y_with_threshold(dishes_points, prices_points)
    prices_dishes_matches = sorted(prices_dishes_matches, key=lambda pair: pair["dish"][0][1])

    final_res = convert_points_to_images(img, prices_dishes_matches, digits_model, graph)
    return final_res


import turtle
import random
import math

def goto(x, y):
	turtle.penup()
	turtle.goto(x, y)
	turtle.pendown()

def draw_cir(r, color):
    turtle.fillcolor(color)
    turtle.begin_fill()
    turtle.circle(r)
    turtle.end_fill()

def draw_pistol(x, y):
    PHI = 360 / 7
    R = 50
    goto(x, y)
    turtle.circle(80)
    goto(x, y+160)
    draw_cir(5, 'red')
    for i in range(0, 7):
        phi_rad = PHI * i * math.pi / 180.0
        goto(math.sin(phi_rad) * R+x, math.cos(phi_rad) * R+60+y)
        draw_cir(22, 'white')

def the_game(start, x, y):
    phi = 360 / 7
    r = 50
    for i in range(start, 7+random.randrange(0,7)):
        phi_rad = phi * i * math.pi / 180.0
        goto(math.sin(phi_rad) * r+x, math.cos(phi_rad) * r+60+y)
        draw_cir(22, 'brown')
        draw_cir(22, 'white')

    goto(math.sin(phi_rad) * r+x, math.cos(phi_rad) * r+60+y)
    draw_cir(22, 'brown')

    start = i % 7
    if start % 7 == 0:
        draw_cir(22, 'yellow')
        draw_cir(22, 'white')
        goto(-150, 200)
        turtle.write("Вы проиграли", font=("Arial", 20, "normal"))
    return start

def main():
    X=100
    Y=100
    start = 0
    turtle.speed(0)
    draw_pistol(X, Y)
    answer = ''
    while answer != 'n':
        answer = turtle.textinput("Поиграем?", "y/n")
        if answer == 'y':
            start=the_game(start, X, Y)
        else:
            pass


# 구현
# 연결 리스트

import sys
input = sys.stdin.readline

string = input().rstrip()
N = len(string)

data = [0] * 600001
prev = [-1] * 600001
next = [-1] * 600001
unused = N+1
cursor = N

for i in range(N):
    data[i+1] = string[i]
    next[i] = i+1
    prev[i+1] = i

def delete(cursor):
    next[prev[cursor]] = next[cursor]
    if next[cursor] != -1:
        prev[next[cursor]] = prev[cursor]
    return prev[cursor]

def insert(cursor, value):
    global unused

    data[unused] = value
    prev[unused] = cursor
    next[unused] = next[cursor]

    next[cursor] = unused
    if next[unused] != -1:
        prev[next[unused]] = unused

    unused += 1

    return unused - 1

M = int(input().rstrip())
for _ in range(M):
    command = input().rstrip()

    if command[0] == 'L':
        if cursor != 0:
            cursor = prev[cursor]
    elif command[0] == 'D':
        if next[cursor] != -1:
            cursor = next[cursor]
    elif command[0] == 'B':
        if cursor != 0:
            cursor = delete(cursor)
    else:
        cursor = insert(cursor, command[2])

curr = next[0]
while curr != -1:
    print(data[curr], end='')
    curr = next[curr]


from django import forms
from .models import Order

class OrderCreateForm(forms.ModelForm):
	DIVISION_CHOICES = (
		('North', 'North'),
		('South', 'South'),
		('Central', 'Central'),
	)

	DISCRICT_CHOICES = (
		('Delhi', 'Delhi'),
		('Bangalore', 'Bangalore'),
		('Mumbai', 'Mumbai'),
	)

	PAYMENT_METHOD_CHOICES = (
		('Visa', 'Visa'),
		('MasterCard','MasterCard')
	)

	division = forms.ChoiceField(choices=DIVISION_CHOICES)
	district =  forms.ChoiceField(choices=DISCRICT_CHOICES)
	payment_method = forms.ChoiceField(choices=PAYMENT_METHOD_CHOICES, widget=forms.RadioSelect())

	class Meta:
		model = Order
		fields = ['name', 'email', 'phone', 'address', 'division', 'district', 'zip_code', 'payment_method', 'account_no', 'transaction_id']


#!/usr/bin/python3

import sys
sys.path.append('debian/lib/python')

import fnmatch
import glob
import stat

from debian_linux.abi import Symbols
from debian_linux.config import ConfigCoreDump
from debian_linux.debian import *

class CheckAbi(object):
    class SymbolInfo(object):
        def __init__(self, symbol, symbol_ref=None):
            self.symbol = symbol
            self.symbol_ref = symbol_ref or symbol

        @property
        def module(self):
            return self.symbol.module

        @property
        def name(self):
            return self.symbol.name

        def write(self, out, ignored):
            info = []
            if ignored:
                info.append("ignored")
            for name in ('module', 'version', 'export'):
                data = getattr(self.symbol, name)
                data_ref = getattr(self.symbol_ref, name)
                if data != data_ref:
                    info.append("%s: %s -> %s" % (name, data_ref, data))
                else:
                    info.append("%s: %s" % (name, data))
            out.write("%-48s %s\n" % (self.symbol.name, ", ".join(info)))

    def __init__(self, config, dir, arch, featureset, flavour):
        self.config = config
        self.arch, self.featureset, self.flavour = arch, featureset, flavour

        self.filename_new = "%s/Module.symvers" % dir

        try:
            version_abi = (self.config['version',]['abiname_base'] + '-' +
                           self.config['abi', arch]['abiname'])
        except KeyError:
            version_abi = self.config['version',]['abiname']
        self.filename_ref = "debian/abi/%s/%s_%s_%s" % (version_abi, arch, featureset, flavour)

    def __call__(self, out):
        ret = 0

        new = Symbols(open(self.filename_new))
        unversioned = [name for name in new if new[name].version == '0x00000000']
        if unversioned:
            out.write("ABI is not completely versioned!  Refusing to continue.\n")
            out.write("\nUnversioned symbols:\n")
            for name in sorted(unversioned):
                self.SymbolInfo(new[name]).write(out, False)
            ret = 1

        try:
            ref = Symbols(open(self.filename_ref))
        except IOError:
            out.write("Can't read ABI reference.  ABI not checked!\n")
            return ret

        symbols, add, change, remove = self._cmp(ref, new)

        ignore = self._ignore(symbols)

        add_effective = add - ignore
        change_effective = change - ignore
        remove_effective = remove - ignore

        if change_effective or remove_effective:
            out.write("ABI has changed!  Refusing to continue.\n")
            ret = 1
        elif change or remove:
            out.write("ABI has changed but all changes have been ignored.  Continuing.\n")
        elif add_effective:
            out.write("New symbols have been added.  Continuing.\n")
        elif add:
            out.write("New symbols have been added but have been ignored.  Continuing.\n")
        else:
            out.write("No ABI changes.\n")

        if add:
            out.write("\nAdded symbols:\n")
            for name in sorted(add):
                symbols[name].write(out, name in ignore)

        if change:
            out.write("\nChanged symbols:\n")
            for name in sorted(change):
                symbols[name].write(out, name in ignore)

        if remove:
            out.write("\nRemoved symbols:\n")
            for name in sorted(remove):
                symbols[name].write(out, name in ignore)

        return ret

    def _cmp(self, ref, new):
        ref_names = set(ref.keys())
        new_names = set(new.keys())

        add = set()
        change = set()
        remove = set()

        symbols = {}

        for name in new_names - ref_names:
            add.add(name)
            symbols[name] = self.SymbolInfo(new[name])

        for name in ref_names.intersection(new_names):
            s_ref = ref[name]
            s_new = new[name]

            if s_ref != s_new:
                change.add(name)
                symbols[name] = self.SymbolInfo(s_new, s_ref)

        for name in ref_names - new_names:
            remove.add(name)
            symbols[name] = self.SymbolInfo(ref[name])

        return symbols, add, change, remove

    def _ignore_pattern(self, pattern):
        ret = []
        for i in re.split(r'(\*\*?)', pattern):
            if i == '*':
                ret.append(r'[^/]*')
            elif i == '**':
                ret.append(r'.*')
            elif i:
                ret.append(re.escape(i))
        return re.compile('^' + ''.join(ret) + '$')

    def _ignore(self, symbols):
        # TODO: let config merge this lists
        configs = []
        configs.append(self.config.get(('abi', self.arch, self.featureset, self.flavour), {}))
        configs.append(self.config.get(('abi', self.arch, None, self.flavour), {}))
        configs.append(self.config.get(('abi', self.arch, self.featureset), {}))
        configs.append(self.config.get(('abi', self.arch), {}))
        configs.append(self.config.get(('abi', None, self.featureset), {}))
        configs.append(self.config.get(('abi',), {}))

        ignores = set()
        for config in configs:
            ignores.update(config.get('ignore-changes', []))

        filtered = set()
        for ignore in ignores:
            type = 'name'
            if ':' in ignore:
                type, ignore = ignore.split(':')
            if type in ('name', 'module'):
                p = self._ignore_pattern(ignore)
                for symbol in symbols.values():
                    if p.match(getattr(symbol, type)):
                        filtered.add(symbol.name)
            else:
                raise NotImplementedError

        return filtered

class CheckImage(object):
    def __init__(self, config, dir, arch, featureset, flavour):
        self.dir = dir
        self.arch, self.featureset, self.flavour = arch, featureset, flavour

        self.changelog = Changelog(version=VersionLinux)[0]

        self.config_entry_base = config.merge('base', arch, featureset, flavour)
        self.config_entry_build = config.merge('build', arch, featureset, flavour)
        self.config_entry_image = config.merge('image', arch, featureset, flavour)

    def __call__(self, out):
        image = self.config_entry_build.get('image-file')
        uncompressed_image = self.config_entry_build.get('uncompressed-image-file')

        if not image:
            # TODO: Bail out
            return 0

        image = os.path.join(self.dir, image)
        if uncompressed_image:
            uncompressed_image = os.path.join(self.dir, uncompressed_image)

        fail = 0

        fail |= self.check_size(out, image, uncompressed_image)

        return fail

    def check_size(self, out, image, uncompressed_image):
        value = self.config_entry_image.get('check-size')

        if not value:
            return 0

        dtb_size = 0
        if self.config_entry_image.get('check-size-with-dtb'):
            for dtb in glob.glob(
                    os.path.join(self.dir, 'arch',
                                 self.config_entry_base['kernel-arch'],
                                 'boot/dts/*.dtb')):
                dtb_size = max(dtb_size, os.stat(dtb).st_size)

        size = os.stat(image).st_size + dtb_size

        # 1% overhead is desirable in order to cope with growth
        # through the lifetime of a stable release. Warn if this is
        # not the case.
        usage = (float(size)/value) * 100.0
        out.write('Image size %d/%d, using %.2f%%.  ' % (size, value, usage))
        if size > value:
            out.write('Too large.  Refusing to continue.\n')
            return 1
        elif usage >= 99.0:
            out.write('Under 1%% space in %s.  ' % self.changelog.distribution)
        else:
            out.write('Image fits.  ')
        out.write('Continuing.\n')

        # Also check the uncompressed image
        if uncompressed_image and self.config_entry_image.get('check-uncompressed-size'):
            value = self.config_entry_image.get('check-uncompressed-size')
            size = os.stat(uncompressed_image).st_size
            usage = (float(size)/value) * 100.0
            out.write('Uncompressed Image size %d/%d, using %.2f%%.  ' % (size, value, usage))
            if size > value:
                out.write('Too large.  Refusing to continue.\n')
                return 1
            elif usage >= 99.0:
                out.write('Uncompressed Image Under 1%% space in %s.  ' % self.changelog.distribution)
            else:
                out.write('Uncompressed Image fits.  ')
            out.write('Continuing.\n')

        return 0

class Main(object):
    def __init__(self, dir, arch, featureset, flavour):
        self.args = dir, arch, featureset, flavour

        self.config = ConfigCoreDump(open("debian/config.defines.dump", "rb"))

    def __call__(self):
        fail = 0

        for c in CheckAbi, CheckImage:
            fail |= c(self.config, *self.args)(sys.stdout)

        return fail

if __name__ == '__main__':
    sys.exit(Main(*sys.argv[1:])())


import openpyxl
from openpyxl.utils import get_column_letter
import os

path = 'C:\\Users\\Arkadiusz\\Desktop\\FV\\Maj'

cur = os.getcwd()                # Check current working directory.
print('Current working directory %s' % cur)  # Print current working directory in console

os.chdir(path)                  # Change the directory
cur2 = os.getcwd()               # Check current working directory
print(cur2)                     # Print current working directory in console

print('-----')                  # Print ------
wb = openpyxl.load_workbook('domeny-tf.xlsx') # Load excell form path
# sheet = wb['domeny-tf']         # Retrieving a sheet from a workbook

sheet = wb.active

# row = sheet.max_row             # Print maximum number of occupied row in console
# print(row)                                  # print row
# print(sheet.max_column)                     # print maximum number of occupied column
# print(get_column_letter(sheet.max_column))  # print maximum column letter of occupied

# for i in range(1,row +1):
#     print(i, sheet.cell(row=i, column=1).value)

# print(tuple(sheet['A1':'C3']))

# for rowOfCellObjects in sheet['A1':'C3']:   # Iteraction over the rows
#     for cellObj in rowOfCellObjects:        # Iteraction over the column
#         print(cellObj.coordinate, cellObj.value)
#     print('---Koniec wiersza---')

list(sheet.columns)  # List sheet column
#
for cellObj in list(sheet.columns)[0]:
    print(cellObj.value)


# from dataclasses import dataclass, field
# from abc import ABCMeta, abstractmethod
import torch
from torch import nn
# @dataclass
# class C:
#     x: int
#     y: int = field(repr=False)
#     z: int = field(repr=False, default=10)
#     t: int = 20

# # @dataclass
# class C2(C):
#     x: int

# class A():
#     # a = 1
#     def __init__(self):
#         # ...
#         pass

#     @property
#     def a(self):
#         pass

#     @property
#     @abstractmethod
#     def b(self):
#         pass

# class B(A):
#     a = 1
#     b = 1
#     # def b(self):
#     #     pass

class DISC(nn.Module):
    def __init__(self):
        super().__init__()
        self.model = nn.Linear(10, 1)
    def forward(self, x):
        return self.model(x).reshape(-1)

class GEN(nn.Module):
    def __init__(self):
        super().__init__()
        self.model = nn.Linear(1, 10)
    def forward(self, x):
        return self.model(x)

disc = DISC()
gen = GEN()

opt_g = torch.optim.Adam(gen.parameters())
opt_d = torch.optim.Adam(disc.parameters())
in_z = torch.randn(10, 1)
criterion = nn.BCELoss()

fake = gen(in_z)
disc_fake = disc(fake.detach())
d_loss = criterion(disc_fake, torch.zeros_like(disc_fake))
opt_d.zero_grad()
d_loss.backward()
opt_d.step()

disc_fake = disc(fake)
g_loss = criterion(disc_fake, torch.ones_like(disc_fake))
opt_g.zero_grad()
g_loss.backward()
opt_g.step()


import sqlite3
from turtle import title

with sqlite3.connect("database1.db") as db:
    cursor = db.cursor()

    # cursor.execute("""CREATE TABLE IF NOT EXISTS staff(
    #     id INTEGER PRIMARY KEY,
    #     FIO VARCHAR(30),
    #     age INTEGER(3),
    #     sex INTEGER NOT NULL DEFAULT 1,
    #     department VARCHAR(100),
    #     title VARCHAR(100)
    # )""")

    # values = [
    #     ("Диденко Д.Н.", "43", "1", "Департамент логистики", "Директор по логистике"),
    #     ("Каруна Т.В.", "35", "2", "Финансово-экономический отдел", "Финансовый директор"),
    #     ("Дворяшина Н.Н.", "33", "2", "Департамент учета и отчетности", "Главный бухгалтер"),
    #     ("Золоторева М.А.", "26", "2", "Отдел по работе с персоналом", "Менеджер по работе с персоналом"),
    #     ("Лучин А.С.", "36", "1", "Департамент логистики", "Директор по транспорту")

    # ]

    # cursor.executemany("INSERT INTO staff(FIO, age, sex, department, title) VALUES(?, ?, ?, ?, ?)", values)
def data_output():
    try:
        db = sqlite3.connect("database1.db")
        cursor = db.cursor()

        for data in cursor.execute("SELECT * FROM staff"): # Этот метод выводит все записи таблицы по строчно
            print(data)
    except sqlite3.Error as e:
        print("Error", e)
    finally:
        cursor.close()
        db.close()

def registration():
    FIO = input("Введите Фамилию и инициалы сотрудника: ")
    age = int(input("Введите возраст сотрудника: "))
    sex = int(input("Введите пол сотрудника 1-муж./2-жен.: "))
    department = input("Введите название отдела/департамента: ")
    title = input("Введите должность сотрудника: ")

    try:
        db = sqlite3.connect("database1.db")
        cursor = db.cursor()

        cursor.execute("SELECT FIO FROM staff WHERE FIO = ?", [FIO])
        if cursor.fetchone() is None:
            values = [FIO, age, sex, department, title]

            cursor.execute("INSERT INTO staff(FIO, age, sex, department, title) VALUES(?, ?, ?, ?, ?)", values)
            db.commit()
            print("Сотрудник зарегистрирован!")
        else:
            print('Такой сотрудник уже существует!')
            registration()
    except sqlite3.Error as e:
        print("Error", e)
    finally:
        cursor.close()
        db.close()

def delete_db(FIO):
    try:
        db = sqlite3.connect("database1.db")
        cursor = db.cursor()

        cursor.execute("DELETE FROM staff WHERE FIO = ?", [FIO])
        db.commit()
        print("Запись удалена")
    except sqlite3.Error as e:
        print("Error", e)
    finally:
        cursor.close()
        db.close()

def update_db(column_name, value, FIO):
    try:
        db = sqlite3.connect("database1.db")
        cursor = db.cursor()

        cursor.execute(f'UPDATE staff SET {column_name} = ? WHERE FIO = ?', (value, FIO))
        db.commit()
        print("Изменения внесены!")
    except sqlite3.Error as e:
        print("Error", e)
    finally:
        cursor.close()
        db.close()


#!/usr/bin/env python

import argparse
import os
import zipfile
import gzip
import tarfile
import contextlib
import tempfile
import json
import subprocess
import pathlib
import pandas as pd
from glob import glob
import multiprocessing as mp
import shutil
import re
import sys

ANALYSIS_NOTEBOOK_TEMPLATE = 'Analysis-Template.ipynb'

def mkdirp(dirpath):
    pathlib.Path(dirpath).mkdir(parents=True, exist_ok=True)

def parse_args():
    parser = argparse.ArgumentParser()
    commands = parser.add_subparsers()
    extract_cmd = commands.add_parser('extract', help='extract test outputs from testground output archive')
    extract_cmd.add_argument('test_output_zip_path', nargs=1,
                             help='path to testground output zip or tgz file')

    extract_cmd.add_argument('--output-dir', '-o', dest='output_dir', default=None,
                             help='path to write output files. default is to create an "analysis" dir next to archive file')
    extract_cmd.set_defaults(subcommand='extract')

    run_notebook_cmd = commands.add_parser('run_notebook',
                                           help='runs latest analysis notebook against extracted test data')
    run_notebook_cmd.add_argument('--mesh', action='store_true', default=False,
                                  help='if true, derive the mesh state when converting data. This takes a long time, so the default is false.')
    run_notebook_cmd.add_argument('test_result_dir', nargs='+',
                                  help='directories to run against. must contain an "analysis" subdir with extracted test data')
    run_notebook_cmd.set_defaults(subcommand='run_notebook')
    return parser.parse_args()

def concat_files(names, outfile):
    for name in names:
        with open(name, 'rb') as f:
            outfile.write(f.read())

# depending on which test runner was used, the collection archive may be either a zip (local docker & exec runner),
# or a tar.gz file (k8s). Unfortunately, the zipfile and tarfile modules are different species of waterfowl,
# so we duck typing doesn't help. So this method extracts whichever one we have to a temp directory and
# returns the path to the temp dir.
# use as a context manager, so the temp dir gets deleted when we're done:
#   with open_archive(archive_path) as a:
#     files = glob(a + '/**/tracer-output')
@contextlib.contextmanager
def open_archive(archive_path):
    # zipfile and tarfile both have an extractall method, at least
    if zipfile.is_zipfile(archive_path):
        z = zipfile.ZipFile(archive_path)
    else:
        z = tarfile.open(archive_path, 'r:gz')

    with tempfile.TemporaryDirectory(prefix='pubsub-tg-archive-') as d:
        z.extractall(path=d)
        yield d

# sugar around recursive glob search
def find_files(dirname, filename_glob):
    path = '{}/**/{}'.format(dirname, filename_glob)
    return glob(path, recursive=True)

PEER_INFO_PATTERN = re.compile(
    r'Host peer ID: ([0-9a-zA-Z]+), seq (\d+), node type: ([a-z]+), node type seq: (\d+), node index: (\d+) / (\d+)')

def extract_peer_info(run_out):
    infos = []
    with open(run_out, 'rt') as f:
        for line in f.readlines():
            m = PEER_INFO_PATTERN.search(line)
            if m:
                pid = m.group(1)
                seq = int(m.group(2))
                node_type = m.group(3)
                node_type_seq = int(m.group(4))
                node_index = int(m.group(5))
                node_index_bound = int(m.group(6))
                infos.append(
                    {'peer_id': pid,
                     'type': node_type,
                     'seq': seq,
                     'node_type_seq': node_type_seq,
                     'node_index': node_index,
                     'node_index_bound': node_index_bound})
    if len(infos) == 0:
        print('warning: no peer info found in {}'.format(run_out))
    return infos

def extract_timing_info(run_out, node_type):
    if node_type == 'honest':
        times = dict(t_warm=0, t_connect=0, t_run=0, t_cool=0, t_complete=0)
    else:
        times = dict(t_connect=0)

    with open(run_out, 'rt') as f:
        for line in f.readlines():
            try:
                obj = json.loads(line)
            except BaseException as err:
                print("error parsing run output: ", err)
                continue
            if 'ts' not in obj or 'event' not in obj or obj['event'].get('type', '') != 'message':
                continue
            msg = obj['event']['message']
            ts = obj['ts']
            if re.match(r'connecting to peers.*', msg):
                times['t_connect'] = ts
                continue

            # the rest of the times are only logged by honest peers
            if node_type != 'honest':
                continue
            if re.match(r'Wait for .* warmup time', msg):
                times['t_warm'] = ts
                continue
            if re.match(r'Wait for .* run time', msg):
                times['t_run'] = ts
                continue
            if re.match(r'Run time complete, cooling down.*', msg):
                times['t_cool'] = ts
                continue
            if msg == 'Cool down complete':
                times['t_complete'] = ts
                continue

    for k, v in times.items():
        if v == 0:
            print('warning: unable to determine time value for {}'.format(k))
    return times

def extract_peer_and_timing_info(run_out_files):
    entries = []
    for filename in run_out_files:
        infos = extract_peer_info(filename)
        if infos is None or len(infos) == 0:
            continue

        # FIXME: we only get the timing info for the first peer in the container
        # unfortunately, getting the times for individual peers requires code changes
        times = extract_timing_info(filename, infos[0].get('type', 'unknown'))
        for info in infos:
            info.update(times)
            entries.append(info)
    return entries

def aggregate_output(output_zip_path, out_dir):
    topology = dict()

    with open_archive(output_zip_path) as archive:
        tracefiles = find_files(archive, 'tracer-output*')
        names = [f for f in tracefiles if 'full' in f]
        if len(names) > 0:
            with gzip.open(os.path.join(out_dir, 'full-trace.bin.gz'), 'wb') as gz:
                concat_files(names, gz)

        names = [f for f in tracefiles if 'filtered' in f]
        if len(names) > 0:
            with gzip.open(os.path.join(out_dir, 'filtered-trace.bin.gz'), 'wb') as gz:
                concat_files(names, gz)

        # copy aggregate metrics files
        names = [f for f in tracefiles if 'aggregate' in f]
        for name in names:
            dest = os.path.join(out_dir, os.path.basename(name))
            shutil.copyfile(name, dest)

        # copy peer score files
        names = find_files(archive, 'peer-scores*')
        for name in names:
            dest = os.path.join(out_dir, os.path.basename(name))
            shutil.copyfile(name, dest)

        # get peer id -> seq mapping & timing info from run.out files
        names = find_files(archive, 'run.out')
        info = extract_peer_and_timing_info(names)
        dest = os.path.join(out_dir, 'peer-info.json')
        with open(dest, 'wt') as f:
            json.dump(info, f)

        # Collect contents of all files of the form 'connections-honest-8-1'
        names = find_files(archive, 'connections*')
        for name in names:
            with open(name, 'r') as infile:
                name = os.path.basename(name)
                _, node_type, node_type_seq, node_idx = name.split('.')[0].split('-')
                conns = json.loads(infile.read())
                topology[node_type + '-' + node_type_seq + '-' + node_idx] = conns or []

    # Write out topology file
    top_path = os.path.join(out_dir, 'topology.json')
    with open(top_path, 'wt') as outfile:
        outfile.write(json.dumps(topology))

def run_tracestat(tracer_output_dir):
    full = os.path.join(tracer_output_dir, 'full-trace.bin.gz')
    filtered = os.path.join(tracer_output_dir, 'filtered-trace.bin.gz')
    if os.path.exists(full):
        tracer_output = full
    elif os.path.exists(filtered):
        tracer_output = filtered
    else:
        print('no event tracer output found, skipping tracestat')
        return

    print('running tracestat on {}'.format(tracer_output))
    try:
        cmd = ['go', 'run', 'github.com/libp2p/go-libp2p-pubsub-tracer/cmd/tracestat', '-cdf', tracer_output]
        p = subprocess.run(cmd, capture_output=True, text=True, check=True)
    except BaseException as err:
        print('error calling tracestat: ', err)
        return

    # split output into summary and latency CDF
    [summary, cdf] = p.stdout.split('=== Propagation Delay CDF (ms) ===')

    with open(os.path.join(tracer_output_dir, 'tracestat-summary.txt'), 'w', encoding='utf8') as f:
        f.write(summary)
    with open(os.path.join(tracer_output_dir, 'tracestat-cdf.txt'), 'w', encoding='utf8') as f:
        f.write(cdf)

    print(summary)

def extract_test_outputs(test_output_zip_path, output_dir=None, convert_to_pandas=False, prep_notebook=True):
    if output_dir is None or output_dir == '':
        output_dir = os.path.join(os.path.dirname(test_output_zip_path), 'analysis')

    raw_output_dir = os.path.join(output_dir, 'raw-data')
    mkdirp(raw_output_dir)
    aggregate_output(test_output_zip_path, raw_output_dir)
    run_tracestat(raw_output_dir)

    if convert_to_pandas:
        import notebook_helper
        print('converting data to pandas format...')
        pandas_dir = os.path.join(output_dir, 'pandas')
        notebook_helper.to_pandas(raw_output_dir, pandas_dir)
    if prep_notebook:
        prepare_analysis_notebook(analysis_dir=output_dir)
    return output_dir

def prepare_analysis_notebook(analysis_dir):
    notebook_out = os.path.join(analysis_dir, 'Analysis.ipynb')
    shutil.copy(ANALYSIS_NOTEBOOK_TEMPLATE, notebook_out)
    shutil.copy('./notebook_helper.py', os.path.join(analysis_dir, 'notebook_helper.py'))
    print('saved analysis notebook to {}'.format(notebook_out))

def run_analysis_notebook(analysis_dir, derive_meshes=False):
    prepare_analysis_notebook(analysis_dir)
    notebook_path = os.path.join(analysis_dir, 'Analysis.ipynb')
    cmd = ['papermill', ANALYSIS_NOTEBOOK_TEMPLATE, notebook_path, '--cwd', analysis_dir]
    if derive_meshes:
        cmd += ['-p', 'DERIVE_MESHES', 'True']
    try:
        subprocess.run(cmd, check=True)
    except BaseException as err:
        print('error executing notebook: {}'.format(err), file=sys.stderr)
        return

def run_notebooks(test_result_dirs, derive_meshes=False):
    for d in test_result_dirs:
        analysis_dir = os.path.join(d, 'analysis')
        if not os.path.exists(analysis_dir):
            print('no analysis dir at {}, ignoring'.format(analysis_dir), file=sys.stderr)
            continue
        print('running analysis in {}'.format(analysis_dir))
        run_analysis_notebook(analysis_dir, derive_meshes=derive_meshes)

def run():
    args = parse_args()
    if args.subcommand == 'extract':
        zip_filename = args.test_output_zip_path[0]
        extract_test_outputs(zip_filename, args.output_dir)
    elif args.subcommand == 'run_notebook':
        run_notebooks(args.test_result_dir, derive_meshes=args.mesh)
    else:
        print('unknown subcommand', file=sys.stderr)
        sys.exit(1)

if __name__ == '__main__':
    run()


from dateutil import parser
from dateutil.relativedelta import relativedelta
import os
global months

#Equipment script
def get_equipment_cost():
  has_equipment = input("Equipment? (y/n) > ")
  print("")
  if has_equipment.lower() == 'y':
    equip_monthly = float(input("Enter monthly equipment cost: "))
    return equip_monthly * months
  else:
    return 0

#Discount script
def get_discount():
  percent_str = input("What is the discount percent? > ")
  percent = int(percent_str) / 100
  return percent

def program():
  global months
  date1 = input("Date with previous provider (MM/DD/YYYY): ")
  date2 = input("Date with Vivint (MM/DD/YYYY): ")

  date1 = parser.parse(date1)
  date2 = parser.parse(date2)
  global months

  rd = relativedelta(date2, date1)
  months = rd.years * 12 + rd.months

  rd = relativedelta(date2, date1)
  day_diff = rd.days

  print("")
  print(f"There are {months} months between {date1:%m/%d/%Y} and {date2:%m/%d/%Y}")
  print("")
  monthdif = int(input("How many months long is the customers contract > "))
  trumonth = monthdif-months
  if 0 <= day_diff <= 3:
    print("\nThe difference between the dates is less than 3 days. The extra month will be calculated automatically.")
    print(f"\nThe payoff period has increased from the initial {trumonth} months to {trumonth + 1} months after applying the 3-day rule")
    trumonth = trumonth + 1
  else:
    print("\nThree day rule does not apply")
    print(f"\nThere are {trumonth} months left for the customer to pay")

  rmr = float(input("\nWhat is the monthly rate? > "))

  discount = input("\nDiscount? (y/n) > ")
  equip_cost = get_equipment_cost()

  if discount == 'y':
    percent = get_discount()
    total = (rmr * trumonth * percent) + equip_cost
  else:
    total = (rmr * trumonth) + equip_cost
  total = round(total, 2)
  print("")
  print(f"The total buyout is ${total}")

program()

while True:
  print("")
  again = input("Run calculation again? (y/n): ")
  if again.lower() == 'y':
    print("")
    os.system('cls' if os.name == 'nt' else 'clear')
    program()
  else:
    break

print("Done")


import random
import string
import requests
import cfscrape
import os
from bs4 import BeautifulSoup

countsPhoto = int(input('Введите количество фотографий: '))

index_element = string.ascii_lowercase + string.digits
# print (index_element)

errors = 0
goods = 0
i = 0

def random_char(y):
     return ''.join(random.choice(index_element) for x in range(y))

def parse_photo():
        print ('Цикл ' + str(i)  + ' пошел')
        index = random_char(6)
        url = 'https://prnt.sc/' +  index
        # print (url)
        scraper = cfscrape.create_scraper()
        r = scraper.get(url)
        soup = BeautifulSoup(r.text)
        # print (soup)
        img_link = soup.find('img', {'class': 'screenshot-image'}).get('src')
        # print (img_link)

        file_name = img_link.split('/')[-1]
        # print (file_name)

        dirName = 'img'
        try:
            os.mkdir(dirName)
        except FileExistsError:
            None

        filepath = os.path.join('./img', file_name)

        img = scraper.get(img_link)
        out = open(filepath, "wb")
        out.write(img.content)
        out.close()

for x in range(countsPhoto):
    i += 1
    try:
        parse_photo()
        goods += 1
        print ('Успешних циклов: ' + str(goods))
    except Exception as e:
        errors += 1
        print ('Проваленых циклов: ' + str(errors))
        None


def letter():
    userone = input('User enter X or O: ').upper()
    if userone not in ('X', 'O'):
        print('Enter an X or an O, por favor')
        letter()
    else:
        print('User 1 entered ' + userone)
        return userone

userone = letter()

usertwo = ''
if userone == 'X':
    usertwo = 'O'
else:
    usertwo = 'X'

print()
print('user one is: ' + userone)
print('user two is: ' + usertwo)
print()

board = []

for x in range(0, 3):
    board.append('[ ]' * 3)

rowNum = 0
def makeboard(board):
#    for colNum, colBox in enumerate(list, start = 1):
#        print(str(colNum) + '  ' + str(colNum))
    print ('    1     2     3')
    for rowNum, rowBox in enumerate(board, start = 1):
        print(str(rowNum) + ' ' + ' '.join(rowBox))
        print()
        return rowNum

makeboard(board)

print(len(board))
print(board[0])

def taketurn(turn):
    print('IT IS ' + turn + '\'S TURN...')
    print('PICK YOUR COORDINATES, ' + turn)
    row = input('ROW: ')
    #if row
    col = input('COLUMN: ')

turn = userone
taketurn(turn)

#      _   _
#     | | | |
#     | |_| |
#      \__, |
#      |___/


import numpy as np
import pylab as plt
from matplotlib.ticker import MultipleLocator

'''
python plot_aFe_aCF.py
'''

# Output file name
outdir = '../ms/figures/'
fout   = outdir + 'aFe_aCF.eps'

# USE z-SCORE TO CONVERT TO 68% UNCERTAINTY

# Continuum fitting measured black hole spins and errors: [value, -err, +err]
aCF_U1543 = [0.8, 0.1, 0.1]    # 68%...?
aCF_CygX1 = [0.9985, 0.0148, 0.0005] # 68%
aCF_1915  = [0.98]             # 3-sigma
aCF_J1655 = [0.7, 0.1, 0.1]    # 68%...?
aCF_LMCX1 = [0.92, 0.07, 0.05] # 68%
aCF_J1550 = [0.34, 0.28, 0.20] # 68%

# Iron line measured black hole spins and errors: [value, -err, +err]
aFe_U1543 = [0.3, 0.1, 0.1]     # 68%
aFe_CygX1 = [0.97, 0.02, 0.014] # 90%
aFe_1915  = [0.98, 0.01, 0.01]  # 68%
aFe_J1655 = [0.92, 0.02, 0.02]  # 90%
aFe_LMCX1 = [0.97, 0.25, 0.02]  # 68%
aFe_J1550 = [0.55, 0.22, 0.15]  # 68%

# Use z-scores to convert uncertainties to 1-sigma level
z90 = 1.645
aFe_CygX1[1], aFe_CygX1[2] = aFe_CygX1[1]/z90, aFe_CygX1[2]/z90
aFe_J1655[1], aFe_J1655[2] = aFe_J1655[1]/z90, aFe_J1655[2]/z90

# Plotting preferences
dpi = 300
xsize, ysize = 8.4, 8.4
left, right, bottom, top = 0.15, 0.97, 0.15, 0.97
fs, fs_sm, lw, pad, tlmaj, tlmin = 28, 24, 2, 12, 10, 5

# Plotting preferences
ts          = 16.0  # Text size
legfs       = 16.0  # Legend font size
symsize     = 300   # Symbol size
symsize_leg = 150   # Symbol size (for legend)
csize       = 0.0   # Capsize for error bars
csize_arrow = 5.0
elw         = 2.0   # Width of error bars
mew         = 2.0   # Marker edge width
limlen      = 0.1   # Length of x error upper/lower limits arrow

a_min, a_max = -1,  1
xmin,  xmax  = 0.0, 1.1
ymin,  ymax  = 0.0, 1.1
xinc_maj, xinc_min = 0.2, 0.05
yinc_maj, yinc_min = 0.2, 0.05
xmajorLocator = MultipleLocator(xinc_maj)
xminorLocator = MultipleLocator(xinc_min)
ymajorLocator = MultipleLocator(yinc_maj)
yminorLocator = MultipleLocator(yinc_min)

mark_U1543 = 'o'  # circle
mark_CygX1 = '^'  # up-triangle
mark_1915  = 'v'  # down-triangle
mark_J1655 = 's'  # square
mark_LMCX1 = 'D'  # diamond
mark_J1550 = '*'  # star

fig = plt.figure(figsize=(8.4, 8.4), dpi=dpi)
fig.subplots_adjust(left=left, right=right, bottom=bottom, top=top)
ax = fig.add_subplot(111)
ax.axhline(y=ymin, xmin=xmin, xmax=xmax, linewidth=lw, color='k')
ax.axhline(y=ymax, xmin=xmin, xmax=xmax, linewidth=lw, color='k')
ax.axvline(x=xmin, ymin=ymin, ymax=ymax, linewidth=lw, color='k')
ax.axvline(x=xmax, ymin=ymin, ymax=ymax, linewidth=lw, color='k')
ax.set_xlabel(r"${\rm Iron\ Line\ Black\ Hole\ Spin,}\ a^{\rm Fe}$",         fontsize=fs, labelpad=pad)
ax.set_ylabel(r"${\rm Continuum\ Fitting\ Black\ Hole\ Spin,}\ a^{\rm CF}$", fontsize=fs, labelpad=pad)
ax.set_xlim(xmin, xmax)
ax.set_ylim(ymin, ymax)
ax.tick_params('both', direction='in', length=tlmaj, width=lw, which='major', labelsize=fs_sm, pad=pad)
ax.tick_params('both', direction='in', length=tlmin, width=lw, which='minor')
ax.xaxis.set_major_locator(xmajorLocator)
ax.xaxis.set_minor_locator(xminorLocator)
ax.yaxis.set_major_locator(ymajorLocator)
ax.yaxis.set_minor_locator(yminorLocator)

ax.plot([xmin,xmax], [ymin,ymax], 'k--', linewidth=lw)

s_U1543 = ax.scatter(aFe_U1543[0], aCF_U1543[0], marker=mark_U1543, s=symsize, facecolors='w', edgecolors='k', linewidths=elw, zorder=3)
ax.errorbar([aFe_U1543[0],aFe_U1543[0]], [aCF_U1543[0],aCF_U1543[0]], \
            xerr=[[aFe_U1543[1],aFe_U1543[1]], [aFe_U1543[2],aFe_U1543[2]]], \
            yerr=[[aCF_U1543[1],aCF_U1543[1]], [aCF_U1543[2],aCF_U1543[2]]], \
            fmt='none', marker=None, markeredgewidth=mew, capsize=csize, elinewidth=elw, color='k', ecolor='k', zorder=2)

s_CygX1 = ax.scatter(aFe_CygX1[0], aCF_CygX1[0], marker=mark_CygX1, s=symsize, facecolors='w', edgecolors='k', linewidths=elw, zorder=3)
ax.errorbar([aFe_CygX1[0],aFe_CygX1[0]], [aCF_CygX1[0],aCF_CygX1[0]], \
            yerr=[[0.0,0.0], [1.0-aCF_CygX1[0],1.0-aCF_CygX1[0]]], \
            fmt='none', marker=None, markeredgewidth=mew, capsize=csize, elinewidth=elw, color='k', ecolor='k', zorder=2)
ax.errorbar([aFe_CygX1[0],aFe_CygX1[0]], [aCF_CygX1[0],aCF_CygX1[0]], \
            xerr=[[aFe_CygX1[1],aFe_CygX1[1]], [aFe_CygX1[2],aFe_CygX1[2]]], \
            fmt='none', marker=None, markeredgewidth=mew, capsize=csize, elinewidth=elw, color='k', ecolor='k', zorder=2)

s_1915  = ax.scatter(aFe_1915[0], aCF_1915[0], marker=mark_1915, s=symsize, facecolors='w', edgecolors='k', linewidths=elw, zorder=3)
ax.errorbar([aFe_1915[0],aFe_1915[0]], [aCF_1915[0],aCF_1915[0]], \
            yerr=[[0.0,0.0], [1.0-aCF_1915[0],1.0-aCF_1915[0]]], \
            fmt='none', marker=None, markeredgewidth=mew, capsize=csize_arrow, elinewidth=elw, color='k', ecolor='k', zorder=2, ylolims=True)
ax.errorbar([aFe_1915[0],aFe_1915[0]], [aCF_1915[0],aCF_1915[0]], \
            xerr=[[aFe_1915[1],aFe_1915[1]], [aFe_1915[2],aFe_1915[2]]], \
            fmt='none', marker=None, markeredgewidth=mew, capsize=csize, elinewidth=elw, color='k', ecolor='k', zorder=2)

s_J1655 = ax.scatter(aFe_J1655[0], aCF_J1655[0], marker=mark_J1655, s=symsize, facecolors='w', edgecolors='k', linewidths=elw, zorder=3)
ax.errorbar([aFe_J1655[0],aFe_J1655[0]], [aCF_J1655[0],aCF_J1655[0]], \
            yerr=[[aCF_J1655[1],aCF_J1655[1]], [aCF_J1655[2],aCF_J1655[2]]], \
            fmt='none', marker=None, markeredgewidth=mew, capsize=csize, elinewidth=elw, color='k', ecolor='k', zorder=2)
ax.errorbar([aFe_J1655[0],aFe_J1655[0]], [aCF_J1655[0],aCF_J1655[0]], \
            xerr=[[aFe_J1655[1],aFe_J1655[1]], [aFe_J1655[2],aFe_J1655[2]]], \
            fmt='none', marker=None, markeredgewidth=mew, capsize=csize, elinewidth=elw, color='k', ecolor='k', zorder=2)

s_LMCX1 = ax.scatter(aFe_LMCX1[0], aCF_LMCX1[0], marker=mark_LMCX1, s=symsize, facecolors='w', edgecolors='k', linewidths=elw, zorder=3)
ax.errorbar([aFe_LMCX1[0],aFe_LMCX1[0]], [aCF_LMCX1[0],aCF_LMCX1[0]], \
            yerr=[[aCF_LMCX1[1],aCF_LMCX1[1]], [aCF_LMCX1[2],aCF_LMCX1[2]]], \
            fmt='none', marker=None, markeredgewidth=mew, capsize=csize, elinewidth=elw, color='k', ecolor='k', zorder=2)
ax.errorbar([aFe_LMCX1[0],aFe_LMCX1[0]], [aCF_LMCX1[0],aCF_LMCX1[0]], \
            xerr=[[aFe_LMCX1[1],aFe_LMCX1[1]], [aFe_LMCX1[2],aFe_LMCX1[2]]], \
            fmt='none', marker=None, markeredgewidth=mew, capsize=csize, elinewidth=elw, color='k', ecolor='k', zorder=2)

s_J1550 = ax.scatter(aFe_J1550[0], aCF_J1550[0], marker=mark_J1550, s=symsize*2.0, facecolors='w', edgecolors='k', linewidths=elw, zorder=3)
ax.errorbar([aFe_J1550[0],aFe_J1550[0]], [aCF_J1550[0],aCF_J1550[0]], \
            xerr=[[aFe_J1550[1],aFe_J1550[1]], [aFe_J1550[2],aFe_J1550[2]]], \
            yerr=[[aCF_J1550[1],aCF_J1550[1]], [aCF_J1550[2],aCF_J1550[2]]], \
            fmt='none', marker=None, markeredgewidth=mew, capsize=csize, elinewidth=elw, color='k', ecolor='k', zorder=2)

ax.text(aFe_U1543[0], aCF_U1543[0]-0.13, r'$4{\rm U}\ 1543$'+'--'r'$47$', verticalalignment='center', horizontalalignment='center', size=ts)
ax.text(aFe_CygX1[0]-0.06, aCF_CygX1[0], r'${\rm Cyg}$'+'\n'+r'${\rm X}$'+'--'r'$1$', verticalalignment='center', horizontalalignment='center', size=ts)
ax.text(aFe_1915[0]+0.095, aCF_1915[0], r'${\rm GRS}$'+'\n'+r'$1915$', verticalalignment='center', horizontalalignment='right', size=ts)
ax.text(aFe_J1655[0], aCF_J1655[0]-0.13, r'${\rm GRO\ J}1655$'+'--'r'$40$', verticalalignment='center', horizontalalignment='center', size=ts)
ax.text(aFe_LMCX1[0]+0.065, aCF_LMCX1[0]-0.05, r'${\rm LMC}$'+'\n'+r'${\rm X}$'+'--'r'$1$', verticalalignment='center', horizontalalignment='center', size=ts)
ax.text(aFe_J1550[0]+aFe_J1550[2], aCF_J1550[0]-0.05, r'${\rm XTE\ J}1550$'+'--'r'$564$', verticalalignment='center', horizontalalignment='center', size=ts)

fig.savefig(fout, bbox_inches=0, dpi=dpi)
plt.close()


from subprocess import Popen, DEVNULL, PIPE, run, TimeoutExpired
from threading import Thread
import sys
import shlex
import os
import time

def print_to_strerr(msg):
    sys.stderr.buffer.write(msg)
    sys.stderr.buffer.flush()

def print_to_stdout(msg):
    sys.stdout.buffer.write(msg)
    sys.stdout.buffer.flush()

def start_node():
    node = Popen(['./target/release/gn-node', '--dev', '--enable-offchain-indexing', 'true'],
                 stderr=PIPE, stdout=DEVNULL)

    start = time.time()
    line = b""
    while b"Running JSON-RPC WS" not in line:
        line = node.stderr.readline()
        print_to_stdout(line)
        if int(time.time() - start) == 10:
            print_to_strerr(b"Node startup timeout, exiting...")
            os._exit(111)
    return node

def start_oracle():
    oracle = Popen(['./target/release/gn-cli', 'oracle', '--activate'],
                   stderr=PIPE, stdout=DEVNULL)

    start = time.time()
    line = b""
    while line == b"":
        line = oracle.stderr.readline()
        if int(time.time() - start) == 10:
            print_to_strerr(b"Oracle startup timeout, exiting...")
            os._exit(222)
    print_to_stdout(line)
    return oracle

def monitor_oracle(oracle, node):
    retcode = monitor_process(oracle)
    if retcode != 0:
        node.kill()
        while node.poll() is None:
            pass
        os._exit(retcode)

def monitor_process(process):
    while True:
        line = process.stderr.readline()
        if line != b"":
            print_to_strerr(line)
        retcode = process.poll()
        if retcode is not None:
            return retcode

def run_tests(*commands, timeout=300):
    try:
        for cmd in commands:
            test = run(shlex.split(cmd), timeout=timeout)
            print("Test finished with return code:", test.returncode)
            return test.returncode
    except TimeoutExpired:
        print_to_strerr(b"Test timeout expired\n")
        return -1

# NOTE: this script is a rushed abomination of bodged half solutions, but it does the job
def main():
    try:
        node = start_node()
        command = "./target/release/gn-cli sudo oracle register"
        run_tests(command, timeout=90)
        oracle = start_oracle()
        oracle_monitor = Thread(target=monitor_oracle, args=(oracle, node,))

        oracle_monitor.start()

        command = "cargo run --release --example guild --features external-oracle -- "

        status = run_tests(command + "join",
                           command + "token",
                           command + "eth",
                           timeout=90)
        node.send_signal(15)
        oracle.send_signal(15)
        while node.poll() is None or oracle.poll() is None:
            pass
        os._exit(status)

    except KeyboardInterrupt:
        node.kill()
        oracle.kill()
        while node.poll() is None or oracle.poll() is None:
            pass

main()


str = input()
left = 0
right = len(str) - 1
count = 0

while left <= right :
    if(str[left] is not str[right]) :
        count += 1
        print(0)
        break
    left +=1
    right -=1
if count == 0 :print(1)


"""
This module for build and start the game
"""
import game_exceptions
import game_menu
import models
import settings

def play():
    """
    This method for game process. Creatу player and enemy objects , depending on your game mode choice.
    Validate inputs.
    :return: None
    """
    player_name = input('Enter your name, please:\n')
    game_menu.menu(player_name.lower())
    game_mode = input('Choose game mode: normal or hard\n')
    game_menu.menu(game_mode.lower())
    while game_mode.lower() not in settings.GAME_MODE:
        game_mode = input('Wrong!. Be attentive. Choose game mode: normal or hard\n')
    start_game = input('If your want start game, enter !start.\n'
                       'For more commands type !help, please.\n')
    while game_menu.menu(start_game.lower()) != '!start':
        start_game = input('If your want start game, enter !start\n')
    if game_mode == 'normal':
        player = models.Player(player_name, game_mode)
        level = 1
        enemy = models.Enemy(level)
    else:
        player = models.HardPlayer(player_name, game_mode)
        level = 1
        enemy = models.HardEnemy(level)
    while True:
        try:
            player.attack(enemy)
            player.defence(enemy)
        except game_exceptions.EnemyDown:
            if game_mode == 'normal':
                print('-------You won this duel!!!-------- \n')
                level += 1
                player.score += 5
                print(f'Next enemy level: {level}\n')
                enemy = models.Enemy(level)
            else:
                print('-------You won this duel!!!-------- \n')
                level += 1
                player.score += 15
                print(f'Next enemy level: {level}\n')
                enemy = models.HardEnemy(level)

if __name__ == '__main__':
    try:
        play()
    except game_exceptions.GameOver as go:
        go.save_score()
        print('Game over!!!')
    except KeyboardInterrupt:
        pass
    finally:
        print('Good bye!!! ;-)')


import numpy as np
import matplotlib.pyplot as plt
import cv2
import os

Y = np.load('out.npy')
Y = np.clip(Y, 0.0125, 0.975)
path = '../Dog-vs-Cat-Tensorflow/datasets/test/'
li = os.listdir(path)
li = sorted([int(x.split('.')[0]) for x in li])
li = [str(x) + '.jpg' for x in li]

for i in range(50):
    y = plt.figure(i)
    plt.imshow(cv2.cvtColor(cv2.imread(path+li[i]), cv2.COLOR_BGR2RGB))
    plt.title(Y[i])
    #y.axes.get_xasix().set_visible(False)
    #y.axes.get_yasix().set_visible(False)
    plt.show()


import os
import json
import requests as req
import pprint as pp
import time
from flask import Flask, request, jsonify
from peewee import SqliteDatabase
from User import User
from helpers import *
import threading
import subscribe
import argparse
from Store import Store

app = Flask(__name__)
db = SqliteDatabase('following.db')

def main():
    parser = argparse.ArgumentParser(description='Notify a Slack channel when Twitch users go live')
    parser.add_argument('-d', '--dev', action='store_true', dest='dev_mode')
    args = parser.parse_args()
    if args.dev_mode:
        print('Starting in dev mode')
        print('Instead of reading from Environment Variables, a local config.ini will be used')
        Store.setup('config.ini')
    else:
        subscribe.check_env_vars()
        Store.setup()

    Store.refresh_access_token()

    subscribe_refresh = threading.Thread(target=subscription_handler, daemon=True)
    subscribe_refresh.start()
    app.run(host='0.0.0.0', port=5000)

@app.route('/twitchbot', methods=['POST'])
def user_update():
    data = request.get_json()['data']
    if data:
        data = data[0]
        if data['type'] == 'live':
            user_id = data['user_id']
            user = User.get(User.user_id == int(user_id))
            curr_time = int(time.time())
            last_live = user.last_live
            user.last_live = curr_time
            user.save()
            print(f'{user.display_name.capitalize()} is live!')
            if last_live is None:
                send_to_slack(data, user)
            else:
                last_live = int(last_live.timestamp())
                if (curr_time - last_live) < 30*60:
                    print(f'{user.display_name.capitalize()} went live recently, not sending message')
                else:
                    send_to_slack(data, user)
    else:
        print('Empty Data - Stream ended')
    return jsonify(success=True)

@app.route('/twitchbot', methods=['GET'])
def accept_challenge():
    print('got GET')
    challenge = request.args.get('hub.challenge')
    topic = request.args.get('hub.topic')
    user_id = topic.split('user_id=')[-1]
    # print(challenge)
    # print(user_id)
    user = User.get(User.user_id == int(user_id))
    user.last_subscribed = int(time.time())
    user.save()
    return challenge, 200, {'ContentType':'text/plain'}

@app.before_request
def before_request():
    db.connect()

@app.after_request
def after_request(response):
    db.close()
    return response

def send_to_slack(data, user):
    stream = make_stream(data)
    message = make_message(user, stream)
    r = req.post(
        Store.slack_webhook,
        headers={ 'Content-type': 'application/json' },
        data=json.dumps(message)
    )
    print(r)

def subscription_handler():
    subscribe.prepare()
    while True:
        print("resubscribing to all")
        for user in User.select():
            subscribe.new_sub(user.user_id)
        time.sleep(Store.subscription_time - 120)

def user_handler():
    while True:
        for user in User.select():
            info = subscribe.get_user_info(user.display_name.lower())
            subscribe.update_or_create(*info)
        update_home()
        time.sleep(5 * 60 * 60)

def update_home():
    while True:
        pass
        # update home with new user data

if __name__ == '__main__':
    main()


import xlrd
import csv
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import style
style.use("ggplot")
from sklearn.cluster import KMeans
import math
from math import radians, cos, sin, asin, sqrt

#Function to convert longitude/latitude distance to km
def haversine(lon1, lat1, lon2, lat2):
    """
    Calculate the great circle distance between two points
    on the earth (specified in decimal degrees)
    """
    # convert decimal degrees to radians
    lon1, lat1, lon2, lat2 = map(radians, [lon1, lat1, lon2, lat2])
    # haversine formula
    dlon = lon2 - lon1
    dlat = lat2 - lat1
    a = sin(dlat/2)**2 + cos(lat1) * cos(lat2) * sin(dlon/2)**2
    c = 2 * asin(sqrt(a))
    km = 6367 * c
    return km

def antenna_classify ():
    homes_path = 'houseList.xlsx' #Opening List of Houses [Location Code, Addresss, LAT, LONG]
    antennas_path = 'antennaLocations.xlsx' #Opening List of Antennas [Location Code, Addresss, LAT, LONG]

    #Number of Cluster Desired
    number_clusters = 71 #44 has been best

    #Clears previous output
    open('output.csv', 'w').close()

    #Opening Specific sheet in the Excel Workbook
    homes_sheet = xlrd.open_workbook(homes_path).sheet_by_index(0)
    antennas_sheet = xlrd.open_workbook(antennas_path).sheet_by_index(0)
    # print("houseList has " + str(homes_sheet.nrows) + " rows and " + str(homes_sheet.ncols) + " columns.")
    # print("antennaLocations has " + str(antennas_sheet.nrows) + " rows and " + str(antennas_sheet.ncols) + " columns.")

    # for row in range(1, homes_sheet.nrows):
    #         print("code: " + str(homes_sheet.cell_value(row, 0)) + " addr: " + str(homes_sheet.cell_value(row, 1)) + " LAT: " + str(homes_sheet.cell_value(row, 2)) + " LONG: " + str(homes_sheet.cell_value(row, 3)))

    # Array of LAT,LONG coordinates for each house
    # Created for numpy array conversion and KMeans
    house_array = []

    # Populates house_array
    for row in range(1, homes_sheet.nrows):
        array_tuple = [homes_sheet.cell_value(row, 2), homes_sheet.cell_value(row, 3)]
        house_array.append(array_tuple)

    # print(house_array)
    # print(len(house_array))

    # Converts to numpy for kmeans clustering
    # This is where the magic happens
    X = np.array(house_array)
    kmeans = KMeans(n_clusters=number_clusters)
    kmeans.fit(X)

    # Centroids Array corresponding to Antenna Locations
    # Labels Array to indicate which cluster each point (house) belongs to
    centroids = kmeans.cluster_centers_
    labels = kmeans.labels_

    # print(centroids)
    # print(labels)

    # List of Colors for visualization
    colors = ["g.","r.","c.","y.", "k.", "b."] * 500

    # Array of arrays to putting each point in its corresponding cluster
    labeled_points = [[] for i in range(number_clusters)]

    # Populating labeled_points
    for i in range(len(X)):
        # print("coordinate:",X[i], "label:", labels[i])
        labeled_points[labels[i]].append(X[i])

        # #LONG AND LAT BACKWARDS ON EXCEL
        # dist = haversine((centroids[labels[i]][1]),[labels[i]][0],X[i][1],X[i][0])
        # # dist = math.sqrt((centroids[labels[i]][0]-X[i][0])**2 +(centroids[labels[i]][1]-X[i][1])**2)
        # distances_from_centroid[labels[i]].append(dist)

        # Plotting all the clusters
        plt.plot(X[i][0], X[i][1], colors[labels[i]], markersize = 10)

    # Array of distances from each house to its corresponding centroid
    distances_from_centroid = [[] for i in range(number_clusters)]
    # index to step through the different centroids corresponding to different clusters
    index = 0
    # iterating through the all clusters of labeled_points and append corresponding distances from centroids to distances_from_centroid
    for clus in labeled_points:
        for point in clus:
            # dist = sqrt((point[1] - centroids[index][1])**2 + (point[0] - centroids[index][0])**2)
            ### NOTE: RELIES ON ORDER OF CENTROIDS TO MATCH THE ORDER OF CLUSTERS (WHICH IS MOST LIKELY THE CASE)
            dist = haversine(point[1], point[0], centroids[index][1], centroids[index][0]) ###IN KM
            dist_ft = dist * 3280.84
            # print(dist)
            # print(dist_ft)
            distances_from_centroid[index].append(dist_ft)
        index += 1
            # print (point)
            # print(len(clus))
            # print(len(labeled_points[0])+len(labeled_points[1])+len(labeled_points[2])+len(labeled_points[3]))

        #LONG AND LAT BACKWARDS ON EXCEL
        # dist = haversine((centroids[labels[i]][1]),centroids[labels[i]][0],l[i][1],X[i][0])
        # dist = math.sqrt((centroids[labels[i]][0]-X[i][0])**2 +(centroids[labels[i]][1]-X[i][1])**2)
        # distances_from_centroid[labels[i]].append(dist)

    # print(labeled_points)
    # print(len(labeled_points))
    # print(type(labeled_points[0]))
    # print(type(centroids))
    # print(type(X))
    # print(distances_from_centroid)

    # below = 0
    # above = 0
    #
    # for x in distances_from_centroid:
    #     maxim = max(x)
    #     if maxim < 500:
    #         below += 1
    #     elif maxim > 500:
    #         above += 1
        # print(maxim)
    # print(min(distances_from_centroid[0]))
    # print(below)
    # print(above)

    # Array of all antennas found in Excel Spreadsheet
    antenna_array = []
    # Populating antenna_array with [Location Code, Address, LAT, LONG]
    for row in range(1, antennas_sheet.nrows):
        array_tuple = [antennas_sheet.cell_value(row, 0), antennas_sheet.cell_value(row, 1), antennas_sheet.cell_value(row, 2), antennas_sheet.cell_value(row, 3)]
        antenna_array.append(array_tuple)

    # print(len(antenna_array))
    # print(len(centroids))

    # Final Array for actual CSV output
    antennas_final = []
    # NOTE: index_antenna relies
    index_antenna = 0
    # Iterating through each centroid in list of centroids corresponding to each cluster
    # Finds the closest Antenna location to match corrresponding centroid
    for cent in centroids:
        temp_best = []
        for point in antenna_array:
            antenna_type = ""
            dist = sqrt((cent[0] - point[2])**2 + (cent[1] - point[3])**2)
            if max(distances_from_centroid[index_antenna]) <= 100:
                antenna_type = "T-1"
            elif max(distances_from_centroid[index_antenna]) <= 200 and max(distances_from_centroid[index_antenna]) > 100:
                antenna_type = "T-2"
            elif max(distances_from_centroid[index_antenna]) <= 300 and max(distances_from_centroid[index_antenna]) > 200:
                antenna_type = "T-3"
            elif max(distances_from_centroid[index_antenna]) <= 400 and max(distances_from_centroid[index_antenna]) > 300:
                antenna_type = "T-4"
            else:
                antenna_type = "T-5"
            if (temp_best == []):
                temp_best = [point, antenna_type]
            elif (dist) < (sqrt((temp_best[0][2] - cent[0])**2 + (temp_best[0][3] - cent[1])**2)):
                temp_best = [point, antenna_type]

        antennas_final.append(temp_best)
        index_antenna += 1

    # print(antennas_final)
    # print(len(antennas_final))

    # Displays a visualization of all clusters and corresponding centroid
    plt.scatter(centroids[:, 0],centroids[:, 1], marker = "x", s=150, linewidths = 5, zorder = 10)
    plt.show()

    # Outputs the AntennaLocationCode, AntennaType of each final antenna to CSV
    with open("output.csv",'w') as resultFile:
        wr = csv.writer(resultFile, delimiter = ",")
        wr.writerow(['AntennaLocationCode', 'AntennaType'])
        for elem in antennas_final:
            wr.writerow([elem[0][0], elem[1]])

#Runs the function
antenna_classify()


import os
import threading
import telebot
from telebot import types
import subprocess
import style_transfer as st_t
import time

def time_to_send(user): #отслеживание появления файла из внешней нейросети
    timer[user] = time.time()
    while True:
        if (time.time() - timer[user]) >= 15:
            if os.path.exists(str(user)+"image3.jpg"):
                with open(str(user)+"image3.jpg", 'rb') as test_image:
                    bot.send_photo(user, test_image, caption='Представляю Вам своё творение. Понадобились недюжинные усилия, но я справился')
                    question_one(user)
                    break
            else:
                timer[user] = time.time()

def delete_user(user, n): #удаление отработанных файлов
    if n == 1: #удаляем начиная заново
        if user in im_name_1:
            im_name_1.pop(user)
    if (n == 1) or (n == 2): #удаляем начиная заново или при смене стиля
        if user in im_name_2:
            im_name_2.pop(user)
        if user in im_name_3:
            im_name_3.pop(user)

def delete_photo(user, n): #удаление отработанных файлов
    if n == 1: #удаляем начиная заново
        if os.path.exists(str(user)+"image1.jpg"):
            os.remove(str(user)+"image1.jpg")
    if (n == 1) or (n == 2): #удаляем начиная заново или при смене стиля
        if os.path.exists(str(user)+"image2.jpg"):
            os.remove(str(user)+"image2.jpg")
        if os.path.exists(str(user)+"image3.jpg"):
            os.remove(str(user)+"image3.jpg")

bot = telebot.TeleBot('token') #адрес бота
im_name_1 = {} #картинка для обработки
im_name_2 = {} #картинки со стилем
im_name_3 = {} #результат
timer = {} #таймер

def help(message):
    user_id = message.chat.id
    bot.send_message(user_id, 'Приветствую! Я талантлвый художник в изгнании.\
    Я отказался от известности, но тоскую по своему ремеслу, и не хочу, чтобы мой прекрасный талант прозябал\
    в безделии и унынии.')
    bot.send_message(user_id, 'Да, я подделывал работы других мастеров, известнейших художников.\
    Но с каким упоением и ни с чем несравнимой радостью я это делал!')
    bot.send_message(user_id, 'Вот пришлите мне совершенно любую картинку, которую хотите изменить.\
    А вслед за нею картину того художника, чей стиль я должен подделать. Уверяю, вы будете удивлены.')

@bot.message_handler(func=lambda message: True, content_types=['text'])
def send_text(message):
    user_id = message.chat.id
    if ('привет' or 'здравствуй') in message.text.lower():
        bot.send_message(user_id, 'Приветствую, пришлите мне картину, которую вы хотите изменить')
    elif ('пока') in message.text.lower():
        bot.send_message(user_id, 'Наши встречи очень много для меня значат. Прощайте.....')
        delete_photo(user_id, 1)
        delete_user(user_id, 1)
        #bot.stop_polling()
    elif ('сотри' or 'удали') in message.text.lower():
        delete_photo(user_id, 1)
        delete_user(user_id, 1)
        bot.send_message(user_id, 'Все следы уничтожены')
    elif ('как дела'or 'как ты') in message.text.lower():
        bot.send_message(user_id, 'Кто-то может сказать, что я счастливчик, но  тем не менее, всё могло быть куда лучше...')
    elif ('вопрос' or 'проблема') in message.text.lower():
        with open('QA.txt', 'a') as bot_feedback:
            bot_feedback.write(str(user_id) + ' ' + message.text + '\n')
        bot.send_message(user_id, 'Отлично, я положил вашу записку в странное приспособление, оставленное  высшими силами.\
        Кто знает, что может произойти?')
    else:
        bot.send_message(user_id, 'Всё-таки, я достаточно занятой человек, чтобы отвечать на вопросы не по моей работе.\
        Но если написать в сообщении слово "вопрос", то силы, что несоизмеримо выше меня, услышат вас\
        А ещё можно написать /help')

@bot.message_handler(func=lambda message: True, content_types=['photo'])
def photo(message):
    user_id = message.chat.id
    fileID = message.photo[-1].file_id
    #если пользователь ещё не отсылал картинок, записываем адрес первой картинки
    if user_id not in im_name_1:
        im_name_1[user_id] = message.photo[-1].file_id
        bot.send_message(message.chat.id, 'У вас отличный вкус!\
        А сейчас пришлите мне картину того художника, чей стиль я должен подделать')
    else:
    	#если пользователь что-то отослал, записываем адрес второй картинки
        im_name_2[user_id] = message.photo[-1].file_id
        #хендлер для выбора способа обработки
        chose_one(user_id)

@bot.callback_query_handler(func=lambda call: True)
def user_answer(call):
    user = call.message.chat.id
    if ((call.data == "0") or (call.data =="1")):
        delete_or_no(user, call.data)
    else:
        convert_image(user, call.data)

def question_one(user):
    if user in im_name_3:
        keyboard = types.InlineKeyboardMarkup()
        keyboard.add(types.InlineKeyboardButton(text="Изменить", callback_data= "0"))
        keyboard.add(types.InlineKeyboardButton(text="Следующая картина", callback_data="1"))
        bot.send_message(user, 'Хотите изменить стилистику, либо изменить следующую картину?', reply_markup=keyboard)

def chose_one(user):
    if user not in im_name_3:
        keyboard = types.InlineKeyboardMarkup()
        keyboard.add(types.InlineKeyboardButton(text="Хочу быстрее", callback_data= "fst"))
        keyboard.add(types.InlineKeyboardButton(text="Могу и подождать", callback_data="slw"))
        bot.send_message(user, 'Хотите результат побыстрее, либо дадите время на детальную проработку?', reply_markup=keyboard)

def convert_image(user, answer):
    if answer == "fst": #быстрый алгоритм
        if len(im_name_1[user]) <= 150: #при повторном запуске в ячейке может быть картинка, а не id файла
            im_name_1[user] = bot.download_file(bot.get_file(im_name_1[user]).file_path)
        im_name_2[user] = bot.download_file(bot.get_file(im_name_2[user]).file_path)
        #запускаем через thread для обеспецения асинхронности
        threading.Thread(target=st_t.photo_connect(im_name_1[user], im_name_2[user], user, im_name_3)).start()
        bot.send_photo(user, im_name_3[user]\
                           , caption='Представляю Вам своё творение. Понадобились недюжинные усилия, но я справился')
        question_one(user)
    elif answer == "slw": #медленный но каественный алгоритм
        with open(str(user)+"image1.jpg", 'wb') as new_file:
            if len(im_name_1[user]) <= 150:
                #при повторном запуске в ячейке может быть картинка, а не id файла
                new_file.write(bot.download_file(bot.get_file(im_name_1[user]).file_path))
            else:
                new_file.write(im_name_1[user])
        with open(str(user)+"image2.jpg", 'wb') as new_file:
            new_file.write(bot.download_file(bot.get_file(im_name_2[user]).file_path))
        im_name_3[user] = str(user)+"image3.jpg"
        bot.send_message(user, 'Тогда я погружаюсь в творческий процесс, на несколько  минут, обычно от двух до пяти.')
        #команда для запуска нейросети. Для снижения нагрузки на память использует cudnn, оптимизатор lbfgs\
        #выдаёт наилучший результат по качеству, хоть и проигрывает adam-у в скорости (порядка 60 секунд)
        command = "python neural_style.py -style_image {} -content_image {} -output_image {}\
         -backend cudnn -optimizer lbfgs".format(str(user)+"image2.jpg", str(user)+"image1.jpg", im_name_3[user])
        p = subprocess.Popen(command) #запускаем сторонний процесс, может одновременно выполняться для нескольких пользователей
        threading.Thread(target=time_to_send(user)).start() #отслеживаем появление результата в папке

def delete_or_no(user, answer):
    if answer == "1":
        delete_photo(user, 1) #удаляем все файлы
        delete_user(user, 1) #очищаем память
        bot.send_message(user, 'Пришлите мне картину, которую вы хотите изменить')
    elif answer == "0":
        delete_user(user, 2) #удаляем всё кроме первого файла
        delete_photo(user, 2) #очищаем память кроме первого файла
        bot.send_message(user, 'Пришлите мне иную картину для вдохновения')

#т.к. возникли проблемы с запуском webhook на локальной машине,
# а времени на веб-сервер из-за загруженности не хватило, обход ошибок телеги выполняем при помощи try/except
while True:
    try:
        bot.polling(none_stop=True, interval=0)
    except:
        time.sleep(5)
"""neural_networks:
    fast: TensorFlow tutorial https://www.tensorflow.org/tutorials/generative/style_transfer
    qualitative: Johnson, Justin, https://github.com/jcjohnson/neural-style
    bot: c-stone studio, Gleb Yakimovich, https://github.com/kolovrado"""


from sortedcontainers import SortedList
class Solution:
    def countSmaller(self, nums: List[int]) -> List[int]:
        # out=[0]*len(nums)
        # for i in range(len(nums)-1):
        #     j= i+1
        #     c=0
        #     while j<len(nums):
        #         if nums[j]<nums[i]:
        #             c+=1
        #         j+=1
        #     out[i] = c
        # return out

        output = []
        arr = SortedList(nums)
        for i in nums:
            idx = arr.index(i)
            output.append(idx)
            arr.remove(i)
        return output


from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response
from django.contrib import messages
from django.utils.translation import ugettext as _
from django.contrib.auth.decorators import login_required
from django.contrib.contenttypes.models import ContentType

from rathings.models import Like, Dislike, dislike_created

@login_required
def like(request, object_id):
    """
    """
    ctype_id = request.GET.get("ctype", None)
    next = request.GET.get("next", None)

    if ctype_id is None:
        messages.add_message(request, messages.ERROR, _("Error interno"))
        return HttpResponseRedirect(request.META.get('HTTP_REFERER'))

    object_ctype = ContentType.objects.get_for_id(ctype_id)
    obj, created = Like.objects.get_or_create(content_type=object_ctype, object_id=object_id, user=request.user)
    if not created:
        messages.add_message(request, messages.INFO, _("Ya te gusta ese comentario"))
    else:
        messages.add_message(request, messages.SUCCESS, _("Ahora te gusta este comentario"))

    if next is not None:
        return HttpResponseRedirect(next)
    return HttpResponseRedirect(request.META.get('HTTP_REFERER'))

@login_required
def dislike(request, object_id):
    """
    """
    ctype_id = request.GET.get("ctype", None)
    next = request.GET.get("next", None)

    if ctype_id is None:
        messages.add_message(request, messages.ERROR, _("Missing ctype_id"))
        return HttpResponseRedirect(request.META.get('HTTP_REFERER'))
    object_ctype = ContentType.objects.get_for_id(ctype_id)
    obj, created = Dislike.objects.get_or_create(content_type=object_ctype, object_id=object_id, user=request.user)
    if not created:
        messages.add_message(request, messages.INFO, _("Ya denunciaste este  {}".format(object_ctype.model)))
    else:
        messages.add_message(request, messages.SUCCESS, _("Acabas de denunciar el {}".format(_(object_ctype.model))))
        dislike_created.send(sender=Dislike, instance=obj)

    if next is not None:
        return HttpResponseRedirect(next)
    return HttpResponseRedirect(request.META.get('HTTP_REFERER'))


# get all Stock Symbols  .
# it should include all stocks in US stock market

# from matplotlib import pyplot as plt
# from datetime import date, timedelta
import pandas as pd
from Getearningcalendar import Getearningcalendar

getcalendar = Getearningcalendar()

fpath_1 = '/datacenter/calendarlist171101-180128.xlsx'
df_1 = getcalendar.read_from_xlsx(fpath_1)
print(df_1.head(5))

list_1 = {}

fpath_2 = '/datacenter/calendarlist0129-0228.xlsx'
df_2 = getcalendar.read_from_xlsx(fpath_2)

print(df_2.head(5))
list_2 = {}

list_tg = {}

list_1['company_name'] = df_1[0][1:].tolist()
list_2['company_name'] = df_2[0][1:].tolist()
list_tg['company_name'] = list_1['company_name'] + list_2['company_name']

list_1['symbol'] = df_1[1][1:].tolist()
list_2['symbol'] = df_2[1][1:].tolist()

list_tg['symbol'] = list_1['symbol'] + list_2['symbol']

list_1['market_cap'] = df_1[2][1:].tolist()
list_2['market_cap'] = df_2[2][1:].tolist()

list_tg['market_cap'] = list_1['market_cap'] + list_2['market_cap']

list_1['reported_date'] = df_1[3][1:].tolist()
list_2['reported_date'] = df_2[7][1:].tolist()

list_tg['reported_date'] = list_1['reported_date'] + list_2['reported_date']

list_1['eps'] = df_1[7][1:].tolist()
list_2['eps'] = df_2[8][1:].tolist()

list_tg['eps'] = list_1['eps'] + list_2['eps']

list_1['num_est'] = df_1[6][1:].tolist()
list_2['num_est'] = df_2[6][1:].tolist()

list_tg['num_est'] = list_1['num_est'] + list_2['num_est']

# print('num_est = ', list_tg['num_est'])

# for i, row in enumerate(list_tg):
#     print(i, row)

# d_s = sorted(list_tg, key = lambda k: list_tg[k][1])

# for i, row in enumerate(list_tg['company_name']):
#     print(i, list_tg['symbol'][i], row)

df = pd.DataFrame.from_dict(list_tg)
df_s = df.sort_values(by=['symbol'])

print(df_s)

df_d = df_s.drop_duplicates(subset='symbol', keep='first')

print('df_d =', df_d)

df_i = df_d.reset_index(drop=True)

print('df_i = ', df_i)

writer = pd.ExcelWriter('/datacenter/calendarlist.xlsx')
df_i.to_excel(writer,'Sheet1')
writer.save()

# # mm/dd/yyyy
# start = '10/01/2017'
# end = '01/26/2018'
#
# # parameters: start date, end date, filtered 1/ unfiltered 0, past p / future f
# # for future = 'f', the eps isn't known yet
#
# list_data = getcalendar.get_calendar_all(start, end, 0)
# #
# # for j, row in enumerate(list_data):
# #     print(j, row)
# #
# getcalendar.write_to_xlsx(list_data, 9)
#
# file_p_1 = '/datacenter/calendarlist0129-0228.xlsx'
#
# df1 = getcalendar.read_from_xlsx(file_p_1)
#
# file_p_2 = '/datacenter/calendarlist171101-180128.xlsx'
#
# df1 = getcalendar.read_from_xlsx(file_p_1)
#
# df2 = getcalendar.read_from_xlsx(file_p_2)
#
# # print(df1[1])
# # print(df2[1])
#
# symbol_1 = df1[1][1:].tolist()
# symbol_2 = df2[1][1:].tolist()
#
# symbols = symbol_1[1:] + symbol_2[1:]
#
# # for i, row in enumerate(symbols):
# #     print(i, row)
#
# symbols_d = list(set(symbols))
#
# symbols_s = sorted(symbols_d)
# for i, row in enumerate(symbols_s):
#     print(i, row)
#
# getcalendar.create_write_file('symbols.txt', symbols_s)

# print(getcalendar.read_txt_file('symbols.txt'))

# list_cols = list(df1.columns.values)
#
# # print(list(df1.columns.values))
#
# list_data = []
#
# for i, row in enumerate(df1[list_cols[0]][1:]):
#     tmp_d_1 = []
#     for j, col in enumerate(list_cols):
#         tmp_d_1.append(df1[list_cols[j]][i + 1])
#     list_data.append(tmp_d_1)
#
# list_filtered = getcalendar.get_filter2(list_data)
#
# for j, cols in enumerate(list_filtered):
#     print(j, cols)

# date_xs = []
# stocks = []
#
# plt.plot(date_xs,  stocks, '.', label='stock')
#
# plt.title('Stock Report')
# plt.legend(bbox_to_anchor=(1, 0), loc=3, borderaxespad=0.2)
#
# plt.show()


import numpy as np
import entropy
import pandas as pd

from pathlib import Path
from helper_functions import convert_assignment_to_clusters as convert_cl

from dhillion import divisive_cluster
import argparse
from all_algos import algo1, algo2, algo3
import time
import warnings
warnings.filterwarnings("ignore", category=np.VisibleDeprecationWarning)

if __name__ == "__main__":
    # pass argument and checking
    parser = argparse.ArgumentParser(description='Argument for R(e_max) algorithm')
    parser.add_argument('-filename',
                        type=str,
                        help='Input filename')

    # parse arg
    args = parser.parse_args()
    filename = Path(args.filename+".csv")
    # filename = Path("ng20.csv")

    data = np.genfromtxt(filename, delimiter=',')
    m, n = data.shape
    # k = args.K
    print("Dimenions of data: %d, %d" %(m, n))

    k_list = list(range(2,20)) + list(range(20, 51, 10)) + [100,200,500,1000,2000]

    e_list = []
    R_e_list = []
    nguyen_impurity_list = []
    nguyen_time_list = []

    dhllion_impurity_list = []
    dhllion_time_list = []

    for k in k_list:
    # nguyen 2021
        nguyen_begin = time.time()
        assnment = algo1(data)
        partitions = convert_cl(assnment, data)

        if len(partitions) == k:
            clusters = partitions
        elif len(partitions) > k:
            clusters = algo2(len(partitions), k, partitions)
        else:
            clusters = algo3(len(partitions), k, partitions)
        nguyen_end = time.time()

        nguyen_time = nguyen_end - nguyen_begin
        impurity_nguyen, e, R_e = entropy.partition_entropy(partitions, data, converted = True)

        e_list.append(e)
        R_e_list.append(R_e)
        nguyen_impurity_list.append(impurity_nguyen)
        nguyen_time_list.append(nguyen_time)

        # dhillion et al
        s = np.random.randint(low=1, high=100, size=1)[0]
        dhillion_begin = time.time()
        dc_dhillion = divisive_cluster(init_type = "dhillion", data = data, k = k, seed = s)
        dc_dhillion.k_means()
        dhillion_end = time.time()
        dhillion_time = dhillion_end - dhillion_begin
        impurity_dhillion = dc_dhillion.get_impurity()

        dhllion_impurity_list.append(impurity_dhillion)
        dhllion_time_list.append(dhillion_time)

        print("K = ", k)
        print("Nguyen et. al. result R(e): {R_e:.2f}, e: {e:.2f}, entropy: {impurity:.2f}, taking {time:.2f}(s)".format(R_e = R_e, e = e, impurity = impurity_nguyen, time = nguyen_time))
        print("Dhillion et. al. result entropy: {impurity:.2f}, taking {time:.2f}(s)".format(impurity = impurity_dhillion, time = dhillion_time))

    df = pd.DataFrame(data = {'k':k_list, 'e': e_list, 'R(e)':R_e_list, \
                'entropy_nguyen': nguyen_impurity_list, "nguyen_time":nguyen_time_list,\
                'dhllion_nguyen': dhllion_impurity_list, "dhllion_time":dhllion_time_list})
    name = args.filename+"_entropies.csv"
    df.to_csv(name, index = False)


# Shared memory 를 만들기 위해서 Manger 모듈 import
from multiprocessing import Manager
# Pro1 프로세스 import
from Step_1.Pro1 import Pro1
from Step_1.Pro2 import Pro2

class body:
    def __init__(self):
        # 1. Shared memory 의 구조를 선언
        self.shared_mem = self.make_memory(label=[])

    def run(self):
        process_list = [Pro1(self.shared_mem), Pro2(self.shared_mem)]       # 리스트에 실행 시키고 싶은 프로세스 넣기
        job_list = []                         # 프로세스 실행후 join 시키기 위해서 리스트 준비

        for __ in process_list:
            __.start()
            job_list.append(__)

        for job in job_list:
            job.join()

    def make_memory(self, label):
        # Tip 및 설명
        # 이 기능의 주된 역할을 Shared memory 의 구조를 작성해서 넘겨준다 (return).
        # 이렇게 하면 Shared memory 의 구조를 변경하거나 관리하기 쉽다.
        # 또한 Shared memory 의 사용 용도에 따라서 구조를 적절하게 사용하는 것이 좋으며
        # dict를 사용하는 편이 데이터 관리에 적합하다.
        return Manager().dict({                    # 기본적으로 dict의 특징을 모두 사용할 수 있다.
            'x축_데이터': [],                # 따라서 dict의 사용법을 잘 알아두는 것이 중요하다.
            'y축_데이터': [],
            1: '숫자도_입력이_가능하다.',
            'Name': 'Shared_mem1',           # 이렇게 이름으로 붙여서 메모리를 관리할 수도 있으며 응용하여 아래와 같이
        })

if __name__ == '__main__':
    Model = body()      # body class를 호출
    Model.run()         # body class의 run함수를 사용하여 프로세스 구동