#!/usr/bin/env python3
"""
project: Pythonic Card Deck
created:2021-10-19
@author:seraph
email:seraph776@gmail.com
"""

from collections import namedtuple
from random import choice

# namedtuple used to construct a simple class to represent individual cards:
Card = namedtuple('Card', ['rank', 'suit'])

class CardDeck:
    """A Deck class."""
    # develop 2 lists of ranks and suits:
    ranks: list = [str(n) for n in range(2, 11)] + list('JQKA')
    suits: list = 'spades diamonds clubs hearts'.split()

    def __init__(self):
        """Initialize attributes."""
        # Develop complete deck of 52 cards:
        self._cards = [Card(rank, suit) for suit in self.suits for rank in self.ranks]

    def __len__(self):
        # to get the length of the deck
        return len(self._cards)

    def __getitem__(self, position):
        # To support indexing and slicing:
        return self._cards[position]

def main():
    deck = CardDeck()
    print(len(deck)) # 52
    print(deck[0])   # Card(rank='2', suit='spades')
    print(deck[0][0])  # 2
    print(deck[0][1])  # spades
    # Get a randoom card
    print(choice(deck))

if __name__ == '__main__':
    main()


import youtube_dl
import os
from sys import argv
from pydub import AudioSegment

# PROCESS OF CONVERSION
def process(f):
    audioIN = AudioSegment.from_file(f)
    print("Processing.... " + str(f))
    audioIN.export(f[:-4] + "mp3", format="mp3")
    os.remove(f)

# CONFIG OF DOWNLOAD

download_config = {
    'format': 'bestaudio/best',
    'outtmpl': '%(title)s.%(ext)s',
    'nocheckcertificate': True,
    'postprocessor': [{
        'key': 'FFmpegExtractAudio',
        'preferredcodedc': 'mp3',
        'preferredquality': '192',
    }],
}

# SONG DIRECTORY
if not os.path.exists('Songs'):
    os.mkdir('Songs')

os.chdir('Songs')

# DOWNLOADING
with youtube_dl.YoutubeDL(download_config) as dl:
    with open("../" + argv[1],'r') as f:
        for song_url in f:
            dl.download([song_url])

#CONVERSION
files = os.listdir(".")
for f in files:
    if f.lower()[-4:] == "webm":
        process(f)


import requests
from datetime import datetime
import api_keys

now = datetime.now()
formatted_now_date = now.strftime("%d/%m/%Y")
formatted_now_time = now.time().strftime("%H:%M:%S")
exercise_ep = "https://trackapi.nutritionix.com/v2/natural/exercise"
sheety_url = "https://api.sheety.co/dd81a891f83891fcffdab1dcc7c5a53e/casualWorkoutTracking/workouts"

exercise_params = {
    "query": input("Tell me which exercises you did today: \n"),
    "gender": api_keys.GENDER,
    "weight_kg": api_keys.WEIGHT_KG,
    "height_cm": api_keys.HEIGHT_CM,
    "age": api_keys.AGE

}

exercise_response = requests.post(url=exercise_ep, headers=api_keys.header, json=exercise_params)
exercise_data = exercise_response.json()

headers = {
    "Authorization": f"Bearer {api_keys.BEARER_TOKEN}"
}

for exercise in exercise_data["exercises"]:
    print(exercise)
    print("==========================================")

    body = {
        "workout": {
            "date": formatted_now_date,
            "time": formatted_now_time,
            "exercise": exercise["name"],
            "calories": exercise["nf_calories"],
            "duration": exercise["duration_min"]
        }
    }
    sheety_response = requests.post(url=sheety_url, json=body, headers=headers)
    sheety_data = sheety_response.json()
    print(sheety_data)


from io import BytesIO
from .models import Book
from librarian import DocProvider
from django.http import HttpResponse

class RedakcjaDocProvider(DocProvider):
    """Used for getting books' children."""

    def __init__(self, publishable):
        self.publishable = publishable

    def by_slug(self, slug):
        print(slug)
        return BytesIO(Book.objects.get(catalogue_book_id=slug
                    ).materialize(publishable=self.publishable
                    ).encode('utf-8'))

def serve_file(file_path, name, mime_type):
    def read_chunks(f, size=8192):
        chunk = f.read(size)
        while chunk:
            yield chunk
            chunk = f.read(size)

    response = HttpResponse(content_type=mime_type)
    response['Content-Disposition'] = 'attachment; filename=%s' % name
    with open(file_path, 'rb') as f:
        for chunk in read_chunks(f):
            response.write(chunk)
    return response


#!/usr/bin/env python
# coding=utf-8
'''
Author: Yuxiang Yang
Date: 2021-08-11 10:15:36
LastEditors: Yuxiang Yang
LastEditTime: 2021-08-11 10:28:24
FilePath: /leetcode/剑指 Offer 04. 二维数组中的查找.py
Description:
在一个 n * m 的二维数组中，每一行都按照从左到右递增的顺序排序，每一列都按照从上到下递增的顺序排序。请完成一个高效的函数，输入这样的一个二维数组和一个整数，判断数组中是否含有该整数。
'''
class Solution(object):
    def binarySearch(self, nums, target):
        left = 0
        right = len(nums) - 1
        while left <= right:
            mid = left + (right - left) // 2
            if nums[mid] == target:
                return True
            elif nums[mid] > target:
                right = mid - 1
            else:
                left = mid + 1
        return False

    def findNumberIn2DArray0(self, matrix, target):
        """
        :type matrix: List[List[int]]
        :type target: int
        :rtype: bool
        """
        # 时间复杂度:O(mlogn)
        if not matrix or not matrix[0]:
            return False
        m = len(matrix)
        n = len(matrix[0])
        for i in range(m):
            if matrix[i][0] <= target <= matrix[i][n-1]:
                if self.binarySearch(matrix[i], target):
                    return True
        return False

    def findNumberIn2DArray(self, matrix, target):
        """
        :type matrix: List[List[int]]
        :type target: int
        :rtype: bool
        """
        # 从右上角出发，碰到大于target的列减一，碰到小于target的行加一
        # 时间复杂度:O(m+n)
        if not matrix or not matrix[0]:
            return False
        m = len(matrix)
        n = len(matrix[0])
        i = 0
        j = n-1
        while i < m and j >= 0:
            if matrix[i][j] == target:
                return True
            elif matrix[i][j] > target:
                j -= 1
            else:
                i += 1
        return False

if __name__ == '__main__':
    nums = [[1,4,7,11,15],[2,5,8,12,19],[3,6,9,16,22],[10,13,14,17,24],[18,21,23,26,30]]
    target = 5
    print(Solution().findNumberIn2DArray(nums, target))


def mergeSortedArrays(lists):
    # Write your code here.
    if len(lists) == 1:
        return lists

    def merge_lists(l1, l2):
        i, j = 0, 0
        res = []
        while i < len(l1) and j < len(l2):
            if l1[i] < l2[j]:
                res.append(l1[i])
                i += 1
            else:
                res.append(l2[j])
                j += 1
        while i < len(l1):
            res.append(l1[i])
            i += 1

        while j < len(l2):
            res.append(l2[j])
            j += 1

        return res

    l = 0
    for r in range(1, len(lists)):
        lists[l] = merge_lists(lists[l], lists[r])

    return lists[l]

if __name__ == "__main__":
    print(mergeSortedArrays([ [1,3,5,9,12], [2,3,4,19,22], [-2,11] ]))


# File: pastebin_view.py
#
# Copyright (c) 2019-2023 Splunk Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software distributed under
# the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
# either express or implied. See the License for the specific language governing permissions
# and limitations under the License.
#
#
def _get_data_result(result):

    ctx_result = {}
    data = result.get_data()
    status = result.get_status()

    ctx_result['status'] = status
    if (data):
        ctx_result['data'] = data[0]

    return ctx_result

def display_paste(provides, all_app_runs, context):

    context['results'] = results = []

    for summary, action_results in all_app_runs:
        for result in action_results:
            get_data_result = _get_data_result(result)
            if (get_data_result is None):
                continue
            results.append(get_data_result)

    if provides == 'get data':
        return 'pastebin_display_paste.html'


# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
'''
class Solution:
    def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
        def invert(root):
            if not root:
                return

            invert(root.left)
            invert(root.right)
            root.left, root.right = root.right, root.left

        invert(root)
        return root
'''

#更简洁的写法：
'''
class Solution:
    def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
        if not root:
            return

        self.invertTree(root.left)
        self.invertTree(root.right)
        root.left, root.right = root.right, root.left
        return root
'''

#用stack的迭代法
class Solution:
    def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
        if not root:
            return

        stack = [(root,False)]

        while stack:
                node, visited = stack.pop()
                if node:
                    if visited:
                        node.right, node.left = node.left, node.right
                    else:
                        stack.append((node.right, False))
                        stack.append((node.left, False))
                        stack.append((node,True))
        return root


# -*- encoding:utf-8 -*-
from __future__ import absolute_import

from random import randint

from api.manager.positon_manager import add_activity_location
from commercial.models import Club, CommercialActivity
from utilities.string_utils import random_str

def create_club():
    return Club.objects.create(name=random_str(8), fans_num=8, address=random_str(20), avatar=random_str(10),
                               lat=40 + 0.1 * randint(1, 8), lon=116 + 0.1 * randint(1, 8))

def create_activity(club=None, name='', address='', time_detail='', description='', total_quota=10, participant_num=6,
                    detail=''):
    if not club:
        club = create_club()
    name = name or random_str(8)
    address = address or random_str(20)
    time_detail = time_detail or random_str(20)
    description = description or random_str(30)
    total_quota = total_quota or randint(10, 20)
    participant_num = participant_num or randint(5, 10)
    detail = detail or random_str(8)
    activity = CommercialActivity.objects.create(club=club, name=name, address=address, time_detail=time_detail,
                                                 description=description, total_quota=total_quota,
                                                 participant_num=participant_num, detail=detail, lon=club.lon,
                                                 lat=club.lat)
    add_activity_location(activity.id, club.lon, club.lat)
    return activity


import torch
import numpy as np

class CategoriesSampler():

    def __init__(self, label, n_batch, n_cls, n_per):
        self.n_batch = n_batch
        self.n_cls = n_cls
        self.n_per = n_per

        label = np.array(label)
        self.m_ind = []
        for i in range(max(label) + 1):
            ind = np.argwhere(label == i).reshape(-1)
            ind = torch.from_numpy(ind)
            self.m_ind.append(ind)

    def __len__(self):
        return self.n_batch

    def __iter__(self):
        for i_batch in range(self.n_batch):
            batch = []
            classes = torch.randperm(len(self.m_ind))[:self.n_cls]
            for c in classes:
                l = self.m_ind[c]
                pos = torch.randperm(len(l))[:self.n_per]
                batch.append(l[pos])
            batch = torch.stack(batch).t().reshape(-1)
            yield batch


import matplotlib.pyplot as plt
import geopandas

# 3D Plot
def plot3Dtrajectory(name, desc, x, y, z):
    fig = plt.figure(figsize=(6,6))
    ax = fig.add_subplot(111, projection = '3d')

    ax.plot(x, y, z, color = 'purple', label = 'GPS', marker = '')

    plt.title(name + " " + desc)

    ax.set_xlabel('|X] = km')
    ax.set_ylabel('[Y] = km')
    ax.set_zlabel('[Z] = km')
    ax.set_xlim3d(-33000,33000)
    ax.set_ylim3d(-33000,33000)
    ax.set_zlim3d(-33000,33000)

    plt.savefig("Export/" + name + "_" + desc + '.png')

def plotGroundTrack(name, desc, lat, long, min, max):
    countries = geopandas.read_file(geopandas.datasets.get_path("naturalearth_lowres"))

    countries.plot(color = "grey")
    plt.scatter(long, lat, color = "purple")

    plt.grid()
    plt.ylim(-90,90)
    plt.xlim(-180,180)
    plt.title(name + " " + desc)
    plt.figtext(0.5, 0.15, "Minimale Breite: " + str(min) + "° / maximale Breite: " + str(max) + "°", ha = "center", fontsize = 9, style = "italic")

    plt.savefig("Export/" + name + "_" + desc + '.png')

def polarPlot(name, desc, az, el):

    fig, ax = plt.subplots(1,1, figsize=(8,8), subplot_kw=dict(projection='polar'))

    plt.scatter(az, el, color='purple', label=name)

    ax.set_theta_zero_location("N")
    ax.set_theta_direction(-1)
    plt.figtext(0.54, 0.5, "Elevation", rotation=62.5)
    plt.ylim(90,0)
    plt.title(name + " " + desc)

    plt.savefig("Export/" + name + "_" + desc + '.png')

