#----------------------------------------------------
# Mini Project II
#
# Author: Jinglong ,Wentai ,Weitong
# Collaborators:
# References:
#----------------------------------------------------

import pymongo
from pymongo import MongoClient
import datetime
import json
import sys
import re

client = None
db = None

class selfExitError(Exception):
    """Use to exit program safely"""
    pass

def cursorPrinter(cursor):
    """
    -- cursor cursor object
    print cursor out
    return False if nothing print
    """
    i = 0
    for item in cursor:
        for key in item.keys():
            if key != "_id":
                print(key,end="")
                print(": ",end="")
                print(item[key])
                i+=1
    if i == 0:
        return False
    return True

class User:
    def __init__(self,userId):
        '''
        self.userId current user's uid
        self.questionId is the id of current select question, if not selected it is None
        self.answerId is the id of current select answer, if not selected it is None
        '''
        global client, db
        print("Initializing system...")

        self.userId = userId
        self.questionId = None
        self.answerId = None
        if userId == None:
            userId = "Unregistered"

        print("\tCreating Index... please wait...")
        self.create_index()
        print("{:=^100}".format(" User %s "%userId))

    def create_index(self):
        '''
        create index for posts to get ready for search function
        '''
        length = 0
        for index in db.Posts.list_indexes():
            length+=1
        if length > 1:
            db.Posts.drop_indexes()

        db.Posts.create_index(
           [("terms", "text"),("Tags", "text")], name = "search_index"
        )

    def promptpostAction(self):
        '''
        prompt a question action and go to the question action function
        raise selfExitError if terminate
        '''
        print("You have select: ",end ="")
        is_question = True
        if self.answerId != None:
            is_question = False

        print("please select a post action: ")
        if is_question:
            action = (input('\tAnswer(An)\n\tList answers(La)\n\tVote(V)\n\tBack to menu(m)\n\tterminate program(t)\n')).lower()
        else:
            action = (input("\tVote(V)\n\tBack to selected question(b)\n\tBack to menu(m)\n\tterminate program(t)\n")).lower()

        if action == "an" and is_question:
            self.qAnswer()
        elif action == "v":
            if is_question:
                self.qaVote(self.questionId)
            else:
                self.qaVote(self.answerId)
        elif action == "la" and is_question :
            self.qListAnswers()
        elif action == "b" and not is_question:
            self.answerId = None
        elif action == "m":
            self.questionId = None
            self.answerId = None
        elif action == "t":
            raise selfExitError()
        else:
            print('invalid input!')

    def promptAction(self):
        '''
        prompt for actions
        raise selfExitError if terminate
        '''

        print("Please select an action: \n\tpost a question(p)\n\tsearch for questions(s)\n\tterminate program(t)")
        action = input('Action: ')

        if action == 'p':
            self.postQuestion()
        elif action == 's':
            self.questionId = self.Search()

            while self.questionId != None:
                try:
                    self.promptpostAction()
                except selfExitError:
                    raise selfExitError("terminate")
                except Exception as error:
                    print(error)
        elif action == 't':
            raise selfExitError("terminate")

    def tablePrinter(self,printList,page):
        '''
        Use to print table of search result
        '''
        print("\n")
        keyList = ["Title","CreationDate","Score","AnswerCount"]
        formatt = "|{0:^7}|{1:^61}|{2:^25}|{3:^7}|{4:^13}|"
        number =  len(formatt.format("index",*keyList))
        header = "{:=^%ds}"%number
        print(header.format(" Page%d "%page))
        print(formatt.format("index",*keyList))
        print("-"*number)

        for i in range(0,len(printList)):
            result = []
            for key in keyList:
                result.append(printList[i][key])
            print(formatt.format(i,result[0][:61],result[1][:25],str(result[2])[:7],str(result[3])[:13]))
            print("-"*number)

    def postPrinter(self,postId):
        '''
        use to print a single post
        '''
        cursor = db.Posts.find({"Id": postId})
        print("{:=^100}".format("Information"))
        cursorPrinter(cursor)
        print("="*100)

    def Search(self):
        '''
        search main loop
        return selected id of question (string)
        '''
        keyWords = input("what do you want to search? (use space(' ') to split keywords): ")
        x = input("How many items do you want per page? (invalid input will be changed to 5): ")
        if x.isdigit():
            x = int(x)
        else:
            x = 5

        # get title, body, or tag
        # title, the creation date, the score, and the answer count.
        cursor = db.Posts.aggregate(
           [
             { "$match": { "$text": { "$search": keyWords.lower(), "$caseSensitive": False} } },
             { "$match": {"PostTypeId": "1"}},
             { "$project": { "_id": 0, "Id": 1, "Title": 1, "CreationDate": 1, "Score":  1, "AnswerCount":  1 } }
           ]
        )
        resultList = []
        for item in cursor:
            resultList.append(item)

        assert resultList != [], 'No related item! --- Going back'

        choose = None
        page = 0
        lastpage = False
        while choose == None:
            page += 1
            partList = []

            if len(resultList) < x:
                x = len(resultList)
                lastpage = True

            for i in range(x):
                partList.append(resultList.pop(0))
            self.tablePrinter(partList,page)

            while True:
                if lastpage:
                    action = (input("This is the last page! Select a question by enter index. Enter (b) to go back. :")).lower()
                else:
                    action = (input("Select a question by enter index. Enter (s) to see more. Enter (b) to go back. :")).lower()

                if action == 's' and not lastpage:
                    print("\n")
                    break
                elif action == 'b':
                    raise Exception("--- Going back")
                elif action.isdigit():
                    if int(action) in range(x):
                        choose = partList[int(action)]["Id"]
                        break
                else:
                    print("invalid input. Please enter again.")

        print("successfully select this question. Information below: ")
        self.postPrinter(choose)
        db.Posts.update_one({'Id': choose}, {'$inc': {'ViewCount': 1}})

        cursor.close()
        return choose

    def get_id(self,collectionName):
        """get largest Id"""
        idList = []
        cursor = db[collectionName].find()

        for item in cursor:
            idList.append(int(item['Id']))
        idList.sort(reverse=True)

        id = str(idList[0]+1)
        cursor.close()
        return id

    def check_tags(self,tagName):
        """check tags in Tags"""
        a=[]
        cursor = db.Tags.find({"TagName": tagName})
        for item in cursor:
            a.append(item)
        return a == []

    def postQuestion(self):
        tag_list=[]
        #Prompt the player to enter a question
        Title=input('Please enter a title that you want to enter: ')
        Body=input('Please enter a body that you want to enter : ')
        while True:
            action=input("Press (e) to add a tag or (f) to finish: ")
            if action =='f':
                break
            elif action =='e':
                tag=input('enter a tag name: ')
                if tag not in tag_list:
                    tag_list.append(tag)
            else:
                print("Invalid input!")

        tags = ""
        for tag in tag_list:
            tags += '<'+tag+'>'
        print("Posting question...")

        Id = self.get_id("Posts")
        data={"Id": Id,\
            "PostTypeId":"1",\
            "AcceptedAnswerId":None,\
            "CreationDate":datetime.datetime.now().isoformat(),\
            "Score":0,\
            "ViewCount":0,\
            "Body":Body,\
            "LastEditorUserId":"Anonymous",\
            "LastEdit":datetime.datetime.now().isoformat(),\
            "LastActivityDate":datetime.datetime.now().isoformat(),\
            "Title":Title,\
            "Tags":tags,\
            "AnswerCount":0,\
            "CommentCount":0,\
            "FavoriteCount":0,\
            "ContentLicense":"CC BY-SA 2.5"}
        if self.userId != None:
            data["OwnerUserId"] = self.userId

        temp = [data]
        extraction_terms(temp)

        db.Posts.insert_one(data)
        self.create_index()

        for tag in tag_list:
            if self.check_tags(tag):
                tag_Id = self.get_id("Tags")
                tag_data={"Id":tag_Id,\
                        "TagName":tag,\
                        "Count":1,\
                        "ExcerptPostId": Id,\
                        "WikiPostId": str(int(Id)-1)}
                db.Tags.insert_one(tag_data)
            else:
                db.Tags.update_one({ "TagName": tag },{ "$inc": { "Count": 1 } })

        print("Successfully posted the question.")

    def qAnswer(self):
        """User posts answer base on the question that we have selected"""
        #get user input
        Body = input('Please answer question: ')
        #format the data
        #Set ID self-increment
        print("Posting answer...")

        Id = self.get_id("Posts")
        data={"Id": Id,\
                "PostTypeId":"2",\
                "ParentId":self.questionId,\
                "CreationDate":datetime.datetime.now().isoformat(),\
                "Score":0,\
                "Body":Body,\
                "LastActivityDate":datetime.datetime.now().isoformat(),\
                "CommentCount":0,\
                "ContentLicense":"CC BY-SA 2.5"}
        if self.userId != None:
            data["OwnerUserId"] = self.userId
        #insert the data
        temp = [data]
        extraction_terms(temp)
        db.Posts.insert_one(data)
        self.create_index()
        #Success message

        print("Successfully posted the answer.")

    def qListAnswers(self):
        #find answers of the selected question
        #find the accepted answer
        answers = []

        question = db.Posts.find({"Id":self.questionId})
        for item in question:
            if "AcceptedAnswerId" in item.keys():
                accepted_id = item["AcceptedAnswerId"]
                accepted_answer = db.Posts.find({"Id":accepted_id})
                for aanswer in accepted_answer:
                    aanswer['Body'] = '*' + aanswer['Body']
                    answers.append(aanswer)

        #firstly add accepted answer to the list
        cursor = db.Posts.find({"ParentId":self.questionId},{ "_id": 0, "Id":1,"Body": 1,"CreationDate":1,"Score":1})
        for answer in cursor:
        #check that the accepted answer is not added again
            if len(answers) != 0:
                if answer["Id"] != answers[0]["Id"]:
                    answers.append(answer)
            else:
                answers.append(answer)

        assert len(answers) != 0, "No answer related to this question."
        choose = None

        keyList = ["Body","CreationDate","Score"]
        formatt = "|{0:^7}|{1:^80}|{2:^61}|{3:^25}|"
        number =  len(formatt.format("index",*keyList))
        header = "{:=^%ds}"%number
        print(header.format(" Answers "))
        print(formatt.format("index",*keyList))
        print("-"*number)

        for i in range(0,len(answers)):
            printList = []
            for key in keyList:
                printList.append(answers[i][key])
            text = re.sub(r'[^\w\s]','',printList[0])
            print(formatt.format(i,text[:80],printList[1][:61],str(printList[2])[:25]))
            print("-"*number)

        while True:
            action = (input("Select an answer by enter index. Enter (b) to go back. :")).lower()
            if action == 'b':
                raise Exception("--- Going back")
            elif action.isdigit():

                if int(action) in range(len(answers)):
                    choose = answers[int(action)]["Id"]
                    break
            else:
                print("invalid input. Please enter again.")

        print("successfully select this answer. Information below: ")
        self.answerId = choose

    def qaVote(self,postId):
        """
        -- postId is the id of current selected post
        vote on a post
        """
        print("Voting...")
        if self.userId != None:
            cursor = db.Votes.find({"$and":[{"PostId":postId},{"UserId":self.userId}]})
            for item in cursor:
                raise Exception('You have already voted this one, can not vote again')
        #record vote
        Id = self.get_id("Votes")
        data={"Id": Id,\
                "PostId": postId,\
                "VoteTypeId":"2",\
                "CreationDate":datetime.datetime.now().isoformat(),\
                }
        if self.userId != None:
            data["UserId"] = self.userId
        #insert the data
        db.Votes.insert_one(data)
        #update the score by 1 in posts_collection
        db.Posts.update_one({'Id': postId}, {'$inc': {'Score': 1}})
        print("you have successfully voted!")

