"""
SWF
"""
from __future__ import absolute_import
from .tag import SWFTimelineContainer
from .stream import SWFStream
from .export import SVGExporter
from six.moves import cStringIO
from io import BytesIO

class SWFHeaderException(Exception):
    """ Exception raised in case of an invalid SWFHeader """
    def __init__(self, message):
         super(SWFHeaderException, self).__init__(message)

class SWFHeader(object):
    """ SWF header """
    def __init__(self, stream):
        a = stream.readUI8()
        b = stream.readUI8()
        c = stream.readUI8()
        if not a in [0x43, 0x46, 0x5A] or b != 0x57 or c != 0x53:
            # Invalid signature! ('FWS' or 'CWS' or 'ZFS')
            raise SWFHeaderException("not a SWF file! (invalid signature)")

        self._compressed_zlib = (a == 0x43)
        self._compressed_lzma = (a == 0x5A)
        self._version = stream.readUI8()
        self._file_length = stream.readUI32()
        if not (self._compressed_zlib or self._compressed_lzma):
            self._frame_size = stream.readRECT()
            self._frame_rate = stream.readFIXED8()
            self._frame_count = stream.readUI16()

    @property
    def frame_size(self):
        """ Return frame size as a SWFRectangle """
        return self._frame_size

    @property
    def frame_rate(self):
        """ Return frame rate """
        return self._frame_rate

    @property
    def frame_count(self):
        """ Return number of frames """
        return self._frame_count

    @property
    def file_length(self):
        """ Return uncompressed file length """
        return self._file_length

    @property
    def version(self):
        """ Return SWF version """
        return self._version

    @property
    def compressed(self):
        """ Whether the SWF is compressed """
        return self._compressed_zlib or self._compressed_lzma

    @property
    def compressed_zlib(self):
        """ Whether the SWF is compressed using ZLIB """
        return self._compressed_zlib

    @property
    def compressed_lzma(self):
        """ Whether the SWF is compressed using LZMA """
        return self._compressed_lzma

    def __str__(self):
        return "   [SWFHeader]\n" + \
            "       Version: %d\n" % self.version + \
            "       FileLength: %d\n" % self.file_length + \
            "       FrameSize: %s\n" % self.frame_size.__str__() + \
            "       FrameRate: %d\n" % self.frame_rate + \
            "       FrameCount: %d\n" % self.frame_count

class SWF(SWFTimelineContainer):
    """
    SWF class

    The SWF (pronounced 'swiff') file format delivers vector graphics, text,
    video, and sound over the Internet and is supported by Adobe Flash
    Player software. The SWF file format is designed to be an efficient
    delivery format, not a format for exchanging graphics between graphics
    editors.

    @param file: a file object with read(), seek(), tell() methods.
    """
    def __init__(self, file=None):
        super(SWF, self).__init__()
        self._data = None if file is None else SWFStream(file)
        self._header = None
        if self._data is not None:
            self.parse(self._data)

    @property
    def data(self):
        """
        Return the SWFStream object (READ ONLY)
        """
        return self._data

    @property
    def header(self):
        """ Return the SWFHeader """
        return self._header

    def export(self, exporter=None, force_stroke=False):
        """
        Export this SWF using the specified exporter.
        When no exporter is passed in the default exporter used
        is swf.export.SVGExporter.

        Exporters should extend the swf.export.BaseExporter class.

        @param exporter : the exporter to use
        @param force_stroke : set to true to force strokes on fills,
                              useful for some edge cases.
        """
        exporter = SVGExporter() if exporter is None else exporter
        if self._data is None:
            raise Exception("This SWF was not loaded! (no data)")
        if len(self.tags) == 0:
            raise Exception("This SWF doesn't contain any tags!")
        return exporter.export(self, force_stroke)

    def parse_file(self, filename):
        """ Parses the SWF from a filename """
        self.parse(open(filename, 'rb'))

    def parse(self, data):
        """
        Parses the SWF.

        The @data parameter can be a file object or a SWFStream
        """
        self._data = data = data if isinstance(data, SWFStream) else SWFStream(data)
        self._header = SWFHeader(self._data)
        if self._header.compressed:
            temp = BytesIO()
            if self._header.compressed_zlib:
                import zlib
                data = data.f.read()
                zip = zlib.decompressobj()
                temp.write(zip.decompress(data))
            else:
                import pylzma
                data.readUI32() #consume compressed length
                data = data.f.read()
                temp.write(pylzma.decompress(data))
            temp.seek(0)
            data = SWFStream(temp)
        self._header._frame_size = data.readRECT()
        self._header._frame_rate = data.readFIXED8()
        self._header._frame_count = data.readUI16()
        self.parse_tags(data)

    def __str__(self):
        s = "[SWF]\n"
        s += self._header.__str__()
        for tag in self.tags:
            s += tag.__str__() + "\n"
        return s


import numpy as np
import pandas as pd
from matplotlib import pyplot as plt
import seaborn as sns
from scipy import stats
import collections
import time
from sklearn import cluster
from sklearn.metrics import adjusted_rand_score
import scipy as sp
from tqdm import tqdm
from sklearn.manifold import MDS
from run_dist_mat import *
from chromosome_alignment import *
from scipy.cluster.hierarchy import dendrogram, linkage
import itertools
from mpl_toolkits.mplot3d import Axes3D
from multiprocessing import Pool
from itertools import repeat

def robustness_analysis():
    reads_to_inlcude = "inliers" #"all"
    clustering_method = "pckmeans" # "igs"
    num_chrs = 19

    data = read_data(clustering_method, reads_to_inlcude) #cells with less than 150 reads are deleted: 80.,  84., 105., 113.

    cum_lens = get_chr_cumulative_lengths()

    fig, axes = plt.subplots(4,4, figsize = (20,20))
    for i, bin_size in tqdm(enumerate([200e6, 100e6, 50e6, 25e6])):
        for j, num_samples_for_resampling in tqdm(enumerate([5, 25, 50, 75])):
            print("\n bin size: ", bin_size)
            print("\n num samples: ", num_samples)

            proportion_matching = []
            variances = []
            cell_i_index = 91
            cell_j_index = 93

            cell_i = data.loc[(data.cell_index==cell_i_index) & (data.chr < 20)].copy()
            cell_i['abs_pos'] = -1
            cell_i['abs_pos'] = cell_i.pos.copy() + [cum_lens[ch-1] for ch in cell_i.chr] #encodes the absolute position of the reads along the linear genome
            cell_j = data.loc[(data.cell_index==cell_j_index) & (data.chr < 20)].copy()
            cell_j['abs_pos'] = -1
            cell_j['abs_pos'] = cell_j.pos.copy() + [cum_lens[ch-1] for ch in cell_j.chr] #encodes the absolute position of the reads along the linear genome

            bins, num_bins_per_chr = get_bins(bin_size, cum_lens, num_chrs)

            num_trials = 40
            min_dists = []
            for trial in range(num_trials):

                bin_resampling_dists = []
                for bin_resampling in range(num_samples_for_resampling):
                    cell_i_dist,_ = pckmeans_get_dist_mat_binned_resample(cell_i, bins, num_bins_per_chr)
                    cell_j_dist,_ = pckmeans_get_dist_mat_binned_resample(cell_j, bins, num_bins_per_chr)

                    num_samples_for_ordering = 50
                    ordering_dists = []
                    random_orders = np.zeros((num_samples_for_ordering, 19))
                    for counter, sample in enumerate(range(num_samples_for_ordering)):
                        order = np.arange(1,20)
                        np.random.shuffle(order)
                        random_orders[counter, :] = order

                     ### parallelizing:
                    num_workers = 4
                    with Pool(num_workers) as p:
                        ordering_dists.append(p.starmap(get_aligned_inter_cell_dist, zip(repeat(cell_i_dist), repeat(cell_j_dist), repeat(num_bins_per_chr), repeat(19), random_orders))[0][0])#the first [0] gives the distance component of the output, the second [0] gets the actual distance and not the size of the intersection

                    bin_resampling_dists.append(np.round(np.min(ordering_dists), 4))
                min_dists.append(np.min(bin_resampling_dists))

            axes[j,i].scatter(np.zeros_like(min_dists), min_dists)
            axes[j,i].set_title("bin size {}".format(bin_size/1e6))
            axes[j,i].set_ylabel("sample size: {}".format(num_samples_for_resampling))

    plt.suptitle("cell indeces {} and {}".format(cell_i_index, cell_j_index))
    plt.savefig("figures/sequential_algorithm_bin_resampling_analysis_cells{}_{}.png".format(cell_i_index, cell_j_index))