def elevationPlot(name, desc, el, timeoverHorizon):
    time = []

    if name == "Lageos1":
        for i in range(0, 86401, 120):
            time.append(i)
    else:
        for i in range(0, 86401, 300):
            time.append(i)

    fig = plt.figure(figsize=(8, 6))

    ax = fig.add_subplot(111)
    plt.scatter(time, el, color= "purple")
    plt.ylim(0,90)
    plt.xlim(0, 86400)
    plt.grid()

    plt.title(name + " " + desc)
    plt.figtext(0.5, 0.03, "Sichtbare Zeit: " + str(timeoverHorizon) + "s (" + str(timeoverHorizon / 3600) + "h)", ha = "center", fontsize = 9)

    plt.savefig("Export/" + name + "_" + desc + '.png')


"""Test cases for 'Mailgun' provider module."""
import pytest

import f451_comms.constants as const
import f451_comms.providers.mailgun as mailgun
from f451_comms.exceptions import MissingAttributeError

# =========================================================
#     G L O B A L S   &   P Y T E S T   F I X T U R E S
# =========================================================
_DEFAULT_MSG_ = "Hello World!"
_DEFAULT_TAG_ = "safe"
_DEFAULT_TEST_STRING_ = "_TEST_STRING_"
_DEFAULT_TEST_NAME_ = "Batman"
_DEFAULT_TEST_EMAIL_ = "batman@example.com"
_DEFAULT_TEST_SUBJECT_ = "_TEST_SUBJECT_"

@pytest.fixture()
def mixed_tag_list():
    """Return mixed tag strings."""
    return [_DEFAULT_TAG_, "äpple", "nötter", "blåbär", "three", "four"]

@pytest.fixture()
def mixed_attribs():
    """Return mixed attributes."""
    return {
        const.KWD_FROM_NAME: _DEFAULT_TEST_NAME_,
        const.KWD_TO_EMAIL: _DEFAULT_TEST_EMAIL_,
        const.KWD_SUBJECT: _DEFAULT_TEST_SUBJECT_,
        const.KWD_TAGS: _DEFAULT_TEST_STRING_,
        const.KWD_TRACKING: True,
        const.KWD_TESTMODE: True,
    }

@pytest.fixture()
def mailgunClient(valid_settings, mixed_attribs):
    """Return Nailgun client."""
    return mailgun.Mailgun(
        apiKey=valid_settings.get(
            const.CHANNEL_MAILGUN, const.KWD_PRIV_KEY, fallback=""
        ),
        fromDomain=valid_settings.get(
            const.CHANNEL_MAILGUN, const.KWD_FROM_DOMAIN, fallback=""
        ),
        **mixed_attribs,
    )

# =========================================================
#                T E S T   F U N C T I O N S
# =========================================================
def test_static_process_tag_list(mixed_tag_list):
    """Verify ability to process tag list."""
    # Test happy path
    totNum = len(mixed_tag_list)
    maxNum = totNum + 1
    processed = mailgun.process_tag_list(
        inList=mixed_tag_list,
        maxNum=maxNum,
        minTagLen=mailgun._MIN_TAG_LEN_,
        maxTagLen=mailgun._MAX_TAG_LEN_,
    )
    assert len(processed) == len(mixed_tag_list)

    # Test blank items
    processed = mailgun.process_tag_list(
        inList=["one", "", "", "three"],
        maxNum=10,
        minTagLen=mailgun._MIN_TAG_LEN_,
        maxTagLen=mailgun._MAX_TAG_LEN_,
    )
    assert len(processed) == 2

    # Test max items
    processed = mailgun.process_tag_list(
        inList=["one", "two", "three", "four"],
        maxNum=3,
        minTagLen=mailgun._MIN_TAG_LEN_,
        maxTagLen=mailgun._MAX_TAG_LEN_,
    )
    assert len(processed) == 3

    # Test min/max chars
    processed = mailgun.process_tag_list(
        inList="abc123",
        maxNum=10,
        minTagLen=1,
        maxTagLen=3,
    )
    assert len(processed[0]) == 3
    processed = mailgun.process_tag_list(
        inList=["abc123", "a", "ab"],
        maxNum=10,
        minTagLen=3,
        maxTagLen=10,
    )
    assert len(processed[0]) == 6

    # Test 'ascii' conversion
    processed = mailgun.process_tag_list(
        inList="äpple", maxNum=10, minTagLen=3, maxTagLen=10
    )
    assert processed[0] == "?pple"

def test_create_Tags_object(mixed_tag_list):
    """Verify ability to creata a 'Tag' object."""
    # Test happy path
    totNum = len(mixed_tag_list)
    maxNum = totNum + 1
    obj = mailgun.Tags(
        inList=mixed_tag_list,
        maxNum=maxNum,
        minLen=mailgun._MIN_TAG_LEN_,
        maxLen=mailgun._MAX_TAG_LEN_,
    )
    assert obj.keyword == const.KWD_TAGS
    assert not obj.isRequired
    assert obj.isValid
    assert obj.minNum == 0
    assert obj.maxNum == maxNum
    assert obj.totNum == totNum
    assert len(obj.raw) == totNum
    assert isinstance(obj.clean, list)

    # Test 'maxNum'
    maxNum = len(mixed_tag_list) - 1
    obj = mailgun.Tags(
        inList=mixed_tag_list,
        maxNum=maxNum,
        minLen=mailgun._MIN_TAG_LEN_,
        maxLen=mailgun._MAX_TAG_LEN_,
    )
    assert obj.minNum == 0
    assert obj.maxNum == maxNum
    assert obj.totNum == maxNum
    assert len(obj.raw) == maxNum
    assert len(obj.clean) == maxNum

    # Test assertion that 'tags' can be empty
    obj = mailgun.Tags(
        inList=[""],
        maxNum=10,
        minLen=mailgun._MIN_TAG_LEN_,
        maxLen=mailgun._MAX_TAG_LEN_,
    )
    assert obj.isValid
    assert obj.raw == []
    assert obj.clean == []

def test_create_RecipientData_object(valid_attribs_dict):
    """Verify ability to creata a 'RecipientData' object."""
    # Test happy path
    totNum = len(valid_attribs_dict.items())
    maxNum = totNum + 1
    obj = mailgun.RecipientData(inData=valid_attribs_dict, maxNum=maxNum)
    assert obj.keyword == const.KWD_RECIPIENT_DATA
    assert not obj.isRequired
    assert obj.isValid
    assert obj.minNum == 0
    assert obj.maxNum == maxNum
    assert obj.totNum == totNum
    assert len(obj.raw.items()) == totNum
    assert isinstance(obj.clean, str)
    assert len(obj.clean) > 1

    # Test 'maxNum'
    maxNum = len(valid_attribs_dict.items()) - 1
    obj = mailgun.RecipientData(inData=valid_attribs_dict, maxNum=maxNum)
    assert obj.minNum == 0
    assert obj.maxNum == maxNum
    assert obj.totNum == maxNum
    assert len(obj.raw.items()) == maxNum

    # Test assertion that 'recipient_data' can be empty
    obj = mailgun.RecipientData(inData={}, maxNum=10)
    assert obj.isValid
    assert obj.raw == {}
    assert obj.clean == "{}"

def test_create_Mailgun_object(mailgunClient, valid_settings, mixed_attribs):
    """Verify ability to creata a 'Mailgun' object."""
    client = mailgunClient
    assert client.serviceType == const.SRV_TYPE_EMAIL
    assert client.serviceName == mailgun._SRV_PROVIDER_
    assert client.configSection == mailgun._SRV_CONFIG_SCTN_

    client = mailgun.Mailgun(
        valid_settings.get(const.CHANNEL_MAILGUN, const.KWD_PRIV_KEY, fallback=""),
        valid_settings.get(const.CHANNEL_MAILGUN, const.KWD_FROM_DOMAIN, fallback=""),
        **mixed_attribs,
    )
    assert len(client.defaultTo) == 1
    assert client.defaultTo[0].email == _DEFAULT_TEST_EMAIL_
    assert client.defaultSubject == _DEFAULT_TEST_SUBJECT_
    assert client.defaultTags == [_DEFAULT_TEST_STRING_]
    assert client._tracking
    assert client._testmode

def test_send_message(mocker, mailgunClient):
    """Verify ability to send message."""
    with pytest.raises(MissingAttributeError) as e:
        mailgunClient.send_message("")
    assert e.type == MissingAttributeError
    assert "blank" in e.value.args[0]

    attribs = {
        const.KWD_SUBJECT: "",
        const.KWD_TO_EMAIL: "one@example.com",
    }
    with pytest.raises(MissingAttributeError) as e:
        mailgunClient.send_message(_DEFAULT_MSG_, **attribs)
    assert e.type == MissingAttributeError
    assert "blank" in e.value.args[0]

    attribs = {
        const.KWD_SUBJECT: _DEFAULT_MSG_,
        const.KWD_TO_EMAIL: "",
    }
    with pytest.raises(MissingAttributeError) as e:
        mailgunClient.send_message(_DEFAULT_MSG_, **attribs)
    assert e.type == MissingAttributeError
    assert "blank" in e.value.args[0]

    attribs = {
        const.KWD_SUBJECT: _DEFAULT_MSG_,
        const.KWD_TO_EMAIL: "one@example.com",
        const.KWD_HTML: f"{_DEFAULT_MSG_}",
        const.KWD_RECIPIENT_DATA: {
            "one@example.com": {"first": "First", "last": "Person", "uuid": "12345567"}
        },
        const.KWD_TESTMODE: False,
    }

    mocker.patch.object(mailgunClient, "send_message", autospec=True)
    mailgunClient.send_message(_DEFAULT_MSG_, **attribs)
    mailgunClient.send_message.assert_called_once()

@pytest.mark.slow
def test_send_message_extensive(mocker, mailgunClient, new_attachment_file):
    """Verify ability to send message with more data."""
    attribs = {
        const.KWD_SUBJECT: _DEFAULT_MSG_,
        const.KWD_TO_EMAIL: ["one@example.com", "two@example.com"],
        const.KWD_CC_EMAIL: "cc@example.com",
        const.KWD_BCC_EMAIL: ["bcc@example.com", "", "bcc2@example.com"],
        const.KWD_TAGS: ["äpple", "nötter", "", "blåbär", "three", "four"],
        const.KWD_HTML: f"{_DEFAULT_MSG_}",
        const.KWD_ATTACHMENTS: new_attachment_file,
        const.KWD_INLINE: new_attachment_file,
        const.KWD_RECIPIENT_DATA: {
            "one@example.com": {"first": "First", "last": "Person", "uuid": "12345567"},
            "two@example.com": {"first": "Second", "last": "Human", "uuid": "98765443"},
        },
        const.KWD_TESTMODE: False,
    }

    mockMailgunClient = mailgunClient
    mocker.patch.object(mockMailgunClient, "send_message", autospec=True)
    mailgunClient.send_message(_DEFAULT_MSG_, **attribs)
    mailgunClient.send_message.assert_called_once()

# from inspect import currentframe, getframeinfo
# helpers.pp(capsys, data, currentframe())


from aiogram import types, Dispatcher
from aiogram.dispatcher import FSMContext
from aiogram.dispatcher.filters import Text

async def cmd_start(message: types.Message, state: FSMContext):
    await state.finish()
    await message.answer(
        "Начните ваш заказ (/food)!",
        reply_markup=types.ReplyKeyboardRemove()
    )

async def cmd_cancel(message: types.Message, state: FSMContext):
    await state.finish()
    await message.answer("Действие отменено", reply_markup=types.ReplyKeyboardRemove())

def register_handlers_common(dp: Dispatcher):
    dp.register_message_handler(cmd_start, commands="start", state="*")
    dp.register_message_handler(cmd_cancel, commands="cancel", state="*")
    dp.register_message_handler(cmd_cancel, Text(equals="отмена", ignore_case=True), state="*")


import os
from multiprocessing import Process
from pathlib import Path
from shutil import rmtree
from time import sleep

import lmdb
import pytest
import rocksdb
from rocksdb.errors import RocksIOError

class TestDBPath:
    rocksdb = "test_rocksdb"
    lmdb = "test_lmdb"

def print_process_info(title):
    print("\n--------------------------")
    print(title)
    print("module name:", __name__)
    print("parent process:", os.getppid())
    print("process id:", os.getpid())