###############################################################
def connectToDB():
    '''
    Connect to Database and set global variables
    '''
    global client, db
    port = input("please enter a mango client port: ")
    port = int(port)
    client = MongoClient('localhost', port)
    db = client["291db"]
    print("successfully connect to port %s. Database set to 291db."%port)

def extraction_terms (data):
    '''
    -- data is a list include many dictionaries
    add key "terms" into each dictionary, which value is extracted terms
    '''
    global client, db

    for each in data:
        extractList = list()
        titleList = list()
        bodyList = list()
        try:
            text = each["Title"]
            titleList = text.split(" ")
        except Exception:
            pass
        try:
            text = each["Body"]
            text = re.sub(r"<.*?>", "", text)
            text = re.sub(r'[^\w\s]','',text)
            text = text.replace("\n","").replace("\t","").replace("\r","")
            bodyList = text.split(" ")
        except Exception:
            pass
        for wordList in [titleList,bodyList]:
            for item in wordList:
                if len(item) >= 3:
                    extractList.append(item.lower())

        each['terms'] = list(set(extractList))

def buildCollections():
    '''
    Phrase 1 setup collections
    '''
    global client, db
    collist = db.list_collection_names()

    for fileName in ["Posts","Votes","Tags"]:
        print("Initializing collection %s..."%fileName)
        collist = db.list_collection_names()
        if fileName in collist:
            print("\tThe collection exists. Dropping it...")
            db.drop_collection(fileName)
            print("\t\tSuccessfully drop it")

        print("\tCreating collection %s... please wait..."%fileName)
        currentCollection = db[fileName]
        try:
            with open(fileName+".json",'r') as file:
                print("\t\tLoading data...")
                fileData = json.load(file)
                insideData = fileData[fileName.lower()]["row"]
                if fileName == "Posts":
                    print("\t\tExtraction terms...")
                    extraction_terms(insideData)
                print("\t\tInserting data...")
                currentCollection.insert_many(insideData)
                file.close()
        except FileNotFoundError as error:
            sys.exit("--- Creating failed. %s Please check the file, program ends."%error)

        print("\tSuccessfully create Collection %s.\n"%fileName)

    return

def generate_report(userId):
    '''
    generate and print report
    '''
    global client, db
    print("{:=^100}".format(" User Report "))

    # the number of questions owned and the average score for those questions
    cursor = db.Posts.aggregate([{"$match": {"OwnerUserId": userId,"PostTypeId":"1"}},
    {"$group" : {"_id": {"user": "$OwnerUserId"},"Number of Questions Owned": {"$sum" : 1},"Average Score": {"$avg": "$Score"}}}])
    result = cursorPrinter(cursor)
    if not result:
        print("Number of Questions Owned: 0")
        print("Average Score: 0")
    print("\n")

    # the number of answers owned and the average score for those answers
    cursor = db.Posts.aggregate([{"$match": {"OwnerUserId": userId,"PostTypeId":"2"}},
    {"$group" : {"_id": {"user": "$OwnerUserId"},"Answers Owned": {"$sum" : 1},"Average Score": {"$avg": "$Score"}}}])
    result = cursorPrinter(cursor)
    if not result:
        print("Answers Owned: 0")
        print("Average Score: 0")
    print("\n")

    # the number of votes registered for the user
    cursor = db.Posts.aggregate([{"$match": {"OwnerUserId": userId}},
    {"$project" : {"_id": {"user": "$OwnerUserId"}, "postId": "$Id"}}])
    idList = []
    for item in cursor:
        idList.append(item["postId"])

    cursor = db.Votes.aggregate([{"$match": {"PostId": { "$in": idList }}},
    {"$group" : {"_id": {"user": "$OwnerUserId"}, "Number of Votes": {"$sum" : 1}}}])
    result = cursorPrinter(cursor)

    if not result:
        print("Number of Votes: 0")
    print("\n")

    cursor.close()
    print("{:=^100}".format(" Report Ends "))

def userReport():
    '''
    prompt for an user id
    '''
    global client, db
    while True:
        userId = input("Please enter your user id or s to skip this process: ")
        if userId.lower() == "s":
            return
        elif not userId.isdigit():
            print("Invalid input. User id is a numeric field")
        else:
            print("Generating report...")
            try:
                generate_report(userId)
            except Exception as error:
                print(error)
            return userId

def main():
    global client, db
    try:
        connectToDB()
        buildCollections()

        userId = userReport()
        user = User(userId)
    except Exception:
        sys.exit("Initializing fail. ends.")
    while True:
        try:
            user.promptAction()
        except selfExitError:
            break
        except Exception as error:
            print(error)

    client.close()
    print("Exit successfully, have a nice day.")

if __name__ == "__main__":
    main()


from tree import *
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.datasets import make_moons, make_circles, make_classification

x, y = make_circles(noise = 0.02, random_state=0)
fil = y == 0
y[fil] = -1
x = x.astype(np.float64)
y = y.astype(np.float64)

x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.5, random_state=0)

tree = Tree()
tree.train(x_train,y_train)#make_circles用
tree.graph()

point = 0
for i in range(x_test.shape[0]):
    d = x_test[i]
    o = tree.inference(d)
    if y_test[i] == float(o):
        point += 1

point = (float(point)/float(x_test.shape[0])) * 100.0
print("成功率="+str(point)+"%")#成功率=82.0%


from PIL import Image
import numpy as np
import pywavefront as wav

global textures

def load_image( infilename ) :
    img = Image.open( infilename )
    img.load()
    data = np.asarray( img, dtype="int32" )
    return data

def save_image( npdata, outfilename ) :
    img = Image.fromarray( np.asarray( np.clip(npdata,0,255), dtype="uint8"), "RGB" )
    img.save( outfilename )

def equal ( arr1, arr2 ) :
	if len(arr1) != len(arr2):
		return False

	for i in range(len(arr1)):
		if arr1[i] != arr2[i]:
			return False

	return True

def avg_arrays ( arr1, arr2 ) :
	if len(arr1) != len(arr2):
		return arr1

	arr = [0 for i in range(len(arr1))]
	for i in range(len(arr1)):
		arr[i] = (arr1[i] + arr2[i]) / 2

	return arr

def get_colour( uv, mat ) :
	if mat == 0:
		return (0, 0, 0)
	else:
		tex = textures[mat-1]
		rows = len(tex)-1
		cols = len(tex[0])-1

		i = int(round(uv[1] * rows, 0))
		j = int(round(uv[0] * cols, 0))

		return tex[i][j]

def get_points( scene ) :
	points = []

	m = 0
	for material in scene.mesh_list[0].materials:
		index = 0

		while index < len(material.vertices):
			u = material.vertices[index]
			v = material.vertices[index+1]
			x = material.vertices[index+8]
			y = material.vertices[index+9]
			z = material.vertices[index+10]
			c = get_colour((u,v), m)

			points.append(((u, v), (x, y, z), c))

			index += 11

		m += 1

	return points

def generate_image( data ) :
	n = 1000
	img = [[[0,0,0] for x in range(n)] for y in range(n)]

	for point in data:
		uv = point[0]
		c = point[2]

		i = int(round(uv[1] * (n-1), 0))
		j = int(round(uv[0] * (n-1), 0))

		if False == equal(img[i][j], [0, 0, 0]):
			img[i][j] = avg_arrays(img[i][j], [c[0], c[1], c[2]])
		else:
			img[i][j] = [c[0], c[1], c[2]]

	return img

if __name__ == '__main__':
	alex1 = load_image("img/Alex1.jpg")
	alex2 = load_image("img/Alex2.jpg")
	alex3 = load_image("img/Alex3.jpg")
	textures = [alex1, alex2, alex3]

	origAlex = wav.Wavefront('img/models/Alex.obj')
	#uvMappedAlex = origAlex

	print("loaded successfully :)")

	origPoints = get_points(origAlex)
	#newPoints = get_points(uvMappedAlex)

	final = generate_image(origPoints)
	save_image(final, "combined.jpg")


# -*- coding: utf-8 -*-

import pytest

from vmaas.rest import schemas, tools

ERRATA = [
    'RHBA-2016:2858',
    'RHSA-2017:1931',
]

class TestErrataQuery(object):
    def test_post_multi(self, rest_api):
        """Tests multiple errata using POST."""
        request_body = tools.gen_errata_body(ERRATA)
        errata = rest_api.get_errata(body=request_body).response_check()
        schemas.errata_schema.validate(errata.raw.body)
        assert len(errata) == len(ERRATA)
        for erratum_name in ERRATA:
            assert erratum_name in errata

    @pytest.mark.parametrize('erratum_name', ERRATA)
    def test_post_single(self, rest_api, erratum_name):
        """Tests single erratum using POST."""
        request_body = tools.gen_errata_body([erratum_name])
        errata = rest_api.get_errata(body=request_body).response_check()
        schemas.errata_schema.validate(errata.raw.body)
        assert len(errata) == 1
        erratum, = errata
        assert erratum.name == erratum_name

    @pytest.mark.parametrize('erratum_name', ERRATA)
    def test_get(self, rest_api, erratum_name):
        """Tests single erratum using GET."""
        errata = rest_api.get_erratum(erratum_name).response_check()
        schemas.errata_schema.validate(errata.raw.body)
        assert len(errata) == 1
        erratum, = errata
        assert erratum.name == erratum_name


# Copyright 2021 CDPedistas (see AUTHORS.txt)
#
# This program is free software: you can redistribute it and/or modify it
# under the terms of the GNU General Public License version 3, as published
# by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranties of
# MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR
# PURPOSE.  See the GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program.  If not, see <http://www.gnu.org/licenses/>.
#
# For further info, check  https://github.com/PyAr/CDPedia/

import textwrap
import pytest

from src.web.test_infra import TEST_INFRA_FILENAME, load_test_infra_data, parse_test_infra_file

@pytest.fixture
def test_infra_file(mocker, tmp_path):
    content = """
        [es]
        Portal:Portada # Check page looks OK
        República_Agentina # Article with 'Argentina' title is shown
        # this comment should be ignored
        Satélites_de_Saturno

        [fr]
        Château # Image galleries shouldn't overflow

        [ay]
    """
    filepath = tmp_path / TEST_INFRA_FILENAME
    filepath.write_text(textwrap.dedent(content).strip(), encoding='utf-8')
    mocker.patch('config.LANGUAGE', 'es')
    return str(filepath)