from scipy import integrate
import math
def func1(x):
    return 1 / ((3*x - 1)**0.5)
def func2(x):
    return math.log(x**2 + 1) / x
def func3(x):
    return 1 / (0.2*x**2 + 1)**0.5
def rectangle_method(func, a, b, n):
    h = (b - a)/n
    integral_sum = sum(func(a + i * h) for i in range(n))
    result = h * integral_sum
    return result
def simpson_method(func, a, b, n):
    integral_result = integrate.simps([func(a + i * (b - a) / n) for i in range(n+1)], dx=(b - a) / n)
    return integral_result
def trapezoid_method(func, a, b, n):
    h = (b - a) / n
    nodes = [func(a + i * h) for i in range(n + 1)]
    integral_result = h * (sum(nodes) - 0.5 * (nodes[0] + nodes[n]))
    return integral_result
precision = 0.0001
integrals = [(func1, 1.4, 2.1), (func2, 0.8, 1.6), (func3, 1.3, 2.5)]
methods = [rectangle_method, simpson_method, trapezoid_method]
p_values = [10, 8, 20]
for i, (func, a, b) in enumerate(integrals):
    print(f"Інтеграл {i + 1} (від {a} до {b}):")
    method = methods[i]
    n = p_values[i]
    result = method(func, a, b, n)
    print(f"Метод {i + 1}: {result:af}\n")

Pr11 Шамігулової Аліси.py

Pr11 Шамігулової Аліси.py


from django.urls import path

from .views import RegiaoCreate, EmpresaCreate, AgendamentoColetaCreate, AgendamentoDescarteCreate
from .views import RegiaoUpdate, EmpresaUpdate, AgendamentoColetaUpdate, AgendamentoDescarteUpdate
from .views import RegiaoDelete, EmpresaDelete, AgendamentoColetaDelete, AgendamentoDescarteDelete
from .views import RegiaoList, EmpresaList, AgendamentoColetaList, AgendamentoDescarteList

urlpatterns = [
    #Modelo de criação de url: path('endereco/',NomedaView.as.view(),name='nome_da_url'),
    path ('cadastros/regiao/', RegiaoCreate.as_view(), name='cadastrar-regiao'),
    path ('cadastros/empresa/', EmpresaCreate.as_view(), name='cadastrar-empresa'),
    path ('descarte/agendardescarte/', AgendamentoDescarteCreate.as_view(), name='cadastrar-descarte'),
    path ('coleta/agendarcoleta', AgendamentoColetaCreate.as_view(), name='cadastrar-coleta'),

    path ('editar/regiao/<int:pk>', RegiaoUpdate.as_view(), name='editar-regiao'),
    path ('editar/empresa/<int:pk>', EmpresaUpdate.as_view(), name='editar-empresa'),
    path ('editar/descarte/<int:pk>', AgendamentoDescarteUpdate.as_view(), name='editar-descarte'),
    path ('editar/coleta/<int:pk>', AgendamentoColetaUpdate.as_view(), name='editar-coleta'),

    path ('deletar/regiao/<int:pk>', RegiaoDelete.as_view(), name='deletar-regiao'),
    path ('deletar/empresa/<int:pk>', EmpresaDelete.as_view(), name='deletar-empresa'),
    path ('deletar/descarte/<int:pk>', AgendamentoDescarteDelete.as_view(), name='deletar-descarte'),
    path ('deletar/coleta/<int:pk>', AgendamentoColetaDelete.as_view(), name='deletar-coleta'),

    path ('listar/regiao', RegiaoList.as_view(), name='listar-regiao'),
    path ('listar/empresa', EmpresaList.as_view(), name='listar-empresa'),
    path ('listar/descarte', AgendamentoDescarteList.as_view(), name='listar-descarte'),
    path ('listar/coleta', AgendamentoColetaList.as_view(), name='listar-coleta'),
]


import database
from datetime import datetime
import db_pyMySQL

conn = database.connection

# Thêm tài khoản "user": User sẽ không mã hoá mkhau do xài 2 ngôn ngữ khác nhau,
# nên khi mã hoá xong NodeJS sẽ ko hỗ trợ để giải mã => sẽ không đăng nhập được.

# INSERT:
# Thêm tài khoản khách hàng:
def insert_user(name, email, password, phone, address):
    with conn.cursor() as cur:
        mk = password + database.mysecret_key
        # pas = mk.encode()
        sql = '''
        INSERT INTO khachhang(tenkh, email, matkhau, sodienthoai, diachi)
        VALUES (%s, %s, %s, %s, %s)
        '''
        cur.execute(sql, (name, email, mk, phone, address))
        conn.commit()

# Thêm tài khoản "admin":
def insert_admin(admin, matkhau, ten, diachi, sdt, maquyen):
    with conn.cursor() as cur:
        mk = matkhau + database.mysecret_key
        # pas = database.cipher.encrypt(matkhau)   # Mã hoá mật khẩu
        sql = '''
        INSERT INTO admin(admin, matkhau, tennv, diachi, sodienthoai, maquyen)
        VALUES (%s, %s, %s, %s, %s, %s)
        '''
        cur.execute(sql, (admin, mk, ten, diachi, sdt, maquyen))
        conn.commit()

# Thêm "danh mục" sản phẩm:
def insert_category(ma, ten):
    with conn.cursor() as cur:
        sql = '''
        INSERT INTO danhmuc(madm, tendm)
        VALUES (%s, %s)
        '''
        cur.execute(sql, (ma, ten))
        conn.commit()

# Thêm "nhà sản xuất":
def insert_producer(ma, ten, xuatxu):
    with conn.cursor() as cur:
        sql = '''
        INSERT INTO nhasx(mansx, tennsx, xuatxu)
        VALUES (%s, %s, %s)
        '''
        cur.execute(sql, (ma, ten, xuatxu))
        conn.commit()

# Thêm "loại" sản phẩm:
def insert_type(type_id, name):
    with conn.cursor() as cur:
        sql = '''
        INSERT INTO loaisp(maloai, tenloai)
        VALUES (%s, %s)
        '''
        cur.execute(sql, (type_id, name))
        conn.commit()

# Thêm "sản phẩm":
def insert_product(code, name, price, reduced_price, amount, img, producer_id, type_id):
    with conn.cursor() as cur:
        sql = '''
        INSERT INTO sanpham(code, tensp, gia, giamgia, soluong, hinh, mansx, maloai)
        VALUES (%s, %s, %s, %s, %s, %s, %s, %s)
        '''
        cur.execute(sql, (code, name, price, reduced_price, amount, img, producer_id, type_id))
        conn.commit()

# Thêm mới "Quyền hạn - chức vụ":
def insert_permission(code, name):
    with conn.cursor() as cur:
        sql = '''
        INSERT INTO quyen(maquyen, Ten)
        VALUES (%s, %s)
        '''
        cur.execute(sql, (code, name))
        conn.commit()

# Thêm mới "trạng thái":
def insert_status(ten, trangthai):
    with conn.cursor() as cursor:
        sql = '''
        INSERT INTO trangthai(tentt, trangthai)
        VALUES (%s, %s)
        '''
        cursor.execute(sql, (ten, trangthai))
        conn.commit()

    # UPDATE:

# Sửa profile tài khoản admin:
def update_profile_admin(email, name, address, phone, permission, admin_id):
    with conn.cursor() as cur:
        sql = '''
        UPDATE admin
        SET admin = %s, tennv = %s, diachi = %s, sodienthoai = %s, maquyen = %s
        WHERE manv = %s
        '''
        cur.execute(sql, (email, name, address, phone, permission, admin_id))
        conn.commit()
        return 1

# Cập nhật mật khẩu của admin:
def update_password_admin(pas, admin_id):
    with conn.cursor() as cur:
        password = pas + database.mysecret_key
        sql = '''
        UPDATE admin
        SET matkhau = %s
        WHERE manv = %s
        '''
        cur.execute(sql, (password, admin_id,))
        conn.commit()
        return 1