def f_rocksdb(name: str):
    print_process_info(f"function f_rocksdb({name})")
    data = b"test_test_test_rocksdb"

    try:
        db = rocksdb.DB(TestDBPath.rocksdb, rocksdb.Options(create_if_missing=True))
        db.put(b"name", data)
        print("f_rocksdb as a Writer")
    except RocksIOError:
        sleep(0.1)
        db = rocksdb.DB(TestDBPath.rocksdb, rocksdb.Options(create_if_missing=True), read_only=True)
        if data != db.get(b"name"):
            exit(-1)
        print("f_rocksdb as a Reader")
    sleep(1)

def f_lmdb(name: str):
    print_process_info(f"function f_lmdb({name})")
    data = b"test_test_test_lmdb"

    if name == "prop1":
        env = lmdb.open(TestDBPath.lmdb)
        with env.begin(write=True) as txn:
            txn.put(b"name", data)
        print("f_lmdb as a Writer")
    else:
        sleep(0.1)
        env = lmdb.open(TestDBPath.lmdb)
        with env.begin() as txn:
            if data != txn.get(b"name"):
                exit(-1)
        print("f_lmdb as a Reader")
    sleep(1)

def delete_test_db_dirs():
    db_paths = [Path(f"./{TestDBPath.lmdb}"), Path(f"./{TestDBPath.rocksdb}")]

    for db_path in db_paths:
        if db_path.exists():
            print(f"delete DB({db_path.resolve()})")
            rmtree(db_path)

@pytest.fixture(autouse=True)
def run_around_tests():
    delete_test_db_dirs()
    yield
    delete_test_db_dirs()

class TestMultiProcessLevelDB:
    store_process_functions = [f_rocksdb, f_lmdb]

    @pytest.mark.parametrize("store_process_function", store_process_functions)
    def test_multiprocessing_db(self, store_process_function):
        p1 = Process(target=store_process_function, args=("prop1",))
        p1.start()

        p2 = Process(target=store_process_function, args=("prop2",))
        p2.start()

        p1.join()
        p2.join()

        # RocksDB supports multiprocessing.
        assert p1.exitcode == 0
        assert p2.exitcode == 0


import itertools
from unittest.mock import Mock

from sukoon.kernel import SukoonKernel

def test_all():
    test_data = open("test/basic.py")

    test = ''
    expected = ''
    for line in itertools.chain(test_data, ['']):
        if line.startswith('##'):
            expected += line[2:].lstrip()
        elif line.strip() == '' and test and expected:
            run_single(test, expected)
            test = ''
            expected = ''
        else:
            test += line

def run_single(test, expected):
    kernel = SukoonKernel()
    send_response = Mock()
    kernel.send_response = send_response
    kernel.do_execute(test, False)

    response = send_response.call_args[0][2]['text']
    assert expected == response


import sys
import decimal
import re

from PyQt5.QtWidgets import QDialog
from PyQt5.QtCore import Qt

import user as userdetail
from lib.utils.evalenv import evalenv
from db.models import Selfdefinedformat, Forms
from product.controllers.productcontroller import ProductController
from stuff.controllers.stuffcontroller import StuffController
from labrecord.controllers.labrecordscontroller import LabrecordsController

from lib.xmlwidget.xmlcheckbox import XmlCheckBox
from lib.xmlwidget.xmlcombobox import XmlComboBox
from lib.xmlwidget.xmlexprbox import XmlExprBox
from lib.xmlwidget.xmllineedit import XmlLineEdit
from lib.xmlwidget.xmlsignbox import XmlSignBox
from lib.xmlwidget.xmllabel import XmlTextEdit

from tesui import Ui_Form

# 批记录产品信息类变量
PRODUCT_DICT = {'PBIANHAO': 'prodid', 'PMING': 'prodname', 'PGUIGE': 'spec',
                'PBZGG': 'package', 'PTMING': 'commonname', 'PPIHAO': 'batchno',
                'PSHIJI': 'realamount', 'PJIHUA': 'planamount',
                'PJIXING': 'medkind'
                }
# 批记录物料信息类变量
STUFF_DICT = {'ID': 'stuffid', 'MING': 'stuffname', 'PIHAO': 'batchno',
              'LEIBIE': 'kind', 'GUIGE': 'spec', 'BZGG': 'package',
              'JBDW': 'unit', 'XBZDW': 'spunit', 'ZBZDW': 'mpunit',
              'DBZDW': 'bpunit',
              'JIHUA': 'presamount', 'SHIJI': 'realamount',
              'LINGQU': 'drawamount',
              'SHENGYU': 'restamount', 'TUIKU': 'backamount',
              'SHUIFEN': 'water',
              'HANLIANG': 'content', 'CHANGJIA': 'producer'
              }
STUFF_KIND = {'ZF': (0, 1), 'ZC': 0, 'FC': 1, 'NB': 2, 'WB': 3, 'BC': (2, 3),
              'QC': 4}
# 检验报告类信息变量
# 检品编号，检品名称，批号，半成品取样，成品取样，生产厂家，报告编号，检品数量
LAB_DICT = {'SID': 'chkid', 'SMING': 'chkname', 'JPPIHAO': 'batchno',
            'MQUYANG': 'samplecount', 'PQUYANG': 'samplecount',
            'SPRODUCER': 'producer', 'SBGBH': 'paperno',
            'JPSHULIANG': 'checkamount'
            }

# 对齐方式
alignment = ('L', 'C', 'R')
qtalign = (Qt.AlignLeft, Qt.AlignHCenter, Qt.AlignRight)

