#! /usr/bin/python3
import grpc
import json
import iota.harness.api as api
import iota.protos.pygen.topo_svc_pb2 as topo_svc_pb2
import iota.test.iris.config.netagent.cfg_api as netagent_cfg_api
import iota.test.iris.config.netagent.api as agent_api
import iota.test.iris.testcases.security.utils as utils
import pdb
import time

def Setup(tc):
    tc.workload_pairs = api.GetRemoteWorkloadPairs()

    netagent_cfg_api.DeleteSgPolicies()
    return api.types.status.SUCCESS

def Trigger(tc):
    sg_json_obj = None
    tc.time_matrix = []
    policy_json = "{}/{}_scale_policy.json".format(utils.GetProtocolDirectory("scale"), tc.iterators.apps)

    api.Logger.info("Running test for {}".format(policy_json))
    sg_json_obj = utils.ReadJson(policy_json)
    start = time.time()
    agent_api.ConfigureSecurityGroupPolicies(sg_json_obj.sgpolicies, oper = agent_api.CfgOper.ADD)
    end = time.time()
    agent_api.ConfigureSecurityGroupPolicies(sg_json_obj.sgpolicies, oper = agent_api.CfgOper.DELETE)
    res_time = {}
    res_time["policy"] = policy_json
    res_time["time"] = end - start
    tc.time_matrix.append(res_time)

    api.Logger.info("For policy {} the time taken is {}".format(policy_json, end - start))

    return api.types.status.SUCCESS

def Verify(tc):
    result = api.types.status.SUCCESS
    api.Logger.info("Result is {}".format(tc.time_matrix))
    return result

def Teardown(tc):
    api.Logger.info("Tearing down ...")
    policy_json = "{}/sgpolicy.json".format(api.GetTopologyDirectory())
    sg_json_obj = utils.ReadJson(policy_json)
    agent_api.ConfigureSecurityGroupPolicies(sg_json_obj.sgpolicies, oper = agent_api.CfgOper.ADD)
    return api.types.status.SUCCESS


'''
Чтобы передать функции неограниченное количество элементов,
необходимо использовать звездочки.
*args - список аргументов
**kwargs - список именованных аргументов

На примере задачи. Дан список чисел, длина списка неизвестна,
сложите все числа в списке между собой. Верните сумму.
'''
from random import randint

n = []
for number in range(randint(1, 70)):
    n.append(randint(-100, 100))

print(n)

def sum_list(*numbers):
    '''Функция получает любое количество аргументов'''
    print(type(numbers))
    s = 0
    for i in numbers:
        s += i
    return s

print(sum_list(4, 6, 7, 2))  # можно указывать любое количество чисел
print(sum_list(*n))  # распаковка списка (достать из него только числа и убрать скобки)

def smth(**kwargs):
    '''Именованные аргументы в неограниченном количстве'''
    print(type(kwargs))
    print(kwargs)
    for key, value in kwargs.items():
        print(f'Key: {key}\nValue: {value}')

smth(name='Jagor', Age=26, Hobby='Programming', Pet='Cat')


import boto3
import logging
import os
import shutil
import sys
import yaml

class AWSS3MoveConfig():
    region_name = ''
    '''
    リージョン名
    '''
    access_key_id = None
    '''
    IAMユーザーのアクセスキー
    '''
    secret_access_key = None
    '''
    IAMユーザーのシークレットアクセスキー
    '''

def _load_config(script_path: str):
    '''

    Loads configuration file with YAMS format.
    Configuration file should be located at same directory of specified
    script path, and name should be base name of this script except for
    extension is '.yml'.

    Args:
        script_path (str): script path

    Returns:
        AWSS3MoveConfig: Returns configuration object.

    '''
    config_path = os.path.splitext(script_path)[0] + '.yml'
    with open(config_path, 'r', encoding='utf-8') as file:
        yaml_conf = yaml.load(file, Loader=yaml.SafeLoader)
        config = AWSS3MoveConfig()
        config.region_name = yaml_conf['region_name']
        config.access_key_id = yaml_conf.get('access_key_id')
        config.secret_access_key = yaml_conf.get('secret_access_key')

        return config

def _operation_log(file_path: str, s3bucket_name: str, s3key: str,
                   remove_src: bool):
    '''

    ファイルのアップロード／移動のログを出力します。

    Arts:
        file_path (str): アップロード／移動したファイルのパス
        s3bucket_name (str): アップロード／移動先のS3バケット名
        s3key (str): アップロード／移動先のキー（パス月乃ファイル名）
        remove_src (bool): ファイルを移動した場合はTrue

    '''
    action = 'uploaded'
    if remove_src:
        action = 'moved'

    logging.info(f"{action} {file_path} to s3://{s3bucket_name}/{s3key}")

def _remove_files(file_path: str):
    '''

    指定されたファイル、または指定されたディレクトリ配下のファイル・ディレクトリ
    を削除します。

    Args:
        file_path (str): 削除対象のファイルまたはディレクトリのパス

    '''
    if os.path.isfile(file_path):
        os.remove(file_path)
    elif os.path.isdir(file_path):
        for name in os.listdir(file_path):
            name_path = os.path.join(file_path, name)
            if os.path.isfile(name_path):
                os.remove(name_path)
            elif os.path.isdir(name_path):
                shutil.rmtree(name_path)

def _get_s3_key(s3_folder_path: str, top_dir: str, file_path: str):
    '''

    S3バケットのフォルダ名と、アップロード対象ファイルの最上位パスからの
    相対パスを使用して、S3のキーを取得します。

    Args:
        s3_folder_path (str): S3バケットのフォルダの名前。サブフォルダの階層を
            持つ場合は、フォルダを'/'で区切って指定する。
        top_dir (str): アップロード対象のファイルが格納されているディレクトリの
            最上位ディレクトリ。
        file_path (str): アップロード対象のファイルのパス。
    Returns:
        str: s3パケットのフォルダ名の後ろに、アップロード対象ファイルの
        最上位ディレクトリからの相対パスを'/'で連結した文字列を返します。

    '''
    s3key = file_path

    if top_dir != None and len(top_dir) > 0 and file_path.index(top_dir) == 0:
        s3key = s3key[len(top_dir):len(s3key)]

    if s3key[0] == os.sep:
        s3key = s3key[1:len(s3key)]

    if os.sep != '/':
        s3key = s3key.replace(os.sep, '/')

    if s3_folder_path != None and len(s3_folder_path) > 0:
        s3key = s3_folder_path + '/' + s3key

    return s3key

def upload_file(file_or_dir_path: str, s3bucket_name: str, s3folder_path: str=None,
                remove_src:bool=False, script_path:str=__file__,
                access_key_id:str=None, secret_access_key:str=None):
    '''

    指定されたファイル、または指定されたディレクトリを再帰的に探して取得した
    ファイルを指定されたS3バケットのs3フォルダの下にアップロードします。
    この関数は、引数で指定されたスクリプトパスと同じディレクトリに存在する
    設定ファイル（スクリプトファイルと同じディレクトリに配置された、
    スクリプト名の拡張子が'.yml'であるファイル）から、以下の情報を取得して
    AWSのS3サービスに接続します。

    * region_name - リージョン名
    * access_key_id - (オプション) IAMユーザーのアクセスキー。引数にアクセスキーが
        指定されなかった場合は、設定ファイルから取得したものを使用する。
    * secret_access_key - (オプション) IAMユーザーのシークレットキー。引数に
        シークレットキーが指定されなかった場合は、設定ファイルから取得した
        ものを使用する。

    Args:
        file_or_dir_path (str): アップロード対象のファイルのパス、または
            ファイルを配置したディレクトリを指定します。
        s3bucket_name (str): アップロード先のS3バケット名を指定します。
        s3folder_path (str, optional): アップロード先のS3フォルダ名を
            指定します。S3フォルダがサブフォルダの場合は、フォルダの間を'/'で
            区切ります。この引数を省略するとフォルダ名を付けずにアップロード
            します。
        remove_src (bool, optional): ファイルをアップロード後に
            元のファイルを削除する場合はTrue、削除しない場合はFalseを指定
            します。Trueを指定した場合は、アップロード対象がファイルの場合は
            そのファイルを、ディレクトリの場合は、そのディレクトリ配下の
            ファイル・ディレクトリを削除します。
        script_path (str, optional): スクリプトのパス
        access_key_id (str, optional): IAMユーザーのアクセスキー
        secret_access_key (str, optional): IAMユーザーのシークレットキー

    Raises:
        Exception: file_or_dir_path で指定したパスがファイルでも
            ディレクトリでも無い場合

    '''
    config = _load_config(script_path)
    if access_key_id == None:
        access_key_id = config.access_key_id
    if secret_access_key == None:
        secret_access_key = config.secret_access_key

    s3_client = boto3.client('s3', aws_access_key_id=access_key_id,
                      aws_secret_access_key=secret_access_key)

    if os.path.isfile(file_or_dir_path):
        file_path = file_or_dir_path
        s3key = _get_s3_key(s3folder_path, os.path.dirname(file_path), file_path)
        s3_client.upload_file(file_path, s3bucket_name, s3key)
        _operation_log(file_path, s3bucket_name, s3key, remove_src)
    elif os.path.isdir(file_or_dir_path):
        topdir = os.path.abspath(file_or_dir_path)
        for dirpath, dirnames, filenames in os.walk(topdir):
            filenames.sort()
            for filename in filenames:
                file_path = os.path.join(dirpath, filename)
                s3key = _get_s3_key(s3folder_path, topdir, file_path)
                s3_client.upload_file(file_path, s3bucket_name, s3key)
                _operation_log(file_path, s3bucket_name, s3key, remove_src)
    else:
        raise Exception('Not found source file or directory')

    if remove_src:
        _remove_files(file_or_dir_path)

def main(args):
    file_or_dir_path = args[1]
    s3bucket_name = args[2]
    s3folder_path = args[3]
    remove_src = False
    if len(args) > 4:
        val = args[4].lower()
        remove_src = val == 'true'

    upload_file(file_or_dir_path, s3bucket_name, s3folder_path, remove_src)

if __name__ == '__main__':
    main(sys.argv)


from flask import Flask, render_template, jsonify
import json
import urllib.request

import Station
import Sensor
import StationData

app = Flask(__name__)

app.debug = True

@app.route('/')
def hello_world():
    return 'AirQuality Flask App | Kamil Popczyk'

@app.route('/findAll')
def find_all():
    url_string = 'http://api.gios.gov.pl/pjp-api/rest/station/findAll'
    with urllib.request.urlopen(url_string) as url:
        json_string = str(url.read().decode())

    result = Station.station_from_dict(json.loads(json_string))
    stations_dict = {}
    for station in result:
        stations_dict[station.station_name] = station.id

    return jsonify(stations_dict)

@app.route('/station/<station_id>/sensors')
def stations_sensors_info(station_id):
    url_string = 'http://api.gios.gov.pl/pjp-api/rest/station/sensors/{}'
    with urllib.request.urlopen(url_string.format(station_id)) as url:
        json_string = str(url.read().decode())

    result = Sensor.sensor_from_dict(json.loads(json_string))
    station_sensors_info = []

    for r in result:
        station_sensors_info.append(r.param.param_name)

    return jsonify(station_sensors_info)

@app.route('/location/<station_id>')
def station_data(station_id):
    url_string = 'http://api.gios.gov.pl/pjp-api/rest/data/getData/{}'
    with urllib.request.urlopen(url_string.format(station_id)) as url:
        json_string = str(url.read().decode())

    result = StationData.station_data_from_dict(json.loads(json_string))
    station_data_info = {}

    for r in result.values:
        station_data_info[str(r.date)] = r.value

    return jsonify(station_data_info)

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


from __future__ import annotations

from Classes.Game.Creature import CreatureCard
from Utils import CreatureType
################################################################################

__all__ = ("AbyssalKrakenCard",)

################################################################################
class AbyssalKrakenCard(CreatureCard):

    def __init__(self):

        super().__init__(
            _type=CreatureType.AbyssalKraken,
            name="Abyssal Kraken",
            effect="Grasp a player, causing them to lose two turns or discard two Equipment Cards.",
            description=(
                "A legendary creature lurking in the abyss, known for its massive "
                "tentacles and fearsome strength."
            ),
            image=None,  # type: ignore
        )

################################################################################


# Licensed under a 3-clause BSD style license - see LICENSE.rst

import os

from astropy.io import fits
import configobj
import numpy as np
import pytest

