import glob
import hashlib
import os
import sys
import argparse

class FileComparer:
    def __init__(self, folders, extensions):
        self.folders = folders
        self.extensions = extensions

    def run(self):
        self.results = {}
        for folder in self.folders:
            files = [file for file in glob.glob(os.path.join(folder, "*")) if os.path.isfile(file)]
            for file in files:
                ext = os.path.splitext(file)[1][1:]
                if ext in self.extensions:
                    md5_hash = hashlib.md5()
                    with open(file, 'rb') as f:
                        for chunk in iter(lambda: f.read(4096), b""):
                            md5_hash.update(chunk)
                    self.results.setdefault(md5_hash.hexdigest(), []).append(file)
        return self

    def report(self, target=sys.stdout):
        for files in self.results.values():
            if len(files) > 1:
                print(", ".join(files), file=target)
        return self

def main():
    parser = argparse.ArgumentParser(description='Compare files in two folders.')
    parser.add_argument('folders', metavar='F', type=str, nargs='+', help='a list of folders to compare')
    parser.add_argument('--extensions', type=str, nargs='+', default=['jpg', 'mp3', 'epub'], help='a list of file extensions to compare')
    args = parser.parse_args()

    comparer = FileComparer(args.folders, args.extensions)
    comparer.run().report()

if __name__ == "__main__":
    main()


"""Author : Omkar Damle
	Date : 24th May 2017
	This scraper is used to scrape only the geo tagged tweets in LA area
	"""
from __future__ import print_function
import settings_geo
import tweepy
import dataset
from textblob import TextBlob
from sqlalchemy.exc import ProgrammingError
import json
from nltk.stem import *
from nltk.stem.snowball import SnowballStemmer
import string
from string import maketrans
import unicodedata

def startStream():
	count = 0
	while(True):
		print(count)
		count += 1
		try:
			stream.filter(locations=[-118.5,33.8,-118,34.2], languages=["en"])
		except Exception as e:
			print('Exception raised : ' + str(e))
			continue

db = dataset.connect(settings_geo.CONNECTION_STRING)        #????

class MyStreamListener(tweepy.StreamListener):

	def on_status(self, status):

#		print('-----------------------------------------------')

		if status.retweeted:
			return

		print('Original tweet : ' + status.text)

#ensures that only tweets with coordinates are stored
		if status.coordinates is None:
			return

		description = status.user.description
		loc = status.user.location
		text = status.text
		coords = status.coordinates
		geo = status.geo
		name = status.user.screen_name
		user_created = status.user.created_at
		followers = status.user.followers_count
		id_str = status.id_str
		created = status.created_at
		retweets = status.retweet_count
		bg_color = status.user.profile_background_color
		blob = TextBlob(text)								#sentiment analysis
		sent = blob.sentiment

		if geo is not None:
			geo = json.dumps(geo)

		if coords is not None:
			coords = json.dumps(coords)

		table = db[settings_geo.TABLE_NAME]
		try:
			table.insert(dict(
				user_description=description,
				user_location=loc,
				coordinates=coords,
				text=text,
				geo=geo,
				user_name=name,
				user_created=user_created,
				user_followers=followers,
				id_str=id_str,
				created=created,
				retweet_count=retweets,
				user_bg_color=bg_color,
				polarity=sent.polarity,
				subjectivity=sent.subjectivity,
			))
		except ProgrammingError as err:
			print(err)

	def on_error(self, status_code):
		print(type(self))

		if status_code == 420:
			#returning False in on_data disconnects the stream
#			print("here")
			return False
#print("i am here")
auth = tweepy.OAuthHandler(settings_geo.TWITTER_APP_KEY, settings_geo.TWITTER_APP_SECRET)
auth.set_access_token(settings_geo.TWITTER_KEY, settings_geo.TWITTER_SECRET)
api = tweepy.API(auth)
"""
public_tweets = api.home_timeline()
for tweet in public_tweets:
	print tweet.text

print "now let us see the streams"
"""
stream_listener = MyStreamListener()
stream = tweepy.Stream(auth=api.auth, listener=stream_listener)
#stream.filter(track=settings.TRACK_TERMS, languages=["en"])

startStream()


import numpy as np
# import matplotlib.pyplot as plt
from sklearn.linear_model import LogisticRegression
from data import *

option_num = 0 # P V T options
class_num = 2
ford_num = 10
data, label = dataloader(class_num, option_num)
X,Y = shuffle_2arr(data, label)
X_train, Y_train, X_test, Y_test = split_train_test(X,Y, option_num, ford_num)
X_test, Y_test = valence_class(X_test, Y_test, class_num)
# X_train, Y_train = valence_class(X_train, Y_train, class_num)
print(X_train.shape, X_test.shape)

if class_num == 2:
    logreg = LogisticRegression(solver='lbfgs')
elif class_num == 3:
    logreg = LogisticRegression(solver='lbfgs', multi_class='multinomial') # multinomial / auto/ ovr
logreg.max_iter = 1000
# we create an instance of Neighbours Classifier and fit the data.
logreg.fit(X_train, Y_train)

Pred = logreg.predict(X_test)
print('label\t:',Y_test)
print('predict :',Pred)
total_num = len(Y_test)
correct_answer = 0
for i in range(total_num):
    if Y_test[i] == Pred[i]:
        correct_answer += 1

print('the probability is ')
prob = correct_answer*100 / total_num
print(prob)

# assert False
# # Plot the decision boundary. For that, we will assign a color to each
# # point in the mesh [x_min, x_max]x[y_min, y_max].
# x_min, x_max = X_train[:, 0].min() - .5, X_train[:, 0].max() + .5
# y_min, y_max = X_train[:, 1].min() - .5, X_train[:, 1].max() + .5
# print(x_min)
# h = .02  # step size in the mesh
# xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h))
# print(xx.ravel())
# Pred = logreg.predict(np.c_[xx.ravel(), yy.ravel()])
#
# # Put the result into a color plot
# Pred = Pred.reshape(xx.shape)
# plt.figure(1, figsize=(4, 3))
# plt.pcolormesh(xx, yy, Pred, cmap=plt.cm.Paired)
#
# # Plot also the training points
# plt.scatter(X_train[:, 0], X_train[:, 1], c=Y_train, edgecolors='k', cmap=plt.cm.Paired)
# plt.xlabel('Sepal length')
# plt.ylabel('Sepal width')
#
# plt.xlim(xx.min(), xx.max())
# plt.ylim(yy.min(), yy.max())
# plt.xticks(())
# plt.yticks(())
#
# plt.show()


from typing import Union

from flask import render_template, url_for
from werkzeug.utils import redirect

from app import db
from app.main import bp
from app.main.forms import SearchForm
from app.models import Bookmark, Post, User

@bp.route('/')
def feed():
    posts: Post = Post.query

    bookmarks_count: int = Bookmark.query.count()

    search_form: SearchForm = SearchForm(csrf_enabled=False)

    return render_template(
        'index.html',
        posts=posts,
        bookmarks_count=bookmarks_count,
        search_form=search_form,
    )

@bp.route('/posts/<int:post_id>')
def post(post_id: int):
    post: Post = Post.query.filter_by(id=post_id).first_or_404()

    return render_template(
        'post.html',
        post=post,
        title='post',
    )

@bp.route('/search')
def search():
    search_form: SearchForm = SearchForm(csrf_enabled=False)

    posts: Union[list, Post] = []

    if search_form.validate():
        posts = Post.search_by_like(search_form.s.data, limit=10)

    return render_template(
        'search.html',
        posts=posts,
        search_form=search_form,
        title='search',
    )

@bp.route('/user/<string:username>')
def user_feed(username: str):
    user: User = User.query.filter_by(username=username).first_or_404()

    return render_template(
        'user-feed.html',
        user=user,
        title='user feed',
    )

@bp.route('/tag/<string:tag_name>')
def tag_feed(tag_name: str):
    posts: Post = Post.search_by_like(tag_name, limit=None)

    return render_template(
        'tag-feed.html',
        tag_name=tag_name,
        posts=posts,
        title='tag'
    )

@bp.route('/bookmarks/add/<int:post_id>')
def add_post_to_bookmarks(post_id: int):
    bookmark: Bookmark = Bookmark.query.filter_by(post_id=post_id).first()

    if bookmark:
        return redirect(url_for('main.feed'), code=302)

    post: Post = Post.query.filter_by(id=post_id).first_or_404()

    db.session.add(Bookmark(post_id=post.id))
    db.session.commit()

    return redirect(url_for('main.feed'), code=302)

@bp.route('/bookmarks/remove/<int:bookmark_id>')
def remove_post_from_bookmarks(bookmark_id: int):
    bookmark: Bookmark = Bookmark.query.filter_by(id=bookmark_id).first_or_404()

    db.session.delete(bookmark)
    db.session.commit()

    return redirect(url_for('main.feed'), code=302)

@bp.route('/bookmarks')
def bookmarks():
    bookmarks: Bookmark = Bookmark.query

    return render_template(
        'bookmarks.html',
        bookmarks=bookmarks
    )

@bp.route('/raise_500')
def raise_500():
    raise Exception


import datetime
import dateutil
from money import Money
from api.config import Configuration
from api.circulation_exceptions import *
from core.model.patron import Patron
from core.util import MoneyUtility
from core.util.datetime_helpers import utc_now