class ReadXML(QDialog, Ui_Form):

    def __init__(self, parent=None):
        super().__init__(parent)
        self.setupUi(self)
        self.reader = QtCore.QXmlStreamReader()
        self.writer = QtXmlPatterns.QXmlQuery()
        # self.pix = QtGui.QPixmap(800, 600)
        # self.pix.fill(QtCore.Qt.white)
        # 线框，先把所有线框的信息都保存了，最后再刷新
        self.line_border = list()

        self.current_X = 20
        self.current_Y = 10
        self.form = parent
        # 要查询的记录id
        self.autoid = 0
        # 要查询的内容,0测试，1生产，2检验
        self.type = 0
        self.proddetail = None
        self.stuffdetail = None
        self.mstuffdetail = None
        self.labdetail = None
        self.stuffdetailZF = list()
        self.stuffdetailZC = list()
        self.stuffdetailFC = list()
        self.stuffdetailNB = list()
        self.stuffdetailWB = list()
        self.stuffdetailBC = list()
        self.stuffdetailQC = list()

        self.stuffdetailMZF = list()
        self.stuffdetailMZC = list()
        self.stuffdetailMFC = list()
        self.stuffdetailMNB = list()
        self.stuffdetailMWB = list()
        self.stuffdetailMBC = list()
        self.stuffdetailMQC = list()

    # 中文：14个像素 英文：7个像素，系统中的长度*7 = 像素
    # 中文数*2 = 系统中的长度，中位数*14 = 像素
    # 系统中长度*7 = 像素
    def read(self, file):

        # 传入的是地址
        qfile = QtCore.QFile(file)
        # 找到文件,则设置引擎,否则向xml文件直接添加数据
        if qfile.open(QtCore.QFile.ReadWrite | QtCore.QFile.Text):
            self.reader.setDevice(file)
            self.writer.setDevice(file)
        else:
            self.reader.addData(file)
            s = self.writer.setQuery(file + '/GMPPaper/Title[2]')
            print(s)
        self.reader.setNamespaceProcessing(0)
        self.reader.readNextStartElement()
        if self.reader.isStartDocument():
            self.reader.readNextStartElement()
        # 如果没有读到文档结尾，而且没有出现错误
        while not self.reader.atEnd():
            if self.reader.isStartElement():
                name = self.reader.name()
                if name == "GMPPaper":
                    pass
                # 标题框
                elif name == "Title":
                    self.titleBox()
                # 标题输入框
                elif name == "TextBox":
                    self.inputBox()
                # 线框
                elif name == "Box":
                    self.wireframe()
                # 检测框
                elif name == "CheckBox":
                    self.checkBox()
                # 下拉框
                elif name == "ComboBox":
                    self.comboBox()
                # 签名框
                elif name == "Signature":
                    self.signBox()
                elif name == "Expr":
                    self.exprBox()
                elif name == "br":
                    self.wrapBox()
            # 空格组成的字符，包括换行
            elif self.reader.isWhitespace():
                pass
            # 纯文本
            elif self.reader.isCharacters():
                pass
            self.reader.readNextStartElement()
            # 如果读取过程中出现错误，那么输出错误信息
            # if self.reader.hasError():
            #    print(self.reader.errorString())
            # raise ValueError
        if qfile.isOpen():
            qfile.close()
        # self.update()
        self.scrollAreaWidgetContents.setLineBorder(self.line_border)
        '''
        try:

        except Exception as e:
            print(repr(e))
            pass
            # raise ValueError
        '''

    # 标题框
    def titleBox(self):
        widget = QtWidgets.QLabel(self.scrollAreaWidgetContents)
        widget.setContentsMargins(2, 0, 0, 0)
        self.boxresize(widget)
        # L C R ,左中右对齐
        align = self.reader.attributes().value("align")
        widget.setAlignment(
            QtCore.Qt.AlignVCenter | qtalign[alignment.index(align)])
        widget.setText(self.set_vars(self.reader.readElementText()))

    # 输入框
    def inputBox(self):
        widgetlabel = QtWidgets.QLabel(self.scrollAreaWidgetContents)
        widgetlineedit = QtWidgets.QLineEdit(self.scrollAreaWidgetContents)
        # self.reader.lineNumber()

        # widgetlineedit.setObjectName('widget' + self.reader.columnNumber())
        widgetlabel.setContentsMargins(2, 0, 0, 0)
        widgetlineedit.setContentsMargins(1, 0, 1, 0)
        # self.boxresize(widgetlineedit)
        widgetlabel.move(self.current_X, self.current_Y)
        widgetlabel.setText(
            self.set_vars(self.reader.attributes().value("Title")))
        widgetlineedit.editingFinished.connect(self.widgetedit)

        L_width = int(self.reader.attributes().value("Width")) * 7
        L_height = int(self.reader.attributes().value(
            "Height")) * 7 if self.reader.attributes().value(
            "Height") else 20
        if L_width:
            # 标题长度不为0
            widgetlabel.resize(L_width, L_height)
            self.current_X += L_width
        else:
            # 标题内容不为空
            if self.reader.attributes().value("Title"):
                widgetlabel.adjustSize()
                widgetlabel.resize(widgetlabel.size().width(), L_height)
            else:
                widgetlabel.resize(0, L_height)
            self.current_X += widgetlabel.size().width()
        self.boxresize(widgetlineedit, "MaxLength", "MaxHeight")
        wid = self.reader.attributes().value("ID")
        widgetlineedit.setText(self.set_vars(self.reader.readElementText()))
        if wid:
            try:
                setattr(self, wid, decimal.Decimal(widgetlineedit.text()))
            except:
                setattr(self, wid, '')

    # 线框
    def wireframe(self):
        linewidth = int(self.reader.attributes().value("width")) * 7
        lineheight = int(self.reader.attributes().value("height")) * 20
        penwidth = int(self.reader.attributes().value("PenWidth"))

        qrect = QtCore.QRect(self.current_X, self.current_Y, linewidth,
                             lineheight)

        self.line_border.append((qrect, penwidth))

    # 检测框
    def checkBox(self):
        self.reader.readNextStartElement()
        widget = QtWidgets.QCheckBox(self.scrollAreaWidgetContents)
        # widget.setContentsMargins(2, 0, 0, 0)
        self.boxresize(widget)
        widget.setText(self.set_vars(self.reader.attributes().value("name")))
        widget.setChecked(int(self.reader.readElementText()))
        # self.boxresize(widget)

    # 下拉框
    def comboBox(self):
        index = 0
        widget = QtWidgets.QComboBox(self.scrollAreaWidgetContents)
        self.boxresize(widget)

        # 允许自己填内容，则显示“value”的内容，
        # 否则显示index序号的内容
        if int(self.reader.attributes().value("style")):
            widget.setEditable(
                int(self.reader.attributes().value("style")))
            widget.setCurrentText(
                self.reader.attributes().value("value"))
        else:
            index = int(self.reader.attributes().value("index"))
        # self.boxresize(widget)
        # 循环添加下拉菜单的项目。
        while 1:
            self.reader.readNext()
            if self.reader.name() != 'Item':
                break
            widget.addItem(self.set_vars(self.reader.readElementText()))
        widget.setCurrentIndex(index)

    # 签名框
    def signBox(self):
        widget = QtWidgets.QLineEdit(self.scrollAreaWidgetContents)
        self.boxresize(widget)
        widget.setEnabled(False)
        widget.setStyleSheet("background-color: rgb(255, 0, 0);")
        widget.setText(self.reader.readElementText(1))

    # 表达式
    def exprBox(self):
        widget = QtWidgets.QLineEdit(self.scrollAreaWidgetContents)
        self.boxresize(widget)
        widget.setEnabled(False)
        widget.setStyleSheet("background-color: rgb(85, 255, 255);")
        # style = self.reader.attributes().value("showformat")
        # 后缀
        sibfix = ''
        # 计算过程
        expr = ''
        # 显示的表达式
        va = ''
        vid = self.reader.attributes().value("ID")
        while 1:
            self.reader.readNextStartElement()
            if self.reader.isEndElement() and self.reader.name() == "Expr":
                break
            if self.reader.name() == "subfix":
                sibfix = self.reader.readElementText()
            elif self.reader.name() == "expr":
                expr = self.reader.readElementText()
            elif self.reader.name() == "vars":
                va = self.reader.readElementText()

        # 把文件中的#变量，改为实例中的变量。
        expr = expr.replace('#', 'self.')
        expr = self.set_vars(expr)
        va = self.set_vars(va)

        try:
            result = str(eval(expr, evalenv(self)))
            widget.setText(va + result + sibfix)
            if id:
                setattr(self, id, decimal.Decimal(result))
        except:
            return "公式格式错误"
        # widget.setText(self.reader.readElementText(1))
        if vid:
            setattr(self, vid, result)

    # 换行框
    def wrapBox(self):
        self.current_X = 20
        self.current_Y += 20

    # 设置控件的尺寸
    # w:控件的宽度变量名
    # h:控件的高度变量名
    def boxresize(self, widget, w="width", h="height"):
        self.setStyleSheet("margin:2 2;")
        width = int(self.reader.attributes().value(
            w)) * 7 + 4 if self.reader.attributes().value(
            w) else 134
        height = int(self.reader.attributes().value(
            h)) * 24 if self.reader.attributes().value(
            h) else 24
        widget.resize(width, height)
        widget.move(self.current_X, self.current_Y)
        self.current_X += width

    # 设置表达式
    def set_vars(self, exp):
        items, sys_items = self.get_vars(exp)
        if items:
            for item in set(items):
                try:
                    exp = exp.replace(item, str(getattr(self, item[1:-1])))
                except AttributeError:
                    exp = exp.replace(item, '')
        if sys_items:
            for item in set(sys_items):
                try:
                    # 切片去除头尾的@
                    # 日期类变量
                    if item[1: -1] in (
                    'NIAN', 'YUE', 'RI', 'SHI', 'FEN', 'MIAO'):
                        exp = exp.replace(item,
                                          str(getattr(userdetail, item[1:-1])))
                    # 产品信息类变量
                    elif item[1: -1] in PRODUCT_DICT:
                        if self.proddetail is not None:
                            exp = exp.replace(item, str(
                                self.proddetail[PRODUCT_DICT[item[1: -1]]]))
                        else:
                            try:
                                self.get_sys_vars(0)
                                exp = exp.replace(item, str(
                                    self.proddetail[PRODUCT_DICT[item[1: -1]]]))
                            except IndexError:
                                exp = exp.replace(item, str(''))
                    # 产品物料，分批次
                    elif item[3: -2] in STUFF_DICT or item[3: -3] in STUFF_DICT:
                        # 变量的后缀
                        num = int(re.search(r'\d+', item).group(0)) - 1
                        vals = [x for x in re.split(r'@|\d', item) if x][0]
                        var_list = getattr(self, 'stuffdetail' + item[1: 3])
                        if len(var_list):
                            exp = exp.replace(item, str(
                                getattr(var_list[num], STUFF_DICT[vals[2:]])))
                        else:
                            self.get_sys_vars(1)
                            var_list = getattr(self, 'stuffdetail' + item[1: 3])
                            exp = exp.replace(item, str(
                                getattr(var_list[num], STUFF_DICT[vals[2:]])))
                    # 产品物料，不分批次
                    elif item[4: -2] in STUFF_DICT or item[4: -3] in STUFF_DICT:
                        # 变量的后缀
                        num = int(re.search(r'\d+', item).group(0)) - 1
                        vals = [x for x in re.split(r'@|\d', item) if x][0]
                        var_list = getattr(self, 'stuffdetail' + item[1: 4])
                        if len(var_list):
                            exp = exp.replace(item, str(
                                getattr(var_list[num], STUFF_DICT[vals[3:]])))
                        else:
                            self.get_sys_vars(2)
                            var_list = getattr(self, 'stuffdetail' + item[1: 4])
                            exp = exp.replace(item, str(
                                getattr(var_list[num], STUFF_DICT[vals[3:]])))
                    # 检验报告类信息变量
                    elif item[1: -1] in LAB_DICT:
                        if self.labdetail is not None:
                            exp = exp.replace(item, str(
                                self.labdetail[LAB_DICT[item[1: -1]]]))
                        else:
                            self.get_sys_vars(3)
                            exp = exp.replace(item, str(
                                self.labdetail[LAB_DICT[item[1: -1]]]))
                except:
                    exp = exp.replace(item, str(''))
        return exp

    # 获取系统变量的值
    # kind  获取的数据类型，0生产，1物料，2检验
    def get_sys_vars(self, kind=0):
        if self.autoid != 0:
            try:
                if kind == 0:
                    pm = ProductController()
                    self.proddetail = pm.get_producingplan(autoid=self.autoid)[
                        0]
                elif kind == 1:
                    sm = StuffController()
                    self.stuffdetail = sm.get_prodstuff(self.autoid)
                    for item in self.stuffdetail:
                        stufftype = item.stufftype
                        if stufftype == 0:
                            self.stuffdetailZC.append(item)
                            self.stuffdetailZF.append(item)
                        elif stufftype == 1:
                            self.stuffdetailFC.append(item)
                            self.stuffdetailZF.append(item)
                        elif stufftype == 2:
                            self.stuffdetailNB.append(item)
                            self.stuffdetailBC.append(item)
                        elif stufftype == 3:
                            self.stuffdetailWB.append(item)
                            self.stuffdetailBC.append(item)
                        elif stufftype == 4:
                            self.stuffdetailQC.append(item)
                elif kind == 2:
                    sm = StuffController()
                    self.mstuffdetail = sm.get_Mprodstuff(self.autoid)
                    for item in self.mstuffdetail:
                        stufftype = item.stufftype
                        if stufftype == 0:
                            self.stuffdetailMZC.append(item)
                            self.stuffdetailMZF.append(item)
                        elif stufftype == 1:
                            self.stuffdetailMFC.append(item)
                            self.stuffdetailMZF.append(item)
                        elif stufftype == 2:
                            self.stuffdetailMNB.append(item)
                            self.stuffdetailMBC.append(item)
                        elif stufftype == 3:
                            self.stuffdetailMWB.append(item)
                            self.stuffdetailMBC.append(item)
                        elif stufftype == 4:
                            self.stuffdetailMQC.append(item)
                elif kind == 3:
                    lm = LabrecordsController()
                    self.labdetail = lm.get_labrecord(1, autoid=self.autoid)[0]
            except:
                # traceback.print_exc()
                pass

    # 获得表达式中的普通变量和系统变量
    # {\w*} 普通变量
    # @\w*@ 系统变量
    def get_vars(self, exp):
        pattern1 = re.compile(r'{\w*}')
        pattern2 = re.compile(r'@\w*@')
        return pattern1.findall(exp), pattern2.findall(exp)

    '''
    def paintEvent(self, event):
        if self.line_border:
            #self.pix = self.pix.scaled(self.size())
            pp = QtGui.QPainter(self)
            #pp = QtGui.QPainter(self.pix)
            pen = QtGui.QPen()  # 定义笔格式对象
            for index, item in enumerate(self.line_border):
                print(item)
                pen.setWidth(item[1])  # 设置笔的宽度
                pen.setColor(QtCore.Qt.red)
                pp.setPen(pen)  # 将笔格式赋值给 画笔
                # 根据鼠标指针前后两个位置绘制直线
                pp.drawRect(item[0])
                #self.line_border.pop(index)

            #painter = QtGui.QPainter(self)
            # 在画布上画出
            #painter.drawPixmap(0, 0, self.pix)
    '''

    def widgetedit(self):
        widget = self.sender().objectName()
        # s = self.writer.setQuery("GMPPaper/Title[2]")
        # for item in s:
        #    print(s)
        # num = widget[6:]
        # self.writer.writeCurrentToken()
        # print(self.reader.namespaceUri())

if __name__ == '__main__':
    app = QtWidgets.QApplication(sys.argv)
    mainmenu = ReadXML()

    res = Selfdefinedformat.objects.filter(autoid=2855)
    mainmenu.__setattr__('autoid', 50)
    mainmenu.read(res[0].format)
    mainmenu.show()
    sys.exit(app.exec_())


from rich.table import Table
from rich.console import Console
import os
import sqlite3
from sqlite3 import Error
from colorama import Fore
from colored import fg, attr
from datetime import date, datetime
# =============================================
con = sqlite3.connect("data.db")
os.system("cls")
# =============================================
def sql_connection(con):
    cur = con.cursor()
    cur.execute(
        "CREATE TABLE IF NOT EXISTS ManagerBuy(Id INTEGER PRIMARY KEY AUTOINCREMENT,Price INTEGER, Product_Name TEXT, Date TEXT, Time TEXT)")
    con.commit()
# =============================================
def help_list():
    print(f"""{fg(50)}
███    ███  █████  ███    ██  █████   ██████  ███████ ██████      ██████  ██    ██ ██    ██
████  ████ ██   ██ ████   ██ ██   ██ ██       ██      ██   ██     ██   ██ ██    ██  ██  ██
██ ████ ██ ███████ ██ ██  ██ ███████ ██   ███ █████   ██████      ██████  ██    ██   ████
██  ██  ██ ██   ██ ██  ██ ██ ██   ██ ██    ██ ██      ██   ██     ██   ██ ██    ██    ██
██      ██ ██   ██ ██   ████ ██   ██  ██████  ███████ ██   ██     ██████   ██████     ██   {fg(50)}
{fg(115)}===========================================================================================
**                                 Github : erfanbanaei                                  **
**                                 Twitter: @erfan_banaei                                **
**                                 YouTube: @Hero_Code                                   **
==========================================================================================={fg(115)}{attr(0)}

[{fg(50)}1{fg(50)}{attr(0)}] Init
[{fg(50)}2{fg(50)}{attr(0)}] Add
[{fg(50)}3{fg(50)}{attr(0)}] Show
[{fg(50)}4{fg(50)}{attr(0)}] Edit
[{fg(50)}5{fg(50)}{attr(0)}] Delete
[{fg(50)}6{fg(50)}{attr(0)}] Help
[{fg(50)}7{fg(50)}{attr(0)}] Exit
""")
# =============================================

def add(con):
    Price = int(
        input(f"[{fg(9)}?{fg(9)}{attr(0)}]Enter your purchase price : "))
    Product_Name = input(
        f"[{fg(9)}?{fg(9)}{attr(0)}] Enter your purchase name : ")
    t = datetime.now().time()
    time = f"{t.hour}:{t.minute}"
    date2 = date.today()
    full = (Price, Product_Name, date2, time)
    cur = con.cursor()
    cur.execute(
        "INSERT INTO ManagerBuy(Price, Product_Name, Date, Time) VALUES(?,?,?,?)", full)
    con.commit()
    os.system("cls")
# =============================================
def show(con):
    cur = con.cursor()
    cur.execute('SELECT * FROM ManagerBuy')
    rows = cur.fetchall()
    console = Console()
    table = Table(title="ManagerBuy")

    table.add_column("Id", justify="center", style="cyan")
    table.add_column("Price", justify="center", style="magenta")
    table.add_column("Product Name", justify="center", style="green")
    table.add_column("Date", justify="center", style="yellow")
    table.add_column("Time", justify="center", style="blue")

    for row in rows:
        table.add_row(str(row[0]),str(row[1]),str(row[2]),str(row[3]),str(row[4]))
    console.print(table)
# =============================================
def edit(con):
    try:
        data_id = int(input(f"[{fg(9)}?{fg(9)}{attr(0)}]Enter the ID of the product you want : "))
        new_name  = input(f"[{fg(9)}?{fg(9)}{attr(0)}]Enter the new name of the desired product : ")
        new_price = input(f"[{fg(9)}?{fg(9)}{attr(0)}]Enter the new price of the product you want :")
        full = (new_price,new_name,data_id)
        cur = con.cursor()
        cur.execute(f"UPDATE ManagerBuy SET Price = ?, Product_Name = ? WHERE Id = ?",full)
        con.commit()
    except Error as e:
        print(Fore.RED+ "Error" , e)