def test_parsing_test_infra_file_items_number(test_infra_file):
    """All non empty lines not starting by '#' should be a page to check."""
    data = parse_test_infra_file(test_infra_file)
    assert len(data) == 3

def test_parsing_test_infra_file_read_name_and_check(test_infra_file):
    """Article name and check to do should be loaded in a tuple."""
    data = parse_test_infra_file(test_infra_file)
    name = 'Portal:Portada'
    check = 'Check page looks OK'
    assert (name, check) in data

def test_parsing_test_infra_file_read_empty_check(test_infra_file):
    """No check after title should be interpreted as None."""
    data = parse_test_infra_file(test_infra_file)
    name = 'Satélites_de_Saturno'
    assert (name, None) in data

def test_parsing_test_infra_file_load_other_language(mocker, test_infra_file):
    """All non empty lines not starting by '#' should be a page to check."""
    mocker.patch('config.LANGUAGE', 'fr')
    data = parse_test_infra_file(test_infra_file)
    assert data == [('Château', "Image galleries shouldn't overflow")]

def test_parsing_test_infra_file_not_existing_section(mocker, test_infra_file):
    """Return empty list if section not found."""
    mocker.patch('config.LANGUAGE', 'xy')
    data = parse_test_infra_file(test_infra_file)
    assert data == []

def test_parsing_test_infra_file_empty_section(mocker, test_infra_file):
    """Return empty list if section is empty."""
    mocker.patch('config.LANGUAGE', 'ay')
    data = parse_test_infra_file(test_infra_file)
    assert data == []

@pytest.fixture
def test_infra_data(mocker):
    data = [('foo', 'bar'), ('baz', None)]
    mocker.patch('src.web.test_infra.parse_test_infra_file', return_value=data)
    mocker.patch('config.DIR_ASSETS', 'assets', create=True)
    mocker.patch('config.URL_WIKIPEDIA', 'wiki')
    return data

def test_load_test_infra_data(test_infra_data):
    """Check that data is formed as expected."""
    items = load_test_infra_data()
    assert len(items) == len(test_infra_data)
    assert items[0]['article_name'] == 'foo'
    assert items[0]['check'] == 'bar'
    assert items[1]['article_name'] == 'baz'
    assert items[1]['check'] is None


# -*- coding: utf-8 -*-
"""DNACenterAPI Networks API fixtures and tests.

Copyright (c) 2019 Cisco and/or its affiliates.

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""

import click
import pytest
from json import loads
from tests.environment import DNA_CENTER_VERSION

pytestmark = pytest.mark.skipif(DNA_CENTER_VERSION != '1.3.0', reason='version does not match')

def is_valid_get_vlan_details(result):
    data = result.output.strip()
    return True if data else False

@pytest.mark.networks
def test_get_vlan_details(runner, cli, auth_options):
    result = runner.invoke(cli, ['-v', '1.3.0', *auth_options,
                                 'networks', 'get-vlan-details',
                                 """--"""])
    assert not result.exception
    assert is_valid_get_vlan_details(result)

def is_valid_get_site_topology(result):
    data = result.output.strip()
    return True if data else False

@pytest.mark.networks
def test_get_site_topology(runner, cli, auth_options):
    result = runner.invoke(cli, ['-v', '1.3.0', *auth_options,
                                 'networks', 'get-site-topology',
                                 """--"""])
    assert not result.exception
    assert is_valid_get_site_topology(result)

def is_valid_get_physical_topology(result):
    data = result.output.strip()
    return True if data else False

@pytest.mark.networks
def test_get_physical_topology(runner, cli, auth_options):
    result = runner.invoke(cli, ['-v', '1.3.0', *auth_options,
                                 'networks', 'get-physical-topology',
                                 """--node_type='string'"""])
    assert not result.exception
    assert is_valid_get_physical_topology(result)

def is_valid_get_topology_details(result):
    data = result.output.strip()
    return True if data else False

@pytest.mark.networks
def test_get_topology_details(runner, cli, auth_options):
    result = runner.invoke(cli, ['-v', '1.3.0', *auth_options,
                                 'networks', 'get-topology-details',
                                 """--vlan_id='string'"""])
    assert not result.exception
    assert is_valid_get_topology_details(result)

def is_valid_get_l3_topology_details(result):
    data = result.output.strip()
    return True if data else False

@pytest.mark.networks
def test_get_l3_topology_details(runner, cli, auth_options):
    result = runner.invoke(cli, ['-v', '1.3.0', *auth_options,
                                 'networks', 'get-l3-topology-details',
                                 """--topology_type='string'"""])
    assert not result.exception
    assert is_valid_get_l3_topology_details(result)

def is_valid_get_overall_network_health(result):
    data = result.output.strip()
    return True if data else False

@pytest.mark.networks
def test_get_overall_network_health(runner, cli, auth_options):
    result = runner.invoke(cli, ['-v', '1.3.0', *auth_options,
                                 'networks', 'get-overall-network-health',
                                 """--timestamp=0"""])
    assert not result.exception
    assert is_valid_get_overall_network_health(result)


from setuptools import setup
from codecs import open
import os

def read(f):
    return open(os.path.join(os.path.dirname(__file__), f),encoding='utf8').read()

setup(
    name='mwgencode',
    version='1.2.1',
    author='cxhjet',
    author_email='cxhjet@qq.com',
    description="根据starUML2.8文档产生flask专案的代码",
    long_description='\n\n'.join((read('README.rst'), read('CHANGES.txt'))),
    url='https://bitbucket.org/maxwin-inc/gencode/src/',  # Optional

    py_modules=['manage'],
    packages=['gencode',
              'gencode.gencode',
              'gencode.importxmi',
              'gencode.importmdj',
              'gencode.gencode.sample',
              'gencode.gencode.template',
              'gencode.gencode.template.tests',
              'gencode.gencode.sample.seeds'
           ],
    package_data={
        '': ['*.*']
    },
    classifiers=[
        'Intended Audience :: Developers',
        'License :: OSI Approved :: BSD License',
        'Operating System :: OS Independent',
        'Programming Language :: Python :: 3.5',
        'Programming Language :: Python :: 3.6',
        'Programming Language :: Python :: 3.7',
    ],
    install_requires=[
                      'mwutils>=0.1.29',
                      'mwauth>=0.4.26',
                      'mwsdk>=0.2.12',
                      'mwpermission>=0.1.21',
                      'mw-aiohttp-session>=0.1.4',
                      'mw-aiohttp-babel>=0.1.7',
                      'mw-aiohttp-security>=0.1.3',
                      'SQLAlchemy','pyJWT',
                      'python-consul',
                      'flask_migrate',
                      'flask-babel',
                      'Flask-Cors',
                      'Flask-Redis',
                      'geojson',
                      'redis==2.10.6',
                      'connexion==1.5.2',
                      # 'pymssql==2.1.3'
                      ],
    include_package_data=True,
    # 可以在cmd 执行产生代码
    entry_points={
        'console_scripts': ['gencode=manage:main']
    }
)


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat May 26 13:24:57 2018

@author: Andy Wang, Kelvin Kwok, Riley Kwok

"""
# READ DATA

import pandas as pd

df1 = pd.read_json("data//Status_Data1.json", encoding= 'UTF-8')
df2 = pd.read_json("data//Status_Data2.json", encoding= 'UTF-8')
df3 = pd.read_json("data//Status_Data3.json", encoding= 'UTF-8')
df4 = pd.read_json("data//Status_Data4.json", encoding= 'UTF-8')
df5 = pd.read_json("data//Status_Data5.json", encoding= 'UTF-8')
df6 = pd.read_json("data//Status_Data6.json", encoding= 'UTF-8')
df7 = pd.read_json("data//Status_Data7.json", encoding= 'UTF-8')
df8 = pd.read_json("data//Status_Data8.json", encoding= 'UTF-8')
df9_comcity = pd.read_json("data//Status_Data9_Comment_Data_with_city_code.json", encoding= 'UTF-8')
# df9_city = pd.read_json("Status_Data9_with_city_code.json", error_bad_lines = "False")
province = pd.read_json("data//weibo-china-province-city.json")
task_status = pd.read_json("data//task-status.json", encoding= 'UTF-8')
task_status['text'] = task_status['s_text']
task_status['user_id'] = task_status['uid']
task_status['id'] = task_status['sid']
task_status = task_status.drop(columns = ['s_text', 'uid', 'sid'])

label = pd.read_csv("data//train_label.txt", delimiter = '	', header = None, names = ['ID', 'other', 'category'])

frames = [df1, df2, df3, df4, df5, df6, df7, df8, task_status]
df = pd.concat(frames)
df = df.reset_index(inplace = False).drop(columns = ['index'])

category_dict = dict(zip(label.ID, label.category))

df['label'] = df.id.map(category_dict)

# DATA CLEANING

import re
import jieba

def rm_char(text): #remove symbols and special characters
    text = re.sub(r'[^\u4e00-\u9fa5]', '', text)
    return text

def get_stop_words(): # load stopwords from txt file
    file = open('stopwords-zh.txt','rb').read().decode('utf8').split('\n')
    return set(file)

def rm_tokens(words): # remove stop words and numbers
    words_list = list(words)
    stop_words = get_stop_words()
    for i in range(words_list.__len__())[::-1]:
        if words_list[i] in stop_words:
            words_list.pop(i)
        elif words_list[i].isdigit():
            words_list.pop(i)
    return words_list

def convert_doc_to_wordlist(doc, cut_all = False):
    s_list = re.split('，|【|】|。', doc)
    s_list = map(rm_char, s_list)
    s_list_cut = [rm_tokens(jieba.cut(s, cut_all = cut_all)) for s in s_list]
    word_list = sum(s_list_cut, [])
    return word_list

l = []
x = []
for i in range(len(df)): #segment sentences to words
    l.append(convert_doc_to_wordlist(df.text.iloc[i]))
for j in l: # join cleaned words back to sentence
    x.append(' '.join(j))

df['new'] = pd.DataFrame(x)

df_train = df[df.label.notnull()]
df_test = df[df.label.isnull()]

########### Supervised Modelling ############

# load pre-trained word embeddings wording
with open('sgns.weibo.word', 'rb') as f:
    for line_b in f:
        line_u = line_b.decode('utf-8')

embedding = pd.read_csv('sgns.weibo.word', header = None, sep = ' ')
embedding = embedding.drop(301, 1)
embedding = embedding.set_index(0)

# create a weight matrix for words in training docs
from numpy import asarray
from numpy import zeros
from keras.preprocessing.text import Tokenizer
from keras.preprocessing.sequence import pad_sequences
from keras.models import Sequential
from keras.layers import Dense
from keras.layers import Dropout
from keras.layers import Flatten
from keras.layers import Embedding
import numpy as np
from keras.utils import to_categorical