import sofia_redux.instruments.forcast.hdmerge as u
from sofia_redux.instruments.forcast.tests.resources import raw_testdata

class TestHdmerge(object):

    def make_headers(self):
        hdrl = []
        for i in range(5):
            beam = 'B' if (i % 2) == 0 else 'A'
            hdul = raw_testdata()
            hdul[0].header['NODBEAM'] = beam
            hdul[0].header['AOR_ID'] = f'test_{i}'
            hdul[0].header['ALTI_STA'] = i + 1
            hdul[0].header['ALTI_END'] = i + 10
            hdul[0].header['EXPTIME'] = i * 100 + 1
            hdul[0].header['DTHINDEX'] = i
            hdrl.append(hdul[0].header)
        return hdrl

    def test_success(self):
        hdrl = self.make_headers()

        # reference header is first A file
        ref = hdrl[1]
        # first header is first file
        first = hdrl[0]
        # last header is last file
        last = hdrl[-1]

        merged = u.hdmerge(hdrl)

        # check for a few known reference/first/last keys
        assert merged['AOR_ID'] == ref['AOR_ID']
        assert merged['ALTI_STA'] == first['ALTI_STA']
        assert merged['ALTI_END'] == last['ALTI_END']

        # summed key
        assert merged['EXPTIME'] == np.sum([h['EXPTIME'] for h in hdrl])

        # default key
        assert merged['DTHINDEX'] == -9999

    def test_ref_header(self):
        hdrl = self.make_headers()

        # reference header is specified
        ref = hdrl[3]
        first = hdrl[0]
        last = hdrl[-1]

        merged = u.hdmerge(hdrl, reference_header=ref)

        # check for a few known reference/first/last keys
        assert merged['AOR_ID'] == ref['AOR_ID']
        assert merged['ALTI_STA'] == first['ALTI_STA']
        assert merged['ALTI_END'] == last['ALTI_END']

        # summed key
        assert merged['EXPTIME'] == np.sum([h['EXPTIME'] for h in hdrl])

        # default key
        assert merged['DTHINDEX'] == -9999

    def test_bad_config(self, tmpdir, mocker, capsys):
        mocker.patch('os.path.dirname', return_value=str(tmpdir))

        # missing config file
        hdrl = [fits.Header()]
        with pytest.raises(IOError):
            u.hdmerge(hdrl)
        assert 'missing' in capsys.readouterr().err

        # bad config file
        pth = tmpdir.join('data')
        os.makedirs(pth)
        conf = pth.join('header_merge.cfg')
        conf.write('bad')
        with pytest.raises(configobj.ParseError):
            u.hdmerge(hdrl)
        assert 'Error while loading' in capsys.readouterr().err

    def test_operations(self, tmpdir, mocker, capsys):
        mocker.patch('os.path.dirname', return_value=str(tmpdir))
        pth = tmpdir.join('data')
        os.makedirs(pth)
        conf = pth.join('header_merge.cfg')

        # write config file with all operations, for valid
        # and invalid keys
        conf.write('TEST1 = FIRST\n'
                   'TEST2 = LAST\n'
                   'TEST3 = SUM\n'
                   'TEST4 = SUM\n'
                   'TEST5 = MEAN\n'
                   'TEST6 = MEAN\n'
                   'TEST7 = AND\n'
                   'TEST8 = AND\n'
                   'TEST9 = OR\n'
                   'TEST10 = OR\n'
                   'TEST11 = CONCATENATE\n'
                   'TEST12 = DEFAULT\n'
                   'TEST13 = DEFAULT\n'
                   'TEST14 = DEFAULT\n'
                   'TEST15 = BAD')

        # make headers to combine
        hdr1 = fits.Header({'TEST1': 'A', 'TEST2': 'A', 'TEST3': 1.0,
                            'TEST4': 'A', 'TEST5': 1.0, 'TEST6': 'A',
                            'TEST7': True, 'TEST8': 'A', 'TEST9': True,
                            'TEST10': 'A', 'TEST11': 'A', 'TEST12': 'A',
                            'TEST13': 1, 'TEST14': 1.0, 'TEST15': 'A'})
        hdr2 = fits.Header({'TEST1': 'B', 'TEST2': 'B', 'TEST3': 2.0,
                            'TEST4': 'B', 'TEST5': 2.0, 'TEST6': 'B',
                            'TEST7': False, 'TEST8': 'B', 'TEST9': False,
                            'TEST10': 'B', 'TEST11': 'B', 'TEST12': 'B',
                            'TEST13': 2, 'TEST14': 2.0, 'TEST15': 'B'})
        hdrl = [hdr1, hdr2]

        # merge
        merge = u.hdmerge(hdrl)

        # check values
        # invalid operations default to first header
        assert merge['TEST1'] == 'A'
        assert merge['TEST2'] == 'B'
        assert merge['TEST3'] == 3.0
        assert merge['TEST4'] == 'A'
        assert merge['TEST5'] == 1.5
        assert merge['TEST6'] == 'A'
        assert merge['TEST7'] is False
        assert merge['TEST8'] == 'A'
        assert merge['TEST9'] is True
        assert merge['TEST10'] == 'A'
        assert merge['TEST11'] == 'A,B'
        assert merge['TEST12'] == 'UNKNOWN'
        assert merge['TEST13'] == -9999
        assert merge['TEST14'] == -9999.0
        assert merge['TEST15'] == 'A'

        # check for expected warnings
        capt = capsys.readouterr()
        assert 'SUM operation is invalid for TEST4' in capt.err
        assert 'MEAN operation is invalid for TEST6' in capt.err
        assert 'AND operation is invalid for TEST8' in capt.err
        assert 'OR operation is invalid for TEST10' in capt.err
        assert 'Invalid key merge operation BAD' in capt.err


import matplotlib.pyplot as plt
import csv

x = []
y = []

with open('out_20_200000.csv','r') as csvfile:
    plots = csv.reader(csvfile, delimiter=',')
    for i, row in enumerate(plots):
        print("Printing line {}".format(i))
        x.append(row[0])
        y.append(row[1])

plt.plot(x,y)
plt.show()


# Artificial Neural Network

# Part 1 - Data Preprocessing

# Importing the libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd

# Importing the dataset
dataset = pd.read_json('training.json', lines = True)

X = dataset["cuisine"].values
y = dataset["ingredients"].values

df2 = pd.DataFrame(y)
df3 = df2[0].apply(pd.Series)

result = pd.concat([dataset, df3], axis=1)
result = result.drop('ingredients', axis=1)
result = result.fillna(0)

# Encoding categorical data
from sklearn.preprocessing import LabelEncoder, OneHotEncoder
labelencoder_X_1 = LabelEncoder()
X = labelencoder_X_1.fit_transform(X)

for column in result.columns:
    if result[column].dtype == type(object):
        le = LabelEncoder()
        result[column] = le.fit_transform(result[column])

X = result["cuisine"].values
y = result.iloc[:, 3:42].values

# Splitting the dataset into the Training set and Test set
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.1667, random_state = 0)

# Part 2 - Now let's make the ANN!

# Importing the Keras libraries and packages
import keras
from keras.models import Sequential
from keras.layers import Dense
from keras.utils.np_utils import to_categorical

# Initialising the ANN
classifier = Sequential()

# Adding the input layer and the first hidden layer
classifier.add(Dense(units = 39, kernel_initializer = 'uniform', activation = 'relu', input_dim = 1))

# Adding the second hidden layer
classifier.add(Dense(units = 39, kernel_initializer = 'uniform', activation = 'relu'))

# Adding the output layer
classifier.add(Dense(units = 39, kernel_initializer = 'uniform', activation = 'sigmoid'))

# Compiling the ANN
classifier.compile(optimizer = 'adam', loss = 'binary_crossentropy', metrics = ['accuracy'])

# Fitting the ANN to the Training set
classifier.fit(X_train, y_train, batch_size = 10, epochs = 25)

# Part 3 - Making predictions and evaluating the model

# Predicting the Test set results
#y_pred = classifier.predict(X_test)
#y_pred = (y_pred > 0.5)
#
## Making the Confusion Matrix
#from sklearn.metrics import confusion_matrix
#cm = confusion_matrix(y_test, y_pred)


"""
author: luoboovo
contact: fuyu16032001@gmail.com
datetime:2021/1/13 15:09
software: PyCharm
"""
"""
codeFunction:
"""

class WumingFeng():
    # def __init__(self, thMa, quantity, *args):
    #     self.thMa = thMa
    #     self.quantity = quantity
    #     self.args = args

    def __init__(self, thMa, quantity, likesoup):
        self.thMa = thMa
        self.quantity = quantity
        self.likesoup = likesoup

    def mian1(self, n):
        print(self.thMa, self.quantity, self.likesoup, n)

    def mian(self):
        self.thMa = input("输入要吃的面码")
        self.quantity = int(input("要吃几两面"))
        self.args = input("是否带汤")
        print("加了", self.thMa, "粉", self.quantity, "两", "是否带汤", self.args)

f1 = WumingFeng("鸡肉", 3, 2)
f1.mian1(1)
f2 = WumingFeng("牛肉", 2, "不加青菜")
f2.mian()


from enum import IntEnum
import json
from PyQt5 import Qt
from pathlib import Path
from skimage import io as skio
for function in ('imread', 'imsave', 'imread_collection'):
    skio.use_plugin('freeimage', function)
import time