# Sửa profile tài khoản khách hàng:
def update_profile_user(name, email, phone, address, user_id):
    with conn.cursor() as cur:
        sql = '''
        UPDATE khachhang
        SET tenkh = %s, email = %s, sodienthoai = %s, diachi = %s
        WHERE makh = %s
        '''
        cur.execute(sql, (name, email, phone, address, user_id))
        conn.commit()
        return 1

# Cập nhật mật khẩu của khách hàng:
def update_password_user(pas, user_id):
    with conn.cursor() as cur:
        password = pas + database.mysecret_key
        sql = '''
        UPDATE khachhang
        SET matkhau = %s
        WHERE makh = %s
        '''
        cur.execute(sql, (password, user_id,))
        conn.commit()
        return 1

# Sửa danh mục:
def update_category(name, category_id):
    with conn.cursor() as cur:
        sql = '''
        UPDATE danhmuc
        SET tendm = %s
        WHERE madm = %s
        '''
        cur.execute(sql, (name, category_id,))
        conn.commit()
        return 1

# Sửa loại:
def update_type(name, type_id):
    with conn.cursor() as cur:
        sql = '''
        UPDATE loaisp
        SET tenloai = %s
        WHERE maloai = %s
        '''
        cur.execute(sql, (name, type_id,))
        conn.commit()
        return 1

# Sửa nhà sản xuất:
def update_producer(name, origin, producer_id):
    with conn.cursor() as cur:
        sql = '''
        UPDATE nhasx
        SET tennsx = %s, xuatxu = %s
        WHERE mansx = %s
        '''
        cur.execute(sql, (name, origin, producer_id,))
        conn.commit()
        return 1

# Sửa quyền hạn - chức vụ:
def update_permission(name, permission_id):
    with conn.cursor() as cur:
        sql = '''
        UPDATE quyen
        SET Ten = %s
        WHERE maquyen = %s
        '''
        cur.execute(sql, (name, permission_id,))
        conn.commit()
        return 1

# Sửa trạng thái:
def update_status(name, status_id):
    with conn.cursor() as cur:
        sql = '''
        UPDATE trangthai
        SET tentt = %s
        WHERE trangthai = %s
        '''
        cur.execute(sql, (name, status_id,))
        conn.commit()
        return 1

# Sửa sản phẩm:
def update_product(code, name, price, reduced_price, amount, img, producer_id, type_id, product_id):
    with conn.cursor() as cur:
        sql = '''
        UPDATE sanpham
        SET code = %s, tensp = %s, gia = %s, giamgia = %s, soluong = %s, hinh = %s, mansx = %s, maloai = %s
        WHERE masp = %s
        '''
        cur.execute(sql, (code, name, price, reduced_price, amount, img, producer_id, type_id, product_id))
        conn.commit()
        return 1

    # Chức năng của khách hàng.

# Thêm đơn hàng:
def insert_order(user_id, total, product_id, product_name, price, amount):
    try:
        with conn.cursor() as cur:
            order_date = datetime.today()
            sql_order = '''
                INSERT INTO donhang(makh, tong, ngaydat)
                VALUES (%s, %s, %s);
            '''
            val_order = (user_id, total, order_date)
            sql_orderID = "SELECT LAST_INSERT_ID() as LastID;"
            sql_detailOrder = '''
                INSERT INTO chitietdh(masp, tensp, gia, soluong, madonhang)
                VALUES (%s, %s, %s, %s, %s);
            '''
            arrayProduct = []
            try:
                cur.execute(sql_order, val_order)
                conn.commit()
                cur.execute(sql_orderID)
                lastId = cur.fetchone()
                order_id = lastId['LastID']     # Lấy id của đơn hàng vừa tạo.
                for i in arrayProduct:
                    code = i['masp']
                    name = i['tensp']
                    prices = i['gia']
                    amounts = i['soluong']
                    cur.execute(sql_detailOrder, (code, name, prices, amounts, order_id))
                    conn.commit()
            except:
                conn.rollback()
    finally:  # Ngắt kết nối DB.
        conn.close()

# Sửa đơn hàng: Chỉ sửa được đơn hàng khi trạng thái đơn hàng là 'Đang chờ xử lý', còn lại thì khách hàng ko được sửa.
def update_order(amount, order_id):
    with conn.cursor() as cur:
        sql = "SELECT * FROM donhang WHERE madonhang = %s"
        cur.execute(sql, (order_id,))
        order = cur.fetchone()
        product_id = order['masp']
        # Tìm giá của sản phẩm:
        sql1 = "SELECT gia FROM sanpham WHERE masp = %s"
        cur.execute(sql1, (product_id,))
        gia = cur.fetchone()
        price = amount * gia
        if order['trangthai'] == 0:  # Kiểm tra trạng thái đơn hàng.
            sql = '''
                UPDATE donhang
                SET soluong = %s, gia = %s
                WHERE madonhang = %s
            '''
            cur.execute(sql, (amount, price, order_id,))
            conn.commit()
            return 1
        else:  # Đơn hàng đã được duyệt ko thể sửa.
            return -1


# from unicodedata import lookup
from django.urls import path, include
from rest_framework.routers import SimpleRouter, DefaultRouter  # This for the viewset models in the views
from rest_framework_nested import routers  # This is for the nested routers
from store.models import Product
# from pprint import pprint

from . import views

# This is for the nested routers
router = routers.DefaultRouter()
router.register('products', views.ProductViewSet, basename='products')
router.register('carts', views.CartViewSet, basename='carts')
router.register('customers', views.CustomerViewSet, basename='customers')
router.register('orders', views.OrderViewSet, basename='orders')

# product to review nested routing
products_router = routers.NestedDefaultRouter(router, 'products', lookup='product')  # This registers the url as a nested router
products_router.register('reviews', views.ReviewViewSet, basename='product-reviews')# This allows configuration of the already created nested url
products_router.register('images', views.ProductImageViewSet, basename='product-images')# This allows configuration of the already created nested url

cart_router = routers.NestedDefaultRouter(router, 'carts', lookup='cart')  # This registers the url as a nested router
cart_router.register('items', views.CartItemViewSet, basename='cart-items')# This allows configuration of the already created nested url

# This for the normal viewset
# router = SimpleRouter()
# router.register('products', views.ProductViewSet, basename='products')  # the prefix 'products' is what displays as a url

# router = DefaultRouter()
# router.register('products', views.ProductViewSet, basename='products')

# This is a the url pattern for the nestedviewset(its optional)
# urlpatterns = router.urls + products_router.urls

urlpatterns = [
    ## THIS IS FOR ROUTER
    path('', include(router.urls)),
    path('', include(products_router.urls)),
    path('', include(cart_router.urls)),

    ### THIS IS FOR THE CLASS BASED VIEWS
    # path('products/', views.ProductList.as_view()),  # ".as_views()" generates function url for the CBV
    # path('products/<int:pk>/', views.ProductDetail.as_view()),
    path('category/', views.CategoryList.as_view()),
    # path('category/', views.category_list),
    path('category/<int:pk>/', views.CategoryDetail.as_view()),

    ### THIS IS FOR THE FUNCTION BASED VIEWS
    # path('products/', views.product_list),
    # path('products/<int:pk>/', views.product_detail),
    # path('categories/', views.category_list),
    # path('categories/<int:pk>/', views.category_detail),
    # path('categories/<int:pk>/', views.category_detail, name='category-detail'), # This is for the HyperlinkedRelatedField
]


from itertools import permutations
def primenumber(x):
    if x < 2:
        return False
    for i in range(2, x):
    	if x % i == 0:
            return False
    return True

def solution(numbers):
    answer = 0

    num = []
    for i in range(1, len(numbers)+1) :
        num.append(list(set(map(''.join, permutations(numbers, i)))))
    per = list(set(map(int, set(sum(num, [])))))

    for p in per :
        if primenumber(p) == True :
            answer += 1

    return answer

# ========================================================================
# 2023년 4월 16일 문제를 다시 풀어봄.
from itertools import permutations
def primenumber(x):
    if x < 2:
        return False
    for i in range(2, x):
        if x % i == 0:
            return False
    return True