class PatronUtility(object):
    """Apply circulation-specific logic to Patron model objects."""

    @classmethod
    def needs_external_sync(cls, patron):
        """Could this patron stand to have their metadata synced with the
        remote?

        By default, all patrons get synced once every twelve
        hours. Patrons who lack borrowing privileges can always stand
        to be synced, since their privileges may have just been
        restored.
        """
        if not patron.last_external_sync:
            # This patron has never been synced.
            return True

        now = utc_now()
        if cls.has_borrowing_privileges(patron):
            # A patron who has borrowing privileges gets synced every twelve
            # hours. Their account is unlikely to change rapidly.
            check_every = Patron.MAX_SYNC_TIME
        else:
            # A patron without borrowing privileges might get synced
            # every time they make a request. It's likely they are
            # taking action to get their account reinstated and we
            # don't want to make them wait twelve hours to get access.
            check_every = datetime.timedelta(seconds=5)
        expired_at = patron.last_external_sync + check_every
        if now > expired_at:
            return True
        return False

    @classmethod
    def has_borrowing_privileges(cls, patron):
        """Is the given patron allowed to check out books?

        :return: A boolean
        """
        try:
            cls.assert_borrowing_privileges(patron)
            return True
        except CannotLoan as e:
            return False

    @classmethod
    def assert_borrowing_privileges(cls, patron):
        """Raise an exception unless the patron currently has borrowing
        privileges.

        :raises AuthorizationExpired: If the patron's authorization has expired.
        :raises OutstandingFines: If the patron has too many outstanding fines.

        """
        if not cls.authorization_is_active(patron):
            # The patron's card has expired.
            raise AuthorizationExpired()

        if cls.has_excess_fines(patron):
            raise OutstandingFines()

        from api.authenticator import PatronData
        if patron.block_reason is not None:
            if patron.block_reason is PatronData.EXCESSIVE_FINES:
                # The authentication mechanism itself may know that
                # the patron has outstanding fines, even if the circulation
                # manager is not configured to make that deduction.
                raise OutstandingFines()
            raise AuthorizationBlocked()

    @classmethod
    def has_excess_fines(cls, patron):
        """Does this patron have fines in excess of the maximum fine amount set for their library?

        :param a Patron:
        :return: A boolean
        """
        if not patron.fines:
            return False

        if isinstance(patron.fines, Money):
            patron_fines = patron.fines
        else:
            patron_fines = MoneyUtility.parse(patron.fines)
        actual_fines = patron_fines.amount
        max_fines = Configuration.max_outstanding_fines(patron.library)
        if max_fines is not None and actual_fines > max_fines.amount:
            return True
        return False

    @classmethod
    def authorization_is_active(cls, patron):
        """Return True unless the patron's authorization has expired."""
        # Unlike pretty much every other place in this app, we use
        # (server) local time here instead of UTC. This is to make it
        # less likely that a patron's authorization will expire before
        # they think it should.
        now_local = datetime.datetime.now(tz=dateutil.tz.tzlocal())
        if (patron.authorization_expires
            and cls._to_date(patron.authorization_expires)
            < cls._to_date(now_local)):
            return False
        return True

    @classmethod
    def _to_date(cls, x):
        """Convert a datetime into a date. Leave a date alone."""
        if isinstance(x, datetime.datetime):
            return x.date()
        return x


from typing import Union
# SMTP
from smtplib import SMTP
# Message utils
from .EmailMessage import EmailAttachment, EmailMessageFactory

class EmailManager:
    """
    @version 1.0.1

    Class that provides email functionality, by encapsulating all the process and exposing only the
    facade and setters we are able to hide the underlying complexity of this process, making it a lot
    easier to use.
    It supports basic text messages, as well as attachments. One important thing about attachments is
    that we don't need to worry about the MIMETypes, because they're inferred automatically, also, they
    are processed and attached automatically, so we just need to provide the path to the attachment, and
    the class will do all the required stuff under the hood.
    """

    def __init__(
        self,
        server: str,
        sender: str = None,
        target: Union[str, list] = None,
        subject: str = None,
        email_body: str = '',
        attachments: list = []
    ):
        """
        @param {str} server The SMTP server IP or domain.
        @param {str} sender The email user that sends the message.
        @param {str} target The email target user of the message.
        @param {str} subject The email subject.
        @param {str} email_body The email text body.
        @param {str} attachments The attachments list (path to the attachments, actually).
        """
        self.server = server
        self.sender = sender
        self.target = target
        self.subject = subject
        self.email_body = email_body
        self.attachments = attachments
        # To be set later
        self.root_message = None

    # Setters

    def set_participants(
        self,
        sender: str,
        target: Union[str, list]
    ):
        """
        Sets the participants of the mail (to and from).
        """
        self.sender = sender
        self.target = target

    def set_subject(self, subject):
        """
        Sets the mail subject.
        """
        self.mail_subject = subject

    def set_email_body(self, email_body):
        """
        Sets the mail text body.
        """
        self.email_body = email_body

    def add_attachment(
        self,
        attachment_path: str
    ):
        """
        Adds an attachment to the attachments list.
        """
        self.attachments.append(attachment_path)

    # Facade

    def send(self):
        """
        Facade method to send the email. It calls all the necessary method to, first validate the email
        components, create and initialize the root message (or email tree), attach the text message body,
        attach the attachments and send the message via the SMTP server.
        """
        # We perform a validation of the mandatory mail components (to, from and body)
        self.__validate_mail_components()
        # We create and initialize the root message (the email tree, which will contain the text body and the attachments)
        self.__initialize_root_message()
        # We attach the message body (provided as text) to the root message
        self.__attach_text_message_body()
        # We add the attachments to the root message
        self.__incorporate_attachments()
        # Finally, we actually send the mail
        self.__send_root_message_via_smtp()

    # Private methods

    def __initialize_root_message(self):
        """
        Creates and initialize a root message (MIMEMultipart), to support text and attachments.
        Also, the email data is set, such as email_to, email_from and the subject.
        """
        self.root_message = EmailMessageFactory.create_by_type(EmailMessageFactory.MULTIPART)
        self.root_message['To'] = self.target
        self.root_message['From'] = self.sender
        self.root_message['Subject'] = self.subject

    def __attach_text_message_body(self):
        """
        Attaches the provided text email body to the root message.
        """
        text_message_body = EmailMessageFactory.create_text_message(self.email_body)
        self.root_message.attach(text_message_body)

    def __incorporate_attachments(self):
        """
        Iterates through the attachments list, creating an EmailAttachment instance for each (this
        class prepares the attachment to be ready to be attached directly to the root message, without
        us having to worry about setting the content type, subtype, the file content or the encoding and
        headers).
        """
        for attachment_path in self.attachments:
            attachment = EmailAttachment(attachment_path).create()
            self.root_message.attach(attachment)

    def __send_root_message_via_smtp(self):
        """
        Method to finally send the message via the SMTP protocol, using the specified server.
        """
        with SMTP(self.server) as server:
            server.ehlo()
            server.sendmail(
                self.sender,
                self.target,
                self.root_message.as_string()
            )

    # Validations
    def __validate_mail_components(self):
        """
        Validates that the mandatory data is not empty, throwing an exception if that's the case.
        """
        if (
            not self.sender or
            not self.target or
            not self.email_body
        ):
            raise Exception('The mail cannot be send without the mandatory data (to, from and payload).')


import sys
import json
import platform
import subprocess
import os
import PySide2
from PyQt5 import QtWidgets
from PyQt5.Qt import *
from PyQt5.QtGui import QIcon

from QT_windows import blank_window
from QT_windows.A_Shaitu import shaitu_window
from QT_windows.B_Biaotu import biaotu_window
from QT_windows.C_Biaozhutongji import biaozhutongji_window
from QT_windows.D_Dianjian import dianjian_window
from QT_windows.E_Biaozhunbiangeng import biaozhunbiangeng_window
from database_moudle.data_show_page import DataGrid

from QT_style.style import StackWidget_Style, Mini_Exit_Button_Style, Still_Button_Style, Normal_Button_Style
file_path = r'QT_style/Real_main_window.json'
style_dict = json.load(open(file_path, 'r'))

dirname = os.path.dirname(PySide2.__file__)
plugin_path = os.path.join(dirname, 'plugins', 'platforms')
os.environ['QT_QPA_PLATFORM_PLUGIN_PATH'] = plugin_path