class AgingFluorescence(Qt.QObject):
    def __init__(self, root, out_dir, prefix):
        super().__init__()
        self.positionSetNames = ('reference', 'control', 'exp0', 'exp1', 'exp2')
        self.positionSets = [[] for n in self.positionSetNames]
        self.root = root
        self.get_more_positions_gt = None
        self.out_dir = Path(out_dir)
        self.prefix = prefix
        if not self.out_dir.exists():
            self.out_dir.mkdir(parents=True)
        self.positions_fpath = self.out_dir / (prefix + '_positions.json')
        if self.positions_fpath.exists():
            with open(str(self.positions_fpath), 'r') as f:
                psd = json.load(f)
                for name, set in psd.items():
                    self.positionSets[self.positionSetNames.index(name)] = set

    def get_more_positions(self):
        if hasattr(self, 'pos_get_dialog'):
            raise RuntimeError('get_more_positions() already in progress...')
        self.pos_get_dialog = Qt.QDialog()
        self.pos_get_dialog.setWindowTitle('Getting positions...')
        self.pos_get_dialog.setLayout(Qt.QVBoxLayout())
        self.pos_get_dialog.stop_button = Qt.QPushButton('stop getting positions')
        self.pos_get_dialog.layout().addWidget(self.pos_get_dialog.stop_button)
        self.pos_get_dialog.posSetLabel = Qt.QLabel('reference')
        self.pos_get_dialog.layout().addWidget(self.pos_get_dialog.posSetLabel)
        self.pos_get_dialog.stop_button.clicked.connect(self.stop_getting_positions)
        self.root.pedals.pedalUpChanged.connect(self.on_pedal_up)
        self.pos_get_dialog.show()

    def on_pedal_up(self, pedal, isUp):
        if not isUp:
            if pedal == 0:
                pos = (self.root.dm6000b.stageX.pos, self.root.dm6000b.stageY.pos, self.root.dm6000b.stageZ.pos)
                pl = self.positionSets[self.positionSetNames.index(self.pos_get_dialog.posSetLabel.text())]
                pl.append(pos)
            elif pedal == 1:
                n = self.positionSetNames.index(self.pos_get_dialog.posSetLabel.text())
                n += 1
                if n >= len(self.positionSetNames):
                    n = 0
                self.pos_get_dialog.posSetLabel.setText(self.positionSetNames[n])

    def stop_getting_positions(self):
        self.root.pedals.pedalUpChanged.disconnect(self.on_pedal_up)
        self.pos_get_dialog.close()
        del self.pos_get_dialog

    def save_positions(self):
        with open(str(self.positions_fpath), 'w') as f:
            json.dump({positionSetName : positions for positionSetName, positions in zip(self.positionSetNames, self.positionSets)}, f)

    def acquireForFilterSet(self, filterSetNumber, rw=None):
        imageCount = 4
        self.root.dm6000b.lamp.ilShutterOpened = True
        self.root.dm6000b.lamp.tlShutterOpened = True
        self.root.dm6000b.lamp.intensity = 255
        if filterSetNumber == 0:
            self.root.dm6000b.cubeTurret.cube = 'DFTr0'
        elif filterSetNumber == 1:
            self.root.dm6000b.cubeTurret.cube = 'CYmC0'
        else:
            raise ValueError('filterSetNumber must be 0 or 1')
        self.root.dm6000b.lamp.intensity = 255
        time.sleep(1)
        for positionSetName, positions in zip(self.positionSetNames, self.positionSets):
            for positionIndex, position in enumerate(positions):
                print('posindex: {}, position: {}'.format(positionIndex, position))
                self.root.dm6000b.stageX.pos, self.root.dm6000b.stageY.pos, self.root.dm6000b.stageZ.pos = position
                self.root.dm6000b.waitForReady()
                self.root.dm6000b.lamp.tlShutterOpened = True
                self.root.dm6000b.lamp.intensity = 255
                self.root.camera._camera.AT_Flush()
                buffers = [self.root.camera.makeAcquisitionBuffer() for i in range(imageCount)]
                self.root.camera.shutter = self.root.camera.Shutter.Rolling
                self.root.camera.triggerMode = self.root.camera.TriggerMode.Software
                self.root.camera.cycleMode = self.root.camera.CycleMode.Fixed
                # 10ms brightfield exposure time
                self.root.camera.exposureTime = 0.010
                bfAcquisitionTime = self.root.camera.exposureTime + 0.02
                self.root.camera.frameCount = imageCount
                for buffer in buffers:
                    self.root.camera._camera.AT_QueueBuffer(buffer)
                self.root.camera._camera.AT_Command(self.root.camera.Feature.AcquisitionStart)
                # Wait for TL shutter to open
                time.sleep(1)
                self.root.brightfieldLed.enabled = True
                self.root.brightfieldLed.power = 108
                time.sleep(0.2)
                self.root.camera.commandSoftwareTrigger()
                time.sleep(bfAcquisitionTime)
                self.root.brightfieldLed.enabled = False
                self.root.dm6000b.lamp.tlShutterOpened = False
                self.root.dm6000b.lamp.intensity = 255
                # Wait for TL shutter to close
                time.sleep(1)
                # 50ms fluorescence exposure time
                self.root.camera.exposureTime = 0.050
                fluoAcquisitionTime = self.root.camera.exposureTime + 0.03
                if filterSetNumber == 0:
                    self.root.lumencor.UVEnabled = True
                    self.root.lumencor.UVPower = 4 if positionSetName == "reference" else 255
                    time.sleep(0.08)
                    self.root.camera.commandSoftwareTrigger()
                    time.sleep(fluoAcquisitionTime)
                    self.root.lumencor.UVEnabled = False
                    self.root.lumencor.cyanEnabled = True
                    self.root.lumencor.cyanPower = 255
                    time.sleep(0.08)
                    self.root.camera.commandSoftwareTrigger()
                    time.sleep(fluoAcquisitionTime)
                    self.root.lumencor.cyanEnabled = False
                    self.root.lumencor.greenEnabled = True
                    self.root.lumencor.greenPower = 255
                    time.sleep(0.08)
                    self.root.camera.commandSoftwareTrigger()
                    time.sleep(fluoAcquisitionTime)
                    self.root.lumencor.greenEnabled = False
                    self.root.lumencor.disable()
                    names = ['bf-DFTr', 'DAPI', 'FITC', 'TRITC']
                elif filterSetNumber == 1:
                    self.root.lumencor.blueEnabled = True
                    self.root.lumencor.bluePower = 255
                    time.sleep(0.08)
                    self.root.camera.commandSoftwareTrigger()
                    time.sleep(fluoAcquisitionTime)
                    self.root.lumencor.blueEnabled = False
                    self.root.lumencor.tealEnabled = True
                    self.root.lumencor.tealPower = 255
                    time.sleep(0.08)
                    self.root.camera.commandSoftwareTrigger()
                    time.sleep(fluoAcquisitionTime)
                    self.root.lumencor.tealEnabled = False
                    self.root.lumencor.greenEnabled = True
                    self.root.lumencor.greenPower = 255
                    time.sleep(0.08)
                    self.root.camera.commandSoftwareTrigger()
                    time.sleep(fluoAcquisitionTime)
                    self.root.lumencor.greenEnabled = False
                    self.root.lumencor.disable()
                    names = ['bf-CYmC', 'CFP', 'YFP', 'mCherry']
                for i in range(imageCount):
                    self.root.camera._camera.AT_WaitBuffer(1000)
                self.root.camera._camera.AT_Command(self.root.camera.Feature.AcquisitionStop)
                for i in range(imageCount):
                    imFP = self.out_dir / '{}_{}_{:04}_{}.png'.format(self.prefix, positionSetName, positionIndex, names[i])
                    if rw is not None:
                        rw.showImage(buffers[i])
                    skio.imsave(str(imFP), buffers[i][:2160,:2560])


import unittest
import copy

from modules.report_item import ReportItem
from modules.line_attrs import LineAttrs

class TestReportItem(unittest.TestCase):
    @classmethod
    def setUpClass(cls) -> None:
        cls._example_line: str = (
            "1.196.116.32 -  - [29/Jun/2017:03:50:22 +0300] "
            '"GET /api/v2/banner/25019354 HTTP/1.1" 200 927 "-" '
            '"Lynx/2.8.8dev.9 libwww-FM/2.14 SSL-MM/1.4.1 GNUTLS/2.10.5" '
            '"-" "1498697422-2190034393-4708-9752759" "dc7161be3" 0.390'
        )
        cls._example_line_attrs = LineAttrs(text_line=cls._example_line)
        cls._report_item = ReportItem.from_line_attrs(
            line_attrs=cls._example_line_attrs,
        )

    def test_1_first_item(self) -> None:
        self.assertEqual(self._report_item.count, 1)

    def test_2_append(self) -> None:
        self._report_item.append(self._example_line_attrs)
        self.assertEqual(self._report_item.count, 2)

    def test_calculate(self) -> None:
        self._report_item.times = [1.0, 1.0, 7.0, 3.0, 3.0]
        self._report_item.count = len(self._report_item.times)
        self._report_item.calculate()
        self.assertEqual(self._report_item.time_avg, 3.0)
        self.assertEqual(self._report_item.time_max, 7.0)
        self.assertEqual(self._report_item.time_med, 3.0)

    def test_str(self) -> None:
        self.assertRegex(
            str(self._report_item),
            r'^"count":\d+,"count_perc":[\d\.]+,"time_sum":[\d\.]+,'
            + r'"time_perc":[\d\.]+,"time_avg":[\d\.]+,"time_max":[\d\.]+,'
            + r'"time_med":[\d\.]+$',
        )

    def test_gt(self) -> None:
        prev_item: ReportItem = copy.copy(self._report_item)
        self._report_item.append(self._example_line_attrs)
        self.assertGreater(self._report_item, prev_item)

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


from alive_progress import alive_bar

with open('test.txt') as file:
    numbers = [int(line) for line in file]

class Node:
    def __init__(self, v, i):
        self.v = v
        self.i = i
        self.prev = None
        self.next = None

class Circular:
    def __init__(self, values):
        self.head = None
        for i, v in enumerate(values):
            self.append(Node(v, i))
        self.len = len(values)

    def insert_after(self, ref_node, new_node):
        new_node.prev = ref_node
        new_node.next = ref_node.next
        new_node.next.prev = new_node
        ref_node.next = new_node

    def append(self, new_node):
        if self.head is None:
            self.head = new_node
            new_node.next = new_node
            new_node.prev = new_node
        else:
            self.insert_after(self.head.prev, new_node)

    def print(self, reverse=False):
        if self.head is not None:
            node = self.head
            while True:
                print('{}({})'.format(node.v, node.i), end=' ')
                node = node.next if not reverse else node.prev
                if node == self.head:
                    break
            print()

    def findnode(self, idx):
        node = self.head
        while node.i != idx:
            node = node.next
        return node

    def move(self, idx):
        node_to_move = self.findnode(idx)
        dist = node_to_move.v % (self.len - 1)
        if dist == 0:
            return
        if node_to_move == self.head:
            self.head = node_to_move.next
        node = node_to_move
        for i in range(dist):
            node = node.next
        node_to_move.next.prev = node_to_move.prev
        node_to_move.prev.next = node_to_move.next
        node_to_move.prev = node
        node_to_move.next = node.next
        node.next.prev = node_to_move
        node.next = node_to_move

    def afterzero(self, i):
        dist = i % self.len
        node = self.head
        while node.v != 0:
            node = node.next
        for i in range(dist):
            node = node.next
        return node.v

    def grove(self):
        return sum([self.afterzero(1000), self.afterzero(2000), self.afterzero(3000)])

# Part 1
mixer = Circular(numbers)
for i, n in enumerate(numbers):
    mixer.move(i)
print("Part 1: {}".format(mixer.grove()))

# Part 2
mixer = Circular([n*811589153 for n in numbers])
with alive_bar(10) as bar:
    for round in range(10):
        for i, n in enumerate(numbers):
            mixer.move(i)
        bar()
print("Part 2: {}".format(mixer.grove()))

mixer.print()


import os

def getPackages(dir, includePrivates=False):
    names = os.listdir(dir)
    for name in names:
        if name[0] == '_' and not includePrivates:
            continue
        name_parts = os.path.basename(name).split('.')
        if len(name_parts) > 1 and name_parts[1] != 'py':
            continue
        yield name_parts[0]


import simplejson as json

from flask import url_for, Response, render_template, request, current_app
from flask_babel import gettext as _
from flask_security import login_required
from pgadmin.misc.bgprocess.processes import BatchProcess, IProcessDesc
from pgadmin.utils import PgAdminModule, html
from pgadmin.utils.ajax import bad_request, make_json_response
from pgadmin.utils.driver import get_driver

from config import PG_DEFAULT_DRIVER
from pgadmin.model import Server

MODULE_NAME = 'maintenance'

class MaintenanceModule(PgAdminModule):
    """
    class MaintenanceModule(PgAdminModule)

        A module class for maintenance tools of vacuum which is derived from
        PgAdminModule.

    Methods:
    -------
    * get_own_javascripts()
      - Method is used to load the required javascript files for maintenance
        tool module
    * get_own_stylesheets()
      - Returns the list of CSS file used by Maintenance module
    """
    LABEL = _('Maintenance')

    def get_own_javascripts(self):
        scripts = list()
        for name, script in [
            ['pgadmin.tools.maintenance', 'js/maintenance']
        ]:
            scripts.append({
                'name': name,
                'path': url_for('maintenance.index') + script,
                'when': None
            })

        return scripts

    def get_own_stylesheets(self):
        """
        Returns:
            list: the stylesheets used by this module.
        """
        stylesheets = [
            url_for('maintenance.static', filename='css/maintenance.css')
        ]
        return stylesheets

blueprint = MaintenanceModule(MODULE_NAME, __name__)

class Message(IProcessDesc):
    def __init__(self, _sid, _data, _query):
        self.sid = _sid
        self.data = _data
        self.query = _query

    @property
    def message(self):
        res = _("Maintenance ({0})")

        if self.data['op'] == "VACUUM":
            return res.format(_('Vacuum'))
        if self.data['op'] == "ANALYZE":
            return res.format(_('Analyze'))
        if self.data['op'] == "REINDEX":
            return res.format(_('Reindex'))
        if self.data['op'] == "CLUSTER":
            return res.format(_('Cluster'))

    def details(self, cmd, args):

        res = None

        if self.data['op'] == "VACUUM":
            res = _('VACUUM ({0})')

            opts = []
            if self.data['vacuum_full']:
                opts.append(_('FULL'))
            if self.data['vacuum_freeze']:
                opts.append(_('FREEZE'))
            if self.data['verbose']:
                opts.append(_('VERBOSE'))

            res = res.format(', '.join(str(x) for x in opts))

        if self.data['op'] == "ANALYZE":
            res = _('ANALYZE')
            if self.data['verbose']:
                res += '(' + _('VERBOSE') + ')'

        if self.data['op'] == "REINDEX":
            if 'schema' in self.data and self.data['schema']:
                if 'primary_key' in self.data or\
                                'unique_constraint' in self.data or\
                                'index' in self.data:
                    return _('REINDEX INDEX')
                else:
                    return _('REINDEX TABLE')
            res = _('REINDEX')

        if self.data['op'] == "CLUSTER":
            res = _('CLUSTER')

        res = '
' + html.safe_str(res)

        res += '

'
        res += html.safe_str(
            _("Running Query:")
        )
        res += '
'
        res += html.safe_str(self.query)
        res += '
'

        return res