def solution(numbers):
    answer = 0
    result = []
    for number in range(1, len(numbers)+1):
        first = list(set(map(''.join, permutations(numbers, number))))
        result.append(first)
    unduplicated_numbers = list(set(map(int, sum(result, []))))

    for i in unduplicated_numbers:
        if primenumber(i) == True:
            answer += 1
    return answer


import uvicorn
from fastapi import FastAPI, HTTPException

app = FastAPI()

@app.get("/")
async def root():
    return {"message": "Welcome to basic math operations api!"}

@app.get("/add")
async def add(a: int, b: int):
    return {"result": a + b}

@app.get("/subtract")
async def subtract(a: int, b: int):
    return {"result": a - b}

@app.get("/multiply")
async def multiply(a: int, b: int):
    return {"result": a * b}

@app.get("/divide")
async def divide(a: int, b: int):
    if b == 0:
        raise HTTPException(
            status_code=404, detail='Division by 0 not allowed!')
    return {"result": a / b}

if __name__ == '__main__':
    uvicorn.run("app:app", host="0.0.0.0", port=5000, reload=True)


from FACE_VERIFICATION.validation import Verify
from utils.encrypt import Encrypt
from utils.calling import caller
import pickle

obj1 = Verify()
obj2 = Encrypt()
obj3 = caller()

class RUN:
    def __init__(self):
        pass
    def controller(self,data):
        mode = data['mode']
        if mode == "verify":
            response = obj1.verify(frame_count=1,WINDOW=data['image_area'])
            print(response)
            return response
        if mode == "train":
            response = obj1.generate_embeds(frame_count=2,WINDOW=data['image_area'])
            print(response)
            return response
        if mode == "predict":
            response = obj1.verify(frame_count=1,WINDOW=data['image_area'])
            print(response)
            return response

    def encrypt_controller(self,unique_id=None,data=None,mode=None,_id=None):

        if mode == 'Add' or mode == 'Update':
            data = obj2.encrypt_data(unique_id,data)
            return obj3.database_controller(unique_id,data,mode=mode,_id =_id)

        elif mode == "View":
            data = obj3.database_controller(unique_id,data,mode=mode,_id =_id)
            new_data = []
            for key in data.keys():
                new_data = data[key]
                new_data = obj2.decrypt_data(unique_id,new_data)
                data[key] = new_data

            return data

        else:
            return obj3.database_controller(unique_id,data,mode=mode,_id =_id)


"""Determine the fration of non-built-up land area needed to become autarkic."""
import click
import pandas as pd
import geopandas as gpd

from src.potentials import Potential

@click.command()
@click.argument("path_to_demand")
@click.argument("path_to_potential")
@click.argument("path_to_footprint")
@click.argument("path_to_built_up_area")
@click.argument("path_to_units")
@click.argument("path_to_output")
@click.argument("share_from_pv", type=click.INT)
def necessary_land(path_to_demand, path_to_potential, path_to_footprint, path_to_built_up_area,
                   path_to_units, path_to_output, share_from_pv=100):
    """Determine the fraction of non-built-up land area needed to become autarkic.

    Can vary the share of demand satisfied by rooftop PV.

    Ignores offshore as it distorts total area sizes.
    """
    assert share_from_pv <= 100
    assert share_from_pv >= 0
    share_from_pv = share_from_pv / 100
    demand = pd.read_csv(path_to_demand, index_col=0)["demand_twh_per_year"]
    potentials = pd.read_csv(path_to_potential, index_col=0)
    footprint = pd.read_csv(path_to_footprint, index_col=0)
    built_up_area = pd.read_csv(path_to_built_up_area, index_col=0)
    country_codes = gpd.read_file(path_to_units).set_index("id")["country_code"]

    rooftop_pv = potentials[str(Potential.ROOFTOP_PV)].where(
        potentials[str(Potential.ROOFTOP_PV)] < share_from_pv * demand,
        share_from_pv * demand
    )
    demand_after_rooftops = demand - rooftop_pv
    assert (demand_after_rooftops >= 0).all()

    open_field_potential = potentials[str(Potential.ONSHORE_WIND)] + potentials[str(Potential.OPEN_FIELD_PV)]
    open_field_footprint = footprint[Potential.ONSHORE_WIND.area_name] + footprint[Potential.OPEN_FIELD_PV.area_name]
    fraction_non_built_up_land = fraction_land_where_potential_exists(
        open_field_potential=open_field_potential,
        open_field_footprint=open_field_footprint,
        built_up_area=built_up_area,
        demand_after_rooftops=demand_after_rooftops
    )
    fraction_non_built_up_land.where(
        fraction_non_built_up_land.notna(),
        fraction_land_where_no_potential_exists(
            open_field_potential=open_field_potential,
            open_field_footprint=open_field_footprint,
            built_up_area=built_up_area,
            demand_after_rooftops=demand_after_rooftops,
            country_codes=country_codes
        ),
        inplace=True
    )
    # corner cases
    fraction_non_built_up_land[fraction_non_built_up_land > 1] = 1

    pd.DataFrame(
        index=fraction_non_built_up_land.index,
        data={
            "fraction_non_built_up_land_necessary": fraction_non_built_up_land,
            "fraction_roofs_necessary": rooftop_pv / potentials[str(Potential.ROOFTOP_PV)],
            "rooftop_pv_generation_twh_per_year": rooftop_pv
        }
    ).to_csv(
        path_to_output,
        index=True,
        header=True
    )

def fraction_land_where_potential_exists(open_field_potential, open_field_footprint,
                                         built_up_area, demand_after_rooftops):
    share_of_open_field_potential_necessary = demand_after_rooftops / open_field_potential
    necessary_land = open_field_footprint * share_of_open_field_potential_necessary
    return necessary_land / built_up_area["non_built_up_km2"]

def fraction_land_where_no_potential_exists(open_field_potential, open_field_footprint, built_up_area,
                                            demand_after_rooftops, country_codes):
    factor = open_field_footprint.groupby(country_codes).sum() / open_field_potential.groupby(country_codes).sum()
    factor.name = "km2_per_twh_nationally"
    assert (factor > 10).all()
    assert (factor < 70).all()
    factor = pd.DataFrame(country_codes).join(factor.rename("factor"), on="country_code")["factor"]
    necessary_land = demand_after_rooftops * factor
    return necessary_land / built_up_area["non_built_up_km2"]

if __name__ == "__main__":
    necessary_land()


from pathlib import Path
import re, pickle, os
import pickle, win32net
from time import sleep