# =============================================
def delete_record(con):
    data_id = input(f"[{fg(9)}?{fg(9)}{attr(0)}]Enter the ID of the product you want (9999 => Remove all products) : ")
    cur = con.cursor()
    full = (int(data_id))
    if full == 9999:
        cur.execute(f"DELETE FROM ManagerBuy")
        con.commit()
        print(Fore.GREEN + "Removed all\n\n")
    else:
        cur.execute(f"DELETE FROM ManagerBuy WHERE Id = {full}")
        con.commit()
        print(Fore.GREEN + "Deleted Product\n\n")
# =============================================
def Help():
    print(f"""
Init {fg(50)}=>{fg(50)} {fg(115)}Create Database{fg(115)}{attr(0)}
Add {fg(50)}=>{fg(50)} {fg(115)}Add to Database(Price , Product Name){fg(115)}{attr(0)}
Show {fg(50)}=>{fg(50)} {fg(115)}Show all products{fg(115)}{attr(0)}
Edit {fg(50)}=>{fg(50)} {fg(115)}Product edit{fg(115)}{attr(0)}
Delete {fg(50)}=>{fg(50)} {fg(115)}Remove the product from the list{fg(115)}{attr(0)}
\n\n""")
# =============================================
while True:
    help_list()
    number = input(Fore.CYAN+"┌─["+Fore.LIGHTGREEN_EX+"ManagerBuy"+Fore.BLUE+"~"+Fore.WHITE+"@HOME"+Fore.CYAN+"""]
└──╼ """+Fore.WHITE+"$ ")
# =============================================
    if number == "1":
        os.system("cls")
        sql_connection(con)
        print(Fore.GREEN + "Created Database\n\n")
# =============================================
    elif number == "2":
        os.system("cls")
        add(con)
# =============================================
    elif number == "3":
        os.system("cls")
        show(con)
# =============================================
    elif number == "4":
        os.system("cls")
        edit(con)
# =============================================
    elif number == "5":
        os.system("cls")
        delete_record(con)
# =============================================
    elif number == "6":
        os.system("cls")
        Help()
# =============================================
    elif number == "7":
        quit()


from torch import nn
import torch
from torch.nn import CrossEntropyLoss
from transformers import BertPreTrainedModel, BertConfig, BertModel
from transformers.models.bert.modeling_bert import BertOnlyMLMHead

class BertForPTuning(BertPreTrainedModel):
    def __init__(self, config: BertConfig, prompt_index):
        super().__init__(config)
        self.num_labels = config.num_labels
        self.prompt_index = prompt_index

        self.bert = BertModel(config, add_pooling_layer=False)
        self.cls = BertOnlyMLMHead(config)

        self.prompt_embedding = torch.nn.Embedding(len(prompt_index), config.hidden_size)
        self.lstm_head = torch.nn.LSTM(input_size=config.hidden_size,
                                       hidden_size=config.hidden_size,
                                       num_layers=2,
                                       bidirectional=True,
                                       batch_first=True)
        self.mlp_head = nn.Sequential(nn.Linear(2 * config.hidden_size, config.hidden_size),
                                      nn.ReLU(),
                                      nn.Linear(config.hidden_size, config.hidden_size))
        self.init_weights()

    def set_output_embeddings(self, new_embeddings):
        self.cls.predictions.decoder.weight = new_embeddings.weight

    def forward(
            self,
            input_ids=None,
            attention_mask=None,
            token_type_ids=None,
            position_ids=None,
            head_mask=None,
            inputs_embeds=None,
            labels=None,
            output_attentions=None,
            output_hidden_states=None,
            return_dict=None):
        return_dict = return_dict if return_dict is not None else self.config.use_return_dict

        self.set_output_embeddings(self.bert.embeddings.word_embeddings)

        # 替换embedding
        replace_embedding = self.prompt_embedding(torch.arange(len(self.prompt_index)).to(input_ids.device))[None, :]
        replace_embedding = self.lstm_head(replace_embedding)[0]
        replace_embedding = self.mlp_head(replace_embedding)
        raw_embedding = self.bert.embeddings.word_embeddings(input_ids)
        raw_embedding[:, self.prompt_index, :] = replace_embedding
        inputs_embeds = raw_embedding

        outputs = self.bert(
            input_ids=None,
            attention_mask=attention_mask,
            token_type_ids=token_type_ids,
            position_ids=position_ids,
            head_mask=head_mask,
            inputs_embeds=inputs_embeds,
            output_attentions=output_attentions,
            output_hidden_states=output_hidden_states,
            return_dict=return_dict,
        )

        logits = self.cls(outputs[0])

        loss = None
        if labels is not None:
            loss_fct = CrossEntropyLoss()
            s = attention_mask.shape[0] * attention_mask.shape[1]
            loss = loss_fct(logits.view(s, -1), labels.view(-1))

        # token out / pool out / cls
        output = (logits,) + outputs[1:] + (outputs[0][:, 0],)
        return ((loss,) + output) if loss is not None else output


from flask import Flask, render_template, request, Response
import random
test_app = Flask(__name__)

@test_app.route('/')
def getRandomData():
   context = {"title": "Data table test"}
   data = [{ 'id': i,
             'name': "test_name_{0}".format(random.randint(0,1000)),
             'phone': random.randint(2308,903234),
             'status': random.choice([True, False])
           } for i in range(0,10000)]

   context['data'] = data
   return render_template('table_example.html', **context)

if __name__ == "__main__":
    test_app.run(host ="localhost")


import re
import json
import logging

class Object:  # pylint: disable=too-many-instance-attributes
    def __str__(self):
        return json.dumps(self, default=lambda o: o.__dict__, indent=5)

class Device(Object):

    def __init__(self, uid, version, firmware):
        self.namespace = 'http://www.w3.org/2001/XMLSchema-instance'
        self.location = '../../db/resources/db.xsd'
        self.id = uid
        self.version = version
        self.firmware = firmware

def delete_attrs(obj, paths):
    """
    Delete attributes

    :param cterasdk.common.object.Object object: The object
    :param list[str] paths: List of attributes to remove

    :returns: The modified object
    :rtype: cterasdk.common.object.Object
    """
    for path in paths:
        delete_attr(obj, path)

def delete_attr(obj, path):
    """
    Delete attribute

    :param cterasdk.common.object.Object object: The object
    :param str path: Attribute path

    :returns: The modified object
    :rtype: cterasdk.common.object.Object
    """
    parts = re.findall('[^/]+', path)
    parent = find_attr(obj, parts[:-1])
    remove_attr(parent, parts[-1])

    if len(parts) > 1 and isinstance(parent, Object) and not parent.__dict__:
        grandparent = find_attr(obj, parts[:-2])
        setattr(grandparent, parts[-2], None)

def find_attr(obj, path):
    """
    Find attribute

    :param cterasdk.common.object.Object object: The object
    :param str path: A string or an array of the attribute path

    :returns: The attribute, or ``None`` if not found
    """
    parts = re.findall('[^/]+', path) if isinstance(path, str) else path

    attr = obj
    for part in parts:
        attr = get_attr(attr, part)
        if attr is None:
            logging.getLogger().warning('Could not find attribute. %s', {'path': f'/{"/".join(parts)}'})
            return attr
    return attr

def get_attr(obj, attr):
    """
    Get attribute

    :param cterasdk.common.object.Object object: The object
    :param str attr: The name of the attribute to retrieve

    :returns: The attribute, or ``None`` if not found
    """
    if isinstance(obj, list):
        try:
            attr = int(attr)
            return obj[attr]
        except ValueError:
            logging.getLogger().warning('Could not find attribute.')
            return None

    return getattr(obj, attr, None)

def remove_attr(obj, attr):
    """
    Remove attribute

    :param cterasdk.common.object.Object object: The object
    :param str attr: The name of the attribute to remove
    """
    if isinstance(obj, list):
        remove_array_element(obj, attr)
    else:
        try:
            delattr(obj, attr)
        except AttributeError:
            logging.getLogger().warning('Failed to remove attribute. Attribute not found. %s', {'attr': attr})

def remove_array_element(array, attr):

    try:
        attr = int(attr)
        if attr <= len(array) - 1:
            array.pop(attr)
        else:
            logging.getLogger().warning('Could not remove array item. Index out of range. %s', {'index': attr})
    except ValueError:
        pass

    if remove_array_element_by_key(array, '_uuid', attr):
        return

    remove_array_element_by_key(array, 'name', attr)

def remove_array_element_by_key(array, key, value):
    for index, element in enumerate(array):
        element_value = getattr(element, key, None)
        if element_value == value:
            return array.pop(index)
    return None


import pandas as pd
import numpy as np
from sklearn.ensemble import RandomForestClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import confusion_matrix, accuracy_score
from sklearn.model_selection import train_test_split
from sklearn.naive_bayes import GaussianNB
from sklearn import tree
from sklearn import svm
import warnings
warnings.filterwarnings('ignore')

def getData(category):
    crime_rate_df = pd.read_csv('dataset/boston_crime_2021-2022.csv', dtype=str)
    crime_dictionary = ['LARCENY', 'M/V ACCIDENT', 'LIQUOR', 'INCEST', 'MANSLAUGHTER', 'MISSING PERSON',
                        'PROPERTY - LOST', 'MURDER', 'FRAUD', 'PROSTITUTION', 'RAPE', 'ROBBERY', 'ASSAULT',
                        'SICK/INJURED/MEDICAL', 'TOWED MOTOR VEHICLE', 'TRESPASSING', 'VIOLATION', 'ANIMAL',
                        'AUTO THEFT', 'FIREARM/WEAPON', 'HUMAN TRAFFICKING', 'DRUGS', 'SEX OFFENSE', 'ARSON',
                        'VANDALISM', 'SEARCH WARRANT', 'KIDNAPPING', 'DEATH INVESTIGATION', 'CHILD ABUSE', 'HARASSMENT']

    crime_list = [0, 1, 2, 3, 4, 5,
                  6, 7, 8, 9, 10, 11, 12,
                  13, 14, 15, 16, 17,
                  18, 19, 20, 21, 22, 23,
                  24, 25, 26, 27, 28, 29]
    for j in range(len(crime_list)):
        crime_rate_df.loc[crime_rate_df['OFFENSE_DESCRIPTION'].str.contains(crime_dictionary[j]), 'GROUP'] = crime_list[j]

    crime_rate_df = crime_rate_df.dropna()

    Weekday = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]
    for i in range(len(Weekday)):
        crime_rate_df['DAY_OF_WEEK'] = np.where((crime_rate_df.DAY_OF_WEEK == Weekday[i]), i, crime_rate_df.DAY_OF_WEEK)
    X = crime_rate_df.drop([category, 'OFFENSE_DESCRIPTION', 'Location', 'DISTRICT', 'Dates', 'STREET', 'YEAR'], axis=1).values
    Y = crime_rate_df[[category]].values

    x_train, x_test, y_train, y_test = train_test_split(X, Y, train_size=0.8)
    return x_train, y_train, x_test, y_test

def getTable(cm, i, all=False):
    TP = cm[i][0][0]
    FP = cm[i][0][1]
    FN = cm[i][1][0]
    TN = cm[i][1][1]
    TPR = TP / (TP + FN)
    TNR = TN / (TN + FP)
    ACC = (TP + TN) / (TP + TN + FP + FN)
    d = {'Accuracy': [ACC], 'True positive rate': [TPR], 'True negative rate': [TNR]}
    dfx = pd.DataFrame(data=d)
    if all:
        return TP, FP, FN, TN, TPR, TNR, ACC
    return dfx