@blueprint.route("/")
@login_required
def index():
    return bad_request(
        errormsg=_("This URL can not be called directly!")
    )

@blueprint.route("/js/maintenance.js")
@login_required
def script():
    """render the maintenance tool of vacuum javascript file"""
    return Response(
        response=render_template("maintenance/js/maintenance.js", _=_),
        status=200,
        mimetype="application/javascript"
    )

@blueprint.route('/create_job/<int:sid>/<int:did>', methods=['POST'])
@login_required
def create_maintenance_job(sid, did):
    """
    Args:
        sid: Server ID
        did: Database ID

        Creates a new job for maintenance vacuum operation

    Returns:
        None
    """
    if request.form:
        # Convert ImmutableDict to dict
        data = dict(request.form)
        data = json.loads(data['data'][0], encoding='utf-8')
    else:
        data = json.loads(request.data, encoding='utf-8')

    index_name = None

    if 'primary_key' in data and data['primary_key']:
        index_name = data['primary_key']
    elif 'unique_constraint' in data and data['unique_constraint']:
        index_name = data['unique_constraint']
    elif 'index' in data and data['index']:
        index_name = data['index']

    # Fetch the server details like hostname, port, roles etc
    server = Server.query.filter_by(
        id=sid).first()

    if server is None:
        return make_json_response(
            success=0,
            errormsg=_("Couldn't find the given server")
        )

    # To fetch MetaData for the server
    driver = get_driver(PG_DEFAULT_DRIVER)
    manager = driver.connection_manager(server.id)
    conn = manager.connection()
    connected = conn.connected()

    if not connected:
        return make_json_response(
            success=0,
            errormsg=_("Please connect to the server first.")
        )

    utility = manager.utility('sql')

    # Create the command for the vacuum operation
    query = render_template(
        'maintenance/sql/command.sql', conn=conn, data=data,
        index_name=index_name
    )

    args = [
        '--host', server.host, '--port', str(server.port),
        '--username', server.username, '--dbname',
        data['database'],
        '--command', query
    ]

    try:
        p = BatchProcess(
            desc=Message(sid, data, query),
            cmd=utility, args=args
        )
        manager.export_password_env(p.id)
        p.start()
        jid = p.id
    except Exception as e:
        current_app.logger.exception(e)
        return make_json_response(
            status=410,
            success=0,
            errormsg=str(e)
        )

    # Return response
    return make_json_response(
        data={'job_id': jid, 'status': True, 'info': 'Maintenance job created.'}
    )


from werkzeug.urls import url_parse

from odoo.addons.test_mail_full.tests.common import TestMailFullCommon
from odoo.addons.test_mail_sms.tests.common import TestSMSRecipients
from odoo.tests import tagged, users

class TestMailThreadInternalsCommon(TestMailFullCommon, TestSMSRecipients):

    @classmethod
    def setUpClass(cls):
        super(TestMailThreadInternalsCommon, cls).setUpClass()

        cls.test_portal_records, cls.test_portal_partners = cls._create_records_for_batch(
            'mail.test.portal',
            2,
        )
        cls.test_portal_nop_records, _ = cls._create_records_for_batch(
            'mail.test.portal.no.partner',
            2,
        )
        cls.test_rating_records, cls.test_rating_partners = cls._create_records_for_batch(
            'mail.test.rating',
            2,
        )
        cls.test_simple_records, _ = cls._create_records_for_batch(
            'mail.test.simple',
            2,
        )

@tagged('mail_thread', 'portal')
class TestMailThreadInternals(TestMailThreadInternalsCommon):

    @users('employee')
    def test_notify_get_recipients_groups(self):
        """ Test redirection of portal-enabled records """
        test_records = [
            self.test_portal_records[0].with_env(self.env),
            self.test_portal_nop_records[0].with_env(self.env),
            self.test_rating_records[0].with_env(self.env),
            self.test_simple_records[0].with_env(self.env),
        ]
        for test_record in test_records:
            with self.subTest(test_record=test_record):
                is_portal = test_record._name != 'mail.test.simple'
                has_customer = test_record._name != 'mail.test.portal.no.partner'
                partner_fnames = test_record._mail_get_partner_fields(introspect_fields=False)

                if is_portal:
                    self.assertFalse(
                        test_record.access_token,
                        'By default access tokens are False with portal'
                    )

                groups = test_record._notify_get_recipients_groups(
                    self.env['mail.message'], False,
                )
                portal_customer_group = next(
                    (group for group in groups if group[0] == 'portal_customer'),
                    False
                )

                if is_portal and has_customer:
                    # should have generated the access token, required for portal links
                    self.assertTrue(
                        test_record.access_token,
                        'Portal should generate access token'
                    )
                    # check portal_customer content and link
                    self.assertTrue(
                        portal_customer_group,
                        'Portal Mixin should add portal customer notification group'
                    )
                    portal_url = portal_customer_group[2]['button_access']['url']
                    parameters = url_parse(portal_url).decode_query()
                    self.assertEqual(parameters['access_token'], test_record.access_token)
                    self.assertEqual(parameters['model'], test_record._name)
                    self.assertEqual(parameters['pid'], str(test_record[partner_fnames[0]].id))
                    self.assertEqual(parameters['res_id'], str(test_record.id))
                else:
                    self.assertFalse(
                        portal_customer_group,
                        'Portal Mixin should not add portal customer notification group'
                    )


# The goal of this project is to replicate hangman using python
# A sample file is provided that should help with printing the hangman in the terminal

def terminal(misses):
    initial = ["   ____________", "   | /         ", "   |/          ", "   |           ", "   |           ", "   |           ", "   |           ", "   |           ", "   |           ", "   |           ", "   |           ", "___|__________"]
    final = ["   ____________", "   | /        |", "   |/         |", "   |         ( )", "   |         _|_", "   |        |   |", "   |     <--|   |-->", "   |        |___|","   |         / \ ","   |        /   \\","   |      o|     |o", "___|__________"]
    for val in range(len(initial)):
        if misses > val:
            print(final[val])
        else:
            print(initial[val])

if __name__ == "__main__":
    for val in range(12):
        terminal(val)


## Multiple inheritance
class Student:
    name = "Joe"
    Id = 123
    def StudDetails(self):
        print(f"name: {self.name}, id : {self.Id}")

class Department(Student):
    dep = "CSE"
    def DepDetails(self):
        print(f"department : {self.dep}")

class Admin(Department):
    def Display(self):
        print("detail are:")

A = Admin()
A.DepDetails()
A.StudDetails()


import os
import bpy
import pathlib
import ifcopenshell
import blenderbim.tool as tool
from blenderbim.bim.ifc import IfcStore

def refresh():
    PsetTemplatesData.is_loaded = False

class PsetTemplatesData:
    data = {}
    is_loaded = False

    @classmethod
    def load(cls):
        cls.is_loaded = True
        cls.data["primary_measure_type"] = cls.primary_measure_type()
        cls.data["pset_template_files"] = cls.pset_template_files()
        cls.data["pset_templates"] = cls.pset_templates()
        cls.data["pset_template"] = cls.pset_template()
        cls.data["prop_templates"] = cls.prop_templates()

    @classmethod
    def primary_measure_type(cls):
        schema = tool.Ifc.schema()
        version = tool.Ifc.get_schema()
        return [
            (t, t, ifcopenshell.util.doc.get_type_doc(version, t).get("description", ""))
            for t in sorted([d.name() for d in schema.declarations() if hasattr(d, "declared_type")])
        ]

    @classmethod
    def pset_template_files(cls):
        results = []
        pset_dir = os.path.join(bpy.context.scene.BIMProperties.data_dir, "pset")
        files = os.listdir(pset_dir)
        for f in files:
            results.append((os.path.join(pset_dir, f), os.path.splitext(os.path.basename(f))[0], "Global Pset Template"))

        pset_dir = tool.Ifc.resolve_uri(bpy.context.scene.BIMProperties.pset_dir)
        if os.path.isdir(pset_dir):
            for path in pathlib.Path(pset_dir).glob("*.ifc"):
                results.append((str(path), os.path.splitext(os.path.basename(str(path)))[0], "Project Pset Template"))

        return sorted(results, key=lambda x: x[1])

    @classmethod
    def pset_templates(cls):
        if not IfcStore.pset_template_file:
            IfcStore.pset_template_path = bpy.context.scene.BIMPsetTemplateProperties.pset_template_files
            IfcStore.pset_template_file = ifcopenshell.open(IfcStore.pset_template_path)
        return [(str(t.id()), t.Name, "") for t in IfcStore.pset_template_file.by_type("IfcPropertySetTemplate")]

    @classmethod
    def pset_template(cls):
        props = bpy.context.scene.BIMPsetTemplateProperties
        template_id = props.pset_templates
        if not template_id:
            return {}
        info = IfcStore.pset_template_file.by_id(int(template_id)).get_info()
        del info["id"]
        del info["type"]
        del info["OwnerHistory"]
        del info["HasPropertyTemplates"]
        return info

    @classmethod
    def prop_templates(cls):
        props = bpy.context.scene.BIMPsetTemplateProperties
        template_id = props.pset_templates
        if not template_id:
            return []
        return [e.get_info() for e in IfcStore.pset_template_file.by_id(int(template_id)).HasPropertyTemplates or []]


import matplotlib.pyplot as plt
import numpy as np

Y = np.random.normal(loc=0, scale=1, size=10000)
X = np.random.random(size=10000)

plt.hist2d(X, Y,  bins=100)
plt.colorbar()

plt.show()


import logging

from pylons import request, response, session, tmpl_context as c, url
from pylons.controllers.util import abort, redirect

from photosync.lib.base import BaseController, render
from photosync import fb
from photosync.model import User
from photosync.model.meta import Session
from photosync.lib import helpers as h

log = logging.getLogger(__name__)

class FbauthController(BaseController):

    requires_logged_in_user = False

    def index(self):
        code = request.GET.getone('code')
        nexturl = request.GET.get('nexturl')
        if nexturl:
            # we are acting only as an auth server.
            # redirect to the server that wants the auth code
            redirect(nexturl+'?code=%s' % code)
            return

        token = fb.get_access_token(code)
        if not token:
            #lame... this failed for some reason
            h.flash("The login process failed :(")
            redirect(url('index'))
            return
        fbuser = fb.GraphUser(access_token=token)

        if session.get('user_id'):
            # a user is already logged in
            user = Session.query(User).filter_by(id=session.get('user_id')).first()
        else:
            # the user is not already logged in, let's see if they have
            # already created an account before
            user = Session.query(User).filter_by(fb_uid=fbuser.id).first()

        if user:
            # the user does have an account, let's update their auth token
            user.fb_uid = fbuser.id
            user.fb_access_token = token
            Session.commit()
        else:
            # the user does not have an account.  We need to create a new one
            # for them.
            for attempt in xrange(3):
                user = User(fb_uid=fbuser.id,
                            fb_access_token=token)
                Session.add(user)
                Session.commit()
                user = Session.query(User).filter_by(fb_uid=fbuser.id).first()
                if user:
                    break
                log.error("Failed to create user with fb_uid=%r attempt %r",
                          fbuser.id, attempt)

        if not user:
            log.error("Trying to log in, but couldn't get a user object. "
                      "user=%r code=%r token=%r fbuser=%r",
                      user, code, token, fbuser)

        session['user_id'] = user.id
        session['fb_access_token'] = token
        session.save()
        log.info("Logged in user %s %s: %s",
                 fbuser.first_name,
                 fbuser.last_name,
                 user)
        redirect(url('index'))


import lxml
import requests  # 导入网页请求库
from bs4 import BeautifulSoup  # 导入网页解析库
import pprint  # 使打印出来的列表更方便看
import json  # 用于将列表字典（json格式）转化为相同形式字符串，以便存入文件
import pandas as pd
import time

def start_requests(url):
    print(url)  # 用这条命令知道当前在抓取哪个链接，如果发生错误便于调试
    r = requests.get(url)
    return r.content

def parse(text, k):
    for i in range(0, k):
        soup = BeautifulSoup(text, 'lxml')
        movie_list = soup.find_all('li', class_=' j_thread_list clearfix')
        for movie in movie_list:
            mydict = {}
            mydict['name'] = movie.find('a').text
            mydict['lianjie'] = "http://tieba.baidu.com" + movie.find('a')['href']
            email = movie.find('span', class_='tb_icon_author')['title'].replace('主题作者: ', '')
            mydict['email'] = email if email else None  # 抓取10页就总会遇到这种特殊情况要处理

            mydict['xi'] = movie.find('span').text
            result_list.append(mydict)  # 向全局变量result_list中加入元素
        nextpage = soup.find('a', class_='next pagination-item ')  # 找到“下一页”位置
        if nextpage:  # 找到的就再解析，没找到说明是最后一页，递归函数parse就运行结束
            nexturl = 'http:' + nextpage['href']
            text = start_requests(nexturl)