class Scanner:

    wordList = ""
    ignored_type = ""
    ignored_dir = ""

    # this will store all of the file dictionsaries
    files = []

    # This is the path that will be scanned
    p = ''

    # The code that iterates through the path from above
    def directory_file_iteration(self):
        ignored_directories = self.getIgnoredDirectories()
        ignored_filetypes = self.getIgnoredFileTypes()

        for i in Path(self.p).rglob("*"):

            # If there are directories in the "ignored directories.p" file, then it will iterate through them to see if file should be ignored
            if len(ignored_directories) > 0:

                # If the path of the file is in the ignored directories file, it will move to the next file
                if os.path.normpath(i.parents[0]) in ignored_directories:
                    continue
                # if the file type of the file is in the ignored filetypes, it will move to the next file
                if Path(i).suffix.lower() in ignored_filetypes or len(Path(i).suffix) == 0 and "none" in ignored_filetypes:
                    continue

                # if it passes both, it will check if it's actually a file
                else:
                    if i.is_file():
                        # creating a file dictionary of attributes
                        fileDict = {"filename":i.name,"pathParent":i.parents[0],"fullPath":i, "filetype":Path(i).suffix, "flag":False, "data":{"filename":"","filecontents":"","ssn":"","phone":"","email":[], "cc":""}}
                        self.files.append(fileDict)

                    else:
                        continue

            # if there are none in ignored directories.p it will run this
            elif Path(i).suffix in ignored_filetypes:
                continue
            else:
                if i.is_file():

                    fileDict = {"filename":i.name,"pathParent":i.parents[0],"fullPath":i, "filetype":Path(i).suffix, "flag":False, "data":{"filename":"","filecontents":"","ssn":"","phone":"","email":[], "CC":""}}
                    self.files.append(fileDict)

    # checking to see if a keyword is in a filename
    def checkFileNames(self):
        for file_ in self.files:
            for word in self.wordList:
                if word.lower() in str(file_["filename"].lower()):
                    file_["flag"] = True
                    file_["data"]["filename"] = word

    # reading in .txt files and checking for keywords
    def readInTextFile(self):

        for file_ in self.files:
            if file_["filetype"] == ".txt":

                try: # trying to open the file, sometimes it won't read because it isn't always ascii characters.
                    f = open(file_["fullPath"], "r")
                    fileContents = f.read()
                    f.close()

                    # searching the contents of the file for keyword
                    for word in self.wordList:
                        if word in fileContents.lower():
                            file_["flag"] = True
                            file_["data"]["filecontents"] = file_["data"]["filecontents"] + " " + word

                    # searching contents of file for SSN
                    file_ = self.ssnSearch(file_, fileContents)

                    # searching for phone numbers
                    file_ = self.phoneNumberSearch(file_, fileContents)

                    # searching for emails

                    file_ = self.emailSearch(file_, fileContents)

                    # searching for credit cards

                    file_ = self.ccSearch(file_, fileContents)

                except UnicodeDecodeError:
                    pass
    def ccSearch(self, file_, fileContents):

        ccAmexFound = re.findall(r'(?<!\d)3[47][0-9]{13}$(?!\d)', fileContents)
        ccVisaFound = re.findall(r'(?<!\d)4[0-9]{12}(?:[0-9]{3})?(?!\d)', fileContents)
        ccMasterCardFound = re.findall(r'(?<!\d)(5[1-5][0-9]{14}|2(22[1-9][0-9]{12}|2[3-9][0-9]{13}|[3-6][0-9]{14}|7[0-1][0-9]{13}|720[0-9]{12}))(?!\d)', fileContents)

        strAmex = ''
        strVisa = ''
        strMaster = ''

        for card in ccAmexFound:
            strAmex = strAmex + " , Amex " + str(card)

        for card in ccVisaFound:
            strVisa = strVisa + " , Visa " + str(card)

        for card in ccMasterCardFound:
            strMaster = strMaster + " , Master " + str(card)

        if len(strAmex) + len(strVisa) + len(strMaster) < 1:
            return file_

        else:
            ccFound = str(strAmex) + str(strVisa) + str(strMaster)
            try:
                file_["flag"] = True
            except:
                pass

            file_["data"]["cc"] = file_["data"]["cc"] + ccFound
            return file_

    def emailSearch(self, file_, fileContents):
        emailFound = re.findall(r'[A-Za-z0-9]+[\._]?[a-z0-9]+[@]\w+[.]\w+', fileContents)

        strEmailFound = ""

        for email in emailFound:
            strEmailFound = strEmailFound + " , " + email

        if len(emailFound) < 1:
            return file_

        else:
            try:
                file_["flag"] = True
            except:
                pass
            file_["data"]["email"] += emailFound

            return file_

    def phoneNumberSearch(self, file_, fileContents):
        phoneFound = re.findall(r'(?<!\d)(?!000|.+0{4})(?:\d{10}|\d{3}-\d{3}-\d{4}|\d{3}\.\d{3}\.\d{4}|\d{3}\s\d{3}\s\d{4}|\(\d{3}\)\s\d{3}\s\d{4})(?!\d)', fileContents)

        strPhoneFound = ""

        for phone in phoneFound:
            strPhoneFound = strPhoneFound + " , " + phone

        if len(phoneFound) < 1:
            return file_
        else:
            try:
                file_["flag"] = True
            except:
                pass
            file_["data"]["phone"] = file_["data"]["phone"] + strPhoneFound

            return file_

    # searching for SSNs
    def ssnSearch(self,file_,fileContents):

        #ssn format: xxxxxxxxx or xxx-xx-xxxx
        ssnFound = re.findall(r'(?<!\d)(?!000|.+0{4})(?:\d{9}|\d{3}-\d{2}-\d{4})(?!\d)', fileContents)

        strSSNFOUND = ""

        for ssn in ssnFound:
            strSSNFOUND = strSSNFOUND + " , " + ssn

        if len(ssnFound) < 1:
            return file_
        else:
            try:
                file_["flag"] = True
            except:
                pass
            file_["data"]["ssn"] = file_["data"]["ssn"] + strSSNFOUND

            return file_

    # Ignore_dir.txt which will hold directories you want to ignore
    def getIgnoredDirectories(self):
        ignored_directories = pickle.load(open("ignored directories.p","rb"))
        return ignored_directories

    # Ignore the file types in this file such as .torrent, .txt
    def getIgnoredFileTypes(self):
        ignored_filetypes = pickle.load(open("ignored filetypes.p", "rb"))
        return ignored_filetypes

    # Setting path to scan
    def setPath(self,i):
        self.p = i

    def getWordList(self):
        self.wordList = pickle.load(open("word list.p", "rb"))

    def checkIfAdmin(self):
        if 'logonserver' in os.environ:
            server = os.environ['logonserver'][2:]
        else:
            server = None

        def if_user_is_admin(Server):
            groups = win32net.NetUserGetLocalGroups(Server, os.getlogin())
            isadmin = False
            for group in groups:
                if group.lower().startswith('admin'):
                    isadmin = True
            return isadmin, groups

        # Function usage
        is_admin, groups = if_user_is_admin(server)

        # Result handeling
        if is_admin == True:
            return True
        else:
            return False
        #print('You are in the following groups:')
        # for group in groups:
        #     print(group)

        #sleep(10)
        #if error: no module named win32api, run these lines in cmd
        #pip uninstall pipywin32
        #pip uninstall pywin32
        #pip install pywin32

    def get_scanning(self, scan_type):

        if scan_type == "quick":

            self.getWordList()
            self.files = [] # removing all data in the files list
            self.directory_file_iteration()
            self.checkFileNames()

        else:
            self.getWordList()
            self.files = [] # removing all data in the files list
            self.directory_file_iteration()
            self.checkFileNames()
            self.readInTextFile()

        return self.files


from selenium import webdriver
import time, re, urllib, requests

from telethon.sync import TelegramClient
from config import api_id, api_hash

client = TelegramClient('name', api_id, api_hash)

client.start()

dlgs = client.get_dialogs()

tegmo = None

for dlg in dlgs:
    if dlg.title == "LTC Click Bot":
        tegmo = dlg

if tegmo == None:
    print("Отсутствует чат с ботом")
    exit()

print(tegmo.title)

# dr_options = webdriver.FirefoxOptions()
# dr_options.set_headless()
# driver = webdriver.Firefox(options=dr_options)

from selenium.webdriver.chrome.options import Options

chrome_options = Options()
chrome_options.add_argument("--headless")
chrome_options.add_argument('--disable-gpu')
chrome_options.add_argument('--log-level=3')
driver = webdriver.Chrome(chrome_options=chrome_options)

tmp_url = ''
n = 0
nn = 0
links = True
links2 = True
try:
    while True:
        msg = client.get_messages(tegmo, limit=1)[0]

        if re.search(r'\bThere is a new site for you to\b', msg.message):
            client.send_message(  tegmo , "🖥 Visit sites")

        if re.search(r'\bPlease stay on the site for at least 10 seconds\b', msg.message):
            time.sleep(10)
            continue

        if re.search(r'\bSorry\b', msg.message):
            time.sleep(10)
            nn = nn + 1
            print('Закончились ссылки ждем','.'*nn,  end='\r')
            client.send_message(  tegmo , "🖥 Visit sites")
            continue

        if re.search(r'\bPress the "Visit website" button to earn LTC\b', msg.message):
            nn = 0
            url = msg.reply_markup.rows[0].buttons[0].url
            if tmp_url == url:
                nn = nn + 1

                print("ссыдка с задежкой", '.'*nn , end='\r')
                time.sleep(5)

                t_el = driver.find_elements_by_class_name('timer')
                text = ''
                for i in t_el:
                    if (len(i.text) > 0):
                        text = i.text
                        i.click()
                print(text)

                if ''.join(text) == '':
                    client.send_message(  tegmo , "🖥 Visit sites")

                links2 = False
                continue
            links = True
            print("переходим по ссылке", url)
            driver.get(url)

            n = n + 1
            print("проходов ",n)

            tmp_url = url
            time.sleep(2)