def predictCrime():
    cm = []
    x_train, y_train, x_test, y_test = getData('GROUP')

    NB_classifier = GaussianNB().fit(x_train, y_train)
    accuracy = accuracy_score(y_test, NB_classifier.predict(x_test))

    print("\n1:")
    print('Implement a Naive Bayesian classifier:')
    print('The accuracy is', accuracy)

    log_reg_classifier = LogisticRegression()
    log_reg_classifier.fit(x_train, y_train)
    accuracy = log_reg_classifier.score(x_train, y_train)

    print("\n2:")
    print('Implement a Logistic regression classifier:')
    print('The accuracy is', accuracy)

    clf = tree.DecisionTreeClassifier(criterion='entropy')
    clf = clf.fit(x_train, y_train)
    prediction = clf.predict(x_test)
    accuracy = accuracy_score(y_test, prediction)

    print("\n3:")
    print('Implement a Decision Tree:')
    print('The accuracy is', accuracy)

    # 5. Use Random Forest classifier
    error_rate = []
    random_forest_table = pd.DataFrame(columns=['n_estimators', 'max_depth', 'accuracy'])
    for i in range(1, 11):
        for j in range(1, 6):
            rf = RandomForestClassifier(n_estimators=i, max_depth=j)
            rf.fit(x_train, y_train)
            error_rate.append(1 - accuracy_score(y_test, rf.predict(x_test)))
            ACC = accuracy_score(y_test, rf.predict(x_test))
            random_forest_table.loc[len(random_forest_table.index)] = [i, j, ACC]

    best_n = error_rate.index(min(error_rate)) % 10 + 1
    best_max = error_rate.index(min(error_rate)) % 5 + 1

    print("\n4:")
    print('Implement a Random Forest classifier :')
    print("The best n_estimators and max_depth are", best_n, "and", best_max)

    rf = RandomForestClassifier(n_estimators=best_n, max_depth=best_max)
    rf.fit(x_train, y_train)
    accuracy = accuracy_score(y_test, rf.predict(x_test))

    print('The accuracy is', accuracy)

predictCrime()


from parlai.core.teachers import FbDeprecatedDialogTeacher, MultiTaskTeacher
from .build import build

import copy
import os

def _path(task, opt):
    # Build the data if it doesn't exist.
    build(opt)
    suffix = ''
    dt = opt['datatype'].split(':')[0]
    if dt == 'train':
        suffix = 'train'
    elif dt == 'test':
        suffix = 'test_2500ex'
    elif dt == 'valid':
        suffix = 'valid_2000ex'

    return os.path.join(
        opt['datapath'], 'CBT', 'CBTest', 'data', task + '_' + suffix + '.txt'
    )

class NETeacher(FbDeprecatedDialogTeacher):
    def __init__(self, opt, shared=None):
        opt['datafile'] = _path('cbtest_NE', opt)
        opt['cloze'] = True
        super().__init__(opt, shared)

class CNTeacher(FbDeprecatedDialogTeacher):
    def __init__(self, opt, shared=None):
        opt['datafile'] = _path('cbtest_CN', opt)
        opt['cloze'] = True
        super().__init__(opt, shared)

class VTeacher(FbDeprecatedDialogTeacher):
    def __init__(self, opt, shared=None):
        opt['datafile'] = _path('cbtest_V', opt)
        opt['cloze'] = True
        super().__init__(opt, shared)

class PTeacher(FbDeprecatedDialogTeacher):
    def __init__(self, opt, shared=None):
        opt['datafile'] = _path('cbtest_P', opt)
        opt['cloze'] = True
        super().__init__(opt, shared)

# By default train on all tasks at once.
class DefaultTeacher(MultiTaskTeacher):
    def __init__(self, opt, shared=None):
        opt = copy.deepcopy(opt)
        opt['task'] = 'cbt:NE,cbt:CN,cbt:V,cbt:P'
        super().__init__(opt, shared)


#!/usr/bin/python3

import urllib.request
import re

CONTENT="http://download.opensuse.org/tumbleweed/repo/oss/media.1/media"
APPDATA="http://download.opensuse.org/tumbleweed/repo/oss/suse/setup/descr/appdata.html"

CNT = urllib.request.urlopen(CONTENT).read().decode('utf-8')
DISTRO = re.findall("openSUSE-(........)-x86_64-Build.*", CNT)

V1 = DISTRO[0]
SNAPDATE=V1[:4] + '-' + V1[4:6] + '-' + V1[6:]

print (SNAPDATE)


import sys
import io
import os
import shutil
import base64
import hashlib
from cryptography.hazmat.primitives.asymmetric.x25519 import X25519PrivateKey
from cryptography.hazmat.primitives.asymmetric.x25519 import X25519PublicKey
from Crypto.Cipher import AES
from Crypto.Util import Counter

RANSOM_EXT = '.INC'

ENC_MARKER = b'INC'

# x25519
X25519_KEY_SIZE = 32

# AES
AES_KEY_SIZE = 16
AES_IV_SIZE = 16

METADATA_SIZE = X25519_KEY_SIZE + len(ENC_MARKER)

ENC_BLOCK_SIZE = 1000000
ENC_BLOCK_STEP = 3 * ENC_BLOCK_SIZE

def derive_encryption_key_data(priv_key_data: bytes,
                               pub_key_data: bytes) -> bytes:
    """Derive encryption key data"""

    # Derive x25519 shared secret
    priv_key = X25519PrivateKey.from_private_bytes(priv_key_data)
    pub_key = X25519PublicKey.from_public_bytes(pub_key_data)
    shared_secret = priv_key.exchange(pub_key)

    # Derive encryption key data
    return hashlib.sha512(shared_secret).digest()

def decrypt_file(filename: str, priv_key_data: bytes) -> bool:
    """Decrypt file"""

    with io.open(filename, 'rb+') as f:

        # Read metadata
        try:
            f.seek(-METADATA_SIZE, 2)
        except OSError:
            return False

        metadata = f.read(METADATA_SIZE)

        if metadata[-len(ENC_MARKER):] != ENC_MARKER:
            return False

        pub_key_data = metadata[:X25519_KEY_SIZE]

        # Derive encryption key data
        key_data = derive_encryption_key_data(priv_key_data, pub_key_data)

        # AES-128 CTR
        key = key_data[:AES_KEY_SIZE]
        iv = key_data[AES_KEY_SIZE : AES_KEY_SIZE + AES_IV_SIZE]
        init_val = int.from_bytes(iv, byteorder='big')
        counter = Counter.new(128, initial_value=init_val,
                              little_endian=False)
        cipher = AES.new(key, AES.MODE_CTR, counter=counter)

        # Remove metadata
        f.seek(-METADATA_SIZE, 2)
        f.truncate()

        # Decrypt file data
        pos = 0

        while True:

            # Decrypt block
            f.seek(pos)
            enc_data = f.read(ENC_BLOCK_SIZE)
            if enc_data == b'':
                break

            data = cipher.decrypt(enc_data)

            f.seek(pos)
            f.write(data)

            pos += ENC_BLOCK_STEP

    return True

#
# Main
#
if len(sys.argv) != 2:
    print('Usage:', os.path.basename(sys.argv[0]), 'filename')
    sys.exit(0)

filename = sys.argv[1]

with io.open('privkey.txt', 'rb') as f:
    priv_key_data = base64.b64decode(f.read())

# Copy file
new_filename = filename
if new_filename.endswith(RANSOM_EXT):
    new_filename = new_filename[:-len(RANSOM_EXT)]
else:
    new_filename += '.dec'
shutil.copy(filename, new_filename)

# Decrypt file
if not decrypt_file(new_filename, priv_key_data):
    print('Error: Failed to decrypt file')
    sys.exit(1)


from flask import Blueprint, render_template, request, redirect, url_for
import pendulum
import requests
from .static.sc.schedule import date_schedule, get_date
from . import db
from .models import User, List, ListFields

views = Blueprint('views', __name__)

@views.route('/')
def main():
    return render_template('index.html')

@views.route('/capacity')
def capacity():
    return render_template('capacity.html', page_class = 'capacity-page', page_title = 'capacity')

@views.route('/todo')
def todo():

    response = List.query.all()
    return render_template('todo.html', page_class = 'todo-page', page_title = 'todo', res=response, len=len(response))

@views.route('/post_task', methods=['POST'])
def post_task():
    text_task = request.form.get('text')
    deadline = request.form.get('deadline')
    task = List(text=text_task, deadline=deadline)
    db.session.add(task)
    db.session.commit()
    return redirect(url_for('views.todo'))

@views.route('/del_task', methods=['POST'])
def del_task():
    k = int(request.form.get('id'))
    task = List.query.filter_by(id=k).first()
    db.session.delete(task)
    db.session.commit()
    return redirect(url_for('views.todo'))

@views.route('/compl_task', methods=['POST'])
def compl_task():
    k = int(request.form.get('id'))
    task = List.query.filter_by(id=k).first()
    task.complete = True
    db.session.commit()
    return redirect(url_for('views.todo'))

@views.route('/encompl_task', methods=['POST'])
def encompl_task():
    k = int(request.form.get('id'))
    task = List.query.filter_by(id=k).first()
    task.complete = False
    db.session.commit()
    return redirect(url_for('views.todo'))

@views.route('/schedule/today')
def schedule():

    today = pendulum.now()
    d = today.strftime("%d/%m/%Y")
    today_sc = date_schedule(1307, today)
    return render_template('schedule.html',
        page_class = 'schedule-page', page_title = 'schedule',
         sc_date = d, sc = today_sc, current_date = today, pendulum = pendulum)

@views.route('/schedule/date/<n>/<m>/<y>')
def scdate(n, m, y):

    date = get_date([int(n), int(m), int(y)])
    d = date.strftime("%d/%m/%Y")
    today_sc = date_schedule(1307, date)
    return render_template('schedule.html',
        page_class = 'schedule-page', page_title = 'schedule',
        sc_date = d, sc = today_sc, current_date = date, pendulum = pendulum)


import os
import platform
import re
import shutil
import subprocess
import unittest

import bug_reducer.swift_tools as swift_tools

@unittest.skipUnless(platform.system() == 'Darwin',
                     'func_bug_reducer is only available on Darwin for now')
class FuncBugReducerTestCase(unittest.TestCase):

    verbose = False

    def setUp(self):
        self.file_dir = os.path.dirname(os.path.abspath(__file__))
        self.reducer = os.path.join(os.path.dirname(self.file_dir),
                                    'bug_reducer', 'bug_reducer.py')
        self.build_dir = os.path.abspath(
            os.environ['BUGREDUCE_TEST_SWIFT_OBJ_ROOT'])

        (root, _) = os.path.splitext(os.path.abspath(__file__))
        self.root_basename = ''.join(os.path.basename(root).split('_'))
        self.tmp_dir = os.path.join(
            os.path.abspath(os.environ['BUGREDUCE_TEST_TMP_DIR']),
            self.root_basename)
        subprocess.call(['mkdir', '-p', self.tmp_dir])

        self.module_cache = os.path.join(self.tmp_dir, 'module_cache')
        self.sdk = subprocess.check_output(['xcrun', '--sdk', 'macosx',
                                            '--toolchain', 'Default',
                                            '--show-sdk-path']).strip("\n")
        self.tools = swift_tools.SwiftTools(self.build_dir)
        self.passes = ['--pass=-bug-reducer-tester']

        if os.access(self.tmp_dir, os.F_OK):
            shutil.rmtree(self.tmp_dir)
        os.makedirs(self.tmp_dir)
        os.makedirs(self.module_cache)

    def _get_test_file_path(self, module_name):
        return os.path.join(self.file_dir,
                            '{}_{}.swift'.format(
                                self.root_basename, module_name))

    def _get_sib_file_path(self, filename):
        (root, ext) = os.path.splitext(filename)
        return os.path.join(self.tmp_dir, os.path.basename(root) + '.sib')

    def run_swiftc_command(self, name):
        input_file_path = self._get_test_file_path(name)
        sib_path = self._get_sib_file_path(input_file_path)
        args = [self.tools.swiftc,
                '-module-cache-path', self.module_cache,
                '-sdk', self.sdk,
                '-Onone', '-parse-as-library',
                '-module-name', name,
                '-emit-sib',
                '-resource-dir', os.path.join(self.build_dir, 'lib', 'swift'),
                '-o', sib_path,
                input_file_path]
        return self.run_check_call(args)

    def run_check_call(self, args):
        if FuncBugReducerTestCase.verbose:
            print('Cmd: {}'.format(' '.join(args)))
        result_code = subprocess.check_call(args)
        if FuncBugReducerTestCase.verbose:
            print('Result Code: {}'.format(result_code))
        return result_code

    def run_check_output(self, args):
        if FuncBugReducerTestCase.verbose:
            print('Cmd: {}'.format(' '.join(args)))
        raw_output = subprocess.check_output(args)
        if FuncBugReducerTestCase.verbose:
            print('Raw Output: {}'.format(raw_output))
        return raw_output

    def test_basic(self):
        name = 'testbasic'
        result_code = self.run_swiftc_command(name)
        assert result_code == 0, "Failed initial compilation"
        args = [
            self.reducer,
            'func',
            self.build_dir,
            self._get_sib_file_path(self._get_test_file_path(name)),
            '--sdk=%s' % self.sdk,
            '--module-cache=%s' % self.module_cache,
            '--module-name=%s' % name,
            '--work-dir=%s' % self.tmp_dir,
            ('--extra-silopt-arg='
             '-bug-reducer-tester-target-func=__TF_test_target'),
            '--extra-silopt-arg=-bug-reducer-tester-failure-kind=opt-crasher'
        ]
        args.extend(self.passes)
        output = self.run_check_output(args).split("\n")
        self.assertTrue("*** Successfully Reduced file!" in output)
        self.assertTrue("*** Final Functions: " +
                        "$s9testbasic6foo413yyF" in output)
        re_end = 'testfuncbugreducer_testbasic_'
        re_end += '92196894259b5d6c98d1b77f19240904.sib'
        output_file_re = re.compile(r'\*\*\* Final File: .*' + re_end)
        output_matches = [
            1 for o in output if output_file_re.match(o) is not None]
        self.assertEqual(sum(output_matches), 1)
        # Make sure our final output command does not have -emit-sib in
        # the output. We want users to get sil output when they type in
        # the relevant command.
        self.assertEqual([], [o for o in output if '-emit-sib' in o])