class MainWidget(QtWidgets.QMainWindow, QWidget):

    def __init__(self):
        super(MainWidget, self).__init__()
        self.app = QApplication(sys.argv)
        self.scaleRate = 1
        self.init_ui(self.scaleRate)
        self.setup_ui()
        self.add_shadow()

    def init_ui(self, scaleRate):

        self.resize(1322 * scaleRate, 830 * scaleRate)

    def setup_ui(self):

        # self.setWindowOpacity(0.97)  # 设置窗口透明度
        self.setAttribute(Qt.WA_TranslucentBackground)  # 设置窗口背景透明----
        self.setWindowFlag(Qt.FramelessWindowHint)  # 隐藏边框
        self.setWindowIcon(QIcon('./images/shuguang.png'))

        self.base_widget = QtWidgets.QWidget()  # 创建透明窗口
        self.base_widget.setObjectName('base_widget')
        self.base_layout = QtWidgets.QGridLayout()
        self.base_widget.setLayout(self.base_layout)
        self.base_widget.setAttribute(Qt.WA_TranslucentBackground)

        self.main_widget = QtWidgets.QWidget()
        self.main_widget.setObjectName('main_widget')
        self.main_widget.setStyleSheet('QWidget#main_widget{border-top-left-radius:25px;border-bottom-left-radius:25px;'
                                       'border-top-right-radius:0px;border-bottom-right-radius:0px;'
                                        'background-image: url(./images/background7.png);'
                                       '}' )
        self.base_layout.addWidget(self.main_widget,0,0)

        self.main_layout = QtWidgets.QGridLayout()
        self.main_layout.setContentsMargins(105, 0, 0, 0)
        self.main_widget.setLayout(self.main_layout)

        self.setCentralWidget(self.base_widget)  # 设置窗口主部件

        # 退出及最小化按钮
        self.exit = Mini_Exit_Button_Style(self, **style_dict['Exit_Button_Style'])
        self.exit.clicked.connect(self.exit_onClick_Button)

        self.mini = Mini_Exit_Button_Style(self, **style_dict['Mini_Button_Style'])
        self.mini.clicked.connect(lambda: self.showMinimized())

        self.refresh = Mini_Exit_Button_Style(self, **style_dict['Refresh_Button_Style'])
        self.refresh.clicked.connect(self.refresh_onClick_Button)

        self.homepage = Mini_Exit_Button_Style(self, **style_dict['Homepage_Button_Style'])
        self.homepage.clicked.connect(self.homepage_onClick_Button)

        # 右侧“切换界面”窗口
        self.Init_window_StackWidget = StackWidget_Style(self, **style_dict['Init_window_StackWidget_Style'])
        self.main_layout.addWidget(self.Init_window_StackWidget)

        #左侧菜单栏图标
        self.button1 = Still_Button_Style(self, **style_dict['Shaitu_Still_Button_Style'])
        self.button1.clicked.connect(self.button1_onClick_Button)

        self.button2 = Still_Button_Style(self, **style_dict['Biaotu_Still_Button_Style'])
        self.button2.clicked.connect(self.button2_onClick_Button)

        self.button3 = Still_Button_Style(self, **style_dict['Biaozhutongji_Still_Button_Style'])
        self.button3.clicked.connect(self.button3_onClick_Button)

        self.button4 = Still_Button_Style(self, **style_dict['Dianjian_Still_Button_Style'])
        self.button4.clicked.connect(self.button4_onClick_Button)

        self.button5 = Still_Button_Style(self, **style_dict['Biaozhun_Still_Button_Style'])
        self.button5.clicked.connect(self.button5_onClick_Button)

        self.button6 = Normal_Button_Style(self, **style_dict['Database_Button_Style'])
        self.button6.clicked.connect(self.button6_onClick_Button)

        self.button7 = Normal_Button_Style(self, **style_dict['VIA_Button_Style'])
        self.button7.clicked.connect(self.button7_onClick_Button)

        tools_str = [getattr(blank_window, "WindowDemo"),
                     getattr(shaitu_window, "Shaitu_window_StackWidget"),
                     getattr(biaotu_window, "Biaozhu_window_StackWidget"),
                     getattr(biaozhutongji_window, "Biaozhujiancha_window_StackWidget"),
                     getattr(dianjian_window, "Dianjian_window_StackWidget"),
                     getattr(biaozhunbiangeng_window, "Biaozhunbiangeng_window_StackWidget"),
                     ]
        for i in range(6):
            self.Init_window_StackWidget.addWidget(tools_str[i]())

    def add_shadow(self):
        # 添加阴影
        self.effect_shadow = QtWidgets.QGraphicsDropShadowEffect(self)
        self.effect_shadow.setOffset(0, 0)  # 偏移
        self.effect_shadow.setBlurRadius(10)  # 阴影半径
        self.effect_shadow.setColor(Qt.gray)  # 阴影颜色
        self.main_widget.setGraphicsEffect(self.effect_shadow)  # 将设置套用到widget窗口中

    def mousePressEvent(self, event):
        if event.button() == Qt.LeftButton:
            self.m_flag = True
            self.m_Position = event.globalPos() - self.pos()  # 获取鼠标相对窗口的位置
            event.accept()
            self.setCursor(QCursor(Qt.OpenHandCursor))  # 更改鼠标图标

    def mouseMoveEvent(self, QMouseEvent):
        if Qt.LeftButton and self.m_flag:
            self.move(QMouseEvent.globalPos() - self.m_Position)  # 更改窗口位置
            QMouseEvent.accept()
            if len(self.app.screens()) == 1:
                self.scaleRate = 1
            else:
                self.scaleRate = self.app.screens()[1].logicalDotsPerInch() / 96
            self.init_ui(self.scaleRate)
            self.add_shadow()

    def mouseReleaseEvent(self, QMouseEvent):
        self.m_flag = False
        self.setCursor(QCursor(Qt.ArrowCursor))

    def exit_onClick_Button(self):
        app = QApplication.instance()  # 退出应用程序
        app.quit()

    def refresh_onClick_Button(self):
        QApplication.processEvents()  # 刷新界面
        status_bool = [False, False, False, False, False, False]
        i = self.Init_window_StackWidget.currentIndex()
        status_bool[i - 1] = True
        self.button1.setAutoExclusive(False)
        self.button1.setChecked(status_bool[0])
        self.button1.setAutoExclusive(True)
        self.button2.setAutoExclusive(False)
        self.button2.setChecked(status_bool[1])
        self.button2.setAutoExclusive(True)
        self.button3.setAutoExclusive(False)
        self.button3.setChecked(status_bool[2])
        self.button3.setAutoExclusive(True)
        self.button4.setAutoExclusive(False)
        self.button4.setChecked(status_bool[3])
        self.button4.setAutoExclusive(True)
        self.button5.setAutoExclusive(False)
        self.button5.setChecked(status_bool[4])
        self.button5.setAutoExclusive(True)
        self.button6.setAutoExclusive(False)
        self.button6.setChecked(status_bool[5])
        self.button6.setAutoExclusive(True)

    def homepage_onClick_Button(self):
        self.Init_window_StackWidget.setCurrentIndex(0)
        self.button1.setAutoExclusive(False)
        self.button1.setChecked(False)
        self.button1.setAutoExclusive(True)
        self.button2.setAutoExclusive(False)
        self.button2.setChecked(False)
        self.button2.setAutoExclusive(True)
        self.button3.setAutoExclusive(False)
        self.button3.setChecked(False)
        self.button3.setAutoExclusive(True)
        self.button4.setAutoExclusive(False)
        self.button4.setChecked(False)
        self.button4.setAutoExclusive(True)
        self.button5.setAutoExclusive(False)
        self.button5.setChecked(False)
        self.button5.setAutoExclusive(True)
        self.button6.setAutoExclusive(False)
        self.button6.setChecked(False)
        self.button6.setAutoExclusive(True)

    def button1_onClick_Button(self):
        self.Init_window_StackWidget.setCurrentIndex(1)

    def button2_onClick_Button(self):
        self.Init_window_StackWidget.setCurrentIndex(2)

    def button3_onClick_Button(self):
        self.Init_window_StackWidget.setCurrentIndex(3)

    def button4_onClick_Button(self):
        self.Init_window_StackWidget.setCurrentIndex(4)

    def button5_onClick_Button(self):
        self.Init_window_StackWidget.setCurrentIndex(5)

    def button6_onClick_Button(self):
        self.datapage = DataGrid()
        self.datapage.show()

    def button7_onClick_Button(self):
        fp = r'via-src-2.0.11/dist/via.html'
        systemType: str = platform.platform()  # 获取系统类型
        if 'mac' in systemType:  # 判断以下当前系统类型
            fp: str = fp.replace("\\", "/")  # mac系统下,遇到`\\`让路径打不开,不清楚为什么哈,觉得没必要的话自己可以删掉啦,18行那条也是
            subprocess.call(["open", fp])
        else:
            fp: str = fp.replace("/", "\\")  # win系统下,有时`/`让路径打不开
            os.startfile(fp)

def main():

    QApplication.setAttribute(Qt.AA_EnableHighDpiScaling)
    app = QApplication(sys.argv)
    main_wnd = MainWidget()
    main_wnd.show()
    app.exec()

if __name__ == '__main__':
    main()


import pytest
from selenium import webdriver
import time
import math
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

@pytest.fixture(scope="function")
def browser():
    print("\nstart browser for test..")
    browser = webdriver.Chrome()
    yield browser
    time.sleep(3)
    print("\nquit browser..")
    browser.quit()

@pytest.mark.parametrize('url', ["236895", "236896", "236897", "236898", "236899", "236903", "236904", "236905"])
def test_guest_should_see_login_link(browser, url):
    link = f"https://stepik.org/lesson/{url}/step/1"
    browser.get(link)
    textarea =  WebDriverWait(browser, 10).until(EC.visibility_of_element_located((By.CLASS_NAME, "textarea")))
    #textarea = browser.find_element_by_css_selector("textarea")
    answer = math.log(int(time.time()))
    textarea.send_keys(str(answer))
    button = WebDriverWait(browser, 5).until(EC.element_to_be_clickable((By.CLASS_NAME, "submit-submission")))
    button.click()
    WebDriverWait(browser, 15).until(EC.visibility_of_element_located((By.CLASS_NAME, "smart-hints__hint")))
    result_test = browser.find_element_by_class_name("smart-hints__hint")
    assert result_test.text == "Correct!", "Incorrect: Test has not been passed"