except Exception as ex:
    print(ex)
finally:
    driver.close()


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# mid2sheet.py
# Midi-Files -> Sheets for Musicbox (30 notes, starting from F)
# (c) 2017 Niklas Kannenberg <kannenberg@airde.net> and Gunnar J.
# Released under the GPL v3 or later, see file "COPYING"
#
#   ToDo
#     - Use 'pypdf' instead of external 'pdfjam' for PDF merging, avoid latex
#       (to much dependencies)
#
#   Bugs
#     - No whitespace in path/to/script allowed
#       pdfjam and rm will not work, see subprocess.call()
#     - exits if input/output folder not exists, better create output folder
#
#
# Useful links:
# https://mido.readthedocs.io/en/latest/midi_files.html
# http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.html
# http://stackoverflow.com/questions/3444645/merge-pdf-files
# https://pythonhosted.org/PyPDF2/
#
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#

import mido
import os
import pandas as pd
import matplotlib.pyplot as plt
import subprocess
import datetime

# version of this software
version            =     0.3

# print lot of debug messages?
debug              =       0

# directories
inputdir           = os.getcwd()+"/input"    # input directory, e.g. "/input"
outputdir          = os.getcwd()+"/output"   # output directory for PDFs

# notes and y_mm
yBase       =   5.5           # y_mm first note
yAbst       =   58.5 / 29.0   # y_mm between notes
yUppr       =   70.0          # y_mm whole strip

# Plot
x8beat      =     4.0         # x_mm per 1/8 beat
minbeat     =     7.9         # minimal playable x-distance for one note
xprmax      =   250.0         # printable size, A4 Landscape
preplt      =     8.0         # space for note names on plot, do not change

# lut midi-note -> y_mm
notemmlut   = [   #  Note       # y_mm                  # name
              [   53,           yBase +  0 * yAbst  ],  #  F

              [   55,           yBase +  1 * yAbst  ],  #  G

              [   60,           yBase +  2 * yAbst  ],  #  C

              [   62,           yBase +  3 * yAbst  ],  #  D

              [   64,           yBase +  4 * yAbst  ],  #  E
              [   65,           yBase +  5 * yAbst  ],  #  F

              [   67,           yBase +  6 * yAbst  ],  #  G

              [   69,           yBase +  7 * yAbst  ],  #  A
              [   70,           yBase +  8 * yAbst  ],  #  A#
              [   71,           yBase +  9 * yAbst  ],  #  H
              [   72,           yBase + 10 * yAbst  ],  #  C
              [   73,           yBase + 11 * yAbst  ],  #  C#
              [   74,           yBase + 12 * yAbst  ],  #  D
              [   75,           yBase + 13 * yAbst  ],  #  D#
              [   76,           yBase + 14 * yAbst  ],  #  E
              [   77,           yBase + 15 * yAbst  ],  #  F
              [   78,           yBase + 16 * yAbst  ],  #  F#
              [   79,           yBase + 17 * yAbst  ],  #  G
              [   80,           yBase + 18 * yAbst  ],  #  G#
              [   81,           yBase + 19 * yAbst  ],  #  A
              [   82,           yBase + 20 * yAbst  ],  #  A#
              [   83,           yBase + 21 * yAbst  ],  #  H
              [   84,           yBase + 22 * yAbst  ],  #  C
              [   85,           yBase + 23 * yAbst  ],  #  C#
              [   86,           yBase + 24 * yAbst  ],  #  D
              [   87,           yBase + 25 * yAbst  ],  #  D#
              [   88,           yBase + 26 * yAbst  ],  #  E
              [   89,           yBase + 27 * yAbst  ],  #  F

              [   91,           yBase + 28 * yAbst  ],  #  G

              [   93,           yBase + 29 * yAbst  ],  #  A
              ]

print("-> Converting .mid to .pdf for Musicbox  -  mid2sheet v"+str(version))
print("--------------------------------------------------------")
print("Input from Folder: "+inputdir)
print("Output  to Folder: "+outputdir)

# midi note number to y_mm
def get_mm(note):
    retval = -1
    for i in range(len(notemmlut)):
        if (notemmlut[i][0] == note):
            retval = notemmlut[i][1]
    return retval

# name of midi note number
def get_name(note):
    names = [ "C","C#","D","D#","E","F","F#","G","G#","A","A#","H" ]
    return names[note % 12]

# returns 1 if note is to close to last note on same line
def get_terr(notes, pos):
    gap = 9999
    for i in range(0,pos):
        if(notes.note[i] == notes.note[pos]):
            gap = notes.x[pos] - notes.x[i]
    if(gap < minbeat): # gap < min_gap
        return 1 # not playable
    else:
        return 0 # OK

# mm -> inch (for matplotlib)
def mm2in(mm):
    return mm/10/2.54  # mm to inch