def write_json(result):
    s = json.dumps(result, indent=4, ensure_ascii=False)
    with open('movies.json', 'w', encoding='utf-8') as f:
        f.write(s)

def main():
    text = start_requests(baseurl)
    k = 5
    parse(text, k)
    write_json(result_list)  # 所有电影都存进去之后一起输出到文件

if __name__ == '__main__':
    baseurl = 'https://tieba.baidu.com/f?kw=%E7%81%AB%E7%84%B0%E4%B9%8B%E7%BA%B9%E7%AB%A0if&ie=utf-8&pn=0'
    result_list = []
    main()

def get_content(url):
    '''
    分析贴吧的网页文件，整理信息，保存在列表变量中
    '''

    # 初始化一个列表来保存所有的帖子信息：
    comments = []
    # 首先，我们把需要爬取信息的网页下载到本地
    html = get_html(url)

    # 我们来做一锅汤
    soup = BeautifulSoup(html, 'lxml')

    # 按照之前的分析，我们找到所有具有‘ j_thread_list clearfix’属性的li标签。返回一个列表类型。
    liTags = soup.find_all('li', attrs={'class': ' j_thread_list clearfix'})

    # 通过循环找到每个帖子里的我们需要的信息：
    for li in liTags:
        # 初始化一个字典来存储文章信息
        comment = {}
        # 这里使用一个try except 防止爬虫找不到信息从而停止运行
        try:
            # 开始筛选信息，并保存到字典中
            comment['title'] = li.find(
                'a', attrs={'class': 'j_th_tit '}).text.strip()
            comment['link'] = "http://tieba.baidu.com/" + \
                              li.find('a', attrs={'class': 'j_th_tit '})['href']
            comment['name'] = li.find(
                'span', attrs={'class': 'tb_icon_author '})['title'].replace('主题作者：'.encode('utf-8'),
                                                                             ''.encode('utf-8'))
            comment['time'] = li.find(
                'span', attrs={'class': 'pull-right is_show_create_time'}).text.strip()
            comment['replyNum'] = li.find(
                'span', attrs={'class': 'threadlist_rep_num center_text'}).text.strip()
            comments.append(comment)
        except:
            print('出了点小问题')

    return comments

def Out2File(dict):
    '''
    将爬取到的文件写入到本地
    保存到当前目录的 TTBT.txt文件中。

    '''
    with open('TTBT.txt', 'a+') as f:
        for comment in dict:
            f.write('标题： {} \t 链接：{} \t 发帖人：{} \t 发帖时间：{} \t 回复数量： {} \n'.format(
                comment['title'], comment['link'], comment['name'], comment['time'], comment['replyNum']))

        print('当前页面爬取完成')

def main(base_url, deep):
    url_list = []
    # 将所有需要爬去的url存入列表
    for i in range(0, deep):
        url_list.append(base_url + '&pn=' + str(50 * i))
    print('所有的网页已经下载到本地！ 开始筛选信息。。。。')

    # 循环写入所有的数据
    for url in url_list:
        content = get_content(url)
        Out2File(content)
    print('所有的信息都已经保存完毕！')


#Comentário de Uma Linha

"""
Comentário de Várias Linhas
"""

print("Olá Mundo!") #Comentário em qualquer linha

#Declaração de Variáveis

a = 1
b = "Arte"
c = True
d = False
e = 1
f = a + e

if a > e:
	print(e)
elif a == e:
	print(b)
else:
	print(d)

# while a <= 10:
# 	print(a)
# 	a += 1

lista1 = [1,3,5,7,9]
lista2 = ["a","b","c","d","e"]

# for i in lista1:
# 	print(i)

for i in range(5,21,5): # Parâmetros Inicio,Fim,Passo (Os dois últimos são opcionais)
	print(i)


"""
# Squared positives

Given a list with the following items:
`1, 3, -2, -4, -7, -3, -8, 12, 19, 6, 9, 10, 14`

Create a new list which contains the positive items' squared value.
"""

numbers = [1, 3, -2, -4, -7, -3, -8, 12, 19, 6, 9, 10, 14]
postives = filter(lambda x: x > 0, numbers)

result = map(lambda n: n*n, postives)
print(list(result))


import random
from numpy.random.mtrand import randint
import pandas as pd
import numpy as np

tsp = [[0, 400, 500, 300], [400, 0, 300, 500],
       [500, 300, 0, 400], [300, 500, 400, 0]]

class HillClimbing:
    def __init__(self):
        self.data = HillClimbing.load_data()
        self.rows = self.data.shape[0]
        self.cols = self.data.shape[1]

    @staticmethod
    def load_data():
        df = pd.read_csv("TSP48.csv", sep=";", header=None)
        return df

    def randomSolution(self):
        solution = np.random.permutation(self.rows)
        return solution

    def routeLength(self, solution):
        routeLength = 0
        for i in range(self.rows):
            # print(type(self.data[solution[i-1]][solution[i]]))
            routeLength += self.data[solution[i-1]][solution[i]]
            # print(i, solution[i-1], solution[i])

        return routeLength

    def ListComparison(self, list1, list2):
        for el1, el2 in zip(list1, list2):
            if(el1 == el2):
                pass
            else:
                return False
        return True

    def getNeighboursInsert(self, solution):
        neighbours = []
        solution = list(solution)
        for i in range(len(solution)):
            for j in range(len(solution)):
                neighbour = solution.copy()

                item = neighbour.pop(i)
                neighbour.insert(j, item)
                duplicate = False
                for x in neighbours:
                    if(self.ListComparison(neighbour, x)):
                        duplicate = True
                if(duplicate):
                    continue
                else:
                    neighbours.append(neighbour)
        return neighbours

    def getNeighboursSwap(self, solution):
        neighbours = []
        for i in range(len(solution)):
            for j in range(i+1, len(solution)):
                neighbour = solution.copy()
                neighbour[i] = solution[j]
                neighbour[j] = solution[i]
                neighbours.append(neighbour)
        return neighbours

    def getBestNeighbour(self, neighbours):
        # bestRouteLength = self.routeLength(neighbours[0])
        # bestNeighbour = neighbours[0]
        # for neighbour in neighbours:
        #     currentRouteLength = self.routeLength(neighbour)
        #     if(currentRouteLength < bestRouteLength):
        #         bestRouteLength = currentRouteLength
        #         bestNeighbour = neighbour
        randNeighbour = random.choice(neighbours)
        bestRouteLength = self.routeLength(randNeighbour)
        bestNeighbour = randNeighbour
        return bestNeighbour, bestRouteLength

    def InsertN(self, solution):
        if(isinstance(solution, np.ndarray)):
            solution = solution.tolist()
        while True:
            id1 = randint(0, self.rows - 1)
            id2 = randint(0, self.rows - 1)

            if id1 != id2:
                break
        val = solution[id1]
        solution.insert(id2, val)
        if id1 < id2:
            solution.pop(id1)
        else:
            solution.pop(id1+1)

        bestRouteLength = self.routeLength(solution)
        bestNeighbour = solution
        return bestNeighbour, bestRouteLength

    def HillClimb(self, multistart, maxIteration):
        bestResult = []
        bestRoute = []
        for _ in range(multistart):
            currentSolution = self.randomSolution()
            print(currentSolution)
            currentRouteLength = self.routeLength(currentSolution)
            print(currentRouteLength)
            neighbours = self.getNeighboursSwap(currentSolution)
            bestNeighbour, bestNeighbourRouteLength = self.getBestNeighbour(
                neighbours)
            iterator = 0
            # while bestNeighbourRouteLength < currentRouteLength:
            for x in range(maxIteration):
                if(bestNeighbourRouteLength < currentRouteLength):
                    currentSolution = bestNeighbour
                    currentRouteLength = bestNeighbourRouteLength
                    neighbours = self.getNeighboursSwap(currentSolution)
                    bestNeighbour, bestNeighbourRouteLength = self.getBestNeighbour(
                        neighbours)
                    print(bestNeighbour, bestNeighbourRouteLength)
                    iterator = iterator + 1
                    print("iteration", iterator)
                else:
                    print("iteration", iterator)
                    neighbours = self.getNeighboursSwap(currentSolution)
                    bestNeighbour, bestNeighbourRouteLength = self.getBestNeighbour(
                        neighbours)
                    iterator = iterator + 1
                print("currentLen", currentRouteLength,
                      "new", bestNeighbourRouteLength)
            bestResult.append(currentSolution)
            bestRoute.append(currentRouteLength)
        # print(neighbours[0], neighbours[1], neighbours[2])
        return bestResult, bestRoute

    def HillClimbInsert(self, multistart, maxIteration):
        bestResult = []
        bestRoute = []
        for _ in range(multistart):
            currentSolution = self.randomSolution()
            print(currentSolution)
            currentRouteLength = self.routeLength(currentSolution)
            print(currentRouteLength)
            bestNeighbour, bestNeighbourRouteLength = self.InsertN(
                currentSolution)
            iterator = 0
            # while bestNeighbourRouteLength < currentRouteLength:
            for x in range(maxIteration):
                if(bestNeighbourRouteLength < currentRouteLength):
                    currentSolution = bestNeighbour
                    currentRouteLength = bestNeighbourRouteLength
                    bestNeighbour, bestNeighbourRouteLength = self.InsertN(
                        currentSolution)
                    print(bestNeighbour, bestNeighbourRouteLength)
                    iterator = iterator + 1
                    print("iteration", iterator)
                else:
                    print("iteration", iterator)
                    bestNeighbour, bestNeighbourRouteLength = self.InsertN(
                        currentSolution)
                    iterator = iterator + 1
                print("currentLen", currentRouteLength,
                      "new", bestNeighbourRouteLength)
            bestResult.append(currentSolution)
            bestRoute.append(currentRouteLength)
        # print(neighbours[0], neighbours[1], neighbours[2])
        return bestResult, bestRoute

TSP = HillClimbing()
bestResult, bestRoute = TSP.HillClimbInsert(1, 100000000)
print(bestResult, bestRoute)
# print(TSP.getNeighboursInsert([1, 2, 3]))


'''
Pie charts are very much similar to stack plots but only for a certain period of time
Mostly used to show %share of each variable

Slices are the weight of each activities
cols is the color of each slice
Shadow just to make chart beautiful
Start angle is the angle to start for first division

Explode is to make a particular slice a bit exploded. We have normal size
of all slice except eating

we do autopct to optionally overlay the percentages on to the graph itself.
Here in autopct we could give how many numbers after decimal we want etc
'''
import matplotlib.pyplot as plt

slices = [7,2,2,13]
activities = ['sleeping','eating','working','playing']
cols = ['c','m','r','b']

plt.pie(slices,
        labels=activities,
        colors=cols,
        startangle=90,
        shadow= True,
        explode=(0,0.1,0,0),
        autopct='%1.2f%%')

plt.title('Interesting Graph\nCheck it out')
plt.show()


#Linked list

#This is node strcuture
class node():
    def __init__(self, data):
        self.data = data
        self.next = None

#Class linked list which holds the head node of a linked list

class linkedList():
    def __init__(self):
        self.head = None

    def printNode(self):
        temp = self.head
        while(temp):
            print("{} ".format(temp.data))
            temp = temp.next

    def insertBeginnig(self, val):
        tempNode = node(val)
        tempNode.next = self.head
        self.head = tempNode

    def insertLast(self, val):
        tempNode = node(val)
        last = self.head

        while(last.next):
            last = last.next
        last.next = tempNode

    def find(self, val):
        if (self.head == None):
            return 0;
        temp = self.head

        while(temp):
            if(temp.data == val):
                return 1
            temp = temp.next
        return 0

    def delete(self, val):
        if(self.head == None):
            print("list is empty")
            return

        if(self.head.data == val):
            print("key found")
            self.head = self.head.next

        temp = self.head
        while(temp.next):
            if(temp.next.data == val):
                print("node found to delete")
                temp.next = temp.next.next
                break
            else:
                temp = temp.next

llist = linkedList()

node1 = node(10)
node2 = node(20)
node3 = node(30)

llist.head = node1
node1.next = node2
node2.next = node3