from PyQt5 import QtCore, QtWidgets
import sys
import os
import strTool
import threading
from PyQt5.QtCore import QBasicTimer
from PyQt5.QtCore import QThread, pyqtSignal
import time
##########################################
global path
path = ""
startpath = "F:/summerImmunedroid2021/spring2022/lotsOfApp/strava"
time_in_sec = 0
##########################################
#ui界面设置

class Thread(QThread):
    _signal = pyqtSignal(int) #定义信号类型为整型
    def __init__(self):
        super(Thread, self).__init__()
    def __del__(self):
        self.wait()
    def run(self):
        for i in range(1,101):
            global time_in_sec
            time.sleep(time_in_sec/100)
            self._signal.emit(i)  #发射信号

class Ui_MainWindow(object):

    def setupUi(self, MainWindow):

        #主窗口参数设置
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(848, 721)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")

        # 设置分析按键参数
        self.analyze = QtWidgets.QPushButton(self.centralwidget)
        # Qrect(a,b,c,d):以(a,b)为左上角，给定宽度c和高度d的矩形
        self.analyze.setGeometry(QtCore.QRect(57, 260, 175, 28))
        self.analyze.setObjectName("file")
        self.analyze.setStyleSheet("background-color:rgb(111,180,219)")
        self.analyze.setStyleSheet(
            "QPushButton{background-color:rgb(111,180,219)}"  # 按键背景色
            "QPushButton:hover{color:green}"  # 光标移动到上面后的前景色
            "QPushButton{border-radius:6px}"  # 圆角半径
            "QPushButton:pressed{background-color:rgb(180,180,180);border: None;}"  # 按下时的样式
        )

        # 设置进度条参数
        self.pbar = QtWidgets.QProgressBar(self.centralwidget)
        self.pbar.setGeometry(200,400,480,28)
        self.pbar.setValue(0)

        # 设置路径按钮参数
        self.file = QtWidgets.QPushButton(self.centralwidget)
        self.file.setGeometry(QtCore.QRect(57, 200, 175, 28))
        self.file.setObjectName("analyze")
        self.file.setStyleSheet("background-color:rgb(111,180,219)")
        self.file.setStyleSheet(
            "QPushButton{background-color:rgb(111,180,219)}"  # 按键背景色
            "QPushButton:hover{color:green}"  # 光标移动到上面后的前景色
            "QPushButton{border-radius:6px}"  # 圆角半径
            "QPushButton:pressed{background-color:rgb(180,180,180);border: None;}"  # 按下时的样式
        )

        # 设置显示窗口参数
        self.fileT = QtWidgets.QPushButton(self.centralwidget)
        self.fileT.setGeometry(QtCore.QRect(300, 200, 480, 28))
        self.fileT.setObjectName("file")
        self.fileT.setStyleSheet("background-color:rgb(111,180,219)")
        self.fileT.setStyleSheet(
            "QPushButton{background-color:rgb(111,180,219)}"  # 按键背景色
            "QPushButton:hover{color:green}"  # 光标移动到上面后的前景色
            "QPushButton{border-radius:6px}"  # 圆角半径
            "QPushButton:pressed{background-color:rgb(180,180,180);border: None;}"  # 按下时的样式
        )

        #主窗口及菜单栏标题栏设置
        MainWindow.setCentralWidget(self.centralwidget)
        self.menubar = QtWidgets.QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 848, 26))
        self.menubar.setObjectName("menubar")
        MainWindow.setMenuBar(self.menubar)
        self.statusbar = QtWidgets.QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusbar)

        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

        ################button按钮点击事件回调函数################

        self.file.clicked.connect(self.msg)
        self.analyze.clicked.connect(self.androanalyze)

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "ImmuneDroid"))
        self.file.setText(_translate("MainWindow", "choose"))
        self.fileT.setText(_translate("MainWindow", ""))
        self.analyze.setText(_translate("MainWindow", "start"))

    #########选择图片文件夹#########

    def msg(self,Filepath):
        global path
        path = QtWidgets.QFileDialog.getOpenFileName(None,"choose file",startpath,"All Files (*);;Text Files (*.txt)")  # 起始路径
        # print(m)
        self.fileT.setText(path[0]) #m[0]是包含文件的路径

    #########分析函数入口#########
    def androanalyze(self):
        local_path = ""
        local_path = repr(path[0])
        case = local_path.split("/")
        apk_name = case[-1]
        dir_path = local_path.replace(apk_name,"")
        file_size = os.path.getsize(local_path.replace("'",""))
        print("apk_name: " + apk_name)
        print("dir_path: " + dir_path)
        print("file_size: " + str(file_size))
        global time_in_sec
        time_in_sec = (int)(file_size/15100)
        print("time_in_sec: " + str(time_in_sec))
        t = threading.Thread(target=strTool.main_analysis,args = (dir_path,apk_name))
        t.setDaemon(True) #不必等待子线程
        t.start()
        self.fileT.setText("start! please wait!")
        self.thread = Thread()
        self.thread._signal.connect(self.signal_accept)
        self.thread.start() # 调用自定义Thread类型中run函数
    def signal_accept(self,msg):
        self.pbar.setValue(int(msg))
        if self.pbar.value() == 100:
            self.fileT.setText("finish!")

#########主函数入口 #########

if __name__ == '__main__':
    app = QtWidgets.QApplication(sys.argv)
    mainWindow = QtWidgets.QMainWindow()
    ui = Ui_MainWindow()
    ui.setupUi(mainWindow)
    mainWindow.show()
    sys.exit(app.exec_())


'''
Created on Oct 6, 2014

@author: Tuan
'''
import codecs
import json
import os

from src.utils.constant import QUALIA_CLASS_FILE, WRITING_MODE, CODEC, \
    READING_MODE
from src.utils.helper import Alphabet

class ClassAlphabet(object):
    def __init__(self):
        if os.path.isfile(QUALIA_CLASS_FILE):
            with codecs.open(QUALIA_CLASS_FILE, READING_MODE, CODEC) as file_handler:
                self.class_alphabet = Alphabet.json_loads(json.load(file_handler))
        else:
            ClassAlphabet.initiate_alphabet()

    def size(self):
        return self.class_alphabet.num_labels

    def get_class_index(self, label_str):
        if self.class_alphabet.has_label(label_str.lower()):
            return self.class_alphabet.get_index(label_str.lower())
        return None

    def get_class(self, class_index):
        return self.class_alphabet.get_label(class_index)

    @classmethod
    def initiate_alphabet(cls):
        class_alphabet = Alphabet()
        class_alphabet.add('formal')
        class_alphabet.add('telic')
        class_alphabet.add('agentive')
        class_alphabet.add('constitutive')
        with codecs.open(QUALIA_CLASS_FILE, WRITING_MODE, CODEC) as file_handler:
            json.dump(class_alphabet.json_dumps(), file_handler)


#!/usr/bin/env python3

from restaurant_crud import RestaurantCRUD
from flask import Flask, render_template, request, url_for, redirect, jsonify, flash
import bleach

# Oauth2 imports
from flask import session as login_session
from flask import make_response
import string, random
from oauth2client.client import flow_from_clientsecrets
from oauth2client.client import FlowExchangeError
import httplib2, json, requests

app = Flask(__name__)
crud = RestaurantCRUD()

CLIENT_ID = json.loads(
    open('client_secrets.json', 'r').read())['web']['client_id']
APPLICATION_NAME = "Restaurant Menu Application"

@app.route("/login", methods=["GET", "POST"])
def showLogin():
    state = "".join(random.choice(string.ascii_letters + string.digits) for x in range(32))
    login_session["state"] = state
    data = request.form
    if request.method == "POST":
        return redirect(url_for("restaurant"))
    return render_template("login.html", STATE=state)

@app.route('/gconnect', methods=['POST'])
def gconnect():
    # Validate state token
    if request.args.get('state') != login_session['state']:
        response = make_response(json.dumps('Invalid state parameter.'), 401)
        response.headers['Content-Type'] = 'application/json'
        return response
    # Obtain authorization code
    code = request.data

    try:
        # Upgrade the authorization code into a credentials object
        oauth_flow = flow_from_clientsecrets('client_secrets.json', scope='')
        oauth_flow.redirect_uri = 'postmessage'
        credentials = oauth_flow.step2_exchange(code)
    except FlowExchangeError:
        response = make_response(
            json.dumps('Failed to upgrade the authorization code.'), 401)
        response.headers['Content-Type'] = 'application/json'
        return response

    # Check that the access token is valid.
    access_token = credentials.access_token
    url = ('https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=%s'
           % access_token)
    h = httplib2.Http()
    result = json.loads(h.request(url, 'GET')[1])
    # If there was an error in the access token info, abort.
    if result.get('error') is not None:
        response = make_response(json.dumps(result.get('error')), 500)
        response.headers['Content-Type'] = 'application/json'
        return response

    # Verify that the access token is used for the intended user.
    gplus_id = credentials.id_token['sub']
    if result['user_id'] != gplus_id:
        response = make_response(
            json.dumps("Token's user ID doesn't match given user ID."), 401)
        response.headers['Content-Type'] = 'application/json'
        return response

    # Verify that the access token is valid for this app.
    if result['issued_to'] != CLIENT_ID:
        response = make_response(
            json.dumps("Token's client ID does not match app's."), 401)
        print ("Token's client ID does not match app's.")
        response.headers['Content-Type'] = 'application/json'
        return response

    stored_access_token = login_session.get('access_token')
    stored_gplus_id = login_session.get('gplus_id')
    if stored_access_token is not None and gplus_id == stored_gplus_id:
        response = make_response(json.dumps('Current user is already connected.'),
                                 200)
        response.headers['Content-Type'] = 'application/json'
        return response

    # Store the access token in the session for later use.
    login_session['access_token'] = credentials.access_token
    login_session['gplus_id'] = gplus_id

    # Get user info
    userinfo_url = "https://www.googleapis.com/oauth2/v1/userinfo"
    params = {'access_token': credentials.access_token, 'alt': 'json'}
    answer = requests.get(userinfo_url, params=params)

    data = answer.json()

    login_session['username'] = data['name']
    login_session['picture'] = data['picture']
    login_session['email'] = data['email']
    # ADD PROVIDER TO LOGIN SESSION
    login_session['provider'] = 'google'

    # see if user exists, if it doesn't make a new one
    user_id = crud.getUserID(data["email"])
    if not user_id:
        user_id = crud.createUser(login_session)
    login_session['user_id'] = user_id

    output = ''
    output += '