# convert one midi file
def do_convert(infile, outfile, fname):

    mid        = mido.MidiFile(infile)      # the input file
    now        = datetime.datetime.now()    # actual time
    sig_cnt    = 0                          # counter for signature messages
    tim_cnt    = 0                          # counter for timing messages

    # midi timing ticks per beat
    ticks_4th  = mid.ticks_per_beat
    ticks_8th  = ticks_4th / 2

    # data frame for all midi events of melody track
    datacols   = ['time','tdiff','type','track','bytes']
    data       = pd.DataFrame(columns=datacols)

    # data frame for note_on events
    notecols   = ['time','note','name', 'x', 'y', 'bar']
    notes      = pd.DataFrame(columns=notecols)

    # list all tracks
    if(debug):
        print("Tracks  : " + str(len(mid.tracks)))
        for i in range(len(mid.tracks)):
            track_len = len(mid.tracks[i])
            print("Track " + str(i) + " : " + str(track_len) + " events")

    # extract all messages from all tracks to data frame 'data'
    for i, track in enumerate(mid.tracks):

        for msg in track:

            if(msg.type == "time_signature"):
                time_signature = msg.dict()
                numerator = time_signature['numerator']
                denominator = time_signature['denominator']
                sig_cnt += 1
                if(debug):
                    print("Timing  : " + str(numerator) + "/" + str(denominator))

            if(msg.type == "set_tempo"):
                set_tempo = msg.dict()
                tempo = round((500000 / set_tempo['tempo']) * 120, 2)
                tim_cnt += 1
                if(debug):
                    print("Tempo   : " + str(tempo) + " bpm")

            data = data.append({ 'time'  : 0,
                                 'tdiff' : msg.time,
                                 'type'  : msg.type,
                                 'track' : i,
                                 'bytes' : msg.bytes()  }, ignore_index=True)

    # warnings for tracks, tempo and signature
    if(len(mid.tracks) != 1):
        print("-> WARNING: Midi file has " + str(len(mid.tracks)) + " tracks instead of 1")
    if(sig_cnt != 1):
        print("-> WARNING: Midi file has " + str(sig_cnt) + " signature messages instead of 1. " +
              "Using " + str(numerator) + "/" + str(denominator))
    if(tim_cnt != 1):
        print("-> WARNING: Midi file has " + str(tim_cnt) + " tempo messages instead of 1. " +
              "Using " + str(tempo) + " bpm.")

    # calculate absolute timing values
    for i in range(1, len(data)):
        # actual time difference
        tdiffnext = data.tdiff[i]
        # accumulate time only for same track
        if(data.track[i] == data.track[i-1]):
            timeacc   = data.time[i-1]
        else:
            timeacc   = 0
        data.loc[i, 'time'] = timeacc + tdiffnext

    # extract all 'note_on' events from 'data' to 'notes
    for i in range(len(data)):
       #         event == note_on   AND         velocity > x
       if(data.type[i] == 'note_on' and data.bytes[i][2] > 0):

         thisnote  = data.bytes[i][1]
         mtime = data.time[i]
         x_val = ( mtime / ticks_8th ) * x8beat

         notes = notes.append({ 'time' : data.time[i],
                                'note' : thisnote,
                                'name' : get_name(thisnote),
                                'x'    : x_val,
                                'y'    : get_mm(thisnote),
                                'bar'  : (data.time[i] /
                                         (4 * ticks_4th * (numerator/denominator))) + 1
                              }, ignore_index=True)

    # mm per bar
    mm_bar = 8 * x8beat * (numerator/denominator)
    # bars per page
    bars_pp = int((xprmax - preplt) / mm_bar)

    # debug
    if(debug):
        #print("--- DATA ---")
        #print(data)
        print("--- NOTES ---")
        print(notes)

    # generate plot
    # -----------------------------

    # size of one strip
    strip_x  = mm2in(preplt + bars_pp * mm_bar) # X-Size of plot
    strip_y  = mm2in(yUppr)                     # Y-Size of plot
    hlines_x = mm2in(preplt)  # start of horizontal note lines
    newpage = 1  # flag for newpage
    pagecnt = 0  # page counter
    poffs   = 0  # x-offset for current page

    # for all notes  (can't manipulate k in 'for' loop but in 'while' loop)
    k = 0
    while(k < len(notes) ):

      # create a new plot
      if( newpage==1 ):

        newpage = 0            # reset flag
        pagecnt = pagecnt + 1  # increment page counter

        if(pagecnt > 1):       # re plot last notes on current page
          while( (notes.bar[k] ) >=  bars_pp * (pagecnt - 1) + 1 ):
            k -= 1
          k += 1 # undo last while, no 'do-while' loop in python

        # frame line width, hacked
        plt.rcParams['axes.linewidth'] = 0.2

        # x-offset for this page
        poffs = mm2in( -preplt + (pagecnt-1) * mm_bar * bars_pp )

        # create figure
        f  = plt.figure(figsize=(strip_x,strip_y), dpi=300,frameon=False)
        ax = plt.subplot(111)
        # figure has no borders
        plt.subplots_adjust(left=0,right=1,bottom=0,top=1)

        # plot 30 horizontal lines
        for i in range(len(notemmlut)):

          yy = mm2in(notemmlut[i][1]) # y-val
          nnote = get_name(notemmlut[i][0])  # name of the acutal note

          if(nnote == "C"):          #  C-Lines
            plt.plot([hlines_x,strip_x],[yy,yy],color="black", linewidth=0.4)
          elif nnote.endswith("#"):  # #-Lines (Black keys)
            plt.plot([hlines_x,strip_x],[yy,yy],color="black", linewidth=0.1, linestyle=':')
          else:                      # Normal Lines
            plt.plot([hlines_x,strip_x],[yy,yy],color="black", linewidth=0.2)

          # add the name of the note
          if(i%2 ==0): ofs = 0.1    # indent every 2nd note
          else:        ofs = 0.0    # no indent
          ax.text(.1+ofs,yy, nnote, fontsize=5,verticalalignment='center',rotation=90)

        # plot beat lines
        for i in range(bars_pp * numerator):
          xx = mm2in(mm_bar) / numerator # x per bar
          if(i % numerator == 0):
            # plot line (full bar)
            plt.plot([hlines_x+xx*i, hlines_x+xx*i ],
                     [mm2in(notemmlut[0][1]), mm2in(notemmlut[-1][1])],color="black",linewidth=0.4)
            # plot bar number
            ax.text( hlines_x+xx*i + (xx/2), mm2in(notemmlut[0][1]) - mm2in(2.5),
                   str(int(1+ i/numerator + bars_pp * (pagecnt-1))),
                   fontsize=5,horizontalalignment='center',)
          else:
            # plot line (beat)
            plt.plot([hlines_x+xx*i, hlines_x+xx*i ],
                     [mm2in(notemmlut[0][1]), mm2in(notemmlut[-1][1])],
                      color="black",linewidth=0.1, linestyle=':')

        # add song name and info
        ax.text( hlines_x + mm2in(4), yy + mm2in(2),
                 str(pagecnt) + "     " + fname + "       " +
                 str(numerator) + "/" + str(denominator) + "   " + str(tempo) + " bpm",
                 fontsize=8, horizontalalignment='left')
        ax.text( mm2in(xprmax) / 2, yy + mm2in(2),
                 "Generated in " + now.strftime('%Y-%m-%d') +
                 " with mid2sheet v" + str(version)  ,
                 fontsize=5, horizontalalignment='left')

        # vertical start line
        plt.plot([hlines_x,hlines_x],[0,strip_y],color="black", linewidth=0.4)
        plt.xticks([])
        plt.yticks([])
        ax.axis([0,strip_x, 0, strip_y])

      # end if newpage

      # position of note to plot
      xx = mm2in(notes.x[k])
      yy = mm2in(notes.y[k])
      xx = xx -poffs

      # plot one note
      if(notes.y[k] != -1): # normal note
        plt.plot(xx,yy,marker='.',color='white',markersize=12)
        plt.plot(xx,yy,marker='.',color='black',markersize=8)
        plt.plot(xx,yy,marker='.',color='white',markersize=5)
        # fill red, if timing is to short
        if(get_terr(notes, k)):
          plt.plot(xx,yy,marker='.',color='red',markersize=3)
      else: # plot error note name (not in musicbox range)
        ax.text( xx,mm2in(1),get_name(int(notes.note[k])),
                 fontsize=5,color='red', horizontalalignment='center',)

      # prepare new page, if this note was already outside current page
      if( (notes.bar[k] ) >  bars_pp * pagecnt + 1  ):
        newpage = 1
        # save current page to file
        filename = outfile + "_%03d" % (pagecnt) + '.pdf'
        f.savefig(filename, bbox_inches='tight')
      # next note (manually in while loop)
      else:
        k += 1

      # for all notes

    # save last page to file
    filename = outfile + "_%03d" % (pagecnt) + '.pdf'
    f.savefig(filename, bbox_inches='tight')

    # combine pdfs, TODO: switch to PyPDF2
    subprocess.call("pdfjam " + outfile  + "_*.pdf  --nup 1x2 --a4paper --landscape  --noautoscale true --delta '0.5cm 0.5cm'  --outfile " + outfile + ".pdf", shell=True)
    subprocess.call("rm " + outfile  + "_*.pdf ", shell=True)

    # result: list of notes with x,y mm values
    return notes

# convert all files
for filename in os.listdir(inputdir):

    if filename.endswith(".mid"):

        inpfile      = inputdir+"/"+filename

        outfile_name = filename.rsplit('.', 1)[0]
        outfile      = outputdir+"/"+outfile_name

        print("--------------------------------------------------------")
        print("-> Input File  : "+filename)
        print("-> Output File : "+outfile_name + ".pdf")

        do_convert(inpfile, outfile, outfile_name)

print("--------------------------------------------------------")
print("DONE")


from django.contrib.auth.decorators import user_passes_test, login_required
from django.http import HttpResponse, HttpResponseRedirect
from django.http import JsonResponse
from django.shortcuts import render, redirect
from apps.rfid.models import GeneralAssembly
from hybridjango.utils import group_test

class Ballot:
    nr = 0
    title = 'Avstemning'
    choices = [
        'Blank',
        'Vevkom',
        'Bedkom',
        'Arrkom',
        'Jentekom',
        'Redaksjonen',
    ]
    only_members = True
    empty_votes = True
    is_attending = True
    has_voted = []
    votes = []
    active = True

class Suggestion:
    num = 0
    author = "Ikke vevsjef"
    suggestion_text = "Vevkom burde ta over styret"
    suggestions_enabled = False

empty_vote = 'Tomt'
suggestion_list = []

@user_passes_test(group_test("Tellekorps"))
def overview(request):
    user = request.user
    if request.method == 'POST':
        if 'ballot_form' in request.POST:
            Ballot.title = request.POST.get('title', 'Avstemning')
            Ballot.only_members = True if request.POST.get('membersOnly') else False
            Ballot.empty_votes = True if request.POST.get('empty_votes') else False
            Ballot.is_attending = True if request.POST.get('is_attending') else False
            Ballot.choices = [v for k, v in request.POST.items() if k.startswith('choice-')]
            Ballot.votes = []
            Ballot.has_voted = []
            Ballot.nr += 1
        return HttpResponseRedirect('#')
    elif 'active' in request.GET:
        Ballot.active = not (request.GET['active'] == 'Deaktiver')
    return render(
        request, 'ballot/overview.html', context={
            'active': Ballot.active,
            },
        )