print("Normal list")
llist.printNode()
#Insett node at the beginning
llist.insertBeginnig(50)
print("insert beginning list")
llist.printNode()

#Insert at the end of a linked list
llist.insertLast(70)
print("insert last list")
llist.printNode()

print("searching for a list")
print("is it found == {}".format(llist.find(45)))

print("deleting a key from linked list")
llist.delete(70)
print("llist after deleting 70")
llist.printNode()


#!/usr/bin/python3

import re, os
import RPi.GPIO as GPIO

# SensorId from /sys/bus/w1/devices
sensorid = "10-000802e78248"
sensorpath = "/sys/bus/w1/devices/%s/w1_slave" % sensorid

pin_led = 11

def read_temp(pfad):
    temp = None
    try:
        GPIO.output(pin_led, GPIO.LOW)
        datei = open(pfad, "r")
        zeile = datei.readline()
        if re.match(r"([0-9a-f]{2} ){9}: crc=[0-9a-f]{2} YES", zeile):
            zeile = datei.readline()
            m = re.match(r"([0-9a-f]{2} ){9}t=([+-]?[0-9]+)", zeile)
            if m:
                temp = float(m.group(2))/1000
        datei.close()
    except IOError:
        print( "Could not read the sensor" )
        GPIO.output(pin_led, GPIO.HIGH)
    return temp

def send_temp(temp):
    print( temp )

if __name__ == '__main__':
    GPIO.setwarnings(False)
    GPIO.setmode(GPIO.BOARD)
    GPIO.setup(pin_led, GPIO.OUT)

    temp = read_temp(sensorpath)

    if None != temp:
        send_temp(temp)


from tkinter import *
from tkinter import filedialog
from PIL import Image, ImageTk
from tkinter import ttk
import subprocess
import tkinter.messagebox as MessageBox
import mysql.connector as mysql
import cv2 as cv
import numpy as np

tela = Tk()

def sair_tela():
    tela.destroy()
    return

tela.title("Cadastro do Serviço")
tela.configure(background='#d3d3d3')
tela.geometry("700x500")
tela.resizable(False,False)
largura = 700
altura = 500

#campos de cadastro
lbl_titulo = Label(tela, text="Cadastro do serviço").place(x=300, y=10)

lbl_codigo = Label(tela, text="Codigo do serviço", bg="#d3d3d3")
txt_codigo = Entry(tela, width=20, borderwidth=1, fg="blue", bg="white")
lbl_codigo.place(x=50, y=50)
txt_codigo.place(x=50, y=70)

lbl_nome_servico = Label(tela, text="Nome do serviço", bg="#d3d3d3")
txt_nome_servico = Entry(tela, width=40, borderwidth=1, fg="blue", bg="white")
lbl_nome_servico.place(x=200, y=50)
txt_nome_servico.place(x=200, y=70)

lbl_data_atualizacao = Label(tela, text="Data de atualização", bg="#d3d3d3")
txt_data_atualizacao = Entry(tela, width=20, borderwidth=1, fg="blue", bg="white")
lbl_data_atualizacao.place(x=500, y=50)
txt_data_atualizacao.place(x=500, y=70)

lbl_data_cadastro = Label(tela, text="Data de cadastro", bg="#d3d3d3")
txt_data_cadastro = Entry(tela, width=20, borderwidth=1, fg="blue", bg="white")
lbl_data_cadastro.place(x=500, y=100)
txt_data_cadastro.place(x=500, y=120)

lbl_valor = Label(tela, text="Valor", bg="#d3d3d3")
txt_valor = Entry(tela, width=20, borderwidth=1, fg="blue", bg="white")
lbl_valor.place(x=50, y=100)
txt_valor.place(x=50, y=120)

lbl_duracao = Label(tela, text="Tempo de duração", bg="#d3d3d3")
txt_duracao = Entry(tela, width=20, borderwidth=1, fg="blue", bg="white")
lbl_duracao.place(x=200, y=100)
txt_duracao.place(x=200, y=120)

#campo de descriçao Text
lbl_desc = Label(tela, text="Descrição", bg="#d3d3d3")
txt_desc =Text(tela)
lbl_desc.place(x=50, y=150)
txt_desc.place(x=50, y=170, width=400, height=100)

# Função para salvar
def salvar():
    var_codigo = txt_codigo.get()
    var_nome_servico = txt_nome_servico.get()
    var_data_atualizacao = txt_data_atualizacao.get()
    var_data_cadastro = txt_data_cadastro.get()
    var_valor = txt_valor.get()
    var_duracao = txt_duracao.get()
    var_descricao = txt_desc.get("1.0", "end-1c")

    if var_nome_servico == "":
        MessageBox.showinfo("Erro", "O campo Nome do serviço é obrigatório.")
    else:
        conectar = mysql.connect(host="localhost", user="root", password="", database="dogins")
        cursor = conectar.cursor()
        cursor.execute(f"INSERT INTO servicos (codigo_servico, nome_servico, data_atualizacao, data_cadastro, valor, duracao, descricao) VALUES ('{var_codigo}','{var_nome_servico}','{var_data_atualizacao}', '{var_data_cadastro}', '{var_valor}', '{var_duracao}', '{var_descricao}')")
        conectar.commit()
        MessageBox.showinfo("Mensagem", "Cadastro Realizado com Sucesso")
        conectar.close()

# Função para excluir
def excluir():
    if txt_codigo.get() == "":
        MessageBox.showinfo("ALERTA", "Digite o código para deletar")
    else:
        conectar = mysql.connect(host="localhost", user="root", password="", database="dogins")
        cursor = conectar.cursor()
        cursor.execute("DELETE FROM servicos WHERE codigo_servico='" + txt_codigo.get() + "'")
        conectar.commit()
        MessageBox.showinfo("Mensagem", "Informação Excluída com Sucesso")
        conectar.close()

# Função para atualizar
def atualizar():
    var_codigo = txt_codigo.get()
    var_nome_servico = txt_nome_servico.get()
    var_data_atualizacao = txt_data_atualizacao.get()
    var_data_cadastro = txt_data_cadastro.get()
    var_valor = txt_valor.get()
    var_duracao = txt_duracao.get()
    var_descricao = txt_desc.get("1.0", "end-1c")

    if var_nome_servico == "":
        MessageBox.showinfo("ALERTA", "O campo Nome do serviço é obrigatório.")
    else:
        conectar = mysql.connect(host="localhost", user="root", password="", database="dogins")
        cursor = conectar.cursor()
        cursor.execute("UPDATE servicos SET nome_servico = %s, data_atualizacao = %s, data_cadastro = %s, valor = %s, duracao = %s, descricao = %s WHERE codigo_servico = %s",
                       (var_nome_servico, var_data_atualizacao, var_data_cadastro, var_valor, var_duracao, var_descricao, var_codigo))
        conectar.commit()
        MessageBox.showinfo("Status", "Informação Atualizada com Sucesso")
        conectar.close()

# Função para selecionar registros
def select():
    if txt_codigo.get() == "":
        MessageBox.showinfo("ALERTA", "Por favor, digite o código.")
    else:
        conectar = mysql.connect(host="localhost", user="root", password="", database="dogins")
        cursor = conectar.cursor()
        cursor.execute("SELECT * FROM servicos WHERE codigo_servico='" + txt_codigo.get() + "'")
        rows = cursor.fetchall()

        if len(rows) > 0:
            servico = rows[0]
            txt_nome_servico.delete(0, END)
            txt_nome_servico.insert(END, servico[1])
            txt_data_atualizacao.delete(0, END)
            txt_data_atualizacao.insert(END, servico[2])
            txt_data_cadastro.delete(0, END)
            txt_data_cadastro.insert(END, servico[3])
            txt_valor.delete(0, END)
            txt_valor.insert(END, servico[4])
            txt_duracao.delete(0, END)
            txt_duracao.insert(END, servico[5])
            txt_desc.delete("1.0", END)
            txt_desc.insert(END, servico[6])
        else:
            MessageBox.showinfo("ALERTA", "Nenhum registro encontrado para o código informado.")

        conectar.close()

#armazenando imagens nas variaveis
foto_salvar = PhotoImage(file= r"imgs\salvar-arquivo.png")
foto_excluir = PhotoImage(file= r"imgs\lixeira.png")
foto_alterar = PhotoImage(file= r"imgs\editar.png")
foto_consultar = PhotoImage(file= r"imgs\lupa.png")
foto_sair = PhotoImage(file= r"imgs\excluir.png")

#criando botoes do crud
btn_salvar = Button(tela, text="Salvar", image=foto_salvar, compound=TOP, command=salvar)
btn_salvar.place(x=130, y=390)

btn_excluir = Button(tela, text="Excluir", image=foto_excluir, compound=TOP, command=excluir)
btn_excluir.place(x=210, y=390)

btn_alterar = Button(tela, text="Alterar", image=foto_alterar, compound=TOP, command=atualizar)
btn_alterar.place(x=290, y=390)

btn_consultar = Button(tela, text="Consultar", image=foto_consultar, compound=TOP, command=select)
btn_consultar.place(x=370, y=390)

btn_sair = Button(tela, text="Sair", image=foto_sair, compound=TOP, command=sair_tela)
btn_sair.place(x=500, y=390)

#posicionamento de tela no centro da tela do computador
largura_screen = tela.winfo_screenwidth()
altura_screen = tela.winfo_screenheight()
posx = largura_screen/2 - largura/2
posy = altura_screen/2 - altura/2
print(largura_screen, altura_screen)
tela.geometry("%dx%d+%d+%d" % (largura,altura,posx,posy))

tela.mainloop()


import io

import discord
from discord.ext import commands
import voxelbotutils as vbu

class ModerationCommands(vbu.Cog, name="Moderation Commands"):

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

    @vbu.command()
    @commands.is_owner()
    async def listall(self, ctx, user:discord.User=None):
        """Lists either a user's entire list of keywords or the entire database"""

        async with vbu.Database() as db:
            if user:
                full = await db("SELECT * FROM keywords WHERE userid = $1;", user.id)
            else:
                full = await db("SELECT * FROM keywords;")

        text = []
        for x in full:
            user = self.bot.get_user(x['userid']) or await self.bot.fetch_user(x['userid'])
            text.append(f"User: {user.name}({user.id}) - Keyword: {x['keyword']}")
        text = "\n".join(sorted(text)) + "\n"
        await ctx.send(file=discord.File(io.StringIO(text), filename="AllUsers.txt"))

    @vbu.command()
    @commands.is_owner()
    async def forceremove(self, ctx, user:discord.User, keyword:str):
        """Forcibly removes a keyword from a user"""

        async with vbu.Database() as db:
            await db("DELETE FROM keywords WHERE userid = $1 AND keyword = $2;", user.id, keyword)

        await ctx.send(f"Removed `{keyword}` from {user.name}'s list")

    @vbu.command()
    @commands.is_owner()
    async def forceadd(self, ctx, user:discord.User, keyword:str):
        """Forcibly adds a keyword to a user"""

        async with vbu.Database() as db:
            await db("INSERT INTO keywords VALUES ($1, $2);", user.id, keyword)
        await ctx.send(f"Added `{keyword}` to {user.name}'s list")

def setup(bot):
    bot.add_cog(ModerationCommands(bot))


import pytest

from validr import T, SchemaError
from . import case, compiler

@case({
    T.list(T.int): [
        ([], []),
        ([1, 2], [1, 2]),
        (range(3), [0, 1, 2]),
    ],
    T.list(T.int).optional: {
        'valid': [
            None,
            [],
        ],
        'invalid': [
            123,
        ]
    },
    T.list(T.int).unique: {
        'valid': [
            [1, 2, 3],
        ],
        'invalid': [
            [1, 2, '2'],
        ]
    },
    T.list(T.dict(key=T.int)).unique: {
        'valid': [
            [{'key': 1}, {'key': 2}],
        ],
        'invalid': [
            [{'key': 1}, {'key': 1}],
        ]
    },
    T.list(T.dict(key=T.dict(key=T.int))).unique: {
        'valid': [
            [{'key': {'key': 1}}, {'key': {'key': 2}}],
        ],
        'invalid': [
            [{'key': {'key': 1}}, {'key': {'key': 1}}]
        ]
    },
    T.list(T.list(T.int)).unique: {
        'valid': [
            [
                [1, 1],
                [2, 2],
            ],
        ],
        'invalid': [
            [
                [1, 2],
                [1, 2],
            ],
        ]
    },
    T.list(T.list(T.dict(key=T.int))).unique: {
        'valid': [
            [
                [{'key': 1}, {'key': 1}],
                [{'key': 2}, {'key': 2}],
            ],
        ],
        'invalid': [
            [
                [{'key': 1}, {'key': 2}],
                [{'key': 1}, {'key': 2}],
            ],
        ]
    },
    T.list(T.int).minlen(1).maxlen(3): {
        'valid': [
            [1],
            [1, 2, 3],
        ],
        'invalid': [
            [],
            [1, 2, 3, 4],
        ]
    }
})
def test_list():
    pass