Welcome, '
    output += login_session['username']
    output += '!
'
    output += ' '
    flash("you are now logged in as %s" % login_session['username'])
    print ("done!")
    return jsonify(output={"body": output})

@app.route('/fbconnect', methods=['POST'])
def fbconnect():
    if request.args.get('state') != login_session['state']:
        response = make_response(json.dumps('Invalid state parameter.'), 401)
        response.headers['Content-Type'] = 'application/json'
        return response
    access_token = request.data
    print ("access token received %s " % access_token)

    app_id = json.loads(open('fb_client_secrets.json', 'r').read())[
        'web']['app_id']
    app_secret = json.loads(
        open('fb_client_secrets.json', 'r').read())['web']['app_secret']
    url = 'https://graph.facebook.com/oauth/access_token?grant_type=fb_exchange_token&client_id=%s&client_secret=%s&fb_exchange_token=%s' % (
        app_id, app_secret, access_token)
    h = httplib2.Http()
    result = h.request(url, 'GET')[1]

    # Use token to get user info from API
    userinfo_url = "https://graph.facebook.com/v2.8/me"
    '''
        Due to the formatting for the result from the server token exchange we have to
        split the token first on commas and select the first index which gives us the key : value
        for the server access token then we split it on colons to pull out the actual token value
        and replace the remaining quotes with nothing so that it can be used directly in the graph
        api calls
    '''
    print(result)
    token = result.split(',')[0].split(':')[1].replace('"', '')

    url = 'https://graph.facebook.com/v2.8/me?access_token=%s&fields=name,id,email' % token
    h = httplib2.Http()
    result = h.request(url, 'GET')[1]
    # print "url sent for API access:%s"% url
    # print "API JSON result: %s" % result
    data = json.loads(result)
    login_session['provider'] = 'facebook'
    login_session['username'] = data["name"]
    login_session['email'] = data["email"]
    login_session['facebook_id'] = data["id"]

    # The token must be stored in the login_session in order to properly logout
    login_session['access_token'] = token

    # Get user picture
    url = 'https://graph.facebook.com/v2.8/me/picture?access_token=%s&redirect=0&height=200&width=200' % token
    h = httplib2.Http()
    result = h.request(url, 'GET')[1]
    data = json.loads(result)

    login_session['picture'] = data["data"]["url"]

    # see if user exists
    user_id = crud.getUserID(login_session['email'])
    if not user_id:
        user_id = crud.createUser(login_session)
    login_session['user_id'] = user_id

    output = ''
    output += '
Welcome, '
    output += login_session['username']

    output += '!
'
    output += ' '

    flash("Now logged in as %s" % login_session['username'])
    return jsonify(output={"body": output})

def gdisconnect():
    # Only disconnect a connected user.
    access_token = login_session.get('access_token')
    if access_token is None:
        response = make_response(
            json.dumps('Current user not connected.'), 401)
        response.headers['Content-Type'] = 'application/json'
        return response
    url = 'https://accounts.google.com/o/oauth2/revoke?token=%s' % access_token
    h = httplib2.Http()
    result = h.request(url, 'GET')[0]
    if result['status'] == '200':
        response = make_response(json.dumps('Successfully disconnected.'), 200)
        response.headers['Content-Type'] = 'application/json'
        return response
    else:
        response = make_response(json.dumps('Failed to revoke token for given user.'))#, 400))
        response.headers['Content-Type'] = 'application/json'
        return response

def fbdisconnect():
    facebook_id = login_session['facebook_id']
    # The access token must me included to successfully logout
    access_token = login_session['access_token']
    url = 'https://graph.facebook.com/%s/permissions?access_token=%s' % (facebook_id,access_token)
    h = httplib2.Http()
    result = h.request(url, 'DELETE')[1]
    return "you have been logged out"

# Disconnect based on provider
@app.route('/disconnect')
def disconnect():
    print(login_session)
    if 'provider' in login_session:
        if login_session['provider'] == 'google':
            gdisconnect()
            del login_session['gplus_id']
            del login_session['access_token']
        if login_session['provider'] == 'facebook':
            fbdisconnect()
            del login_session['facebook_id']
        del login_session['username']
        del login_session['email']
        del login_session['picture']
        del login_session['user_id']
        del login_session['provider']
        flash("You have successfully been logged out.")
        return redirect(url_for('restaurant'))
    else:
        flash("You are not logged in")
        return redirect(url_for('restaurant'))

@app.route("/")
@app.route("/restaurant")
def restaurant():
    restaurants = crud.get_all_restaurants()
    return render_template("restaurant.html", restaurants=restaurants, session=login_session)

@app.route("/restaurant/new", methods=["GET", "POST"])
def newRestaurant():
    if "username" not in login_session:
        return redirect("/login")

    if request.method == "POST":
        # store form data
        data = request.form

        # check which button is clicked - either CREATE or CANCEL
        if data["action"] == "CREATE":
            # clean data
            rest_data = bleach.clean(data["name"])
            # perform create operation on database
            crud.create_restaurant(rest_data)
            # flash message to inform user
            flash("New Restaurant {} Created!".format(rest_data))

        # redirect to home page for both action of either CREATE or CANCEL
        return redirect(url_for('restaurant'))
    else: # else GET request
        return render_template("restaurant_op.html", restaurant="", op="add")

@app.route("/restaurant/<int:r_id>/edit", methods=["GET", "POST"])
def editRestaurant(r_id):
    if "username" not in login_session:
        return redirect("/login")

    if request.method == "POST":
        data = request.form
        # check which button is clicked - either UPDATE or CANCEL
        if data["action"] == "UPDATE":
            rest_data = bleach.clean(data["name"])
            crud.update_restaurant_name(r_id, rest_data)
            flash("Restaurant {} Updated!".format(rest_data))

        return redirect(url_for('restaurant'))
    else:
        r = crud.get_restaurant(r_id)
        return render_template("restaurant_op.html", restaurant=r, op="edit")

@app.route("/restaurant/<int:r_id>/delete", methods=["GET", "POST"])
def deleteRestaurant(r_id):
    if "username" not in login_session:
        return redirect("/login")

    if request.method == "POST":
        data = request.form

        # check which button is clicked - either DELETE or CANCEL
        if data["action"] == "DELETE":
            r = crud.get_restaurant(r_id)
            crud.delete_restaurant(r_id)
            flash("Restaurant {} Deleted!".format(r.name))

        return redirect(url_for('restaurant'))
    else:
        r = crud.get_restaurant(r_id)
        return render_template("restaurant_op.html", restaurant=r, op="delete")

@app.route("/restaurant/<int:r_id>/", methods =["GET", "POST"])
def restaurantMenuItem(r_id):
    # read restaurant and its menu items from database
    r = crud.get_restaurant(r_id)
    m = crud.get_rest_menu_items(r_id)

    # collect all courses provided by restaurant
    courses =[]
    for i in m:
        # prepare a course list
        courses.append(i.course)

    # get unique set of courses
    courses = list(set(courses))

    return render_template("menu.html", courses=courses, restaurant=r, items=m)

@app.route("/restaurant/<int:r_id>/<int:m_id>/edit", methods=["GET", "POST"])
def editMenuItem(r_id, m_id):
    if "username" not in login_session:
        return redirect("/login")

    r = crud.get_restaurant(r_id)
    m = crud.get_menu_item(r.id, m_id)
    m_all = crud.get_rest_menu_items(r_id)

    # prepare course list
    courses = []
    for i in m_all:
        courses.append(i.course)
    courses = list(set(courses))

    if request.method == "POST":
        data = request.form

        # check if button submit is UPDATE or CANCEL
        if data["action"] == "UPDATE":
            item_name = bleach.clean(data["name"])
            item_desc = bleach.clean(data["description"])
            item_price = bleach.clean(data["price"])
            item_course = bleach.clean(data["course"])

            # check and update the new-course to item_course
            if item_course == "OTHER":
                new_course = bleach.clean(data["new-course"])
                # update the item_course to value new-course
                item_course = new_course if item_course == "OTHER" else item_course

            crud.update_menu_item(r.id, m.id, item_name, item_course, item_desc, item_price)
            flash("Menu Item {} Updated!".format(item_name))
        return redirect(url_for('restaurantMenuItem', r_id=r.id))
    else:
        return render_template("menuitem_op.html", restaurant=r, courses=courses, item=m, op="edit")