t = Tokenizer()
t.fit_on_texts(df.new)
vocab_size = len(t.word_index)+1
encoded_docs = t.texts_to_sequences(df_train.new)

labels_keras = np.array(df_train.label)
y_label = to_categorical(labels_keras, num_classes = 13)

max_length = 200
padded_docs = pad_sequences(encoded_docs, maxlen=max_length, padding='post')
print(padded_docs)

embeddings_index = dict()
for i in range(len(embedding)):
	word = embedding.index[i]
	coefs = embedding.iloc[i,:].astype('float32')
	embeddings_index[word] = coefs

embedding_matrix = zeros((vocab_size, 300))
for word, i in t.word_index.items():
	embedding_vector = embeddings_index.get(word)
	if embedding_vector is not None:
		embedding_matrix[i] = embedding_vector

from keras import backend as K

def f1(y_true, y_pred):
    def recall(y_true, y_pred):
        """Recall metric.

        Only computes a batch-wise average of recall.

        Computes the recall, a metric for multi-label classification of
        how many relevant items are selected.
        """
        true_positives = K.sum(K.round(K.clip(y_true * y_pred, 0, 1)))
        possible_positives = K.sum(K.round(K.clip(y_true, 0, 1)))
        recall = true_positives / (possible_positives + K.epsilon())
        return recall

    def precision(y_true, y_pred):
        """Precision metric.

        Only computes a batch-wise average of precision.

        Computes the precision, a metric for multi-label classification of
        how many selected items are relevant.
        """
        true_positives = K.sum(K.round(K.clip(y_true * y_pred, 0, 1)))
        predicted_positives = K.sum(K.round(K.clip(y_pred, 0, 1)))
        precision = true_positives / (predicted_positives + K.epsilon())
        return precision
    precision = precision(y_true, y_pred)
    recall = recall(y_true, y_pred)
    return 2*((precision*recall)/(precision+recall+K.epsilon()))

model = Sequential()
e = Embedding(vocab_size, 300, weights=[embedding_matrix], input_length= max_length, trainable=False)
model.add(e)
model.add(Flatten())
model.add(Dense(50, activation='relu'))
model.add(Dropout(0.3))
model.add(Dense(13, activation='softmax'))

model.compile(optimizer='Adadelta', loss='categorical_crossentropy', metrics=[f1])

history = model.fit(padded_docs, y_label, epochs=20, verbose=1, batch_size = 16, validation_split=0.3)

import matplotlib.pyplot as plt
def modelplot(history):
    plt.plot(history.history['f1'])
    plt.plot(history.history['val_f1'])
    plt.title('model accuracy')
    plt.ylabel('accuracy')
    plt.xlabel('epoch')
    plt.legend(['train', 'test'], loc='upper left')
    plt.axis([0,20,0.3,1])
    plt.show()
    plt.plot(history.history['loss'])
    plt.plot(history.history['val_loss'])
    plt.title('model loss')
    plt.ylabel('loss')
    plt.xlabel('epoch')
    plt.legend(['train', 'test'], loc='upper left')
    plt.axis([0,20,0,4])
    plt.show()

modelplot(history)

'''
encoded_docs = t.texts_to_sequences(df_test.new)
padded_docs_y = pad_sequences(encoded_docs, maxlen=max_length, padding='post')
model.predict()
'''

#####################################
from sklearn.feature_extraction.text import TfidfVectorizer, CountVectorizer

no_features = None #can be any integer i.e. 20, 50 etc. If None, use all words

# TF-IDF
tfidf_vectorizer = TfidfVectorizer(max_features= no_features)
tfidf_vectorizer.fit(df.new)
tfidf = tfidf_vectorizer.transform(df_train.new)
tfidf_real = tfidf_vectorizer.transform(df_test.new)

tfidf_feature_names = tfidf_vectorizer.get_feature_names()
tfidf_vectorizer.idf_
tfidf.toarray()

# LDA
tf_vectorizer = CountVectorizer(max_features=no_features)
tf_vectorizer.fit(df.new)
tf = tf_vectorizer.transform(df_train.new)
tf_feature_names = tf_vectorizer.get_feature_names()
tf.toarray()

# Neural network
model = Sequential()
e = Embedding(1438, 10173, weights=[dense], trainable=False)
model.add(e)
model.add(Flatten())
model.add(Dense(10173, activation='relu'))
model.add(Dropout(0.2))
model.add(Dense(13, activation='softmax'))

model.compile(optimizer='Adadelta', loss='categorical_crossentropy', metrics=['acc'])

history = model.fit(tfidf, y_label, epochs=20, verbose=1,validation_split=0.3)

# Run NMF
from sklearn.decomposition import NMF, LatentDirichletAllocation
no_topics = 13
nmf = NMF(n_components=no_topics, init='nndsvd').fit(tfidf)
W = nmf.fit_transform(tfidf)
H = nmf.components_

# Run LDA
lda = LatentDirichletAllocation(n_components=no_topics, learning_method='online', learning_offset=50.).fit(tf)
W_lda = lda.fit_transform(tf)
H_lda = lda.components_

def display_topics(model, feature_names, no_top_words):
    for topic_idx, topic in enumerate(model.components_):
        print ("Topic %d:" % (topic_idx))
        print (" ".join([feature_names[i]
                        for i in topic.argsort()[:-no_top_words - 1:-1]]))

no_top_words = 15
display_topics(nmf, tfidf_feature_names, no_top_words)
display_topics(lda, tf_feature_names, no_top_words)

#######################################
tfidf_df = pd.DataFrame(tfidf.toarray())
dummies = pd.get_dummies(df_train.user_id)
dummies = dummies.reset_index(inplace = False).drop(columns = ['index'])
tfidf_new = pd.concat([tfidf_df, dummies], axis = 1)

from sklearn.model_selection import train_test_split
y = df_train.label
x_train, x_test, y_train, y_test = train_test_split(tfidf_new, y, test_size=0.3, random_state=1)

import xgboost as xgb
m = xgb.XGBClassifier(n_estimators=100, max_depth=8, learning_rate=0.1)
train1 = m.fit(x_train, y_train)
predict = m.predict(x_test)

m1 = xgb.XGBClassifier()
train2 = m1.fit(x_train, y_train)
predict2 = m1.predict(x_test)

from sklearn.metrics import f1_score
f1_score(y_test, predict2, average = 'micro')

from sklearn.metrics import precision_recall_fscore_support as score
precision, recall, fscore, support = score(y_test, predict2)
print('precision: {}'.format(precision))
print('recall: {}'.format(recall))
print('fscore: {}'.format(fscore))
print('support: {}'.format(support))

from sklearn.metrics import precision_recall_fscore_support
precision_recall_fscore_support(y_test, predict2)

from catboost import CatBoostClassifier
from sklearn.metrics import confusion_matrix
from sklearn.metrics import roc_curve, auc
from catboost import CatBoost

m_cat = CatBoostClassifier(iterations = 2000, loss_function = 'MultiClass')
m_cat.fit(x_train, y_train)
y_pred_cat = m_cat.predict(x_test)

from sklearn.metrics import f1_score
f1_score(y_test, y_pred_cat, average = 'micro')

tfidf_df = pd.DataFrame(tfidf_real.toarray())
dummies = pd.get_dummies(df_test.user_id)
dummies = dummies.reset_index(inplace = False).drop(columns = ['index'])
x_true = pd.concat([tfidf_df, dummies], axis = 1)

y_pred_actual = m_cat.predict(x_true)
y_pred_actual = pd.DataFrame(y_pred_actual)
df_test_pred = pd.concat([df_test.reset_index(inplace = False).drop(columns = ['index']), y_pred_actual], axis = 1)

df_test_pred['label'] = df_test_pred.iloc[:,-1]
df_test_pred = df_test_pred.drop([0], axis=1)

########
from sklearn.ensemble import RandomForestClassifier
m_rand = RandomForestClassifier()
m_rand.fit(x_train, y_train)
predict_rand = m_rand.predict(x_test)

from sklearn.metrics import f1_score
f1_score(y_test, predict_rand, average = 'micro')

y_pred_actual_rand = m_rand.predict(x_true)

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

final_df = pd.concat([df_test_pred, df_train])
final_df = final_df.reset_index(inplace = False).drop(columns = ['index'])

# Saving files

final_df.to_csv("Final_2.csv",encoding='utf-8-sig')
final1.to_csv('team_2.txt', sep='\t', index=False)


from typing import Sequence, Mapping

def maximum_value(max_weight: int, items: Sequence[Mapping[str, int]]) -> int:

    items = [i for i in items if i["weight"] <= max_weight]
    count = len(items)
    knapsack = [[0 for c in range(max_weight + 1)] for r in range(count + 1)]

    for index, item in enumerate(items, start=1):
        for capacity in range(1, max_weight + 1):
            value_without_item = knapsack[index - 1][capacity]
            if item["weight"] > capacity:
                knapsack[index][capacity] = value_without_item
                continue
            running_value = knapsack[index - 1][capacity - item["weight"]]
            value_with_item = running_value + item["value"]
            knapsack[index][capacity] = max(value_without_item, value_with_item)
    return knapsack[count][max_weight]


#!/usr/bin/env python
import numpy as np
# scipy version stuff
try:
    from scipy.misc import imread
except:
    from scipy.ndimage import imread
import pandas as pd