if __name__ == '__main__':
    unittest.main()


from .helpers import update_or_create_badge

def create_user_badge(code, category, project, user):
    log_description = 'Migration for project {}'.format(project.pk)
    item = {
        'name': project.name,
        'date': project.start.date(),
    }
    update_or_create_badge(
        user_from=user,
        user_to=user,
        code=code,
        category=category,
        items=[item],
        description=log_description)

def create_consultant_project_role_badge(consultant_project_role):
    code = consultant_project_role.exo_role.code
    category = consultant_project_role.exo_role.categories.first().code
    user = consultant_project_role.consultant.user
    create_user_badge(code, category, consultant_project_role.project, user)

def create_user_project_role_badge(user_project_role):
    code = user_project_role.exo_role.code
    category = user_project_role.exo_role.categories.first().code
    user = user_project_role.user
    create_user_badge(code, category, user_project_role.project, user)


pkgname = "gtkmm"
pkgver = "4.12.0"
pkgrel = 0
build_style = "meson"
make_check_wrapper = ["weston-headless-run"]
hostmakedepends = ["meson", "pkgconf", "glib-devel"]
makedepends = [
    "gtk4-devel",
    "cairomm-devel",
    "pangomm-devel",
    "gdk-pixbuf-devel",
    "libepoxy-devel",
]
checkdepends = ["weston"]
pkgdesc = "C++ bindings for Gtk4"
maintainer = "q66 <q66@chimera-linux.org>"
license = "LGPL-2.1-or-later"
url = "https://www.gtkmm.org"
source = f"$(GNOME_SITE)/gtkmm/{pkgver[:-2]}/gtkmm-{pkgver}.tar.xz"
sha256 = "fbc3e7618123345c0148ef71abb6548d421f52bb224fbda34875b677dc032c92"

@subpackage("gtkmm-devel")
def _devel(self):
    return self.default_devel(
        extra=[
            "usr/lib/gtkmm-4.0",
        ]
    )


import os

import openai
from flask import Flask, render_template, request, jsonify
from openai.error import ServiceUnavailableError, InvalidRequestError, RateLimitError

openai.api_key = os.environ.get('OPENAI_API_KEY')
app = Flask(__name__, template_folder='templates', static_folder='static')

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/api/speech-to-text', methods=['POST'])
def speech_to_text():
    transcript = request.json['transcript']
    messages = [{"role": "system", "content": "Ты дружелюбный, но саркастичный бот."},
                {"role": "user", "content": transcript}]
    print('Вопрос:', transcript)
    try:
        response = openai.ChatCompletion.create(
            model="gpt-3.5-turbo",
            messages=messages,
            temperature=0.5,
            max_tokens=1000,
            top_p=1.0,
            frequency_penalty=0.5,
            presence_penalty=0.0,
        )
    except ServiceUnavailableError:
        return jsonify({'response': 'Извините, сервер openAI перегружен и не отвечает.'})
    except InvalidRequestError as e:
        return jsonify({'response': f'Проблема с запросом, {e}'})
    except RateLimitError:
        return jsonify({'response': 'Превышен лимит запросов в минуту.'})
    except BaseException as e:
        return jsonify({'response': f'Неизвестная ошибка: {e}'})

    print('GPT:', response.choices[0].message.content)
    return jsonify({'response': response.choices[0].message.content})

if __name__ == '__main__':
    app.run(debug=True)


import sys
from magma import *
from mantle import *
from rom import ROM
from mantle.lattice.mantle40.MUX import Mux4
from mantle.lattice.mantle40.register import _RegisterName, Register
from boards.icestick import IceStick

def DefineUART (n, init=0, ce=False, r=False, s=False):

  class _UART(Circuit):
    """Construct a UART connection"""
    """Inputs:  data : BIT, valid : BIT"""
    """Outputs: TX : BIT, run : BIT, ready : BIT"""
    name = _RegisterName('UART', n, init, ce, r, s)
    IO = ["data", In(Array(8,Bit)), "valid", In(Bit), "TX", Out(Bit), "ready", Out(Bit)] + ClockInterface(ce,r,s)

    @classmethod
    def definition(uart):

      baud = 1
      logn = 4

      # Latch data in at start of each packet and insert head bit (0)
      data_in = Register(9, ce=True)

      # Latch valid in at start of each packet
      valid_in = DFF(ce=True)

      # Cycle through UART packet
      count    = Counter(logn, ce=True, r=True)
      done     = Decode(15, logn)(count)

      # After 16-bit UART, transition run from 1->0 for 1 cycle and then start next block
      run   = DFF(ce=True)
      run_n = LUT3([0,0,1,0, 1,0,1,0])
      run_n(done, valid_in, run)
      run(run_n)
      wire(baud, run.CE)

      # After 16 bits, reset counter to send out next UART packet
      reset = LUT2((I0&~I1))(done, run)
      count(CE=baud, RESET=reset)

      # Shift out the 16-bit packet
      shift = PISO(9, ce=True)
      load  = LUT2(I0&~I1)(valid_in,run)
      shift(1,data_in,load)
      wire(baud, shift.CE)

      # Wire shift output to TX
      wire(shift, uart.TX)

      # Ready is set when UART packet finishes: allow new inputs and data latch
      ready = LUT2(~I0 & I1)(run, baud)
      wire(ready, uart.ready)

      # Only allow new data latch when ready is set
      valid_in(CE=ready)
      wire(uart.valid,valid_in.I)
      data_in(CE=ready)
      wire(array(uart.data[7], uart.data[6], uart.data[5], uart.data[4],
                 uart.data[3], uart.data[2], uart.data[1], uart.data[0], 0 ), data_in)

  return _UART

def UART(n, init=0, ce=False, r=False, s=False, **kwargs):
    return DefineUART(n, init, ce, r, s)(**kwargs)


import copy
import random
from constants import *

class Game:
    def __init__(self):
        self.num_games = 0
        self.num_wins = 0
        self.num_losses = 0
        self.num_draws = 0
        self.num_blackjacks = 0

        self.amount_played = 0
        self.profit = 0
        self.max_profit = 0
        self.max_loss = 0
        self.max_loss_streak = 0
        self.curr_loss_streak = 0
        self.max_win_streak = 0
        self.curr_win_streak = 0

        self.bet = 0
        self.playing_cards = []
        self.card_counts = [0] * 10
        self.true_count = 0

        self.doubledown = False
        self.stand = False

        self.player_sum = 0
        self.player_cards = []
        self.dealer_sum = 0
        self.dealer_cards = []
        self.player_has_ace = False
        self.dealer_has_ace = False
        self.dealer_upcard_value = 0

        self.state = None
        self.reset_game()

    def reset_game(self):
        self.player_cards = []
        self.dealer_cards = []
        self.stand = False
        self.doubledown = False
        self.bet = DEFAULT_BET
        self.init_cards()

    def init_cards(self):
        if not self.cards_sufficient():
            self.get_new_decks()

        self.player_has_ace = False
        self.dealer_has_ace = False

        card_1, is_ace = self.deal_card(self.player_cards)
        self.player_has_ace = is_ace or self.player_has_ace

        card_2, is_ace = self.deal_card(self.dealer_cards)
        self.dealer_has_ace = is_ace or self.dealer_has_ace

        card_3, is_ace = self.deal_card(self.player_cards)
        self.player_has_ace = is_ace or self.player_has_ace

        card_4, is_ace = self.deal_card(self.dealer_cards)
        self.dealer_has_ace = is_ace or self.dealer_has_ace

        self.player_sum = self.get_card_value(card_1) + self.get_card_value(card_3)
        self.dealer_sum = self.get_card_value(card_2) + self.get_card_value(card_4)
        self.dealer_upcard_value = self.get_card_value(card_2)

        self.state = self.make_state()

    def cards_sufficient(self):
        return len(self.playing_cards) > NUM_DECK * 52 // 6

    def get_card_value(self, card):
        rank, _ = card
        if rank == ACE:
            return 1
        elif rank in [JACK, Queen, KING]:
            return 10
        return int(rank)

    def calculate_hand(self, cards_sum, has_ace):
        A_active = False
        if has_ace > 0 and cards_sum + 10 <= 21:
            A_active = True
        actual_sum = cards_sum + A_active * 10
        return actual_sum, A_active

    # Generate new decks of playing cards
    def get_new_decks(self):
        self.playing_cards = []
        for rank in RANKS:
            for suit in SUITS:
                for n in range(NUM_DECK):
                    self.playing_cards.append((rank, suit))

        for i in range(9):
            self.card_counts[i] = 4 * NUM_DECK  # 4 cards for per deck per rank
        self.card_counts[9] = 16 * NUM_DECK     # 16 cards for 10's value
        self.true_count = 0

    def deal_card(self, cards_list):
        card = random.choice(self.playing_cards)
        self.playing_cards.remove(card)
        self.update_card_count(card)
        cards_list.append(card)

        is_ace = False
        if card[0] == ACE:
            is_ace = True

        return card, is_ace

    def update_card_count(self, card_removed):
        card_value = self.get_card_value(card_removed)
        self.card_counts[card_value - 1] -= 1

        if card_value >= BIG_CARD_VALUE or card_removed[0] == ACE:
            self.true_count -= 1
        elif card_value <= SMALL_CARD_VALUE:
            self.true_count += 1

    def is_game_over(self):
        return self.stand or self.state == STATE_WIN or self.state == STATE_LOSE or self.state == STATE_DRAW or self.state == STATE_BLACKJACK

    def make_state(self):
        # Calculate actual hands after counting A as 11 as needed
        actual_player_sum, player_A_active = self.calculate_hand(self.player_sum, self.player_has_ace)
        actual_dealer_sum, _ = self.calculate_hand(self.dealer_sum, self.dealer_has_ace)

        dealer_bj = len(self.dealer_cards) == 2 and actual_dealer_sum == 21
        player_bj = len(self.player_cards) == 2 and actual_player_sum == 21

        # Dealer blackjack
        if dealer_bj:
            if player_bj:
                return STATE_DRAW
            else:
                return STATE_LOSE

        # 21!
        if actual_player_sum == 21:
            # Call a stand for player, and don't make state again
            self.act_stand(False)

            # Player blackjack
            if player_bj:
                return STATE_BLACKJACK
            else:
                if actual_dealer_sum != 21:
                    return STATE_WIN
                else:
                    return STATE_DRAW

        # Player busts
        if actual_player_sum > 21:
            return STATE_LOSE

        # Player stands
        if self.stand:
            if actual_dealer_sum > 21 or actual_player_sum > actual_dealer_sum:
                return STATE_WIN
            elif actual_dealer_sum == actual_player_sum:
                return STATE_DRAW
            return STATE_LOSE

        # Game not over #
        card_value_available = [0] * 10
        for i in range(10):
            if self.card_counts[i] > 0:
                card_value_available[i] = 1

        if USE_SIMPLE_STATES:
            return (self.player_sum, self.player_has_ace, self.dealer_upcard_value)
        return (self.player_sum, self.player_has_ace, self.dealer_upcard_value, *card_value_available)

    def act_hit(self):
        # Give player a card
        card, is_ace = self.deal_card(self.player_cards)
        self.player_has_ace = is_ace or self.player_has_ace
        self.player_sum += self.get_card_value(card)

        # Make state based on the updated player cards
        self.state = self.make_state()

    def act_stand(self, make_state=True):
        actual_player_sum, player_A_active = self.calculate_hand(self.player_sum, self.player_has_ace)

        while True:
            actual_dealer_sum, dealer_A_active = self.calculate_hand(self.dealer_sum, self.dealer_has_ace)

            if actual_dealer_sum >= 17:
                # Break unless dealer gets a soft 17 and follows hit on soft 17 policy
                if not (HIT_SOFT_17 and actual_dealer_sum == 17 and dealer_A_active):
                    break
            card, is_ace = self.deal_card(self.dealer_cards)
            self.dealer_has_ace = is_ace or self.dealer_has_ace
            self.dealer_sum += self.get_card_value(card)

        # Make state based on the updated cards
        self.stand = True
        if make_state:
            self.state = self.make_state()

    def act_double(self):
        if self.can_double():
            self.bet *= 2
            self.doubledown = True
            self.act_hit()
            if not self.is_game_over():
                self.act_stand()

    def act_split(self):
        if self.can_split():
            self.player_sum = self.get_card_value(self.player_cards[0])
            self.player_cards.pop()
            self.state = self.make_state()

    def can_double(self):
        return ALLOW_DOUBLE and not self.doubledown and (not DOUBLE_WITH_2_CARDS_ONLY or len(self.player_cards) == 2)

    def can_split(self):
        return ALLOW_SPLIT and len(self.player_cards) == 2 and self.player_cards[0][0] == self.player_cards[1][0]

    def check_reward(self):
        if not self.is_game_over():
            return 0
        if self.state == STATE_BLACKJACK:
            return BLACKJACK_PAYRATE
        if self.state == STATE_WIN:
            return 1
        if self.state == STATE_DRAW:
            return 0
        return -1

    def update_stats(self):
        self.num_games += 1
        self.amount_played += self.bet

        profit_delta = 0
        if self.state == STATE_WIN:
            self.num_wins += 1
            profit_delta = self.bet
        elif self.state == STATE_BLACKJACK:
            self.num_blackjacks += 1
            profit_delta = BLACKJACK_PAYRATE * self.bet
        elif self.state == STATE_DRAW:
            self.num_draws += 1
        elif self.state == STATE_LOSE:
            self.num_losses += 1
            profit_delta = -self.bet

        self.profit += profit_delta

        if self.profit > self.max_profit:
            self.max_profit = self.profit
        if self.profit < self.max_loss:
            self.max_loss = self.profit

        self.curr_loss_streak = min(self.curr_loss_streak + profit_delta, 0)
        if self.curr_loss_streak < self.max_loss_streak:
            self.max_loss_streak = self.curr_loss_streak

        self.curr_win_streak = max(self.curr_win_streak + profit_delta, 0)
        if self.curr_win_streak > self.max_win_streak:
            self.max_win_streak = self.curr_win_streak

    def simulate_one_step(self, action):
        # If the current state is already terminal, return None
        if self.is_game_over():
            return None, self.check_reward()

        # Perform action based on the parameter
        if action == HIT:
            self.act_hit()
        elif action == STAND:
            self.act_stand()

        return self.state, self.check_reward()

    def print_counts(self):
        print(self.card_counts)
        print(self.true_count)

    def sync(self, game):
        self.num_losses = game.num_losses
        self.num_draws = game.num_draws
        self.num_wins = game.num_wins
        self.num_blackjacks = game.num_blackjacks
        self.num_games = game.num_games
        self.max_loss = game.max_loss
        self.max_profit = game.max_profit
        self.max_loss_streak = game.max_loss_streak
        self.max_win_streak = game.max_win_streak
        self.curr_loss_streak = game.curr_loss_streak
        self.curr_win_streak = game.curr_win_streak
        self.profit = game.profit
        self.amount_played = game.amount_played

        self.playing_cards = game.playing_cards
        self.card_counts = game.card_counts
        self.true_count = game.true_count

        self.dealer_cards = game.dealer_cards
        self.dealer_sum = game.dealer_sum
        self.dealer_has_ace = game.dealer_has_ace