@app.route("/restaurant/<int:r_id>/<int:m_id>/delete", methods=["GET", "POST"])
def deleteMenuItem(r_id, m_id):
    if "username" not in login_session:
        return redirect("/login")

    r = crud.get_restaurant(r_id)
    m = crud.get_menu_item(r.id, m_id)
    if request.method == "POST":
        data = request.form
        if data["action"] == "DELETE":
            crud.delete_menu_item(r.id, m.id)
            flash("Menu Item {} Deleted!".format(m.name))
        return redirect(url_for('restaurantMenuItem', r_id=r.id))
    else:
        return render_template("menuitem_op.html", restaurant=r, item=m, op="delete")

@app.route("/restaurant/<int:r_id>/new", methods=["GET", "POST"])
def newMenuItem(r_id):
    if "username" not in login_session:
        return redirect("/login")

    r = crud.get_restaurant(r_id)
    m = crud.get_rest_menu_items(r_id)

    # get all courses
    courses =[]
    for i in m:
        courses.append(i.course)
    courses = list(set(courses))

    if request.method == "POST":
        data = request.form
        if data["action"] == "CREATE":
            item_name = bleach.clean(data["name"])
            item_desc = bleach.clean(data["description"])
            item_price = bleach.clean(data["price"])
            course = bleach.clean(data["course"])
            item_course = bleach.clean(data["course"])

            # check and update the new-course to item_course
            if item_course == "OTHER":
                new_course =bleach.clean(data["new-course"])
                item_course = new_course if item_course == "OTHER" else item_course

            crud.create_menu_item(r.id, item_name, item_desc, item_course, item_price)
            flash("New Menu Item {} Created!".format(item_name))
        return redirect(url_for('restaurantMenuItem', r_id=r.id))
    else:
        return render_template("menuitem_op.html", restaurant=r, courses=courses, item='', op="add")

@app.route("/restaurant/<int:r_id>/menu/JSON", methods=["GET"])
def getRestaurantMenuItemJSON(r_id):
    menu_items = crud.get_rest_menu_items(r_id)
    return jsonify(MenuItems=[{
        "name":i.name,
        "price":i.price,
        "course":i.course,
        "description":i.description
        } for i in menu_items])

if __name__ == "__main__":
    # super secure key for flash messaging
    app.secret_key = "super secret key"
    # debug mode
    app.debug = True
    app.run(host="127.0.0.1", port=8000)


from PySide2 import QtWidgets, QtGui, QtCore
from PySide2.QtGui import QIcon
from PySide2.QtCore import Qt
from ...hall.hall import Hall
import sqlite3
class AddHallDialog(QtWidgets.QDialog):
    """
    Dijalog za dodavanje nove hale.
    """
    def __init__(self, parent=None):
        """
        Inicijalizator dijaloga za dodavanje novog hale.

        :param parent: roditeljski widget.
        :type parent: QWidget
        """
        super().__init__(parent)
        self.setWindowTitle("Dodaj halu")
        self.setWindowIcon(QIcon("resources/icons/plus.png"))
        self.vbox_layout = QtWidgets.QVBoxLayout()
        self.form_layout = QtWidgets.QFormLayout()
        self.places_total_input = QtWidgets.QSpinBox(self)
        self.places_total_input.setGeometry(QtCore.QRect(400, 50, 101, 22))
        self.places_total_input.setMaximum(100000)
        self.places_total_input.setSingleStep(100)

        self.hall_type = QtWidgets.QComboBox(self)
        self.hall_type.addItem("sobna temperatura (19°C do 25°C)")
        self.hall_type.addItem("rashladna hala (1°C do 18°C)")
        self.hall_type.addItem("hala za zamrzavanje (-10°C do 0°C)")

        self.button_box = QtWidgets.QDialogButtonBox(QtWidgets.QDialogButtonBox.Ok
            | QtWidgets.QDialogButtonBox.Cancel, parent=self)

        self.form_layout.addRow("Mesta u hali:", self.places_total_input)

        self.form_layout.addRow("Tip Hale: ", self.hall_type)

        self.vbox_layout.addLayout(self.form_layout)
        self.vbox_layout.addWidget(self.button_box)

        self.button_box.accepted.connect(self._on_accept)
        self.button_box.rejected.connect(self.reject)

        self.setLayout(self.vbox_layout)
        self.new_hall = None

    def _on_accept(self):
        """
        Metoda koja se poziva kada se pritisne na dugme ok.
        Prvo proverava popunjenost forme.
        Ukoliko neko polje nije popunjeno korisniku se prikazuje upozorenje.
        """
        if self.places_total_input.text() == "0":
            QtWidgets.QMessageBox.warning(self,
            "Provera ukupno mesta", "Polje mora biti popunjeno!", QtWidgets.QMessageBox.Ok)
            return
        elif int(self.places_total_input.text()) > 100000:
            QtWidgets.QMessageBox.warning(self,
            "Provera ukupno mesta", "Polje mora biti manje od 100000!", QtWidgets.QMessageBox.Ok)
            return
        elif int(self.places_total_input.text()) % 100 != 0:
            QtWidgets.QMessageBox.warning(self,
            "Provera ukupno mesta", "Polje mora biti deljiv sa 100!", QtWidgets.QMessageBox.Ok)
            return
        self.new_hall = self.get_hall()
        self.accept()

    def _hall_type(self, hall_type):
        """
        Metoda koja dobavlja podatke tabele i vraća kojeg je tipa hala.

        :param type: tip hale može biti određeni tekst
        :type ps: str
        :returns: int -- tip hale 1,2,3
        """
        if hall_type == "sobna temperatura (19°C do 25°C)":
            return 1
        elif hall_type == "rashladna hala (1°C do 18°C)":
            return 2
        else:
            return 3

    def get_hall(self):
        """
        Metoda koja dobavlja podatke tabele i inicializuje halu.

        :returns: Hall -- nova kreirana hala.
        """
        conn = sqlite3.connect('plugins\\rs_ac_singidunum_magacin\\db\\warehouse.db')
        c = conn.cursor()
        for i in  c.execute('SELECT seq FROM sqlite_sequence WHERE name = "halls"'):
            number = int(str(i).replace("(","").replace(",)","").replace("('","").replace("',)",""))
        conn.commit()
        conn.close()

        return Hall("Hala " + str(number+1), 0, int(self.places_total_input.text()), self._hall_type(self.hall_type.currentText()))


from collections import defaultdict
import sys

input = sys.stdin.readline

n= int(input())
times=[0]*(n+1)
graph=defaultdict(list)
for i in range(1,n+1):
    lst = list(map(int,input().split()))
    times[i]= lst[0]
    if lst[1]==0:
        continue
    for j in lst[2:]:
        graph[i].append(j)

for i in range(1,n+1):
    if i in graph:
        time =0
        for j in graph[i]:
            time = max(time,times[j])
            print(i,time)
        print()
        times[i]+=time
        print(times)

print(times)
print(graph)


from pathlib import Path

def get_nums():
    text = Path("problem_01.txt").read_text().strip()
    return [int(line) for line in text.split("\n")]

def part_a():
    nums = get_nums()
    count = 0
    for i in range(1, len(nums)):
        if nums[i] > nums[i-1]:
            count += 1
    return count

def part_b():
    nums = get_nums()
    count = 0
    for range_end in range(3, len(nums)):
        if nums[range_end] > nums[range_end-3]:
            count += 1
    return count

print(part_a())
print(part_b())


#!/usr/bin/env python3
"""Transcode python streams

Usage:
  transcode.py inout <inpath> <outpath>
  transcode.py glob_base <glob_expr> <out_base>

Options:
  -h --help     Show this screen.
"""
from docopt import docopt

import pandas as pd
import os.path
import os
import struct
from glob import glob
from jsonlinesreader import JsonLinesReader
from fact.credentials import create_factdb_engine
from tqdm import tqdm

db = create_factdb_engine()
event_integer_value_order = [
    'Night',
    'Run',
    'Event',
    'Trigger',
]

NAMES = None

event_double_value_order = ['Az_deg', 'Zd_deg']

def main(inpath, outpath):
    night, run = night_run_from_inpath(inpath)
    runinfo = get_runinfo(night, run)

    os.makedirs(os.path.split(outpath)[0], exist_ok=True)
    with open(outpath, 'wb') as file:
        put_version_header(file)
        dump_runinfo_binary(runinfo, file)
        with JsonLinesReader(inpath) as infile:
            for event in infile:
                dump_event_binary(event, file)

def get_runinfo(night, run):
    return pd.read_sql(
        '''
        SELECT *
        FROM RunInfo
        WHERE
            fNight={night} AND
            fRunID={run}
        '''.format(night=night, run=run),
        con=db)

def put_version_header(file):
    file.write(bytes([0xfa, 0xc7, 0x01]))

def dump_runinfo_binary(runinfo, file):
    ''' write all entries from runinfo into file as 64bit 'd'oubles'''
    d = {}
    for n in runinfo.columns:
        x = runinfo.iloc[0][n]

        if isinstance(x, pd.tslib.Timestamp):
            x = x.asm8.astype('f8')
        try:
            d[n] = float(x)
        except:
            pass

    names = sorted(d.keys())

    global NAMES
    if NAMES is None:
        NAMES = set(names)
    else:
        if not set(names) == NAMES:
            raise "OMG"

    values = [d[name] for name in names]

    _bytes = struct.pack('d'*len(values), *values)
    file.write(_bytes)