def construct_training_data(data_directory, number_data_train=-1, number_data_test=-1, binary_classification=False):
    """Returns training labels and array of images

    Params
    ------
    catalog_path : string path to csv file of catalog
    image_directory : string path to directory containing images
    number_data_train, _test : number of images we want to load. Default to all

    Returns
    -------
    train_images : (Ntrain,color,y,x) array of floats
    train_labels : (Ntrain,) array of ints
        0: dud, 1: sim lens galaxy, 2: sim lens quasar, 3: sim lens cluster

    And test

    Notes
    -----
    Training objects are objects in catalog with split_test_train == 0.
    split_test_train == 1 are the test objects
    split_test_train == -1 are the unknown objects where we want to find lenses

    """
    catalog_path = data_directory + '/sw_data/cutout_catalog/catalog.csv'
    image_directory = data_directory + '/sw_data/cutout_catalog/cutouts'

    catalog = pd.read_csv(catalog_path, index_col=0)

    if 'split_test_train' not in catalog:
        # assign split_test_train
        training_labels = ['dud', 'simulated lensed galaxy', 'simulated lensed quasar', 'simulated lensing cluster', 'known lens']
        catalog['split_test_train'] = -1
        cat_traintest = catalog['object_flavor'].isin(training_labels)
        # TODO: set a seed to make this part reproducible?
        catalog['split_test_train'][cat_traintest] = np.random.randint(2, size=len(catalog[cat_traintest]))

    train_info = catalog[catalog['split_test_train'] == 0][
        ['object_name', 'object_flavor']].values

    if number_data_train > 0:
        choices = np.random.choice(len(train_info), number_data_train, replace=False)
        train_info = train_info[choices]

    train_images = np.zeros((len(train_info), 96, 96, 3))
    train_labels = np.zeros((len(train_info),))
    for ii, training_info in enumerate(train_info):
        image_file = image_directory + '/' + training_info[0]
        train_images[ii] = imread(image_file).astype(np.float32) / 255.0
        if binary_classification:
            if training_info[1] == 'dud':
                train_labels[ii] = 0
            else:
                train_labels[ii] = 1
        else:
            if training_info[1] == 'dud':
                train_labels[ii] = 0
            elif training_info[1] == 'simulated lensed galaxy':
                train_labels[ii] = 1
            elif training_info[1] == 'simulated lensed quasar':
                train_labels[ii] = 2
            elif training_info[1] == 'simulated lensing cluster':
                train_labels[ii] = 3
            elif training_info[1] == 'known lens':
                train_labels[ii] = 4
            else:
                print('training label ' + str(ii) + ' not determined')
                print(training_info[2])

    train_images = np.swapaxes(train_images, 1, 3).astype(np.float32)
    train_labels = train_labels.astype(np.float32)

    test_info = catalog[catalog['split_test_train'] == 1][
        ['object_name', 'object_flavor']].values

    if number_data_test > 0:
        choices = np.random.choice(len(test_info), number_data_test, replace=False)
        test_info = test_info[choices]

    test_images = np.zeros((len(test_info), 96, 96, 3))
    test_labels = np.zeros((len(test_info),))
    for ii, testing_info in enumerate(test_info):
        image_file = image_directory + '/' + testing_info[0]
        test_images[ii] = imread(image_file).astype(np.float32) / 255.0
        if binary_classification:
            if testing_info[1] == 'dud':
                test_labels[ii] = 0
            else:
                test_labels[ii] = 1
        else:
            if testing_info[1] == 'dud':
                test_labels[ii] = 0
            elif testing_info[1] == 'simulated lensed galaxy':
                test_labels[ii] = 1
            elif testing_info[1] == 'simulated lensed quasar':
                test_labels[ii] = 2
            elif testing_info[1] == 'simulated lensing cluster':
                test_labels[ii] = 3
            elif testing_info[1] == 'known lens':
                test_labels[ii] = 4
            else:
                print('testing label ' + str(ii) + ' not determined')
                print(testing_info[2])

    test_images = np.swapaxes(test_images, 1, 3).astype(np.float32)
    test_labels = test_labels.astype(np.float32)

    return train_images, train_labels, test_images, test_labels

if __name__ == '__main__':
    import argparse

    parser = argparse.ArgumentParser(description='run the jobs!')
    parser.add_argument('--catalog',
                        action='store',
                        dest='catalog',
                        default='/farmshare/user_data/ajmcleod/' +
                                'machine_learning/galzoo/strongcnn/catalog/' +
                                'catalog.csv',
                        help='location of catalog csv')
    parser.add_argument('--images',
                        action='store',
                        dest='images',
                        default='/farmshare/user_data/ajmcleod/' +
                                'machine_learning/galzoo/image_files',
                        help='location of directory containing images')
    args = parser.parse_args()

    train_images, train_labels, test_images, test_labels = \
        construct_training_data(args.catalog, args.images)


import time
import datetime
# [START pubsub_quickstart_sub_deps]
from google.cloud import pubsub_v1
# [END pubsub_quickstart_sub_deps]

import os
import sqlalchemy
from sqlalchemy import Table, Column, Integer, String, MetaData
from sqlalchemy import create_engine

engine = create_engine('mysql+pymysql://alvarov:lata5comprar@35.198.8.176:3306/prueba_appengine', echo=True)
#engine = create_engine('mysql+pymysql://alvarov:lata5comprar@/prueba_appengine?unix_socket=/cloudsql/asistente-180018:southamerica-east1:bd-bsa-chequeo-planta', echo=True)
metadata = MetaData()
users = Table('datosConsumo', metadata,
   Column('id', Integer, primary_key=True),
   Column('dispositivo', String(250)),
   Column('valor', String(50)),
   Column('fecha',String(100)),
   Column('fechanow',sqlalchemy.types.DateTime(timezone=True),default=datetime.datetime.utcnow)
)
os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = 'key.json'
#variables

proyecto='asistente-180018'
topico='casa1-consumo-sub1'

def sub(project_id, subscription_name):
    """Receives messages from a Pub/Sub subscription."""
    # [START pubsub_quickstart_sub_client]
    # Initialize a Subscriber client
    client = pubsub_v1.SubscriberClient()
    # [END pubsub_quickstart_sub_client]
    # Create a fully qualified identifier in the form of
    # `projects/{project_id}/subscriptions/{subscription_name}`
    subscription_path = client.subscription_path(
        project_id, subscription_name)

    def callback(message):
        #print(message['PublishTime'])
        print('Received message {} of message ID {}'.format(
            message, message.message_id))

        # Acknowledge the message. Unack'ed messages will be redelivered.
        message.ack()

        print('Acknowledged message of message ID {}\n'.format(
            message.message_id))

        ins = users.insert().values(valor=str(message.data),fecha=str(message.publish_time))
        conn = engine.connect()
        result = conn.execute(ins)

    client.subscribe(subscription_path, callback=callback)
    print('Listening for messages on {}..\n'.format(subscription_path))

    while True:
        time.sleep(60)

if __name__ == '__main__':
    sub(proyecto, topico)


import logging
import os
import subprocess

from pyramid.response import Response
from pyramid.response import FileResponse
from pyramid.view import view_config

from sqlalchemy.exc import DBAPIError
from sqlalchemy import and_

from .models import (
    DBSession, BallotMeasure, Committee, Contract, Stance
    )

BUILD_DIR = 'build'

logger = logging.getLogger(__name__)

class BaseView(object):
    def __init__(self, request):
        self.request = request

    @view_config(route_name='open_ballot', renderer='templates/index.pt')
    def my_view(self):
        return {'one': 'one', 'project': 'open_ballot'}

def app(request):
    logger.info('Building app...')
    if not os.path.exists(BUILD_DIR):
        os.mkdir(BUILD_DIR)
    subprocess.call(['browserify',
                     'open_ballot/js/app.js',
                     '-o', 'build/bundle.js'])
    return FileResponse('build/bundle.js', request=request)

class BallotAjaxView(BaseView):
    @view_config(route_name='ajax_get_ballot', renderer='json',
        request_method='GET')
    def get_ballot(self):
        '''
        Returns a single ballot.  Called with GET /ajax/ballots/{id}
        Note that some ballot measures are missing a ballot type.
        '''

        ballot_measure = BallotMeasure.get_by_id(self.request.matchdict['id'])
        ballot_measure_json = {
            'id': ballot_measure.id,
            'name': ballot_measure._name,
            'prop_id': ballot_measure.prop_id,
            'description': ballot_measure.description,
            'num_yes': ballot_measure.num_yes,
            'num_no': ballot_measure.num_no,
            'passed': ballot_measure.passed,
            'election': {
                'date': ballot_measure.election.date.isoformat()
            }
        }

        if ballot_measure.ballot_type:
            ballot_measure_json.update({'ballot_type': {
                'name': ballot_measure.ballot_type.name,
                'percent_required':\
                    float(ballot_measure.ballot_type.percent_required)
                }
            }
        )

        return ballot_measure_json

    @view_config(route_name='ajax_get_ballots', renderer='json',
        request_method='GET')
    def get_ballots(self):
        '''
        Returns a list of all ballots.  Called with GET /ajax/ballots
        Note that some ballot measures are missing a ballot type.
        '''

        ballot_measure_jsons = []

        for ballot_measure in BallotMeasure.all():
            ballot_measure_json = {
                'id': ballot_measure.id,
                'name': ballot_measure._name,
                'prop_id': ballot_measure.prop_id,
                'description': ballot_measure.description,
                'num_yes': ballot_measure.num_yes,
                'num_no': ballot_measure.num_no,
                'passed': ballot_measure.passed,
                'election': {
                    'date': ballot_measure.election.date.isoformat()
                }
            }

            if ballot_measure.ballot_type:
                ballot_measure_json.update({'ballot_type': {
                    'name': ballot_measure.ballot_type.name,
                    'percent_required':\
                        float(ballot_measure.ballot_type.percent_required)
                    }
                }
            )

            ballot_measure_jsons.append(ballot_measure_json)

        return ballot_measure_jsons

    @view_config(route_name='ajax_get_donations', renderer='json',
        request_method='GET')
    def get_committees(self):
        '''
        Get the committees working on a ballot measure, with their stance.
        Called by GET /ajax/ballots/{id}/committees
        '''
        committee_jsons = []

        ballot_measure = BallotMeasure.get_by_id(self.request.matchdict['id'])
        committees = DBSession.query(Committee).join(
            Stance, and_(
                Stance.ballot_measure_id==ballot_measure.id,
                Stance.committee_id==Committee.id)
            ).join(
                Contract, and_(
                    Contract.committee_id==Committee.id
                )
            )

        for committee in committees:
            # Sum the contracts
            total_spend = sum(map(lambda contract: contract.payment,
                committee.contracts))

            committee_json = {
                'id': committee.id,
                'name': committee.name,
                'election': {
                    'date': committee.election.date.isoformat()
                },
                'stance': {
                    #TODO: Rename this to "supported"?
                    'voted_yes': committee.stance.voted_yes
                },
                'total_spend': total_spend
            }

            committee_jsons.append(committee_json)

        return committee_jsons


"""Support for getting status from a Pi-hole system."""
from homeassistant.components.binary_sensor import BinarySensorEntity
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import CONF_NAME
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_platform import AddEntitiesCallback

from . import PiHoleEntity
from .const import DATA_KEY_API, DATA_KEY_COORDINATOR, DOMAIN as PIHOLE_DOMAIN

async def async_setup_entry(
    hass: HomeAssistant, entry: ConfigEntry, async_add_entities: AddEntitiesCallback
) -> None:
    """Set up the Pi-hole binary sensor."""
    name = entry.data[CONF_NAME]
    hole_data = hass.data[PIHOLE_DOMAIN][entry.entry_id]
    binary_sensors = [
        PiHoleBinarySensor(
            hole_data[DATA_KEY_API],
            hole_data[DATA_KEY_COORDINATOR],
            name,
            entry.entry_id,
        )
    ]
    async_add_entities(binary_sensors, True)

class PiHoleBinarySensor(PiHoleEntity, BinarySensorEntity):
    """Representation of a Pi-hole binary sensor."""

    @property
    def name(self) -> str:
        """Return the name of the sensor."""
        return self._name

    @property
    def unique_id(self) -> str:
        """Return the unique id of the sensor."""
        return f"{self._server_unique_id}/Status"

    @property
    def is_on(self) -> bool:
        """Return if the service is on."""
        return self.api.data.get("status") == "enabled"  # type: ignore[no-any-return]


"""TO-DO: Write a description of what this XBlock is."""

import pkg_resources

from xblock.core import XBlock
from xblock.fields import Scope, String, Integer, Float, Boolean, DateTime
from xblock.fragment import Fragment

from random import choice