import unittest
import pathlib
from helpers import FakeWriter, a_wait

import grole

class TestHeader(unittest.TestCase):

    def test_header(self):
        res = grole.Response(None, 123, 'foo', {'foo': 'bar'}, 'bar')
        writer = FakeWriter()
        a_wait(res._write(writer))
        for line in writer.data.split(b'\r\n'):
            if line.startswith(b'bar'):
                self.assertEqual(line, b'bar 123 foo')
            elif line.startswith(b'Content-Type'):
                self.assertEqual(line, b'Content-Type: text/plain')
            elif line.startswith(b'Content-Length'):
                self.assertEqual(line, b'Content-Length: 0')
            elif line.startswith(b'foo'):
                self.assertEqual(line, b'foo: bar')
            elif line.startswith(b'Server'):
                self.assertEqual(line, b'Server: grole/' + grole.__version__.encode())
            else:
                if line != b'':
                    self.fail('Extra data: ' + line.decode())

class TestBody(unittest.TestCase):

    def test_headers(self):
        res = grole.ResponseBody(b'foo', content_type='bar')
        hdr = {}
        res._set_headers(hdr)
        self.assertDictEqual(hdr, {'Content-Length': 3,
                                   'Content-Type': 'bar'})

    def test_data(self):
        res = grole.ResponseBody(b'foo', content_type='bar')
        writer = FakeWriter()
        a_wait(res._write(writer))
        self.assertEqual(writer.data, b'foo')

    def test_bytes(self):
        res = grole.Response(b'foo')
        self.assertIsInstance(res.data, grole.ResponseBody)

    def test_string(self):
        res = grole.Response('foo')
        self.assertIsInstance(res.data, grole.ResponseString)

    def test_json(self):
        res = grole.Response(['foo'])
        self.assertIsInstance(res.data, grole.ResponseJSON)

    def test_file(self):
        res = grole.Response(grole.ResponseFile('foo'))
        self.assertIsInstance(res.data, grole.ResponseFile)

class TestString(unittest.TestCase):

    def setUp(self):
        self.res = grole.ResponseString('foo', content_type='bar')

    def test_headers(self):
        hdr = {}
        self.res._set_headers(hdr)
        self.assertDictEqual(hdr, {'Content-Length': 3,
                                   'Content-Type': 'bar'})

    def test_data(self):
        writer = FakeWriter()
        a_wait(self.res._write(writer))
        self.assertEqual(writer.data, b'foo')

class TestJSON(unittest.TestCase):

    def setUp(self):
        self.res = grole.ResponseJSON({'foo': 'bar'}, content_type='baz')

    def test_headers(self):
        hdr = {}
        self.res._set_headers(hdr)
        self.assertDictEqual(hdr, {'Content-Length': 14,
                                   'Content-Type': 'baz'})

    def test_data(self):
        writer = FakeWriter()
        a_wait(self.res._write(writer))
        self.assertEqual(writer.data, b'{"foo": "bar"}')

class TestFile(unittest.TestCase):

    def setUp(self):
        testfile = pathlib.Path(__file__).parents[0] / 'test.dat'
        self.res = grole.ResponseFile(str(testfile), content_type='baz')

    def test_headers(self):
        hdr = {}
        self.res._set_headers(hdr)
        self.assertDictEqual(hdr, {'Transfer-Encoding': 'chunked',
                                   'Content-Type': 'baz'})

    def test_data(self):
        writer = FakeWriter()
        a_wait(self.res._write(writer))
        self.assertEqual(writer.data, b'4\r\nfoo\n\r\n0\r\n\r\n')

class TestAuto(unittest.TestCase):

    def test_empty(self):
        res = grole.Response()
        self.assertTrue(isinstance(res.data, grole.ResponseBody))

    def test_bytes(self):
        res = grole.Response(b'foo')
        self.assertTrue(isinstance(res.data, grole.ResponseBody))
        self.assertEqual(res.data._data, b'foo')
        self.assertEqual(res.data._headers['Content-Type'], 'text/plain')

    def test_str(self):
        res = grole.Response('foo')
        self.assertTrue(isinstance(res.data, grole.ResponseString))
        self.assertEqual(res.data._data, b'foo')
        self.assertEqual(res.data._headers['Content-Type'], 'text/html')

    def test_json(self):
        res = grole.Response({'foo': 'bar'})
        self.assertTrue(isinstance(res.data, grole.ResponseJSON))
        self.assertEqual(res.data._data, b'{"foo": "bar"}')
        self.assertEqual(res.data._headers['Content-Type'], 'application/json')

if __name__ == '__main__':
    unittest.main()


# -*- coding: utf-8 -*-
"""
Created on Thu Jan  3 23:47:45 2019

@author: LEX
"""

import time
import math
import torch
import os
import torch.onnx
from model import Languagemodel
from utils.data_utils import Vocab, Txtfile, Data2tensor, SaveloadHP, seqPAD, PAD, EOS, SOS
from utils.core_nns import RNNModel

# Load trained model
def load_model(model_source, use_cuda=False):
    """ Load pretrained model from source
            - model_source: link to '.args' file
            - use_cuda: set it to True if you have GPU
        Return: model, vocab
    """
    #model_args_source = './results/lm.args'
    model_args = SaveloadHP.load(model_source)
    model_args.use_cuda = use_cuda
    language_model = Languagemodel(model_args)
    language_model.model.load_state_dict(torch.load(model_args.trained_model))

    return language_model.model, model_args.vocab

def rev_gen( model, vocab, start_word=SOS):
    """ Generate a review starts with 'start_word', ends with '</s>'
    """
    print('Generating sample review .....................')
    with torch.no_grad():
        word_idx = vocab.w2i[start_word]
        all_words = []
        all_words.append(start_word)
        while word_idx != vocab.w2i[EOS]:
            word_tensor = Data2tensor.idx2tensor([[word_idx]])
            hidden = model.init_hidden(word_tensor.size(0))
            output, hidden = model(word_tensor, hidden)
            label_prob, label_pred = model.inference(output)
            word_idx = label_pred.data[0][0].data.numpy()[0]
            all_words.append(vocab.i2w[word_idx])

        return ' '.join(all_words)

def wd_pred(model, vocab, sentence):
    """ Predict next word
    """
    with torch.no_grad():
        words = sentence.split(' ')
        for i, word in enumerate(words):
            # transform word to tensor
            word_idx = vocab.w2i[word]
            word_tensor = Data2tensor.idx2tensor([[word_idx]])
            if i == 0:
                hidden = model.init_hidden(word_tensor.size(0))
            output, hidden = model(word_tensor, hidden)

    label_prob, label_pred = model.inference(output)
    word_idx = label_pred.data[0][0].data.numpy()[0]

    return vocab.i2w[word_idx]


from selenium import webdriver

options = webdriver.ChromeOptions()
options.add_argument('headless')
driver = webdriver.Chrome(options=options)

#driver.get("http://www.zhgc.com/dllt_wq1/arena.asp")
driver.get("http://www.zhgc.com/dllt_wq2/arena.asp")
file_name = 'write7.txt'

#for i in range(75,217):
for i in range(13,70):
    print("Page No.", i)
    btn = driver.find_element_by_partial_link_text(str(i))
    btn.click()
    data = driver.find_elements_by_xpath('/html/body/table/tbody/tr/td[2]/table[@id="AutoNumber1"]/tbody/tr/td[2]')
    for d in data:
        print(d.text)
        with open(file_name, 'a' , encoding='utf-8') as file_obj:
            file_obj.write(d.text+'\n')


from __future__ import division

import scipy
import setupplots
setupplots.thesis_format()
import matplotlib.pyplot as plt
plt.ion()

import sys
sys.path.insert(0, '/Users/markchilenski/src/bayesimp')

import lines

lines.read_filter_file(
    '/Users/markchilenski/src/bayesimp/spectral_modeling/Be_filter_50_um.dat',
    plot=True,
    title=r'$\SI{50}{\micro m}$ Be filter',
    figsize=(0.5 * setupplots.TEXTWIDTH, 0.5 * setupplots.TEXTWIDTH / 1.618)
)
f = plt.gcf()
a = plt.gca()
a2 = a.twiny()
a2.set_xlim(a.get_xlim())
lam_locs = scipy.asarray([10, 1, 0.5, 0.25, 0.125], dtype=float)
lam_s = [r'$10\vphantom{0123456789}$', r'$1\vphantom{0123456789}$', r'$0.5\vphantom{0123456789}$', r'$0.25\vphantom{0123456789}$', r'$0.125\vphantom{0123456789}$']
E_locs = 1e-3 * scipy.constants.h * scipy.constants.c / (scipy.constants.e * lam_locs * 1e-9)
a2.set_xticks(E_locs)
a2.set_xticklabels(lam_s)
a2.set_xlabel(r"$\lambda$ [nm]")
a.set_title(r'$\SI{50}{\micro m}$ Be filter', y=1.275)
setupplots.apply_formatter(f)
f.savefig("XTOMO_filter.pdf", bbox_inches='tight')
f.savefig("XTOMO_filter.pgf", bbox_inches='tight')