def dump_event_binary(event, file):
    integer_values = [event[name] for name in event_integer_value_order]
    file.write(struct.pack('i'*len(integer_values), *integer_values))

    double_values = [event[name] for name in event_double_value_order]
    file.write(struct.pack('d'*len(double_values), *double_values))

    unixtime = event['UnixTime_s_us'][0] + event['UnixTime_s_us'][1]/1e6
    file.write(struct.pack('d', unixtime))

    dump_arrival_times(event['PhotonArrivals_500ps'], file)
    dump_saturated_pixel(event['SaturatedPixels'], file)

def dump_arrival_times(s, file):
    total_number_of_entries = sum(len(x) for x in s)  # 1byte per entry
    number_of_sublists = len(s)   # 2bytes before each sublist
    total_legth = (
        total_number_of_entries * 1 +
        number_of_sublists * 2
    )
    file.write(struct.pack('I', total_legth))
    for sublist in s:
        file.write(struct.pack('H', len(sublist)))
        file.write(struct.pack('B'*len(sublist), *sublist))

def dump_saturated_pixel(s, file):
    file.write(struct.pack('H', len(s)))
    file.write(struct.pack('H'*len(s), *s))

def make_path(night, run, base, ext):
    year = night[0:4]
    month = night[4:6]
    day = night[6:8]
    filename = "{night}_{run}{ext}".format(night=night, run=run, ext=ext)
    return os.path.join(base, year, month, day, filename)

def night_run_from_inpath(p):
    filename = os.path.split(p)[1]
    basename = filename.split('.')[0]
    night = basename[0:8]
    run = basename[9:12]
    return night, run

if __name__ == '__main__':
    arguments = docopt(__doc__, version='Transcode')
    print(arguments)
    if arguments['inout']:
        main(arguments['<inpath>'], arguments['<outpath>'])
    elif arguments['glob_base']:
        for inpath in sorted(glob(arguments['<glob_expr>'])):
            night, run = night_run_from_inpath(inpath)
            outpath = make_path(
                night, run, arguments['<out_base>'], ext='.phs.bin')
            main(inpath, outpath)


# AutoEncoder : 訓練重建原生data的能力 -> 平常的data我有信心回復平常data原來的樣子(reconstruction error最小化)；但異常的data我就沒辦法有信心回復了!
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import tensorflow as tf
import os
from sklearn.metrics import accuracy_score, precision_score, recall_score
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_absolute_error
from tensorflow.keras import layers, losses
from tensorflow.keras.datasets import fashion_mnist
from tensorflow.keras.models import Model
from tensorflow.keras.models import load_model

# 1. 分割資料成訓練、測試集
(X_train,_),(X_test, _) = fashion_mnist.load_data()

# 2. 歸一化(MinMax Normalization)
x_train = X_train.astype('float32') / 255.
x_test = X_test.astype('float32') / 255.

print (x_train.shape)
print (x_test.shape)

# 定義AutoEncoder模型架構
n_bottle_neck = 64

class Autoencoder(Model): # 繼承Model的屬性
  def __init__(self, latent_dim):
    super(Autoencoder, self).__init__() # 繼承Model的方法
    self.latent_dim = latent_dim
    # 建立 Encoder (Compressing the input)
    self.encoder = tf.keras.Sequential([
      layers.Flatten(),
      layers.Dense(latent_dim, activation='relu'),
    ])
    # 建立 Decoder (Reconstructing the compressed input Encoder made)
    self.decoder = tf.keras.Sequential([
      layers.Dense(784, activation='linear'),
      layers.Reshape((28, 28))
    ])

  def call(self, x): # pic -> encoding -> decoding
    encoded = self.encoder(x)
    decoded = self.decoder(encoded)
    return decoded

def get_model():
  return Autoencoder(n_bottle_neck)

# 3. 新增模型架構並載入訓練好的權重
## 讀取方法I : 建立相同模型並載入權重
# checkpoint_path = 'Autencoder_training_1/ckpt'
# autoencoder = get_model()
# autoencoder.compile(optimizer='adam', loss='mse')
# # Initialize the variables used by optimizers
# autoencoder.train_on_batch(x_train[:1], x_train[:1])
# # Load the state of the Old model
# autoencoder.load_weights(checkpoint_path)

# 讀取方法II : 讀取整個模型，不用再建立一個新的模型架構
model_path = 'Autencoder_training_1/ckpt.h5'
autoencoder = load_model(model_path)
# 4. 使用AutoEncoder 的 Encoder 以及 Decoder
decoded_imgs = np.array(autoencoder.predict(x_test))

# 5. 畫圖顯示
n = 10
plt.figure(figsize=(20, 4))
for i in range(n):
  # display original
  ax = plt.subplot(2, n, i + 1)
  plt.imshow(X_test[i])
  plt.title("original")
  plt.gray()
  ax.get_xaxis().set_visible(False)
  ax.get_yaxis().set_visible(False)

  # display reconstruction
  ax = plt.subplot(2, n, i + 1 + n)
  plt.imshow(decoded_imgs[i])
  plt.title("reconstructed")
  plt.gray()
  ax.get_xaxis().set_visible(False)
  ax.get_yaxis().set_visible(False)
plt.show()


from .pytest_compiler import pytest_compiles
from .question_parser import parse_question
import json

def compile(args):

    rubric = parse_question(args.question_file)

    if args.language == "py" and args.framework == "pytest_scforge":
        data = pytest_compiles(args)
    else:
        raise Exception(
            f"Compilation is not yet supported for {args.language} {args.framework}")

    with open(args.output, "w") as f:
        json.dump({
            "title": "",
            "difficulty": 1,
            "className": "",
            "methodName": "",
            "rubric": rubric,
            **data,
        }, f, indent=4)


import logging
import torch
import shutil

def configure_logging(log_filename):
    logger = logging.getLogger(log_filename)
    # logger = logging.getLogger("my_logger")
    logger.setLevel(logging.DEBUG)
    # Format for our log lines
    formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")

    # Setup console logging
    ch = logging.StreamHandler()
    ch.setLevel(logging.DEBUG)
    ch.setFormatter(formatter)
    logger.addHandler(ch)

    # Setup file logging
    fh = logging.FileHandler(log_filename)
    fh.setLevel(logging.DEBUG)
    fh.setFormatter(formatter)
    logger.addHandler(fh)
    return logger

def save_checkpoint(state, is_best, epoch, checkpoint='checkpoint', filename='checkpoint.pth.tar'):
    filePath = checkpoint + filename + 'epoch:' + str(epoch)
    torch.save(state, filePath)
    if is_best:
        best_filePath = checkpoint + filename + 'best'
        shutil.copyfile(filePath, best_filePath)

def get_learning_rate(optimizer):
    lr = []
    for param_group in optimizer.param_groups:
        lr += [param_group['lr']]
    return lr


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

# In[9]:

import pandas as pd
import requests

# ask user for X-RapidAPI-Key, app_key, and app_id
x_rapidapi_key = input("Enter your X-RapidAPI-Key: ")
app_key = input("Enter your app_key: ")
app_id = input("Enter your app_id: ")

# set up API request parameters
url = "https://edamam-food-and-grocery-database.p.rapidapi.com/api/food-database/v2/parser"
querystring = {"app_key": app_key, "app_id": app_id, "ingr": "champagne"}
headers = {
    "X-RapidAPI-Key": x_rapidapi_key,
    "X-RapidAPI-Host": "edamam-food-and-grocery-database.p.rapidapi.com"
}

# send API request and get response
response = requests.request("GET", url, headers=headers, params=querystring)

# convert response json to a pandas dataframe
results = response.json()["hints"]
df = pd.json_normalize(results)
df_sortie = df[['food.foodId','food.label','food.category','food.foodContentsLabel','food.image']]
df_sortie = df_sortie.head(10)

# save results to csv file
df_sortie.to_csv('extraction_10_premiers_produits_champagne.csv')


import os
import configparser

# config_fname = 'test_params.ini'
config_fname = 'planck2018_params.ini'
config_path, _ = os.path.split(__file__)

config = configparser.ConfigParser()
config.read(config_path + '/' + config_fname)

# Want printout?
verbose = True

# Definitions
mpctokm = 3.08568e19
mpctocm = mpctokm*1e5
deltac = 0
deltab = 4
deltat = 8
real = 0
imag = 1
velreal = 2
velimag = 3

delc = 0
delb = 2
vel = 1
delt = 4

# Constants
Tcmb = 2.726              # CMB temperature at z=0
mproton = 1.6726e-24      # proton mass in g
melectron = 9.11e-28      # electron mass in g
mel_ev = 5.11e5           # electron mass in eV/c^2
lightspeed = 3.0e10       # c in cm/s
critdensity = 1.8791e-29  # rho_c in g/cm^3
sigmat = 0.665e-24        # Thomson cross-section in cm^2
yhe = 0.25                # Helium fraction?
boltzk = 1.3806e-16       # Boltzmann's constant in erg/K
mub = 1.22                # Mean molecular weight, primordial (?)
aSB = 7.56e-15            # u = aSB T^4 => Stefan's constant in ?
u_cmb = aSB*(Tcmb**4)     # energy stored CMB
t_gamma = 3*lightspeed*melectron/(8*sigmat*u_cmb)  # t_gamma in s

# Interpolation redshifts for photon density fluctuations, not used currently
# zs = [1000, 900, 800, 700, 600, 500, 400, 300, 200]

# Parameters (runtime, CICsASS)
# Only a few of the commented ones are needed, and the rest are
# input dynamically
# boxsize = 0.2
# size = 128
# vstream = 0.0
# zstart = 1000.0
# zinit = 50.0
# dz = 3.0