@user_passes_test(group_test("Nestleder"))
def suggestion_overview(request):
    user = request.user
    if request.method == 'POST':
        if 'toggle_suggestions' in request.POST:
            Suggestion.suggestions_enabled = not Suggestion.suggestions_enabled
        elif 'clear_suggestions' in request.POST:
            del suggestion_list[:]
        return HttpResponseRedirect("#")

    return render(request, 'ballot/suggestions.html', context={
            'suggestions_enabled' : Suggestion.suggestions_enabled
    })

@login_required
def post_suggestion(request):
    sugg = Suggestion()
    sugg.num += 1
    sugg.author = request.user
    sugg.suggestion_text = request.POST.get('suggestion_text')
    suggestion_list.append(sugg)

@user_passes_test(group_test("Nestleder"))
def get_suggestions(request):
    json_list = [{
        "author_name" : suggestion.author.full_name,
        "suggestion_text" : suggestion.suggestion_text,
    } for suggestion in suggestion_list]
    return JsonResponse({"suggestion_list" : json_list})

@login_required
def ballot(request):
    return render(request, 'ballot/voteview.html', get_ballot_dict(request.user))

@login_required
def get_choices(request):
    return JsonResponse(get_ballot_dict(request.user))

def get_ballot_dict(user):
    choices = Ballot.choices.copy()
    if Ballot.empty_votes:
        choices.append(empty_vote)
    return {
        'nr': Ballot.nr,
        'title': Ballot.title,
        'choices': choices,
        'has_voted': user.pk in Ballot.has_voted,
        'active': Ballot.active,
        'suggestions_enabled' : Suggestion.suggestions_enabled,
    }

def vote(request):
    if request.method == 'POST':
        user = request.user
        generalassembly = GeneralAssembly.objects.all().last() #fetches the newest made generalassembly object

        if not user.is_authenticated:
            return HttpResponse("Du må være innlogget for å stemme")
        if not Ballot.active:
            return HttpResponse("Avstemningen er ikke aktiv")
        if user.pk < 2:
            return HttpResponse("Linjeforeningen Hybrida kan ikke stemme selv")
        if Ballot.only_members and not user.member:
            return HttpResponse("Kun medlemmer kan stemme")
        if Ballot.is_attending and user not in generalassembly.users.all():
            return HttpResponse("Du må registrere oppmøte for å kunne stemme")
        if user.pk in Ballot.has_voted:
            return HttpResponse("Du har allerede stemt")

        new_vote = request.POST.get("choice", None)
        if new_vote in Ballot.choices or (Ballot.empty_votes and new_vote == empty_vote):
            Ballot.has_voted.append(user.pk)
            Ballot.votes.append(new_vote)
            return HttpResponse("Du stemte på {}.".format(new_vote))

    return HttpResponse("Du avga ingen stemme")

@user_passes_test(group_test("Tellekorps"))
def get_results(request):
    user = request.user
    if not (user.is_authenticated and group_test("Tellekorps")):
        return JsonResponse(
            {"title": "Hvem er best?", "results": [{"name": "vevkom", "votes": 9001}, {"name": "andre", "votes": 0}],
             "total": 9001, "total_nonblank": 9001})
    results = [{'name': choice, 'votes': Ballot.votes.count(choice)} for choice in Ballot.choices]
    total_nonblank = total = len(Ballot.votes)
    if Ballot.empty_votes:
        results.append({'name': empty_vote, 'votes': Ballot.votes.count(empty_vote)})
        total_nonblank -= Ballot.votes.count(empty_vote)
    return JsonResponse({'title': Ballot.title, 'results': results, 'total': total, 'total_nonblank': total_nonblank})


#!/usr/bin/env python3

import argparse
import os
import re
import subprocess
import sys

LOG_FILE_OPTION = 'log_file'
OUTPUT_PATH_OPTION = '--output-path'
ONLY_FAILED_OPTION = '--only-failed'
HUMAN_READABLE_OPTION = '--human-readable'
USE_RUBY_PARSER_OPTION = '--use-ruby'
FIND_COREDUMPS_OPTION = "--find-coredumps"
WRITE_RESULTS_TO_DATABASE_OPTION = "--write-to-database"
HELP_OPTION = '--help'

options = argparse.ArgumentParser(description="CTest parser usage:")
options.add_argument(LOG_FILE_OPTION, help="CTEST LOG FILE PATH")
options.add_argument("-f", ONLY_FAILED_OPTION, action="store_true", help="PARSE ONLY FAILED TESTS")
options.add_argument("-r", HUMAN_READABLE_OPTION, action="store_true", help="HUMAN READABLE OUTPUT")
options.add_argument("-o", OUTPUT_PATH_OPTION, metavar="output_path", help="OUTPUT DIRECTORY PATH")
options.add_argument("-u", USE_RUBY_PARSER_OPTION, action="store_true", help="USE OLD RUBY PARSER")
options.add_argument("-c", FIND_COREDUMPS_OPTION, choices=["url", "files"], help="FIND AND STORE COREDUMPS")
options.add_argument("-w", WRITE_RESULTS_TO_DATABASE_OPTION, action="store_true", help="WRITE TEST RESULTS TO DATABASE")

parserRoot = os.path.dirname(os.path.abspath(__file__))

def parseCtestRuby(opts, path):
    command = [
        "{}/ruby-scripts/parse_ctest_log.rb".format(parserRoot),
        "-l", opts.log_file,
        "-o", "{}/ruby/results".format(path),
        "-j", "{}/ruby/json".format(path),
        "-s", "{}/ruby/ctest_sublogs".format(path)
    ]
    if opts.human_readable:
        command.append("-r")
    if opts.only_failed:
        command.append("-f")
    return subprocess.check_output(command)

def parseCtestPython(opts, path):
    command = [
        "{}/python-scripts/parse_ctest_log.py".format(parserRoot),
        opts.log_file,
        "-o", "{}/python/results".format(path),
        "-j", "{}/python/json".format(path),
        "-s", "{}/python/ctest_sublogs".format(path)
    ]
    if opts.human_readable:
        command.append("-r")
    if opts.only_failed:
        command.append("-f")
    return subprocess.check_output(command)

def storeCoredumpsRuby(opts, buildId, path):
    command = [
        "{}/ruby-scripts/coredump_finder.sh".format(parserRoot),
        buildId,
        opts.find_coredumps
    ]
    coredumps = subprocess.check_output(command)
    writeCoredumpsToFile("{}/ruby/coredump".format(path), coredumps)

def storeCoredumpsPython(opts, buildId, path):
    command = [
        "{}/python-scripts/coredump_finder.py".format(parserRoot),
        buildId,
        opts.find_coredumps
    ]
    coredumps = subprocess.check_output(command)
    writeCoredumpsToFile("{}/python/coredump".format(path), coredumps)

def getLogsDir(output):
    return re.search(b'(Logs dir: |"logs_dir": ")(\w+-\d+)', output).group(2)

def writeCoredumpsToFile(path, coredumps):
    file = open(path, "w")
    file.write("COREDUMPS \\\n")
    file.writelines(coredumps)
    file.close()

def writeToDatabaseRuby(opts, path):
    command = [
        "{}/ruby-scripts/write_build_results.rb".format(parserRoot),
        "-f", "{}/ruby/json".format(path)
    ]
    return subprocess.check_output(command)

def writeToDatabasePython(opts, path):
    command = [
        "{}/python-scripts/write_build_results.py".format(parserRoot),
        "{}/python/json".format(path)
    ]
    return subprocess.check_output(command)

def main(args=None):
    opts = options.parse_args(args=args)
    path = os.path.dirname(os.path.abspath(opts.log_file))
    if opts.output_path:
        path = opts.output_path

    if opts.use_ruby:
        result = parseCtestRuby(opts, path)
        if opts.find_coredumps:
            storeCoredumpsRuby(opts, getLogsDir(result), path)
        if opts.write_to_database:
            writeToDatabaseRuby(opts, path)
    else:
        result = parseCtestPython(opts, path)
        if opts.find_coredumps:
            storeCoredumpsPython(opts, getLogsDir(result), path)
        if opts.write_to_database:
            writeToDatabasePython(opts, path)

if os.path.samefile(__file__, sys.argv[0]):
    main()