class ShowLessonInIframeXBlock(XBlock):
    """
    TO-DO: document what your XBlock does.
    """

    # Fields are defined on the class.  You can access them in your code as
    # self.<fieldname>.

    score = Float(
        values={"min": 0},
        default=None, scope=Scope.user_state,
        help="User answer score",
    )

    state = String(
        default=None, scope=Scope.user_state,
        help="State of xblock",
    )

    href = String(
        display_name="src for IFrame",
        help=("lesson url"),
        default=None,
        scope=Scope.settings,
    )

    width = String(
        display_name="IFrame width",
        help=("IFrame width"),
        default='100%',
        scope=Scope.settings,
    )

    height = String(
        display_name="IFrame Height",
        help=("IFrame Height"),
        default='500px',
        scope=Scope.settings,
    )

    maxscore = Float(
        values={"min": 1},
        default=1, scope=Scope.settings,
        help=("Max score"),
    )

    has_score = True

    def resource_string(self, path):
        """Handy helper for getting resources from our kit."""
        data = pkg_resources.resource_string(__name__, path)
        return data.decode("utf8")

    def studio_view(self, context=None):
        """
        Create a fragment used to display the edit view in the Studio.
        """
        html = self.resource_string("static/html/slif_studio_edit.html")
        frag = Fragment(html.format(self=self))
        frag.add_javascript(self.resource_string("static/js/src/slif_studio_edit.js"))
        frag.initialize_js('SlifStudioEdit')

        return frag

    # TO-DO: change this view to display your data your own way.
    def student_view(self, context=None):
        """
        The primary view of the ShowLessonInIframeXBlock, shown to students
        when viewing courses.
        """
        if not self.href:
            html = self.resource_string("static/html/slif_student_empty.html")
            frag = Fragment(html.format(self=self))
            frag.add_css(self.resource_string("static/css/slif_empty.css"))
            return frag
        else:
            html = self.resource_string("static/html/slif.html")
            frag = Fragment(html.format(self=self))
            frag.add_javascript_url(self.runtime.local_resource_url(self, 'public/js/jschannel.js'))
            frag.add_javascript(self.resource_string("public/js/production.js"))
            frag.add_javascript(self.resource_string("static/js/src/slif.js"))
            # frag.add_css(self.resource_string("public/css/style.css"))
            frag.initialize_js('ShowLessonInIframeXBlock', {'state': self.state,
                                                            'answer': self.score})
        return frag

    @XBlock.json_handler
    def studio_submit(self, data, suffix=''):
        """
        Called when submitting the form in Studio.
        """
        self.href = data.get('href')
        self.width  = data.get('width')
        self.height = data.get('height')

        try:
            m = float(data.get('maxscore'))
            if m >= 1:
                self.maxscore = m
        except:
            pass

        return {'result': 'success'}

    @XBlock.json_handler
    def save_x_state(self, data, suffix=''):
        out = {}

        # save it in string format. Dont need to unpack it
        if 'state' in data['values']:
            self.state = data['values']['state']
            out['state'] = 'ok'

        if 'score' in data['values']:
            score = data['values']['score']
            if score.isdigit():
                self.score = float(score)

                if self.score <= self.maxscore:
                    grade_event = {'value': self.score, 'max_value': self.maxscore}
                    self.runtime.publish(self, 'grade', grade_event)

                out['score'] = self.score

            else:
                out['error'] = 'score: bad type'

        return out

    # TO-DO: change this to create the scenarios you'd like to see in the
    # workbench while developing your XBlock.
    @staticmethod
    def workbench_scenarios():
        """A canned scenario for display in the workbench."""
        return [
            ("ShowLessonInIframeXBlock",
             """<slif/>
             """),
            ("Multiple ShowLessonInIframeXBlock",
             """<vertical_demo>
                <slif/>
                </vertical_demo>
             """),
        ]

    # Everything below is stolen from
    # https://github.com/edx/edx-ora2/blob/master/apps/openassessment/
    #        xblock/lms_mixin.py
    # It's needed to keep the LMS+Studio happy.
    # It should be included as a mixin.

    display_name = String(
        default="SLIFtest!", scope=Scope.settings,
        help="Display name"
    )

    start = DateTime(
        default=None, scope=Scope.settings,
        help="ISO-8601 formatted string representing the start date "
             "of this assignment. We ignore this."
    )

    due = DateTime(
        default=None, scope=Scope.settings,
        help="ISO-8601 formatted string representing the due date "
             "of this assignment. We ignore this."
    )

    weight = Float(
        display_name="Problem Weight",
        help=("Defines the number of points each problem is worth. "
              "If the value is not set, the problem is worth the sum of the "
              "option point values."),
        values={"min": 0, "step": .1},
        scope=Scope.settings
    )

    def has_dynamic_children(self):
        """Do we dynamically determine our children? No, we don't have any.
        """
        return False

    def max_score(self):
        """The maximum raw score of our problem.
        """
        return self.maxscore


#!/usr/bin/env python
"""
A custom class to send logs to rabbitMQ
"""
__author__ = "Lloyd McCarthy"
__license__ = "MIT"

import logging
import kombu

class RabbitMQHandler(logging.Handler):
    """
    Handler that sends message to RabbitMQ using kombu.
    """
    def __init__(self, uri=None, queue='logstash'):
        logging.Handler.__init__(self)
        connection = kombu.Connection(uri, connect_timeout=1)
        connection.connect()
        self.queue = connection.SimpleQueue(queue)

    def emit(self, record):
        """
        Puts the record on a logging queue.
        Arguments:
            record {[type]} -- [description]
        """
        self.queue.put(record.msg)

    def close(self):
        """
        Closes the queue.
        """
        try:
            self.queue.close()
        except AttributeError:
            return None


from django.urls import path
from homepage import views

urlpatterns = [
    path('', views.homepage, name='homepage'),
    path('signup/', views.signup, name = 'signup'),
    path('login/', views.login, name = 'login'),
    path('logout-request/', views.logout_request, name = 'logout_request'),
    path('activate/<uidb64>/<token>/', views.activate, name='activate'),
    path('reset-password/<uidb64>/<token>/', views.reset_password, name='reset_password'),
    path('email-input/', views.email_input, name='email_input'),
    path('tnc/', views.tnc, name='tnc'),
    path('glucose-input/', views.glucose_input, name='glucose_input'),
    path('carbs-input/', views.carbs_input, name='carbs_input'),
    path('insulin-input/', views.insulin_input, name='insulin_input'),
    path('profile-page/', views.profile_page, name='profile_page'),
    path('dashboard/', views.dashboard, name='dashboard'),
    path('dashboard-data/<start_date>/<end_date>/', views.dashboard_data, name='dashboard_data'),
    path('api-glucose/', views.GlucoseView.as_view(), name='GlucoseView'),
    path('api-carbs/', views.CarbsView.as_view(), name='CarbsView'),
    path('api-insulin/', views.InsulinAPIView.as_view(), name='InsulinAPIView'),
    path('analytics-data/<start_date>/<end_date>/', views.analytics_data, name='analytics_data'),
    path('analytics', views.analytics, name='analytics'),
    path('glossary/', views.glossary, name='glossary'),
    path('analytics-trend-data/<day>/<glucose_bool>/', views.analytics_trend_data, name='analytics_trend_data'),
]


import os
from flask import Flask, send_from_directory, jsonify, request, Response
from flask_cors import CORS
import json
import numpy as np
import pandas as pd
import pytz
from datetime import datetime, timedelta
import time
import requests
import math
import sys
from models import metrics, util, arrival_history, wait_times, trip_times, nextbus, constants, errors

"""
This is the app's main file!
"""

# configuration
DEBUG = os.environ.get('FLASK_DEBUG') == '1'

# Create the app
app = Flask(__name__, static_folder='../frontend/build')
CORS(app)

# Test endpoint
@app.route('/api/ping', methods=['GET'])
def ping():
    return "pong"

@app.route('/api/metrics', methods=['GET'])
def metrics_page():
    metrics_start = time.time()
    route_id = request.args.get('routeId')
    if route_id is None:
        route_id = '12'
    start_stop_id = request.args.get('startStopId')
    if start_stop_id is None:
        start_stop_id = '3476'
    end_stop_id = request.args.get('endStopId')

    direction_id = request.args.get('directionId')

    start_date_str = request.args.get('startDate')
    end_date_str = request.args.get('endDate')
    date_str = request.args.get('date')

    if date_str is not None:
        start_date_str = end_date_str = date_str
    else:
        if start_date_str is None:
            start_date_str = '2019-04-08'
        if end_date_str is None:
            end_date_str = start_date_str

    start_time_str = request.args.get('startTime') # e.g. "14:00" (24h time of day)
    end_time_str = request.args.get('endTime') # e.g. "18:00" or "03:00+1" (24h time of day)

    params = {
        'startStopId': start_stop_id,
        'endStopId': end_stop_id,
        'routeId': route_id,
        'directionId': direction_id,
        'startDate': start_date_str,
        'endDate': end_date_str,
        'startTime': start_time_str,
        'endTime': end_time_str,
    }

    data = {
        'params': params
    }

    try:
        route_config = nextbus.get_route_config('sf-muni', route_id)

        start_stop_info = route_config.get_stop_info(start_stop_id)
        if start_stop_info is None:
            raise errors.ValidationError(f"Stop {start_stop_id} is not on route {route_id}")

        data['startStopTitle'] = start_stop_info.title

        if end_stop_id:
            end_stop_info = route_config.get_stop_info(end_stop_id)
            if end_stop_info is None:
                raise errors.ValidationError(f"Stop {end_stop_id} is not on route {route_id}")
            data['endStopTitle'] = end_stop_info.title

        rng = metrics.Range(
            util.get_dates_in_range(start_date_str, end_date_str),
            start_time_str,
            end_time_str,
            pytz.timezone('US/Pacific')
        )

        route_metrics = metrics.RouteMetrics('sf-muni', route_id)

        keys = ['count','avg','min','median','max','percentiles','histogram']

        data['waitTimes'] = route_metrics.get_wait_time_stats(
            direction_id, start_stop_id,
            rng, keys
        )

        data['tripTimes'] = route_metrics.get_trip_time_stats(
            direction_id, start_stop_id, end_stop_id,
            rng, keys
        )

        data['headwayMin'] = route_metrics.get_headway_min_stats(
            direction_id, start_stop_id,
            rng, keys
        )

    except errors.ArrivalHistoryNotFoundError as ex:
        return make_error_response(params, str(ex), 404)
    except errors.ValidationError as ex:
        return make_error_response(params, str(ex), 400)

    metrics_end = time.time()
    data['processingTime'] = (metrics_end - metrics_start)

    res = Response(json.dumps(data, indent=2), mimetype='application/json')
    if not DEBUG:
        res.headers['Cache-Control'] = 'max-age=60'
    return res

def make_error_response(params, error, status):
    data = {
        'params': params,
        'error': error,
    }
    return Response(json.dumps(data, indent=2), status=status, mimetype='application/json')