@pytest.mark.parametrize('schema', [
    T.list.unique,
    T.list(T.dict).unique,
    T.list(T.list).unique,
])
def test_unable_check_unique(schema):
    with pytest.raises(SchemaError) as exinfo:
        compiler.compile(schema)
    assert 'unable to check unique' in exinfo.value.message


#!/usr/bin/env python3

import sys

disq = []
results = {}

for line in sys.stdin:
    v = line.strip().split()
    name = " ".join(v[:-3])
    values = v[-3:]

    if all(score.isdigit() and int(score) > 0 for score in values):
        total = sum(int(score) for score in values)
        results[name] = total
    else:
        disq.append(name)

for name, total in sorted(results.items(), key=lambda x: x[1]):
    print(name + ":", total)

if len(disq) == 0:
    pass
elif len(disq) == 1:
    print("Disqualified:", "".join(disq))
else:
    print("Disqualified:", ", ".join(disq))


#必用なものをインポート
from flask import Flask, request, abort
import os
import scrape as sc
import requests
from pprint import pprint
import json

from linebot import (
    LineBotApi, WebhookHandler
)
from linebot.exceptions import (
    InvalidSignatureError
)
#LINEでのイベントを取得
from linebot.models import (
    MessageEvent, TextMessage, TextSendMessage,
)

app = Flask(__name__)

#環境変数取得
#YOUR_CHANNEL_ACCESS_TOKEN = os.environ["y5bUVlwAsWLFdTDRMc3l/+PR92GUZymNnzFLWZg5oj6ESdpaK00Za2zFO+eqcc2uO+Y4kKUvoGuIVV8zAmUad9wmrK8Y+y8dNEK76wnIQEWmzkfOktPHve93GCI9+SeCpsPLleLlRjij9QbGK3UyrwdB04t89/1O/w1cDnyilFU="]
#YOUR_CHANNEL_SECRET = os.environ["0d1a4eba93553b37d583273475d449ad"]

#line_bot_api = LineBotApi(YOUR_CHANNEL_ACCESS_TOKEN)
#handler = WebhookHandler(YOUR_CHANNEL_SECRET)

line_bot_api = LineBotApi("y5bUVlwAsWLFdTDRMc3l/+PR92GUZymNnzFLWZg5oj6ESdpaK00Za2zFO+eqcc2uO+Y4kKUvoGuIVV8zAmUad9wmrK8Y+y8dNEK76wnIQEWmzkfOktPHve93GCI9+SeCpsPLleLlRjij9QbGK3UyrwdB04t89/1O/w1cDnyilFU=")
handler = WebhookHandler("0d1a4eba93553b37d583273475d449ad")

#アプリケーション本体をopenすると実行される
@app.route("/")
def hello_world():
    return "hello world!"

#/callback　のリンクにアクセスしたときの処理。webhook用。
@app.route("/callback", methods=['POST'])
def callback():
    # get X-Line-Signature header value
    signature = request.headers['X-Line-Signature']

    # get request body as text
    body = request.get_data(as_text=True)
    app.logger.info("Request body: " + body)

    # handle webhook body
    try:
        handler.handle(body, signature)
    except InvalidSignatureError:
        abort(400)

    return 'OK'

#メッセージ受信時のイベント
@handler.add(MessageEvent, message=TextMessage)
def handle_message(event):
    #'''
    #line_bot_apiのreply_messageメソッドでevent.message.text(ユーザのメッセージ)を返信
    #line_bot_api.reply_message(
        #event.reply_token,
        #TextSendMessage(text=event.message.text))
    #'''
    #line_bot_api.reply_message(
        #event.reply_token,
        #TextSendMessage(text=sc.getWeather))
    push_text = event.message.text

    #リプライする文字列
    if push_text == "天気":
        url = 'http://weather.livedoor.com/forecast/webservice/json/v1?city=110010'
        response = requests.get(url)
        weather_data = json.loads(response.text)
        #reply_text = '''
                    #pprint(wether_data['forecasts'][0]['date'])
                    #print('最高気温')
                    #pprint(weather_data['forecasts'][0]['image']['height'])
                    #print('天気予想')
                    #pprint(weather_data['forecasts'][0]['image']['title'])
                    #print('最高気温')
                    #pprint(wether_data['forecasts'][0]['temperature']['max']['celsius'])
                    #print('最低気温')
                    #pprint(weather_data['forecasts'][0]['temperature']['min']['celsius'])
                    #'''
        api_data = requests.get(url).json()
        for weather in api_data['forecasts']:
            weather_date = weather['dateLabel']
            weather_forecasts = weather['telop']
            reply_text = print(weather_date + ':' + weather_forecasts)
        reply_text = api_data["description"]["text"]
    else:
        reply_text = push_text

    #リプライ部分の記述
    line_bot_api.reply_message(event.reply_token,TextSendMessage(text=reply_text))
if __name__ == "__main__":
#    app.run()
    port = int(os.getenv("PORT", 5000))
    app.run(host="0.0.0.0", port=port)


## program to manipulate two matrices ##

import numpy as np

first_rows = int(input('Enter no.of rows for A matrix:'))
first_cols = int(input('Enter no.of cols for A matrix:'))
first= [[0 for c in range(first_cols)] for r in range(first_rows)]

## takes elemnts for matrix ##
for i in range(first_rows):
	for j in range(first_cols):
		ip = int(input('Enter number for A matrix:'))
		first[i][j] = ip

second_rows = int(input('Enter no.of rows for B matrix:'))
second_cols = int(input('Enter no.of cols for B matrix:'))
second = [[0 for c in range(second_cols)] for r in range(second_rows)]
if first_rows == second_rows and first_cols == second_cols:
	## takes elemnts for second matrix ##
	for i in range(second_rows):
		for j in range(second_cols):
			ip = int(input('Enter number for B matrix:'))
			second[i][j] = ip

	first = np.array(first)
	second = np.array(second)
	print(first)
	print(second)
	print('Sum of A+B is:')
	print(first+second)

else:
	print('please enter two matrices order in equally')


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Jul 16 11:52:20 2020