# THIS WILL BREAK IF ARCHIVED
import os
base, _ = os.path.split(__file__)
camb_base = config.get('filenames', 'camb_base')
tf_base = os.path.join(base, 'tfs', '{0}_z{1:03d}.dat')
rf_base = os.path.join(base, 'recfast', config.get('filenames', 'rf_base'))
justcamb = 0

# Parameters (cosmological)
hconst = float(config.get('cosmology', 'hconst'))
omega_m = float(config.get('cosmology', 'omega_m'))
omega_b = float(config.get('cosmology', 'omega_b'))
sigma_8 = float(config.get('cosmology', 'sigma_8'))
ns = float(config.get('cosmology', 'ns'))
omega_r = 4.15e-5/(hconst**2)  # Dodelson (2002) Eq. 2.86
costh = float(config.get('cosmology', 'costh'))


from flask import render_template, url_for, flash, redirect, request, Blueprint
from bookreview.readinglist.forms import ListForm, SearchnaddForm, SearchForm
from bookreview.models import User, Readinglist
from bookreview import create_app,db, bcrypt
from flask_login import login_user, current_user, logout_user, login_required
import requests
import json

readinglist = Blueprint('readinglist', __name__)

# Home page functionality that lists all the current reviews by the user
@readinglist.route('/list')
@readinglist.route('/')
@login_required
def home():
    user = User.query.filter_by(id=current_user.id).first_or_404()
    readinglist = Readinglist.query.filter_by(author=user).all()
    return render_template("books.html", readinglist=readinglist, title = "Bookhead")

# Functionality to add a new review by the user
@readinglist.route("/list/new", methods=['GET', 'POST'])
@login_required
def new_list():
    form = ListForm()
    if form.validate_on_submit():
        alist = Readinglist(bookname=form.bookname.data, review = form.review.data,
            isbn = form.isbn.data,libid = form.libraryid.data,author=current_user)
        db.session.add(alist)
        db.session.commit()
        flash('Your list has been created!', 'success')
        return redirect(url_for('readinglist.home',user_id=current_user.id))
    return render_template('create_list.html', title='New List',
                           form=form, legend='New List')

# Functionality view a particular review
@readinglist.route("/book/<int:list_id>")
@login_required
def alist(list_id):
    alist = Readinglist.query.get_or_404(list_id)
    return render_template('alist.html', title=alist.bookname, alist=alist)

# Functionality to update a review
@readinglist.route("/book/<int:list_id>/update", methods=['GET', 'POST'])
@login_required
def update_list(list_id):
    readinglist = Readinglist.query.get_or_404(list_id)
    if readinglist.author != current_user:
        abort(403)
    form = ListForm()
    if form.validate_on_submit():
        readinglist.bookname = form.bookname.data
        readinglist.review = form.review.data
        readinglist.isbn = form.isbn.data
        readinglist.libid = form.libraryid.data
        db.session.commit()
        flash('Your review has been updated!', 'success')
        return redirect(url_for('readinglist.home',user_id=current_user.id))
    elif request.method == 'GET':
        form.bookname.data = readinglist.bookname
        form.review.data = readinglist.review
        form.isbn.data = readinglist.isbn
        form.libraryid.data = readinglist.libid
    return render_template('create_list.html', title='Update List',
                           form=form, legend='Update List')

# Functionality to delete a review
@readinglist.route("/book/<int:list_id>/delete", methods=['POST'])
@login_required
def delete_list(list_id):
    readinglist = Readinglist.query.get_or_404(list_id)
    if readinglist.author != current_user:
        abort(403)
    db.session.delete(readinglist)
    db.session.commit()
    flash('Your post has been deleted!', 'success')
    return redirect(url_for('readinglist.home',user_id=current_user.id))

# Functionality to add a book review
#@readinglist.route("/book/<int:list_id>/add")
#def addbook(list_id):
    #alist = Readinglist.query.get_or_404(list_id)
#    booklist = ["abcbook","1234book"]
#    return render_template('addbook.html', title='abc', booklist=booklist)

# Functionality to search a book from external API
@readinglist.route("/book/<bookname>/search",methods=['GET', 'POST'])
def booknamesearch(bookname):
    form = SearchnaddForm()
    if form.validate_on_submit():
        alist = Readinglist(bookname=form.bookname.data, review = form.review.data,
            isbn = form.isbn.data,libid = form.libraryid.data,author=current_user)
        db.session.add(alist)
        db.session.commit()
        flash('Your list has been created!', 'success')
        return redirect(url_for('readinglist.home',user_id=current_user.id))
    response_book = requests.get("http://openlibrary.org/search.json?title="+bookname)
    json_response = response_book.json()
    docs = json_response["docs"]
    booklist = []
    for line in docs:
        if "isbn" in line and "lending_edition_s" in line :
            booklist.append(line["title"])
            booklist.append(line["isbn"][0])
            booklist.append(line["lending_edition_s"])
    lngthoflist = len(booklist)
    return render_template("addbook.html", booklist=booklist, lngthoflist = lngthoflist, title = "Add Book",form=form)

# Functionality to add a book review after searching
@readinglist.route("/list/search", methods=['GET', 'POST'])
@login_required
def searchbook():
    form = SearchForm()
    if form.validate_on_submit():
        bookname = form.bookname.data,
        flash('Your search results below', 'success')
        return redirect(url_for('readinglist.booknamesearch',bookname=bookname))
    return render_template('searchbook.html', title='New List',
                           form=form, legend='New List')


import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QHeaderView, QDialog, QMessageBox
from PyQt5.QtCore import QPropertyAnimation, QEasingCurve
from PyQt5 import QtCore, QtWidgets, uic
from PyQt5.uic import loadUi
from PyQt5.QtGui import QDoubleValidator
import sqlite3

class Pagina7():
    def __init__(self):
        #Conectar a la base de datos#
        self.conn = sqlite3.connect("PrgogramaInventarios.db")

    def __str__(self):
        Datos = self.ConsultarLista()
        Aux = ""

        for row in Datos:
            Aux = Aux + str(row) + "\n"
        return Aux

    def ConsultarLista(self):
        c = self.conn.cursor()
        c.execute("SELECT * FROM Lista")

        Dato = c.fetchall()
        #c.close()
        return Dato

    def BuscarLista(self, Referencia):
        c = self.conn.cursor()
        buscar = "SELECT * FROM Lista WHERE Referencia= '{}'".format(Referencia)
        c.execute(buscar)

        Dato = c.fetchall()
        c.close()
        return Dato

    def BuscarListaN(self, Clave):
        c = self.conn.cursor()
        buscar = "SELECT * FROM Lista WHERE Descripcion= '{}'".format(Clave)
        c.execute(buscar)

        Dato = c.fetchall()
        c.close()
        return Dato

    def AgregarLista(self, ID, Referencia, Descripcion, Unidad, Cantidad, Ancho, Largo, Lugar, FolioREQ, Numero, Marca, Color, Proveedor, Stock, TPMov):
        c = self.conn.cursor()
        Agregar = "INSERT INTO Lista (ID, Referencia, Descripcion, Unidad, Cantidad, Ancho, Largo, Lugar, FolioREQ, Numero, Marca, Color, Proveedor, Stock, TPMov ) VALUES('{}', '{}', '{}', '{}', {}, '{}', '{}', '{}', '{}', '{}', '{}', '{}', '{}', {}, '{}')".format(ID, Referencia, Descripcion, Unidad, Cantidad, Ancho, Largo, Lugar, FolioREQ, Numero, Marca, Color, Proveedor, Stock, TPMov)
        c.execute(Agregar)
        n = c.rowcount
        self.conn.commit()
        c.close()
        return n

    def EliminarLista(self, ID):
        c = self.conn.cursor()
        Elimiar = "DELETE FROM Lista WHERE ID='{}'".format(ID)
        c.execute(Elimiar)
        n = c.rowcount
        self.conn.commit()
        c.close()
        return n

    def ActualizarLista(self, ID, Referencia, Descripcion, Unidad, Cantidad, Ancho, Largo, Lugar, FolioREQ, Numero, Marca, Color, Proveedor, Stock, TPMov):
        c = self.conn.cursor()
        Actualizar = "UPDATE Lista SET Referencia='{}', Descripcion='{}', Unidad='{}', Cantidad={}, Ancho='{}', Largo='{}', Lugar='{}', FolioREQ='{}', Numero='{}', Marca='{}', Color='{}', Proveedor='{}', Stock={}, TPMov='{}' WHERE ID={}".format(Referencia, Descripcion, Unidad, Cantidad, Ancho, Largo, Lugar, FolioREQ, Numero, Marca, Color, Proveedor, Stock, TPMov, ID)
        c.execute(Actualizar)
        n = c.rowcount
        self.conn.commit()
        c.close()
        return n


from telegram.ext import Updater, CommandHandler

def get_webhook_info(update, context):
    user_pic = context.bot.get_webhook_info()
    update.message.reply_text(f"webhook info : \n\n{user_pic}")

def runner():
    updater = Updater(token="5333086108:AAGOz98WcjgaJ5SEg208C_XS7rYVZJ8-eT4")
    dispatcher = updater.dispatcher

    dispatcher.add_handler(CommandHandler('start', get_webhook_info))

    updater.start_polling()
    updater.idle()

if __name__ == '__main__':
    print("ishga tushdi ...")
    runner()