@app.route('/api/metrics_by_interval', methods=['GET'])
def metrics_by_interval():
    route_id = request.args.get('routeId')
    if route_id is None:
        route_id = '12'
    start_stop_id = request.args.get('startStopId')
    if start_stop_id is None:
        start_stop_id = '3476'
    end_stop_id = request.args.get('endStopId')

    direction_id = request.args.get('directionId')

    start_date_str = request.args.get('startDate')
    end_date_str = request.args.get('endDate')
    date_str = request.args.get('date')

    if date_str is not None:
        start_date_str = end_date_str = date_str
    else:
        if start_date_str is None:
            start_date_str = '2019-04-08'
        if end_date_str is None:
            end_date_str = start_date_str

    start_time_str = request.args.get('startTime') # e.g. "14:00" (24h time of day)
    end_time_str = request.args.get('endTime') # e.g. "18:00" (24h time of day)

    params = {
        'startStopId': start_stop_id,
        'endStopId': end_stop_id,
        'routeId': route_id,
        'directionId': direction_id,
        'startDate': start_date_str,
        'endDate': end_date_str,
        'date': date_str,
        'startTime': start_time_str,
        'endTime': end_time_str,
    }

    data = {
        'params': params
    }

    if start_time_str is not None and end_time_str is not None:
        # round start_time down and end_time up to allow for even intervals
        start_time = datetime.strptime(start_time_str, '%H:%M').replace(microsecond=0, second=0, minute=0)
        end_time = datetime.strptime(end_time_str, '%H:%M').replace(microsecond=0, second=0, minute=0) - timedelta(hours=1)

        time_str_intervals = []
        while start_time.hour != end_time.hour + 1:
            time_str_intervals.append((
                start_time.strftime('%H:%M'),
                (start_time + timedelta(seconds=3600)).strftime('%H:%M')
            ))
            start_time += timedelta(seconds=3600)
    else:
        if start_time_str or end_time_str:
            return make_error_response(params, f'Need both a start and end time', 404)

        time_str_intervals = constants.DEFAULT_TIME_STR_INTERVALS

    try:
        route_metrics = metrics.RouteMetrics('sf-muni', route_id)

        dates = util.get_dates_in_range(start_date_str, end_date_str)

        keys = ['count','avg','min','median','max','percentiles']

        tz = pytz.timezone('US/Pacific')

        def get_interval_stats(start_time_str, end_time_str):

            rng = metrics.Range(dates, start_time_str, end_time_str, tz)

            return {
                    'startTime': start_time_str,
                    'endTime': end_time_str,
                    'waitTimes': route_metrics.get_wait_time_stats(
                        direction_id, start_stop_id,
                        rng, keys
                    ),
                    'tripTimes': route_metrics.get_trip_time_stats(
                        direction_id, start_stop_id, end_stop_id,
                        rng, keys
                    ),
            }

        data['intervals'] = [
            get_interval_stats(start_time_str, end_time_str)
            for start_time_str, end_time_str in time_str_intervals
        ]
    except errors.ArrivalHistoryNotFoundError as ex:
        return make_error_response(params, str(ex), 404)
    except errors.ValidationError as ex:
        return make_error_response(params, str(ex), 400)

    return Response(json.dumps(data, indent=2), mimetype='application/json')

@app.route('/api/config', methods=['GET'])
def config():
    res = Response(json.dumps({"mapbox_access_token": os.environ.get('MAPBOX_ACCESS_TOKEN')}), mimetype='application/json')
    if not DEBUG:
        res.headers['Cache-Control'] = 'max-age=3600'
    return res

if os.environ.get('METRICS_ALL_IN_ONE') == '1':
    @app.route('/frontend/build/<path:path>')
    def frontend_build(path):
        return send_from_directory('../frontend/build', path)

    @app.route('/', defaults={'path': ''})
    @app.route('/<path:path>')
    def wildcard(path):
        return send_from_directory('../frontend/build', 'index.html')
else:
    @app.route('/')
    def root():
        return """
Hello!

This is the API server Go to port 3000 to see the real app.
"""

if __name__ == '__main__':
    # Bind to PORT if defined, otherwise default to 5000.
    port = int(os.environ.get('PORT', 5000))
    app.run(use_reloader=True, threaded=True, host='0.0.0.0', port=port)


# -*- coding: utf-8 -*-

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

plt.rcParams['font.sans-serif'] = ['Droid Sans Fallback']  # 用来正常显示中文标签
plt.rcParams['axes.unicode_minus'] = False  # 用来正常显示负

obs_x = [-40.0, -50.0, -35.0, -50.0, -60.0, -30.0, -20.0, -30.0, -40.0]
obs_y = [20.0, 0.0, -10.0, 25.0, 20.0, -20.0, 20.0, 5.0, 10.0]

target_x = [-60, -50, -20]
target_y = [30, -20, 0]

plt.figure()
p1 = plt.subplot(111)

p1.scatter(target_y, target_x, s=40, c='cyan', label=u'目标点')
p1.scatter(obs_y, obs_x, s=160, c='red', label=u'障碍物')
for i in range(3):
    p1.text(target_y[i] + 1, target_x[i] + 1, s=u'目标{}'.format(i + 1), fontsize=12, color='black')

u, v = np.zeros((1, 1)), np.zeros((1, 1))

p1.scatter([15], [-15], s=40, c='g')
p1.text(15.2, -14.8, u'当前位置')
u[0, 0] = target_y[0] - 15
v[0, 0] = target_x[0] + 15
p1.quiver(15, -15, u, v, scale=1, units='xy', color='g')
u[0, 0] = target_y[1] - target_y[0]
v[0, 0] = target_x[1] - target_x[0]
p1.quiver(target_y[0], target_x[0], u, v, scale=1, units='xy', color='g')
u[0, 0] = target_y[2] - target_y[1]
v[0, 0] = target_x[2] - target_x[1]
p1.quiver(target_y[1], target_x[1], u, v, scale=1, units='xy', color = 'g')

p1.set_xlabel(u'东向 /m')
p1.set_ylabel(u'北向 /m')

p1.set_aspect(1)
# p1.grid(linestyle='--', linewidth=0.5)
p1.legend(loc='lower left', fontsize=12)
p1.axis([-30, 40, -75, -10])

plt.savefig('setup.svg')

plt.show()


from solvertools.wordlist import WORDS
from solvertools.normalize import slugify, sanitize
from solvertools.util import data_path
from whoosh.index import open_dir
from whoosh import qparser
import re

INDEX = None
QUERY_PARSER = None

def search(pattern=None, clue=None, length=None, count=20):
    """
    Find words and phrases that match various criteria: a regex pattern,
    a clue phrase, and/or a length.

    >>> search('.a.b.c..')[0][1]
    'BARBECUE'
    >>> search('.a....e.', clue='US President')[0][1]
    'VAN BUREN'
    >>> search(clue='lincoln assassin', length=15)[0][1]
    'JOHN WILKES BOOTH'
    """
    global INDEX, QUERY_PARSER
    if clue is None:
        if pattern is None:
            return []
        else:
            return WORDS.search(pattern, count=count, use_cromulence=True)

    if pattern is not None:
        pattern = pattern.lstrip('^').rstrip('$').lower()
        pattern = re.compile('^' + pattern + '$')

    if INDEX is None:
        INDEX = open_dir(data_path('search'))
        QUERY_PARSER = qparser.SimpleParser(
            "definition", schema=INDEX.schema,
            group=qparser.OrGroup.factory(0.9)
        )
        QUERY_PARSER.add_plugin(qparser.GroupPlugin())
        QUERY_PARSER.add_plugin(qparser.BoostPlugin())

    matches = []
    with INDEX.searcher() as searcher:
        results = searcher.search(QUERY_PARSER.parse(clue), limit=20)
        # half-assed query expansion
        clue_parts = set([sanitize(result['text']) for result in results])
        expanded_clue = ", ".join(clue_parts)
        new_clue = '%s, (%s)^0.01' % (clue, expanded_clue)
        results = searcher.search(QUERY_PARSER.parse(new_clue), limit=None)
        seen = set()
        for i, result in enumerate(results):
            text = result['text']
            slug = slugify(text)
            if slug not in seen:
                if length is None or length == len(slug):
                    if pattern is None or pattern.match(slug):
                        seen.add(slug)
                        #crom, text = WORDS.cromulence(slug)
                        score = results.score(i)
                        matches.append((score, text))
                        if len(matches) >= count:
                            break
        return matches


from turtle import Screen
from paddle import Paddle
from ball import Ball
from scoreboard import Scoreboard
import time

# variables
game_is_on = True
SCORE_LIMIT = 21

# objects
r_paddle = Paddle((350, 0))
l_paddle = Paddle((-350, 0))
ball = Ball()
scoreboard = Scoreboard()

# screen setup
screen = Screen()
screen.setup(width=800, height=600)
screen.bgcolor("black")
screen.title("My Pong Game")
screen.tracer(0)

# event listeners
screen.listen()
screen.onkeypress(r_paddle.go_up, "Up")
screen.onkeypress(r_paddle.go_down, "Down")
screen.onkeypress(l_paddle.go_up, "w")
screen.onkeypress(l_paddle.go_down, "s")

# main
while game_is_on:
    time.sleep(ball.move_speed)
    screen.update()
    ball.move()

    # detect wall collision
    if ball.ycor() > 280 or ball.ycor() < -280:
        ball.bounce_y()

    # detect collision with r_paddle
    if ball.distance(r_paddle) < 50 and ball.xcor() > 320 or ball.distance(l_paddle) < 50 and ball.xcor() > -320:
        ball.bounce_x()

    # detect r_paddle misses
    if ball.xcor() > 380:
        ball.reset_position()
        scoreboard.l_point()

    # detect l_paddle misses
    if ball.xcor() < -380:
        ball.reset_position()
        scoreboard.r_point()

    # game over
    if scoreboard.l_score == SCORE_LIMIT or scoreboard.r_score == SCORE_LIMIT:
        game_is_on = False
        scoreboard.game_over()

screen.exitonclick()


# MIT License
#
# Copyright (c) 2019 Red Hat, Inc.

# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.

import logging

import click
from pkg_resources import get_distribution

from packit.cli.build import build
from packit.cli.copr_build import copr_build
from packit.cli.create_update import create_update
from packit.cli.init import init
from packit.cli.local_build import local_build
from packit.cli.push_updates import push_updates
from packit.cli.srpm import srpm
from packit.cli.status import status
from packit.cli.sync_from_downstream import sync_from_downstream
from packit.cli.update import update
from packit.cli.validate_config import validate_config
from packit.config import Config, get_context_settings
from packit.utils.logging import set_logging

logger = logging.getLogger("packit")

class AliasedGroup(click.Group):
    def get_command(self, ctx, cmd_name):
        if cmd_name == "generate":
            click.secho(
                "WARNING: 'packit generate' is deprecated and it "
                "is going to be removed. Use 'packit init' instead.",
                fg="yellow",
            )
            return click.Group.get_command(self, ctx, "init")
        else:
            return click.Group.get_command(self, ctx, cmd_name)