@author: jinlingxing
"""

'''
Implement pow(x, n), which calculates x raised to the power n (xn).

Example 1:

Input: 2.00000, 10
Output: 1024.00000
Example 2:

Input: 2.10000, 3
Output: 9.26100
Example 3:

Input: 2.00000, -2
Output: 0.25000
Explanation: 2-2 = 1/22 = 1/4 = 0.25
Note:

-100.0 < x < 100.0
n is a 32-bit signed integer, within the range [−231, 231 − 1]
'''
class Solution:
    def myPow(self, x: float, n: int) -> float:
        res = 1
        if n<0:
            n = abs(n)
            x = 1/x

        while n>0:
            if n&1:
                res = res * x
            if res ==0:
                return res
            x *= x
            n>>=1
        return res

sol = Solution()
x=2
n=5
sol.myPow(x,n)


from days import addMonth
from http import updateJSON
import settings

def defineActive(activeReminders, response):
	if response['next'] < settings.dayCountActive:
		if response['id'] not in activeReminders:
			activeReminders[ response['id'] ] = response
	else:
		if response['id'] in activeReminders:
			del activeReminders[ response['id'] ]

def setComplete(reminder):
	updateJSON( {str(reminder['id']): {'latest': settings.time.get_obj(), 'next': addMonth( settings.time.get_obj(), reminder['freq_month'] )}} )
	settings.HTTPupdateFlag = True


from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.http import JsonResponse
from django.shortcuts import render
from django.db.models import F
from .models import *

def commodityView(request):
    """商品列表页视图函数"""

    title = "商品列表"
    classContent = "commoditys  "

    # 根据模型CommodityType去查询相应信息
    firsts = CommodityType.objects.values("firsts").distinct()
    typesList  = CommodityType.objects.all()

    # 获取get请求参数
    t = request.GET.get("t", "")  # 分页的商品信息
    s = request.GET.get("s", "sold")  # 商品排序方式，未给出默认销量sola
    p = request.GET.get("p", 1)  # 页数
    n = request.GET.get("n", "")  # 商品搜索

    # 先拿出全部商品数据
    commodity_info = CommodityInfo.objects.all()

    # 分类筛选
    if t:
        types = CommodityType.objects.filter(id=t).first()
        commodity_info = commodity_info.filter(types=types.seconds)

    # 排序筛选
    if s:
        commodity_info = commodity_info.order_by("-" + s)

    # 模糊筛选
    if t:
        commodity_info = commodity_info.filter(name_contains=n)

    # 分页功能
    paginator = Paginator(commodity_info, 6)

    try:
        pages = paginator.page(p)
    except PageNotAnInteger:
        pages = paginator.page(1)
    except EmptyPage:
        pages = paginator.page(paginator.num_pages)

    return render(request, "commodity.html", locals())

def detailView(request, id):
    """商品详细页视图函数"""

    title = "商品介绍"
    classContent  = "details"
    commoditys = CommodityInfo.objects.filter(id=id).first()
    items = CommodityInfo.objects.exclude(id=id).order_by("-sold")[:5]
    likesList = request.session.get("likes", [])
    likes = True if id in likesList else False
    return render(request, "details.html", locals())

def collectView(request):
    """收藏视图函数"""

    id = request.GET.get("id", "")
    result = {"result": "已收藏"}
    likes = request.session.get("likes", [])

    if id and not int(id) in likes:
        CommodityInfo.objects.filter(id=id).update(likes=F("likes") + 1)
        result["result"] = "收藏成功"
        request.session["likes"] = likes + [int(id)]

    return JsonResponse(result)


import bge

from bge.logic import expandPath, globalDict
from scripts.data_loader import load_data

load_data()

def mouse_look(cont):
	""" Transforms player direction and camera angle based on mouse movement. """

	# Basic
	own = cont.owner

	# Sensors
	s_mouse = cont.sensors['mouse']

	# Actuators
	a_mouse_x = cont.actuators['mouse_x']
	a_mouse_y = cont.actuators['mouse_y']

	# Objects
	o_group = own.groupObject

	# Properties
	p_mouse_sensitivity = globalDict['settings']['controls']['mouse_sensitivity']
	p_mouse_invert = globalDict['settings']['controls']['mouse_invert']
	p_invert_fac = 1.0

	if o_group != None:

		# Objects
		o_spatial = o_group.groupMembers['spatial']
		o_armature = o_group.groupMembers['player_armature']

		if s_mouse.positive:

			if p_mouse_invert:
				p_invert_fac = -1.0

			a_mouse_x.sensitivity = [p_mouse_sensitivity, 0]
			a_mouse_y.sensitivity = [0, -p_mouse_sensitivity * p_invert_fac]

			cont.activate(a_mouse_x)
			cont.activate(a_mouse_y)

			globalDict['state']['player']['direction'][0] = round(-a_mouse_x.angle[0] % 360, 2)
			globalDict['state']['player']['direction'][1] = round(-a_mouse_y.angle[1], 2)

			o_armature['direction_y'] = globalDict['state']['player']['direction'][1] + 76

		else:
			cont.deactivate(a_mouse_x)
			cont.deactivate(a_mouse_y)

	pass

def move(cont):
	"""  """

	# Basic
	own = cont.owner

	# Sensors
	s_always = cont.sensors['always']

	# Actuators
	a_motion = cont.actuators['motion']

	# Objects
	o_group = own.groupObject

	# Properties
	p_player = globalDict['state']['player']
	p_velocity_fac = 0.03
	p_run_fac = 1

	if o_group != None:

		# Objects
		o_spatial = o_group.groupMembers['spatial']

		if s_always.positive:

			if p_player['mov_run'] == 1:
				p_run_fac = 2

			p_motion_vec = [
				-p_player['mov_h'] * p_velocity_fac * p_run_fac,
				-p_player['mov_v'] * p_velocity_fac * p_run_fac,
				0
				]

			a_motion.dLoc = p_motion_vec
			cont.activate(a_motion)


## Load Required Packages

from bs4 import BeautifulSoup
import requests
import re
import string
import nltk
from nltk.stem.wordnet import WordNetLemmatizer
import pandas as pd

### Recommend Recipes based on User Input

### Parse HTML to Extract Ingredient List

def get_ingredients(url):
    # Make a GET request to fetch the raw HTML content
    html_content = requests.get(url).text
    # Parse the html content
    soup = BeautifulSoup(html_content, "lxml")
    if any(x in url for x in ('delish', 'countryliving', 'goodhousekeeping')):
        ingredients = [ li.text.replace("\t", "").replace("\n", "").strip() for li in soup.find_all("div", attrs={"class": "ingredient-item"})]
    elif any(x in url for x in ('cookinglight','myrecipes')):
        ingredients = str(soup.find("div", attrs={"class": "ingredients"})).replace("<li>", "").replace("</li>", "").split('\n')[2:-2]
    elif 'damn' in url:
        ingredients = [ li.text for li in soup.find_all("li", attrs={"itemprop": "ingredients"})]
    else:
        ingredients = []
    return ingredients

ingredients1 = get_ingredients('http://www.myrecipes.com/recipe/turkey-bean-chili')
ingredients2 = get_ingredients('https://www.countryliving.com/food-drinks/a23336101/seared-sausage-with-cabbage-and-pink-lady-apples-recipe/')

def process_ingredients(ingredients):
    ingredients = [x.lower() for x in ingredients]
    ingredients = [re.sub(r"([2-9])",r"\1 ", text) for text in ingredients]
    return ingredients

ingredients1 = process_ingredients(ingredients1)

ingredients2 = process_ingredients(ingredients2)

combined_ingredients = ingredients1+ingredients2

## tag each ingredient by type

tagged_ingredients = pd.read_csv(r"Documents/cooking project/tagged_ingredients.csv")

def grocery_tagger(ingredient_list, tags):
    # Define the sorter
    sorter = ['vegetable','fruit','meat','grain','condiment','canned good',
             'spice','baking','frozen','dairy']

    ingredient_list_df = pd.DataFrame(ingredient_list)
    ingredient_list_df['category'] = 0
    ingredient_list_df['name'] = 0
    for index, row in ingredient_list_df.iterrows():
        category = 'unknown'
        name = 'unknown'
        for index2, row2 in tags.iterrows():
            if row2['Name'] in row[0]:
                category = row2['Category']
                name = row2['Name']
                break
        ingredient_list_df.loc[index, 'category'] = category
        ingredient_list_df.loc[index, 'name'] = name
    ingredient_list_df = ingredient_list_df.sort_values('name')
    true_sort = [s for s in sorter if s in ingredient_list_df.category.unique()]
    ingredient_list_df = ingredient_list_df.set_index('category').loc[true_sort].reset_index()
    return ingredient_list_df

grocery_tagger(combined_ingredients, tagged_ingredients)


from . import console_ui
from .stringglob import StringPathGlob

import os

PRIORITY_DEFAULT = 0    # Standard internal priority for a pattern
PRIORITY_USER = 100     # Priority for a user pattern, do what they say.
DBG = 1000              # Never allow the user to override these guys.

class DefaultPolicy(StringPathGlob):

    def __init__(self):
        StringPathGlob.__init__(self, "a")
        pass

class Package:

    patterns = None
    files = None
    excludes = None

    # Symbols provided by this package, right now this is limited to
    # pkgconfig() and pkgconfig32()
    provided_symbols = None

    # Symbols depended upon by this package
    depend_packages = None

    # List of permanent files
    permanent = None

    def __init__(self, name):
        self.name = name
        self.patterns = dict()
        self.files = set()
        self.excludes = set()
        self.permanent = set()

        self.provided_symbols = set()
        self.depend_packages = set()

        self.default_policy = DefaultPolicy()

    def get_pattern(self, path):
        """ Return a matching pattern for the given path.
            This is ordered according to priority to enable
            multiple layers of priorities """
        matches = [p for p in self.patterns if p.match(path)]
        if len(matches) == 0:
            return self.default_policy

        matches = sorted(matches, key=StringPathGlob.get_priority,
                         reverse=True)
        return matches[0]

    def add_file(self, pattern, path, permanent):
        """ Add a file by a given pattern to this package """
        if pattern is None:
            pattern = self.default_policy
        if pattern not in self.patterns:
            self.patterns[pattern] = set()
        self.patterns[pattern].add(path)
        self.files.add(path)
        if permanent:
            self.permanent.add(path)

    def remove_file(self, path):
        """ Remove a file from this package if it owns it """
        pat = self.get_pattern(path)
        if not pat:
            return
        if path in self.patterns[pat]:
            self.patterns[pat].remove(path)
        if path in self.files:
            self.files.remove(path)

    def exclude_file(self, path):
        """ Exclude a file from this package if it captures it """
        pat = self.get_pattern(path)
        if not pat:
            return
        if path in self.files:
            self.files.remove(path)
        self.excludes.add(path)

    def emit_files(self):
        """ Emit actual file lists, vs the globs we have """
        ret = set()
        for pt in self.patterns:
            adds = [x for x in self.patterns[pt] if x not in self.excludes]
            ret.update(adds)
        return sorted(ret)

    def is_permanent(self, path):
        """ Determine if a path if a permanent path or not """
        return path in self.permanent

    def emit_files_by_pattern(self):
        """ Emit file lists, using the globs though. Note that eopkg has no
            exclude concept, this is left for us to handle as we build the
            resulting eopkg ourselves """
        ret = set()
        for pt in self.patterns:
            pat = self.patterns[pt]

            tmp = set([x for x in pat if x not in self.excludes])
            if len(tmp) == 0:
                continue
            # Default policy, just list all the files
            if isinstance(pt, DefaultPolicy):
                ret.update(tmp)
            else:
                ret.add(str(pt))
        return sorted(ret)

class PackageGenerator:

    patterns = None
    packages = None
    permanent = None

    def __init__(self, spec):
        self.patterns = dict()
        self.packages = dict()
        self.permanent = set()

        if spec.pkg_permanent:
            for perm in spec.pkg_permanent:
                self.add_permanent_pattern(perm)

        self.add_pattern("/usr/bin", "main")
        self.add_pattern("/usr/sbin", "main")
        self.add_pattern("/sbin", "main")
        self.add_pattern("/bin", "main")
        self.add_pattern("/usr/share/info", "main")
        self.add_pattern("/usr/lib64/lib*.so.*", "main")
        self.add_pattern("/usr/lib64/haswell/*.so*", "main")
        self.add_pattern("/usr/lib/lib*.so.*", "main")
        self.add_pattern("/usr/lib32/", "32bit")
        self.add_pattern("/usr/lib32/lib*.so.*", "32bit",
                         priority=PRIORITY_DEFAULT+1)
        self.add_pattern("/usr/lib32/haswell/*.so*", "32bit",
                         priority=PRIORITY_DEFAULT+1)

        self.add_pattern("/usr/share/locale", "main")
        self.add_pattern("/usr/share/doc", "main")
        self.add_pattern("/usr/share/{}".format(spec.pkg_name), "main")

        if spec.pkg_libsplit:
            self.add_pattern("/usr/lib64/lib*.so", "devel")
            self.add_pattern("/usr/lib/lib*.so", "devel")
            self.add_pattern("/usr/lib32/lib*.so", "32bit-devel",
                             priority=PRIORITY_DEFAULT+1)

        else:
            self.add_pattern("/usr/lib64/lib*.so", "main")
            self.add_pattern("/usr/lib/lib*.so", "main")
            self.add_pattern("/usr/lib32/lib*.so", "32bit",
                             priority=PRIORITY_DEFAULT+1)

        self.add_pattern("/usr/lib64/lib*.a", "devel")
        self.add_pattern("/usr/lib/lib*.a", "devel")
        self.add_pattern("/usr/lib/pkgconfig/*.pc", "devel")
        self.add_pattern("/usr/lib64/pkgconfig/*.pc", "devel")
        self.add_pattern("/usr/share/pkgconfig/*.pc", "devel")
        self.add_pattern("/usr/include/", "devel")
        self.add_pattern("/usr/share/man3/", "devel",
                         priority=PRIORITY_DEFAULT+1)
        self.add_pattern("/usr/share/man", "main")
        self.add_pattern("/usr/share/aclocal/*.m4", "devel")
        self.add_pattern("/usr/share/aclocal/*.ac", "devel")

        self.add_pattern("/usr/lib32/lib*.a", "32bit-devel")
        self.add_pattern("/usr/lib32/pkgconfig/*.pc", "32bit-devel")
        self.add_pattern("/usr/lib32/lib*.so.*", "32bit")

        # Debug infos get highest priority. you don't override these guys.
        self.add_pattern("/usr/lib64/debug/", "dbginfo", priority=DBG)
        self.add_pattern("/usr/lib/debug/", "dbginfo", priority=DBG)
        self.add_pattern("/usr/lib32/debug/", "32bit-dbginfo", priority=DBG)

        self.add_pattern("/usr/share/gtk-doc/html/", "docs")

        # cmake stuffs
        self.add_pattern("/usr/share/cmake/", "devel")
        self.add_pattern("/usr/lib64/cmake/", "devel")
        self.add_pattern("/usr/lib/cmake/", "devel")
        self.add_pattern("/usr/lib32/cmake/", "32bit-devel")

        # Haskell
        self.add_pattern("/usr/lib64/ghc-*/*/*.a", "devel")

        # Vala..
        self.add_pattern("/usr/share/vala*/vapi/*", "devel")

        # KDE developer documentation
        self.add_pattern("/usr/share/doc/qt5/*.qch", "devel",
                         priority=PRIORITY_DEFAULT+1)
        self.add_pattern("/usr/share/doc/qt5/*.tags", "devel",
                         priority=PRIORITY_DEFAULT+1)

    def add_file(self, path):
        """ Add a file path to the owned list and place it into the correct
            package (main or named subpackage) according to the highest found
            priority pattern rule, otherwise it shall fallback under default
            policy into the main package itself.

            This enables a fallback approach, whereby subpackages "steal" from
            the main listing, and everything that is left is packaged into the
            main package (YpkgSpec::name), making "abandoned" files utterly
            impossible. """

        target = "main"  # default pattern name
        pattern = self.get_pattern(path)
        if pattern:
            target = self.patterns[pattern]

        permanent = False
        for perm in self.permanent:
            if perm.match(path):
                permanent = True
                break

        if target not in self.packages:
            self.packages[target] = Package(target)
        self.packages[target].add_file(pattern, path, permanent)

    def remove_file(self, path):
        """ Remove a file from our set, in any of our main or sub packages
            that may currently own it. """

        for pkg in self.packages:
            self.packages[pkg].remove_file(path)

    def get_pattern(self, path):
        """ Return a matching pattern for the given path.
            This is ordered according to priority to enable
            multiple layers of priorities """
        matches = [p for p in self.patterns if p.match(path)]
        if len(matches) == 0:
            return None

        matches = sorted(matches, key=StringPathGlob.get_priority,
                         reverse=True)
        return matches[0]

    def add_pattern(self, pattern, pkgName, priority=PRIORITY_DEFAULT):
        """ Add a pattern to the internal map according to the
            given priority. """

        obj = None
        is_prefix = False
        if pattern.endswith(os.sep):
            if not StringPathGlob.is_a_pattern(pattern):
                is_prefix = True

        obj = StringPathGlob(pattern, prefixMatch=is_prefix, priority=priority)
        self.patterns[obj] = pkgName

    def add_permanent_pattern(self, pattern):
        """ Add a pattern to our mapping of permanent paths. """
        obj = None
        is_prefix = False
        if pattern.endswith(os.sep):
            if not StringPathGlob.is_a_pattern(pattern):
                is_prefix = True

        obj = StringPathGlob(pattern, prefixMatch=is_prefix)
        self.permanent.add(obj)

    def emit_packages(self):
        """ Ensure we've finalized our state, allowing proper theft and
            exclusion to take place, and then return all package objects
            that we've managed to generate. There is no gaurantee that
            a "main" package will be generated, as patterns may omit
            the production of one. """

        for package in self.packages:
            for comparison in self.packages:
                if comparison == package:
                    continue
                for file in self.packages[comparison].emit_files():
                    self.packages[package].exclude_file(file)

    def get_file_owner(self, file):
        """ Return the owning package for the specified file """
        rname = os.path.realpath(file)
        for pkg in self.packages:
            package = self.packages[pkg]
            if file in package.files:
                return package
            elif rname in package.files:
                return package
        return None