@click.group("packit", cls=AliasedGroup, context_settings=get_context_settings())
@click.option("-d", "--debug", is_flag=True, help="Enable debug logs.")
@click.option("--fas-user", help="Fedora Account System username.")
@click.option("-k", "--keytab", help="Path to FAS keytab file.")
@click.option(
    "--remote",
    default=None,
    help=(
        "Name of the remote to discover upstream project URL, "
        "If this is not specified, default to the first remote."
    ),
)
@click.option(
    "--dry-run",
    is_flag=True,
    help="Do not perform any remote changes (pull requests or comments).",
)
@click.version_option(
    version=get_distribution("packitos").version, message="%(version)s"
)
@click.pass_context
def packit_base(ctx, debug, fas_user, keytab, dry_run, remote):
    """Integrate upstream open source projects into Fedora operating system."""
    if debug:
        # to be able to logger.debug() also in get_user_config()
        set_logging(level=logging.DEBUG)

    c = Config.get_user_config()
    c.debug = debug or c.debug
    c.dry_run = dry_run or c.dry_run
    c.fas_user = fas_user or c.fas_user
    c.keytab_path = keytab or c.keytab_path
    c.upstream_git_remote = remote or c.upstream_git_remote
    ctx.obj = c

    if ctx.obj.debug:
        set_logging(level=logging.DEBUG)
        set_logging(logger_name="sandcastle", level=logging.DEBUG)
    else:
        set_logging(level=logging.INFO)

    packit_version = get_distribution("packitos").version
    logger.debug(f"Packit {packit_version} is being used.")

packit_base.add_command(update)
packit_base.add_command(sync_from_downstream)
packit_base.add_command(build)
packit_base.add_command(copr_build)
packit_base.add_command(create_update)
packit_base.add_command(push_updates)
packit_base.add_command(srpm)
packit_base.add_command(status)
packit_base.add_command(init)
packit_base.add_command(local_build)
packit_base.add_command(validate_config)

if __name__ == "__main__":
    packit_base()


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

import unittest
import sys

sys.path.append('..')
import numpy as np
from op_test import OpTest
import paddle.fluid as fluid
import paddle

paddle.enable_static()

def test_class1(op_type, typename):
    class TestExpandAsBasic(OpTest):
        def setUp(self):
            self.set_mlu()
            self.op_type = "expand_as_v2"
            self.python_api = paddle.expand_as
            x = np.random.rand(100).astype(typename)
            target_tensor = np.random.rand(2, 100).astype(typename)
            self.inputs = {'X': x}
            self.attrs = {'target_shape': target_tensor.shape}
            bcast_dims = [2, 1]
            output = np.tile(self.inputs['X'], bcast_dims)
            self.outputs = {'Out': output}

        def set_mlu(self):
            self.__class__.use_mlu = True
            self.place = paddle.device.MLUPlace(0)
            self.__class__.no_need_check_grad = True

        def test_check_output(self):
            self.check_output_with_place(self.place)

    cls_name = str(op_type) + "_" + str(typename) + "_1"
    TestExpandAsBasic.__name__ = cls_name
    globals()[cls_name] = TestExpandAsBasic

def test_class2(op_type, typename):
    class TestExpandAsOpRank2(OpTest):
        def setUp(self):
            self.set_mlu()
            self.op_type = "expand_as_v2"
            self.python_api = paddle.expand_as
            x = np.random.rand(10, 12).astype(typename)
            target_tensor = np.random.rand(10, 12).astype(typename)
            self.inputs = {'X': x}
            self.attrs = {'target_shape': target_tensor.shape}
            bcast_dims = [1, 1]
            output = np.tile(self.inputs['X'], bcast_dims)
            self.outputs = {'Out': output}

        def set_mlu(self):
            self.__class__.use_mlu = True
            self.place = paddle.device.MLUPlace(0)
            self.__class__.no_need_check_grad = True

        def test_check_output(self):
            self.check_output_with_place(self.place)

    cls_name = str(op_type) + "_" + str(typename) + "_2"
    TestExpandAsOpRank2.__name__ = cls_name
    globals()[cls_name] = TestExpandAsOpRank2

def test_class3(op_type, typename):
    class TestExpandAsOpRank3(OpTest):
        def setUp(self):
            self.set_mlu()
            self.op_type = "expand_as_v2"
            self.python_api = paddle.expand_as
            x = np.random.rand(2, 3, 20).astype(typename)
            target_tensor = np.random.rand(2, 3, 20).astype(typename)
            self.inputs = {'X': x}
            self.attrs = {'target_shape': target_tensor.shape}
            bcast_dims = [1, 1, 1]
            output = np.tile(self.inputs['X'], bcast_dims)
            self.outputs = {'Out': output}

        def set_mlu(self):
            self.__class__.use_mlu = True
            self.place = paddle.device.MLUPlace(0)
            self.__class__.no_need_check_grad = True

        def test_check_output(self):
            self.check_output_with_place(self.place)

    cls_name = str(op_type) + "_" + str(typename) + "_3"
    TestExpandAsOpRank3.__name__ = cls_name
    globals()[cls_name] = TestExpandAsOpRank3

def test_class4(op_type, typename):
    class TestExpandAsOpRank4(OpTest):
        def setUp(self):
            self.set_mlu()
            self.op_type = "expand_as_v2"
            self.python_api = paddle.expand_as
            x = np.random.rand(1, 1, 7, 16).astype(typename)
            target_tensor = np.random.rand(4, 6, 7, 16).astype(typename)
            self.inputs = {'X': x}
            self.attrs = {'target_shape': target_tensor.shape}
            bcast_dims = [4, 6, 1, 1]
            output = np.tile(self.inputs['X'], bcast_dims)
            self.outputs = {'Out': output}

        def set_mlu(self):
            self.__class__.use_mlu = True
            self.place = paddle.device.MLUPlace(0)
            self.__class__.no_need_check_grad = True

        def test_check_output(self):
            self.check_output_with_place(self.place)

    cls_name = str(op_type) + "_" + str(typename) + "_4"
    TestExpandAsOpRank4.__name__ = cls_name
    globals()[cls_name] = TestExpandAsOpRank4

# Test python API
class TestExpandAsV2API(unittest.TestCase):
    def test_api(self):
        input1 = np.random.random([12, 14]).astype("float32")
        input2 = np.random.random([2, 12, 14]).astype("float32")
        x = fluid.layers.data(
            name='x', shape=[12, 14], append_batch_size=False, dtype="float32"
        )

        y = fluid.layers.data(
            name='target_tensor',
            shape=[2, 12, 14],
            append_batch_size=False,
            dtype="float32",
        )

        out_1 = paddle.expand_as(x, y=y)

        exe = fluid.Executor(place=fluid.MLUPlace(0))
        res_1 = exe.run(
            fluid.default_main_program(),
            feed={"x": input1, "target_tensor": input2},
            fetch_list=[out_1],
        )
        assert np.array_equal(res_1[0], np.tile(input1, (2, 1, 1)))

for _typename in {
    'float16',
    'float32',
    'int64',
    'int32',
    'int8',
    'uint8',
    'bool',
}:
    test_class1('expand_as_v2', _typename)
    test_class2('expand_as_v2', _typename)
    test_class3('expand_as_v2', _typename)
    test_class4('expand_as_v2', _typename)

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


# bazel build polygerrit-ui/app:gr-app
# mitmdump -s "serve-app-locally.py ~/gerrit/bazel-bin/polygerrit-ui/app"
from mitmproxy import http
import argparse
import os
import zipfile

class Server:
    def __init__(self, bundle):
        self.bundle = bundle
        self.bundlemtime = 0
        self.files = {
            'polygerrit_ui/elements/gr-app.js': '',
            'polygerrit_ui/elements/gr-app.html': '',
            'polygerrit_ui/styles/main.css': '',
        }
        self.read_files()

    def read_files(self):
        if not os.path.isfile(self.bundle):
            print("bundle not found!")
            return
        mtime = os.stat(self.bundle).st_mtime
        if mtime <= self.bundlemtime:
            return
        self.bundlemtime = mtime
        with zipfile.ZipFile(self.bundle) as z:
            for fname in self.files:
                print('Reading new content for ' + fname)
                with z.open(fname, 'r') as content_file:
                    self.files[fname] = content_file.read()

    def response(self, flow: http.HTTPFlow) -> None:
        self.read_files()
        for name in self.files:
            if name.rsplit('/', 1)[1] in flow.request.pretty_url:
                flow.response.content = self.files[name]

def expandpath(path):
    return os.path.expanduser(path)

def start():
    parser = argparse.ArgumentParser()
    parser.add_argument("bundle", type=str)
    args = parser.parse_args()
    return Server(expandpath(args.bundle))


import config
import logging
import asyncio
from aiogram import Bot, Dispatcher, executor, types
from selenium import webdriver
import os

options = webdriver.ChromeOptions()
options.binary_location = os.environ.get('GOOGLE_CHROME_BIN')
options.add_argument('--headless')
options.add_argument('--disable-dev-shm-usage')
options.add_argument('--no-sandbox')

br = webdriver.Chrome(executable_path=os.environ.get('CHROMEDRIVER_PATH'), options=options)

logging.basicConfig(level=logging.INFO)

bot = Bot(token=config.TOKEN)
dp = Dispatcher(bot)

users = []

@dp.message_handler(commands=['userlist'])
async def start(message: types.Message):
	mess = ''
	for i in range(len(users)):
		mess = mess + str(i+1) + ' '+ str(users[i][0]) + ' ' + str(users[i][1]) + '\n'
	if mess == '':
		await message.answer('список пуст')
	else:
		await message.answer(mess)

@dp.message_handler(commands=['start'])
async def start(message: types.Message):
	global users, last_check
	sub = 0
	for i in range(len(users)):
		if users[i][0] == message.from_user.id:
			pos_user = i
			sub = 1
			break
	if sub == 0:
		users.append([message.from_user.id,True])
		await message.answer('Старт')
	else:
		users[pos_user][1] = True
		await message.answer('Старт')
	last_check = None

@dp.message_handler(commands=['stop'])
async def stop(message: types.Message):
	global users
	sub = 0
	for i in range(len(users)):
		if users[i][0] == message.from_user.id:
			pos_user = i
			sub = 1
			break
	if sub == 0:
		await message.answer('Вы и так не нажали старт')
		users.append([message.from_user.id,False])
	else:
		users[pos_user][1] = False
		await message.answer('Стоп')

async def parse():
	global last_check
	last_check = None
	while True:
		br.refresh()
		br.get('https://www.epicgames.com/store/ru/free-games')
		html = br.find_element_by_class_name('css-1442lgn-CardGrid-styles__group').text
		if last_check != html:
			last_check = html
			for i in range(len(users)):
				if users[i][1] == True:
					await bot.send_message(users[i][0],html)
		await asyncio.sleep(600)

if __name__ == '__main__':
	loop = asyncio.get_event_loop()
	loop.create_task(parse())
	executor.start_polling(dp, skip_updates=True, loop=loop)