import requests
import os
import sys
script_dir = os.path.dirname(os.path.abspath(__file__))
sys.path.append(os.path.dirname(script_dir))
from print_response import print_response

# https://pokeapi.co/api/v2

def main():
    count = 1
    url = 'http://pokeapi.co/api/v2/pokemon'
    headers = {'Accept': 'application/json'}
    params = {
        "limit": 200
    }
    resp = requests.get(url, headers=headers,params=params)
    resp.raise_for_status()

    data = resp.json()
    breakpoint()
    while data['next']:
        resp = requests.get(data['next'], headers=headers)
        resp.raise_for_status()
        count +=1
        print_response(resp, filename=f"pokemon/get_all_pokemon_{count}")
        data = resp.json()

    # for pokemon in resp.json()['results']:
    #     resp = requests.get(pokemon['url'], headers=headers)
    #     breakpoint()
    #     if resp.ok:
    #         print_response(
    #             resp, filename=f"/python_extra/req/pokemon/get_{pokemon['name']}")
    #     else:
    #         print(f"could not load {pokemon['name']} details")

if __name__ == '__main__':
    main()


import speech_recognition as sr
r=sr.Recognizer()
with sr.Microphone() as source:
	print("calibrating , wait")
	r.adjust_for_ambient_noise(source,duration=5)
	print("ok, speak now")
	audio=r.listen(source)
	print('done')

strin=r.recognize_sphinx(audio)
print(strin)


import self as self

class employee:
    count = 0
    salaries = []

    def __init__(self, name, familyname, salary, department):
        self.name = name
        self.familyname = familyname
        self.salary = salary
        self.department = department

        employee.salaries.append(self.salary)
        employee.count = employee.count + 1

    def averagesalary(self, salaries):
        totalsalary = 0
        salcount = len(salaries)
        for salary in salaries:
            totalsalary = totalsalary + salary
        avgsalary = totalsalary / salcount
        print("Average salary is", avgsalary)

class fulltimeEmployee(employee):

    def __init__(self, name, familyname, salary, department):
        employee.__init__(self, name, familyname, salary, department)

employee1 = employee("Sahithya", "Gadde", 100000, "CS")
employee2= fulltimeEmployee("Roshna","Toke", 239478,"CS")
employee3= employee("Bharani", "Yellanki", 105000,"CS")
employee4= fulltimeEmployee("Alekhya","Thangellapelly", 160341,"CS")
print("Total Number of employees ",employee.count)
print("Names of the employers are")
print(employee1.name)
print(employee2.name)
print(employee3.name)
print(employee4.name)
employee1.averagesalary(employee.salaries)


from fastapi import APIRouter
from api.api_v1.endpoints import analysis, validation, inventory

## File to include all routers

api_router = APIRouter()

# Add analysis endpoints
api_router.include_router(
    analysis.router,
    prefix="/analysis",
    tags=["analysis"],
    responses={404: {"description": "Not found"}},
)

# Add validation endpoints
api_router.include_router(
    validation.router,
    prefix="/validation",
    tags=["validation"],
    responses={404: {"description": "Not found"}},
)

# Add inventory endpoints
api_router.include_router(
    inventory.router,
    prefix="/inventory",
    tags=["inventory"],
    responses={404: {"description": "Not found"}},
)


from flask import Flask
import compiler

app = Flask(__name__)

@app.route('/translate', methods=['POST'])
def index():
    try:
        code = compiler.compile(request.form['program'])
        return code
    except compiler.BrainfuckCompilerError:
        return '', 400

if __name__ == '__main__':
    print('Serving on :3000')
    app.run(port=3000)


# https://school.programmers.co.kr/learn/courses/30/lessons/77484#fn1

def solution(lottos, win_nums):
    cnt = 0;zero_cnt = 0
    for i in lottos:
        if i == 0:
            zero_cnt += 1
            continue

        if i in win_nums:
            cnt += 1
            continue

    luck = 7- (cnt + zero_cnt)
    unluck = 7 - cnt

    if luck == 7:
        luck = 6
    if unluck == 7:
        unluck = 6

    return [luck,unluck]

[PGM]_로또의최고순위와최저순위.py


from .pyslinger import IR
from .write import write_as_bits
from .read import FanSpeed, Modes

def args_to_params(args):
    def fromval(cls, something):
        try:
            something = int(something)
        except:
            pass
        if isinstance(something, int):
            return cls(something)
        else:
            return cls[something]

    mode = fromval(Modes, args[0])
    temp = int(args[1])
    speed = fromval(FanSpeed, args[2])
    power_cycle = bool(int(args[3]))
    return mode, temp, speed, power_cycle

def send(gpio_pin, mode, temp, speed, power_cycle):
    protocol = "RAW"
    protocol_config = dict(
        one_duration=1000,
        zero_duration=1000)
    ir = IR(gpio_pin, protocol, protocol_config)
    code = write_as_bits(mode, temp, speed, power_cycle)
    ir.send_code(code)

if __name__ == "__main__":
    from sys import argv
    from os import environ

    gpio_pin = int(environ('GPIO_PIN', 25))

    send(gpio_pin, *args_to_params(argv[1:]))


"""
Fizz buzz challenge
change the word method to subroutine.
There are a few ways to do this challenge

"""
# This solution uses a nested if statement
# if i mod 5 = 0 it then tests to see if i mod 3 is also 0 this is a fizzbuzz
def fizzBuzz1():
	for i in range(1,101):
		if i % 5 == 0:
			if i % 3 == 0:
				print("FizzBuzz")
			else:
				print("Buzz")
		elif i % 3 == 0:
			print("Fizz")
		else:
			print(i)

# this subroutine uses mod 15 first to test for fizz buzzes
# then mod 5 then mod 3.
def fizzBuzz2():
	for i in range(1,101):
		if i % 15 == 0:
			print("fizzBuzz")
		elif i % 5 == 0:
			print("Buzz")
		elif i % 3 == 0:
			print("Fizz")
		else:
			print(i)

fizzBuzz1()
fizzBuzz2()


def adding_function():
    sum_=0
    while True:
        number = input('Enter a number to add, hit enter if you don''t want to add any more numbers')
        print(f">{number}<")
        if number == '':
            print(f'Total={sum_}')
            break
        else:
            sum_+= int(number)

adding_function()


#===============================================================================
# This file creates the cog which makes requests using the Google APIs
# to manage the committee spreadsheets and completed quest submissions.
#
# This cog also executes automatic updates for both the spreadsheets and the database
#===============================================================================

# imports used for the google API,
# Which for some reason is a lot
from __future__ import print_function
import os.path
from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import InstalledAppFlow
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError
from googleapiclient.http import MediaIoBaseDownload

# Basic Discord tools
import discord
from discord.ext import commands, tasks
# Used to handle dates when uploading and downloading
import datetime
import dateparser
# Used to handle the update cycle loop
import asyncio
import logging

class google_interact(commands.Cog):
    """Handles any bot action which involves
    using the google API
    """
    def __init__(self, bot):
        """Initializes the cog.
        Stores the parent bot and calls
        the method which sets up the google
        API tools
        """
        self._bot = bot
        self._logger = logging.getLogger('bot activity')
        self.setupAPI()

        self.updateTimer.start()

    @commands.Cog.listener()
    async def on_connect(self):
        """Gathers references to the announcements
        and DB_interactions cogs when the bot connects to
        discord's servers
        """
        self._announce = self._bot.get_cog("announceSystem")
        self._db = self._bot.get_cog("db_interact")

    @commands.Cog.listener()
    async def on_ready(self):
        """Gathers a reference to the server"""
        self._guildRef = self._bot.get_guild(236626664304410634)

    def setupAPI(self):
        """Sets up the tools necessary for the google API.
        This was mostly taken from the google API docs,
        so it would be best to reference those for additional information
        """
        creds = None
        SCOPES = ["https://www.googleapis.com/auth/spreadsheets", "https://www.googleapis.com/auth/drive"]
        # The file token.json stores the user's access and refresh tokens, and is
        # created automatically when the authorization flow completes for the first
        # time.
        try:
            if os.path.exists('token.json'):
                creds = Credentials.from_authorized_user_file('token.json', SCOPES)
            # If there are no (valid) credentials available, let the user log in.
            if not creds or not creds.valid:
                if creds and creds.expired and creds.refresh_token:
                    creds.refresh(Request())
                else:
                    flow = InstalledAppFlow.from_client_secrets_file(
                        'credentials.json', SCOPES)
                    creds = flow.run_local_server(port=0)
                # Save the credentials for the next run
                with open('token.json', 'w') as token:
                    token.write(creds.to_json())
        except Exception as e:
            self._logger.critical("Google_interactions:setupAPI:Setup Error: %s", str(e))

        # Create the services necessary for the actions the bot makes,
        # and store the IDs for the quest spreadsheets
        self._sheetService = build("sheets", "v4", credentials=creds)
        self._driveService = build("drive", "v3", credentials=creds)
        self._spreadsheetID = ("1cst4m3t9BXADFpFbqZYmK7MPCaFrZ3Pq0Qz_sHxA0kw",
                               "1AtJ4sc7DvVHpuU0YWaWUVyPe0vB2gOKVPlOfraT8_Sc",
                               "1Es7IgyfmyJDxZ53aBZ_Sjqlw2-r3bv03rUhjnT3dT0M")

    async def updateSelf(self):
        """Updates the database using info from the
        master spreadsheet. This includes member info
        and completed quests.
        """
        # updating the approved completed quests, and deleting the rejected completions
        range_ = "Pending Quests submits!A3:L"

        try:
            result = self._sheetService.spreadsheets().values().get(
                        spreadsheetId=self._spreadsheetID[0], range=range_).execute()
        except Exception as e:
            self._logger.error("Google_interactions:updateSelf:Get Error: %s in master %s", str(e), range_)
            return

        rows = result.get("values", [])
        self._logger.info("Google_interactions:updateSelf: gathered %s items from master %s\n%s", str(len(rows)), range_, str(rows))
        unreviewed = [] # Used to track items which need to be returned

        for row in rows: # for each item
            if len(row) == 10: # If the row does not have an item in the "approved" column
                unreviewed.append(row) # Add to unreviewed items
            elif row[10].upper() == "SUBMISSION ERROR": # If it was previously returned because of an error
                unreviewed.append(row) # Return it to the spreadsheet
            elif row[10].upper() == "YES": # If it was approved
                complete = await self._db.questSubmit(int(row[0]), int(row[3]), row[9]) # Try to add it to the user's log
                if not complete: # If it did not add,
                    # return it to the spreadsheet
                    row[10] = "SUBMISSION ERROR"
                    unreviewed.append(row)
            # If it was rejected, it is simply ignored

        try:
            # Clear the old submissions
            errorType = "Clear"
            self._sheetService.spreadsheets().values().clear(
                spreadsheetId=self._spreadsheetID[0], range=range_).execute()
            self._logger.info("Google_interactions:updateSelf: cleared all items from master %s", range_)
            if unreviewed != []: # if there are items to be returned
                # Send the items back to the spreadsheet
                body = {"values":unreviewed}
                valueInput="RAW"
                errorType = "Update"
                self._sheetService.spreadsheets().values().update(
                    spreadsheetId=self._spreadsheetID[0], range=range_,
                    valueInputOption=valueInput, body=body).execute()
                self._logger.info("Google_interactions:updateSelf: added %s items to %s\n%s", str(len(unreviewed)), range_, str(unreviewed))
        except Exception as e:
            self._logger.error("Google_interactions:updateSelf:%s Error: %s in master %s", errorType, str(e), range_)
            return

        # updating the member database
        range_ = "Members!A:P"

        # Grab the items from the spreadsheet
        try:
            result = self._sheetService.spreadsheets().values().get(
                    spreadsheetId=self._spreadsheetID[0], range=range_).execute()
        except Exception as e:
            self._logger.error("Google_interactions:updateSelf:Get Error: %s in master %s", str(e), range_)
            return

        rows = result.get("values", [])
        self._logger.info("Google_interactions:updateSelf: gathered %s items from master %s\n%s", str(len(rows)), range_, str(rows))

        if rows[0][1].upper() == "YES": # If there were edits put into the sheet
            # Reset the edited field to "NO"
            try:
                self._sheetService.spreadsheets().values().update(
                    spreadsheetId=self._spreadsheetID[0], range="Members!B1:B1",
                    valueInputOption="RAW", body={"values" : [["NO"]]}).execute()
            except Exception as e:
                self._logger.error("Google_interactions:updateSelf:Update Error: %s in master Members!B1:B1", str(e))
                return
            else:
                self._logger.info("Google_interactions:updateSelf: set master Members!B1:B1 to 'NO'")

            for row in rows[2:]: # For each member
                # Get the member's info from discord
                memberId = int(row[0])
                member = self._guildRef.get_member(memberId)
                if len(row) == 16: # If there are items in the edits column
                    editField = row[15] # Grab the edits
                    if editField.lower() == "remove": # If they are being removed, send to delete method
                        await self._db.deleteMember(memberId)
                    else:
                        # Split the edits by commas, add a change to update the member's discord name,
                        # then send the request to the database
                        editField = editField.split(",")
                        editField.append("discordname:'" + member.name + "#" + member.discriminator)
                        await self._db.editMemberItems(memberId, editField)
                        # Check to ensure the level of the member did not become outdated
                        await self._db.checkMemberLevel(memberId)
                else: # If no edits were made to the item
                    # Update the member's discord name, then
                    # Check the member's level and rank
                    editField = ["discordname:'" + member.name + "#" + member.discriminator,]
                    await self._db.editMemberItems(memberId, editField)
                    await self._db.checkMemberLevel(memberId)

            # Clear the old edits
            range_ = "Members!P3:P"
            try:
                self._sheetService.spreadsheets().values().clear(
                    spreadsheetId=self._spreadsheetID[0], range=range_).execute()
            except Exception as e:
                self._logger.error("Google_interactions:updateSelf:Clear Error: %s in master %s", str(e), range_)
                return
            else:
                self._logger.info("Google_interactions:updateSelf: cleared all items from master %s", range_)

        else: # If no edits were made,
            # Update each member's discord name in the database
            for row in rows[2:]:
                memberId = int(row[0])
                member = self._guildRef.get_member(memberId)
                editField = ["discordname:'" + member.name + "#" + member.discriminator,]
                await self._db.editMemberItems(memberId, editField)

    async def updateQuests(self):
        """Updates the assorted items which are related to
        quests, such as loading the quest list into the database
        and taking quest submissions to put into the master sheet
        """
        # collect quests and put into database
        ranks = {"F":0, "E":1, "D":2, "C":3, "B":4, "A":5, "S":6, "S+":7}
        quests = []
        # Repeatable Quests
        range_ = "Repeatable!A2:G"
        questType = "repeatable"
        try:
            result = self._sheetService.spreadsheets().values().get(
                spreadsheetId=self._spreadsheetID[1], range=range_).execute()
        except Exception as e:
            self._logger.error("Google_interactions:updateQuests:Get Error: %s in quests %s", str(e), range_)
            return

        rows = result.get("values", [])
        self._logger.info("Google_interactions:updateQuests: Gathered %s items from quests %s\n%s", str(len(rows)), range_, str(rows))
        for row in rows:
            if len(row) >= 6:
                desc = row[2] + " - " + row[5]
                rank = -1
                if len(row) > 6:
                    if "Rank " in row[6]:
                        rank = row[6][row[6].find("Rank ") + 5] # Find the letter after Rank
                        rank = ranks[rank] # Convert the letter to the given number

                quests.append((row[0], row[1], desc, rank, row[3], row[4], questType))

        # Ranked Quests
        ranges = ("F Rank!A2:G", "E Rank!A2:G", "D Rank!A2:G",
                  "C Rank!A2:G", "B Rank!A2:G", "A Rank!A2:G",
                  "S Rank!A2:G", "S+ Rank!A2:G")

        for i in range(len(ranges)):
            range_ = ranges[i]
            rank = i
            try:
                result = self._sheetService.spreadsheets().values().get(
                    spreadsheetId=self._spreadsheetID[1], range=range_).execute()
            except Exception as e:
                self._logger.error("Google_interactions:updateQuests:Get Error: %s in quests %s", str(e), range_)
                return

            rows = result.get("values", [])
            self._logger.info("Google_interactions:updateQuests: Gathered %s items from quests %s\n%s", str(len(rows)), range_, str(rows))
            for row in rows:
                if len(row) >= 6:
                    desc = row[2] + " - " + row[5]
                    questType = "ranked"
                    if len(row) > 6:
                        if "Heroic" in row[6]:
                            questType = "heroic"

                    quests.append((row[0], row[1], desc, rank, row[3], row[4], questType))

        # Special Quests
        range_ = "Event Specific!A2:F"
        try:
            result = self._sheetService.spreadsheets().values().get(
                spreadsheetId=self._spreadsheetID[1], range=range_).execute()
        except Exception as e:
            self._logger.error("Google_interactions:updateQuests:Get Error: %s in quests %s", str(e), range_)
            return

        rows = result.get("values", [])
        self._logger.info("Google_interactions:updateQuests: Gathered %s items from quests %s\n%s", str(len(rows)), range_, str(rows))
        for row in rows:
            if len(row) >= 6:
                desc = row[2] + " - " + row[5]
                rank = -1
                questType = "special"
                if len(row) > 6:
                    if "Rank " in row[6]:
                        rank = row[6][row[6].find("Rank ") + 5] # Find the letter after Rank
                        rank = ranks[rank] # Convert the letter to the given number
                    if "Heroic" in row[6]:
                        questType = questType + " - heroic"
                    if "Repeatable" in row[6]:
                        questType = questType + " - repeatable"

                quests.append((row[0], row[1], desc, rank, row[3], row[4], questType))

        # Send all the quests to the database
        complete = await self._db.loadQuests(quests)
        if not complete:
            self._logger.critical("Google_interactions:updateQuests:Error: Could not upload quests to database\n%s", str(quests))

        # collect the quest images
        # driveIDs are the ids for each folder that has posters,
        # and ranks are the rank of the quest each ID has
        driveIDs = ('1eqncAKw4-ruaBviZuSNGw-k9QIFM__l_', '1u4hDaq9BH8JURrQsUeLgshIHNLJXYQyI',
                    '1nIpzZUEYTaX8bRe_f_7LcLHnEdIzKZ8s', '1JQ09XQ9UIyBKI21J-QmLpTehXF7L6IR7',
                    '1II9tzExIzQmbE25Do3q8ieib81C56nxK', '1pha0nkvdDGxvRu_2YZT9q3zMbxrx1X6d',
                    '1xLsYmdKHTkRkqg0ptGSZmMtl4mmcqV_1', '16Nl2f5GepUOQgpK73dk4yNVxjWZpXxRP')
        ranks = ('F', 'E', 'D', 'C', 'B', 'A', 'S', 'S+')

        for i in range(len(driveIDs)): # for each folder
            # grab the ID and rank
            ID = driveIDs[i]
            rank = ranks[i]
            #logging
            query = f"'{ID}' in parents and mimeType='image/jpeg'"
            files = []

            page_token=None
            while True:
                try:
                    response = self._driveService.files().list(q=query,
                                                           spaces='drive',
                                                           fields='nextPageToken, '
                                                           'files(id, name)',
                                                           pageToken=page_token).execute()
                except Exception as e:
                    print(e)
                    #logging
                    return

                files.extend(response.get('files', []))
                page_token = response.get('nextPageToken', None)
                if page_token is None:
                    break

            self._logger.info("Google_interactions:updateQuests: found %s total items in drive %s\n%s", str(len(files)), rank, str(files))
            for file in files:
                fileName = file.get("name")
                fileID = file.get("id")
                if not os.path.exists(f"./questPics/{rank}/{fileName}"):
                    self._logger.info("Google_interactions:updateQuests: new file found; downloading image %s - ID %s", fileName, fileID)
                    try:
                        request = self._driveService.files().get_media(fileId=fileID)

                        with open(f"./questPics/{rank}/{fileName}", "wb") as file:
                            downloader = MediaIoBaseDownload(file, request)
                            done = False
                            while not done:
                                status, done = downloader.next_chunk()
                                self._logger.info("Google_interactions:updateQuests: Download %s", str(int(status.progress() * 100)))

                    except Exception as e:
                        self._logger.error("Google_interactions:updateQuests:Downloader Error: %s for file %s in drive %s", str(e), fileName, rank)
                    else:
                        self._logger.info("Google_interactions:updateQuests: file downloaded under questPics\\%s\\%s", rank, fileName)

        # updating the announcements
        range_ = "Quests to announce!A2:D"
        try:
            result = self._sheetService.spreadsheets().values().get(
                    spreadsheetId=self._spreadsheetID[0], range=range_).execute()
        except Exception as e:
            self._logger.error("Google_interactions:updateQuests:Get Error: %s in master %s", str(e), range_)
            return

        rows = result.get("values", [])
        self._logger.info("Google_interactions:updateQuests: gathered %s items from master %s\n%s", str(len(rows)), range_, str(rows))
        if rows != []:
            await self._announce.addAnnouncements(rows)

        # clear old announcements
        try:
            self._sheetService.spreadsheets().values().clear(
                    spreadsheetId=self._spreadsheetID[0], range=range_).execute()
        except Exception as e:
            self._logger.error("Google_interactions:updateQuests:Clear Error: %s in master %s", str(e), range_)
            return
        else:
            self._logger.info("Google_interactions:updateQuests: cleared all items from master %s", range_)

        # collect submissions and put into the approval spreadsheet
        range_ = "Form Responses 1!A2:R"
        questlist = [] # quests that can be added
        failedQuests = [] # quests with submission errors
        try:
            file = self._sheetService.spreadsheets().values().get(
                spreadsheetId=self._spreadsheetID[2], range=range_).execute()

            submissions = file.get("values", [])
            self._logger.info("Google_interactions:updateQuests: gathered %s items from submissions %s\n%s", len(submissions), range_, str(submissions))
        except Exception as e:
            self._logger.error("Google_interactions:updateQuests:Get Error: %s in submissions %s", str(e), range_)
            return

        for submit in submissions:
            if len(submit) < 18:
                continue
            quest = []
            # Search for the member based on their discord name
            # If not found return the submission and quit
            memInfo = await self._db.fetchMemberName(submit[17])
            if memInfo == "error" or memInfo == "none found":
                self._logger.warning("Google_interactions:updateQuests:Quit Warning: Member %s could not be found for quest submission", submit[17])
                failedQuests.append(submit)
                continue
            quest.append(str(memInfo[0])) # Member ID
            quest.append(submit[1]) # Member Name
            quest.append(submit[2].lower()) # Quest Type

            # The data layout for each quest type is different.
            # Each if statement has the data collection for a given type
            if quest[2] == "repeatable":
                questInfo = await self._db.fetchQuest(submit[12]) # get the quest info
                # If not found, return submission and quit
                if questInfo == "error" or questInfo == "none found":
                    self._logger.warning("Google_interactions:updateQuests:Quit Warning: Quest %s could not be found for quest submission", submit[12])
                    failedQuests.append(submit)
                    continue
                quest.append(questInfo[0]) # quest number
                quest.append(questInfo[1]) # quest name
                for i in range(4): # empty data columns
                    quest.append('')
            elif quest[2] == "ranked":
                questInfo = await self._db.fetchQuest(submit[8])
                if questInfo == "error" or questInfo == "none found":
                    self._logger.warning("Google_interactions:updateQuests:Quit Warning: Quest %s could not be found for quest submission", submit[8])
                    failedQuests.append(submit)
                    continue
                quest.append(questInfo[0]) # Quest Number
                quest.append(questInfo[1]) # Quest Name
                quest.append('') # Empty column
                quest.append(submit[9]) # Quest Committee witnesses
                quest.append(submit[10]) # Other witnesses
                quest.append(submit[11]) # additional proof
            elif quest[2] == "heroic":
                questInfo = await self._db.fetchQuest(submit[3])
                if questInfo == "error" or questInfo == "none found":
                    self._logger.warning("Google_interactions:updateQuests:Quit Warning: Quest %s could not be found for quest submission", submit[3])
                    failedQuests.append(submit)
                    continue
                quest.append(questInfo[0]) # quest Number
                quest.append(questInfo[1]) # quest name
                quest.append(submit[4]) # other participants
                quest.append(submit[5]) # Quest Committee witnesses
                quest.append(submit[6]) # other witnesses
                quest.append(submit[7]) # additional proof
            else: # Special quests
                questInfo = await self._db.fetchQuest(submit[13])
                if questInfo == "error" or questInfo == "none found":
                    self._logger.warning("Google_interactions:updateQuests:Quit Warning: Quest %s could not be found for quest submission", submit[13])
                    failedQuests.append(submit)
                    continue
                quest.append(questInfo[0]) # Quest Number
                quest.append(questInfo[1]) # Quest Name
                quest.append('') # Empty column
                quest.append(submit[14]) # Quest Committee witnesses
                quest.append(submit[16]) # Other witnesses
                quest.append(submit[15]) # additional proof

            quest.append(dateparser.parse(submit[0]).date().strftime("%m/%d/%Y")) # add the date submitted
            questlist.append(quest) # add to the return list

        if questlist != []: # if at least one quest was successfully parsed
            # add them to the pending quest submissions sheet in the master spreadsheet
            range_="Pending Quests submits!A3:J"
            values = {"values":questlist}

            try:
                result = self._sheetService.spreadsheets().values().append(
                    spreadsheetId=self._spreadsheetID[0], range=range_,
                    valueInputOption="RAW", body=values).execute()
            except Exception as e:
                self._logger.error("Google_interactions:updateQuests:Append Error: %s in master %s", str(e), range_)
                return
            else:
                self._logger.info("Google_interactions:updateQuests: added %s items to master %s\n%s", str(len(questlist)), range_, str(questlist))

        # Clear the added submissions and return the failed parsed quests
        range_ = "Form Responses 1!A2:R"
        try:
            self._sheetService.spreadsheets().values().clear(
                spreadsheetId=self._spreadsheetID[2], range=range_).execute()
        except Exception as e:
            self._logger.error("Google_interactions:updateQuests:Clear Error: %s in submissions %s", str(e), range_)
            return
        else:
            self._logger.info("Google_interactions:updateQuests: cleared all items in submissions %s", range_)

        if failedQuests != []: # If at least one failed
            # Record the amount of failed submissions
            # to add to the pending quest submissions sheet
            failed = len(failedQuests)
            values = {"values":failedQuests}
            try:
                sheet = "master" # for logging purposes
                self._sheetService.spreadsheets().values().update(
                    spreadsheetId=self._spreadsheetID[2], range=range_,
                    valueInputOption="RAW", body=values).execute()
                self._logger.info("Google_interactions:updateQuests: added %s items to submissions %s\n%s", str(len(failedQuests)), range_, str(failedQuests))

                range_ = "Pending Quests submits!M1:M1" # for logging purposes
                sheet = "submissions"
                self._sheetService.spreadsheets().values().update(
                    spreadsheetId=self._spreadsheetID[0], range=range_,
                    valueInputOption="RAW", body={"values":[[str(failed)]]}).execute()
                self._logger.info("Google_interactions:updateQuests: set submissions %s to value %s", range_, str(failed))
            except Exception as e:
                self._logger.error("Google_interactions:updateQuests:Update Error: %s in %s %s", str(e), sheet, range_)
                return

        else: # if no failures, update the value to be 0
            try:
                self._sheetService.spreadsheets().values().update(
                    spreadsheetId=self._spreadsheetID[0], range="Pending Quests submits!M1:M1",
                    valueInputOption="RAW", body={"values":[["0"]]}).execute()
            except Exception as e:
                self._logger.error("Google_interactions:updateQuests:Update Error: %s in submissions Pending Quests submits!M1:M1", str(e))
                return
            else:
                self._logger.info("Google_interactions:updateQuests: set submissions Pending Quests submits!M1:M1 to value 0")

    async def updateSpreadsheet(self):
        """Update the master spreadsheet with information from
        the database, which is primarily targeted at the member
        and current pending announcements spreadsheets
        """
        # Update members spreadsheet
        range_ = "Members!A3:O"
        valueInput = "RAW"

        # Get all the items in the adventurers table from the database
        values = await self._db.getFromTableFilter("adventurers", order="lastname ASC")
        if values == "error":
            return
        else:
            for i in range(len(values)):
                temp = list(values[i])
                temp[0] = str(temp[0])
                values[i] =  temp

        body = {
            "values" : values
            }
        # Remove the old information and send the new data
        try:
            errorType = "Clear"
            self._sheetService.spreadsheets().values().clear(
                spreadsheetId=self._spreadsheetID[0], range=range_).execute()
            self._logger.info("Google_interactions:updateSpreadsheet: cleared all items from master %s", range_)

            errorType = "Update"
            self._sheetService.spreadsheets().values().update(
                spreadsheetId=self._spreadsheetID[0], range=range_,
                valueInputOption=valueInput, body=body).execute()
            self._logger.info("Google_interactions:updateSpreadsheet: added %s items to master %s\n%s", str(len(values)), range_, str(values))
        except Exception as e:
            self._logger.error("Google_interactions:updateSpreadsheet:%s Error: %s in master %s", errorType, str(e), range_)
            return

        # Update pending announcements
        values = await self._announce.get_all() # get_all returns a 2D nested list
        # Index 0 is weekly quests
        range_ = "Announcement List!A3:B"
        body = {
            "values" : values[0]
            }

        try:
            errorType = "Clear"
            self._sheetService.spreadsheets().values().clear(
                    spreadsheetId=self._spreadsheetID[0], range=range_).execute()
            self._logger.info("Google_interactions:updateSpreadsheet: cleared all items from master %s", range_)

            errorType = "Append"
            self._sheetService.spreadsheets().values().append(
                            spreadsheetId=self._spreadsheetID[0], range=range_,
                            valueInputOption=valueInput, body=body).execute()
            self._logger.info("Google_interactions:updateSpreadsheet: added %s items to master %s\n%s", str(len(values[0])), range_, str(values[0]))
        except Exception as e:
            self._logger.error("Google_interactions:updateSpreadsheet:%s Error: %s in master %s", errorType, str(e), range_)
            return

        # Index 1 is event quests
        range_ = "Announcement List!D3:F"
        body = {
            "values" : values[1]
            }

        try:
            errorType = "Clear"
            self._sheetService.spreadsheets().values().clear(
                    spreadsheetId=self._spreadsheetID[0], range=range_).execute()
            self._logger.info("Google_interactions:updateSpreadsheet: cleared all items from master %s", range_)

            errorType = "Append"
            self._sheetService.spreadsheets().values().append(
                            spreadsheetId=self._spreadsheetID[0], range=range_,
                            valueInputOption=valueInput, body=body).execute()
            self._logger.info("Google_interactions:updateSpreadsheet: added %s items to master %s\n%s", str(len(values[0])), range_, str(values[0]))
        except Exception as e:
            self._logger.error("Google_interactions:updateSpreadsheet:%s Error: %s in master %s", errorType, str(e), range_)
            return

    async def uploadSpreadsheet(self, memberId):
        """Uploads a member's quest log to the
        Member Quest Log sheet in the master spreadsheet.
        """
        range_ = "Member Quest Log!A2:C2"
        valueInput = "RAW"
        member = await self._db.fetchMember(memberId)
        if member == "none found" or member == "error":
            self._logger.warning("Google_interactions:uploadSpreadsheet:Quit Warning: member %s could not be found in database", str(memberId))
            return

        values = [[str(memberId), member[1], datetime.datetime.today().strftime("%d/%m/%Y")]]
        body = {
            "values" : values
            }

        try:
            self._sheetService.spreadsheets().values().update(
                spreadsheetId=self._spreadsheetID[0], range=range_,
                valueInputOption=valueInput, body=body).execute()
        except Exception as e:
            self._logger.error("Google_interactions:uploadSpreadsheet:Update Error: %s in master %s", str(e), range_)
            return False
        else:
            self._logger.info("Google_interactions:uploadSpreadsheet: updated master %s with items %s", range_, str(values))

        range_ = "Member Quest Log!A4:G"
        dbname = str(memberId) + "questLog"
        values = await self._db.getFromTableFilter(dbname, order="number ASC")
        body = {
            "values" : values
            }

        try:
            errorType = "Clear"
            self._sheetService.spreadsheets().values().clear(
                spreadsheetId=self._spreadsheetID[0], range=range_).execute()
            self._logger.info("Google_interactions:uploadSpreadsheet: cleared all items from master %s", range_)

            errorType = "Append"
            self._sheetService.spreadsheets().values().append(
                spreadsheetId=self._spreadsheetID[0], range=range_,
                valueInputOption=valueInput, body=body).execute()
            self._logger.info("Google_interactions:uploadSpreadsheet: added %s items to master %s\n%s", str(len(values)), range_, str(values))
        except Exception as e:
            self._logger.error("Google_interactions:uploadSpreadsheet:%s Error: %s in master %s", errorType, str(e), range_)
            return False

        return True

    async def runUpdate(self):
        self._logger.info("Google_interactions:runUpdate: running update cycle")
        await self.updateSelf()
        await self.updateQuests()
        await self.updateSpreadsheet()
        self._logger.info("Google_interactions:runUpdate: completed update cycle")

    @tasks.loop(seconds=5.0)
    async def updateTimer(self):
        """The primary method which controls when the bot
        checks for and makes announcements
        """
        now = datetime.datetime.now() # right now
        nextTime = datetime.datetime.combine(datetime.datetime.today(), datetime.time(hour=2)) # a datetime representing the next target cycle time
        if nextTime < now: # if the nextTime object is behind right now
            nextTime = nextTime + datetime.timedelta(days=1) # push it up by 1 day

        difference = nextTime - now # take the time difference between right now and the next target cycle
        self._logger.info("Google_interactions:updateTimer: Time set to next update cycle: %s to %s", str(difference), str(nextTime))
        await asyncio.sleep(difference.total_seconds()) # Set a timer for the next update

        await self.runUpdate() # Run all the updates

    @updateTimer.before_loop
    async def before_timer(self):
        print('update is waiting...')
        await self._bot.wait_until_ready()
        print('update is ready!')


from lib.data_worker import DataWorker

import time
import requests
import re
from urllib import parse as urllib_parse

req_headers = {
    'Connection':'keep-alive',
    'Cache-Control': 'max-age=0',
    'Upgrade-Insecure-Requests': '1',
    'User-Agent': 'hcmc.io.bot.v1',
    'Accept-Encoding': 'gzip, deflate',
    'Accept-Language': 'en-US,en;q=0.9',
}

REDDIT_REQUEST_TEMPLATE = "https://www.reddit.com/r/%s/about.json"
REDDIT_ID_REGEX = re.compile(r"\/r\/([\d\w\-\_\.]+)/?")

class RedditMembersRawDataWorker(DataWorker):
    update_frequency = 60 * 10

    def __init__(self):
        pass

    def fetch_data(self):
        r = requests.get("http://db.xyz.hcmc.io/data/coins.json")
        data = r.json()

        for row in data:
            if not row:
                continue

            if not ('community' in row and 'reddit' in row['community']):
                # There is not reddit links for current row item
                continue

            links = row['community']['reddit']

            if not links:
                # There is not reddit links for current row item
                continue

            data = dict(
                ts=int(time.time()),
                members=0,
                members_active=0,
            )

            for link in links:
                url = urllib_parse.urlparse(link)
                matches = REDDIT_ID_REGEX.findall(url.path)

                if not matches:
                    continue

                page_id = matches[0]

                # slow down to prevent ip ban
                time.sleep(0.5)
                r = requests.get(REDDIT_REQUEST_TEMPLATE % page_id, headers=req_headers)

                resp = r.json()

                if 'error' in resp:
                    if resp['error'] == 403:
                        # private community
                        continue

                    elif resp['error'] == 404:
                        # doesn't exists or banned
                        continue

                if 'kind' in resp and resp['kind'] == 'Listing':
                    # this is not sub reddit (skipping)
                    continue

                resp = resp['data']

                data['members'] += resp['subscribers']
                data['members_active'] += resp['active_user_count']

            self.save(row['id'], data)

    def save(self, coin_id, data):
        if data is None:
            return

        # In real parser we will get last entry from db and check if current data differs
        # from latest saved and if not we will skip it.

        print(coin_id, data)


import flask
import os
import werkzeug

app = flask.Flask(__name__)
app.debug = True

@app.route("/", methods=['GET', 'POST'])
def Galerey():
    if flask.request.method == 'GET':
        directory = 'static'
        files = os.listdir(directory)
        return flask.render_template('Galerey.html', fileslist=files)
    try:
        fs = flask.request.files['image']
        fs.save('static/' + werkzeug.secure_filename(fs.filename))
    except ValueError:
        return flask.render_template('Galerey.html', error="Ошибки!")
    return flask.redirect('/')

app.run()


from math import floor

num = int(input())
mtx = [[int(s) if s.isdigit() else s for s in input().split()] for _ in range(num)]

p = ()
for i in range(len(mtx)):
    for ii in range(len(mtx[i])):
        if mtx[i][ii] == 'P':
            p = i, ii

def move(row, col, comm, num):
    if comm == 'up':
        if row == 0:
            return num - 1, col
        return row - 1, col
    elif comm == 'right':
        if col == num - 1:
            return row, 0
        return row, col + 1
    elif comm == 'down':
        if row == num - 1:
            return 0, col
        return row + 1, col
    elif comm == 'left':
        if col == 0:
            return row, num - 1
        return row, col - 1

lst = []
lst.append([p[0], p[1]])
coins = 0
command = input()
while command:
    n_pos = move(p[0], p[1], command, num)
    lst.append([n_pos[0], n_pos[1]])
    if mtx[n_pos[0]][n_pos[1]] == 'X':
        coins = floor(coins / 2)
        break
    else:
        coins += mtx[n_pos[0]][n_pos[1]]
        mtx[n_pos[0]][n_pos[1]] = 'P'
        mtx[p[0]][p[1]] = 0
    if coins >= 100:
        break
    p = n_pos
    command = input()
if coins >= 100:
    print(f"You won! You've collected {coins} coins.")
else:
    print(f"Game over! You've collected {coins} coins.")
print('Your path:')
[print(_) for _ in lst]

SoftUni/Python-Advanced/exam prep/02. Collecting Coins.py


# آسمان شکر آباد
# https://quera.ir/problemset/contest/6082/سؤال-آسمان-شکر-آباد
# pourya.2374@gmail.com

n, m = tuple(map(int, input().split(' ')))
result = 0
for _ in range(n):
    for item in input():
        if item == '*':
            result += 1
print(result)


def add_tuple(tuple_a=(), tuple_b=()):
    newtuple_a = ''
    newtuple_b = ''

    if len(tuple_a) >= 2 and len(tuple_b) >= 2:
        print("both available:" )
        newtuple_a = tuple_a
        newtuple_b = tuple_b
    if len(tuple_a) >= 2:
        print("only tuple a  available." )
        newtuple_a = tuple_a
    if len(tuple_b) >= 2:
        print("only tuple b available." )
        newtuple_b = tuple_b
    if len(tuple_a) < 2 or len(tuple_b) < 2:
        print("tuples missing one or more:")
        print("a:",tuple_a)
        print("b",tuple_b)
        print("----replaced: tuples----")
        if len(tuple_a) == 0:
            newtuple_a = 0, 0,
            print("newtuple_a: {} ".format(newtuple_a))
        elif len(tuple_a) == 1:
            newtuple_a = tuple_a[0], 0,
            print("newtuple_a: {} ".format(newtuple_a))
        if len(tuple_b) == 0:
            newtuple_b = 0, 0,
            print("newtuple_b: {} ".format(newtuple_b))
        elif len(tuple_b) == 1:
            newtuple_b = tuple_b[0], 0,
            print("newtuple_b: {} ".format(newtuple_b))

    sum_tuple = newtuple_a[0] + newtuple_b[0], newtuple_a[1] + newtuple_b[1]

    print("sum:.....")
    # print()
    return (sum_tuple)

tuple_a = (1, 89)
tuple_b = (88, 11)
new_tuple = add_tuple(tuple_a, tuple_b)
print(new_tuple)

print(add_tuple(tuple_a, (1, )))
print(add_tuple(tuple_a, ()))
print(add_tuple((), (4, 8, 8)))


import unittest
import subprocess

from practice import *

proc = subprocess.Popen(
        ['python', 'practice.py'],
        stdout=subprocess.PIPE,
        stderr=subprocess.STDOUT)

print_text = proc.communicate()[0]

delim = print_text.split('\n')

class TestCanOpenFiles(unittest.TestCase):
	def test_can_make_a_file_pointer(self):
		self.assertIsInstance(
            txt,
            file
        )
	def test_can_read_file_contents(self):
		self.assertEqual(
			contents[0:3],
			'DON'
		)
	def test_can_print_file_to_screen(self):
		self.assertEqual(
			str(delim[41]).rstrip(),
			"P2: Cuz they're made of... wood?"
		)

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


import uvicorn
from fastapi import FastAPI
from pydantic import BaseModel
from typing import List, Optional
from joblib import load

class PredictionRequest(BaseModel):
    feature_vector: List[float]
    score: Optional[bool] = False

clf = load('service/model.joblib')

app = FastAPI()

@app.post("/prediction")
def predict(request: PredictionRequest):
    response = {}

    prediction = clf.predict([request.feature_vector])
    response["is_inlier"] = int(prediction[0])

    if request.score:
        scores = clf.score_samples([request.feature_vector])
        response["anomaly_score"] = scores[0]

    return response

@app.get("/model_information")
def model_information():
    return clf.get_params()

if __name__ == "__main__":
    uvicorn.run(app, host="0.0.0.0", port=8000)


import os
import datetime
import time
from threading import Thread
from collections import deque
from misc import Direction
import json

class State:
    def __init__(self, dispatcher):
        self.dispatcher = dispatcher
        self.buffer = deque(maxlen=128)
        self.state = {}
        self.stateFile = None
        self.enable = self.checkSdCardPresence()
        self.enableDateCheck = False #always false in this version

        self.state["display"] = {
                "display1": {
                    "type": "display", "connection": "display1",
                    "payload": {
                        "screen1": {}, "screen2": {}, "screen3": {}, "screen4": {},
                        "leds": {}, "backlight": {}, "sound": {}, "icons": {},
                    }
                },
                "display2": {
                    "type": "display", "connection": "display2",
                    "payload": {
                        "screen1": {}, "screen2": {}, "screen3": {}, "screen4": {},
                        "leds": {}, "backlight": {}, "sound": {}, "icons": {},
                    }
                },
                "display3": {
                    "type": "display", "connection": "display3",
                    "payload": {
                        "screen1": {}, "screen2": {}, "screen3": {}, "screen4": {},
                        "leds": {}, "backlight": {}, "sound": {}, "icons": {},
                    }
                },
            }
        self.state["gpio"] = {}
        self.state["led"] = {}

        if self.enable and self.thereIsStateToLoad():
            self.loadState()

        if self.enable:
            self._thread = Thread(target = self.stateThread)
            self._thread.start()

    def checkSdCardPresence(self):
        if os.path.exists("/dev/mmcblk0p1"):
            print(" [*] Sd card present.")
            return True
        else:
            print(" [*] Sd card NOT present. Save State disabled.")
            return False

        return False

    def openStateFile(self):
        try:
            self.stateFile = open("/media/state.json", "w+")
        except Exception as e:
            print(e)
            self.enable = False

    def thereIsStateToLoad(self):
        if os.path.isfile("/media/state.json"):
            if os.path.getsize("/media/state.json") > 0:
                print(" [*] There is state to load")
                return True

        print(" [*] No state to load")
        return False

    def loadState(self):
        try:
            stateFile = open("/media/state.json", "r")
            config = json.load(stateFile)
            stateFile.close()
            #print(config)

            self.state = config

            if self.enableDateCheck == True:
                if "date" in config:
                    configDate = datetime.datetime.strptime(config["date"], '%Y-%m-%d %H:%M:%S.%f')
                    timePassed = datetime.datetime.now() - configDate

                    if c.total_seconds() < 5*60:
                        print(" [*] The state will be loaded. Hard reboot detected less than 5 minutes ago.")
                    else:
                        print(" [*] The state won't be loaded. Hard reboot detected more than 5 minutes ago.")
                        return

            if "display1" in config["display"]:
                self.dispatcher(config["display"]["display1"], Direction.ToDisplays, save=False)
                print(" [*] Loading Display 1 state")
            if "display2" in config["display"]:
                self.dispatcher(config["display"]["display2"], Direction.ToDisplays, save=False)
                print(" [*] Loading Display 1 state")
            if "display3" in config["display"]:
                self.dispatcher(config["display"]["display3"], Direction.ToDisplays, save=False)
                print(" [*] Loading Display 1 state")
            if "gpio1" in config["gpio"]:
                self.dispatcher(config["gpio"]["gpio1"], Direction.ToGpios, save=False)
                print(" [*] Loading Gpio 1 state")
            if "gpio2" in config["gpio"]:
                self.dispatcher(config["gpio"]["gpio2"], Direction.ToGpios, save=False)
                print(" [*] Loading Gpio 2 state")
            if "gpio3" in config["gpio"]:
                self.dispatcher(config["gpio"]["gpio3"], Direction.ToGpios, save=False)
                print(" [*] Loading Gpio 3 state")
            if "gpio4" in config["gpio"]:
                self.dispatcher(config["gpio"]["gpio4"], Direction.ToGpios, save=False)
                print(" [*] Loading Gpio 4 state")
            if "gpio5" in config["gpio"]:
                self.dispatcher(config["gpio"]["gpio5"], Direction.ToGpios, save=False)
                print(" [*] Loading Gpio 5 state")
            if "gpio6" in config["gpio"]:
                self.dispatcher(config["gpio"]["gpio6"], Direction.ToGpios, save=False)
                print(" [*] Loading Gpio 6 state")
            if "led1" in config["led"]:
                self.dispatcher(config["led"]["led1"], Direction.ToLeds, save=False)
                print(" [*] Loading Led 1 state")
            if "led2" in config["led"]:
                self.dispatcher(config["led"]["led2"], Direction.ToLeds, save=False)
                print(" [*] Loading Led 2 state")
            if "led3" in config["led"]:
                self.dispatcher(config["led"]["led3"], Direction.ToLeds, save=False)
                print(" [*] Loading Led 3 state")

        except Exception as e:
            print(e)
            print(" [x] Could not load the saved State")

    def stateThread(self):
        save = False

        while 1:
            while len(self.buffer) > 0:
                message = self.buffer.popleft()

                self.state["date"] = str(datetime.datetime.now())

                if "type" in message:
                    if message["type"] == "display":
                        self.saveDisplay(message)
                        save = True
                    elif message["type"] == "gpio":
                        self.saveGpio(message)
                        save = True
                    elif message["type"] == "led":
                        self.saveLed(message)
                        save = True

            if save:
                self.writeStateToFile()
                save = False

            time.sleep(0.5)

    def saveLed(self, message):
        if message["connection"] == "led1":
            self.state["led"]["led1"] = message
        elif message["connection"] == "led2":
            self.state["led"]["led2"] = message
        elif message["connection"] == "led3":
            self.state["led"]["led3"] = message

    def saveDisplay(self, message):
        disp_name =  message["connection"]

        self.state["display"][disp_name]["type"] = "display"
        self.state["display"][disp_name]["connection"] = disp_name
        if "screen1" in message["payload"]: self.state["display"][disp_name]["payload"]["screen1"].update(message["payload"]["screen1"])
        if "screen2" in message["payload"]: self.state["display"][disp_name]["payload"]["screen2"].update(message["payload"]["screen2"])
        if "screen3" in message["payload"]: self.state["display"][disp_name]["payload"]["screen3"].update(message["payload"]["screen3"])
        if "screen4" in message["payload"]: self.state["display"][disp_name]["payload"]["screen4"].update(message["payload"]["screen4"])
        if "icons" in message["payload"]: self.state["display"][disp_name]["payload"]["icons"].update(message["payload"]["icons"])
        if "leds" in message["payload"]: self.state["display"][disp_name]["payload"]["leds"].update(message["payload"]["leds"])
        if "backlight" in message["payload"]: self.state["display"][disp_name]["payload"]["backlight"].update(message["payload"]["backlight"])
        if "sound" in message["payload"]: self.state["display"][disp_name]["payload"]["sound"].update(message["payload"]["sound"])

    def saveGpio(self, message):
        if message["connection"] == "gpio1":
            self.state["gpio"]["gpio1"] = message
        elif message["connection"] == "gpio2":
            self.state["gpio"]["gpio2"] = message
        elif message["connection"] == "gpio3":
            self.state["gpio"]["gpio3"] = message
        elif message["connection"] == "gpio4":
            self.state["gpio"]["gpio4"] = message
        elif message["connection"] == "gpio5":
            self.state["gpio"]["gpio5"] = message
        elif message["connection"] == "gpio6":
            self.state["gpio"]["gpio6"] = message

    def writeStateToFile(self):
        try:
            stateFile = open("/media/state.json", "w+")
            stateFile.truncate(0)
            stateFile.write(json.dumps(self.state))
            stateFile.close()
        except Exception as e:
            print(e)
            print(" [x] Error writing to State file!")

    def saveState(self, message):
        self.buffer.append(message)


produtos = ('Teclado', 30,'Mouse', 25, 'Tela', 150, 'Pen-Drive', 60, 'Mouse-Pad', 20)

P = produtos

print('      -lista de Produtos-')

for n in range(len(P)):
    if n % 2 == 0:
        print(f'{P[n]:.<20}', end='')
    else:
        print(f'R$ {P[n]:.2f}')


import tensorflow as tf
import numpy as np

bandits = [0.2, 0, -0.2, -5]
num_bandits = len(bandits)

def pullBandit(band):
    rand = np.random.randn(1)
    if rand > band:
        return 1
    else:
        return -1

tf.compat.v1.reset_default_graph()

W = tf.Variable(tf.ones([num_bandits]))

chosen_action = tf.argmax(W,0)

reward_holder = tf.compat.v1.placeholder(dtype=tf.float32, shape=[1])
action_holder = tf.compat.v1.placeholder(dtype=tf.int32, shape=[1])
responsible_action = tf.slice(W, action_holder, [1])
loss = -(tf.math.log(responsible_action) * reward_holder)
optimizer = tf.compat.v1.train.GradientDescentOptimizer(0.001)
update = optimizer.minimize(loss)

num_steps = 1000

e = 0.3 # Chance of picking a random action

init = tf.compat.v1.global_variables_initializer()

with tf.compat.v1.Session() as sess:
    init.run()
    i = 0
    while i < num_steps:
        if np.random.rand(1) < e:
            act = np.random.randint(num_bandits)
        else:
            act = sess.run(chosen_action)
        reward = pullBandit(bandits[act])
        _,rw,w = sess.run([update, responsible_action, W], feed_dict = {
            reward_holder: [reward],
            action_holder: [act]
        })
        if i % 100 == 0:
            print(w)
        i+=1
    print(w)

print("Done")


#!/usr/bin/env python3
"""
Unit tests for UpdatableProcess class

Automation of MitM Attack on WiFi Networks
Bachelor's Thesis UIFS FIT VUT
Martin Vondracek
2016
"""
import typing as _typing
import unittest as _unittest

from wifimitm.updatableProcess import UpdatableProcess

class TestUpdatableProcess(_unittest.TestCase):
    def __init__(self, methodName='runTest'):
        super().__init__(methodName)
        self.process = None  # type: _typing.Optional[UpdatableProcess]

    @classmethod
    def setUpClass(cls):
        # logging.basicConfig(format='[%(asctime)s] %(funcName)s: %(message)s', level=logging.DEBUG)
        # logging.captureWarnings(True)
        # warnings.simplefilter('always', ResourceWarning)
        cls.continuously_running_cmd = ['ping', '127.0.0.1']

    def tearDown(self):
        if self.process and issubclass(type(self.process), UpdatableProcess):
            self.process.cleanup()
            del self.process

    class UpdatableProcessSubclass(UpdatableProcess):
        def update(self):
            super().update()

    def test_abc(self):
        with self.assertRaisesRegex(TypeError, "Can't instantiate abstract class UpdatableProcess"):
            self.process = UpdatableProcess(self.continuously_running_cmd)

    def test_update(self):
        self.process = self.UpdatableProcessSubclass(self.continuously_running_cmd)
        self.process.cleanup()
        with self.assertRaisesRegex(ValueError, "Can't call update on process after cleanup was performed."):
            self.process.update()

    def test_stop1(self):
        self.process = self.UpdatableProcessSubclass(self.continuously_running_cmd)
        self.process.stop()
        self.assertIsNotNone(self.process.poll(), 'Process did not stopped on stop.')

    def test_stop2(self):
        self.process = self.UpdatableProcessSubclass(self.continuously_running_cmd)
        self.process.cleanup()
        with self.assertRaisesRegex(ValueError, "Can't call stop on process after cleanup was performed."):
            self.process.stop()

    def test_cleanup(self):
        self.process = self.UpdatableProcessSubclass(self.continuously_running_cmd)
        self.process.cleanup()

        self.assertIsNotNone(self.process.poll(), 'Process did not stopped on cleanup.')
        self.assertFalse(self.process._finalizer.alive)
        self.assertIsNone(self.process.stdout)
        self.assertTrue(self.process.stdout_r.closed)
        self.assertTrue(self.process.stdout_w.closed)
        self.assertIsNone(self.process.stderr)
        self.assertTrue(self.process.stderr_r.closed)
        self.assertTrue(self.process.stderr_w.closed)
        self.assertTrue(self.process.cleaned)

    def test___enter__(self):
        with self.UpdatableProcessSubclass(self.continuously_running_cmd) as self.process:
            self.assertIsNone(self.process.poll(), 'Process did not started on __enter__.')
            self.process.stop()

    def test___exit__(self):
        with self.UpdatableProcessSubclass(self.continuously_running_cmd) as self.process:
            self.process.stop()
        self.assertIsNotNone(self.process.poll(), 'Process did not stopped on __exit__.')
        self.assertTrue(self.process.cleaned, 'Process did not clean on __exit__.')

    def test__del__1(self):
        with self.assertWarnsRegex(ResourceWarning,
                                   'Process {} was not stopped correctly. Stopping it by destructor, which is not'
                                   ' always safe!'.format(self.UpdatableProcessSubclass.__name__)):
            self.process = self.UpdatableProcessSubclass(self.continuously_running_cmd)
            self.process = 'replacement'

    def test__del__2(self):
        with self.assertWarnsRegex(ResourceWarning,
                                   'Process {} was not stopped correctly. Stopping it by destructor, which is not'
                                   ' always safe!'.format(self.UpdatableProcessSubclass.__name__)):
            self.process = self.UpdatableProcessSubclass(self.continuously_running_cmd)
            del self.process
            self.process = None


import sys
import datetime

from PycnometerUi import *
from addPycnometerUi import *

from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
from PyQt5.QtSql import *

class Pycnometer(QWidget):
    def __init__(self, parent=None):
        QWidget.__init__(self, parent)
        self.pycno = Ui_DBPycnometer()
        self.pycno.setupUi(self)
        self.connectDb()
        self.loadPycnometer()

        self.pycno.pushButtonAdd.clicked.connect(self.pushButtonAddClicked)
        self.pycno.pushButtonUpdate.clicked.connect(self.pushButtonUpdateClicked)
        self.pycno.pushButtonDelete.clicked.connect(self.pushButtonDeleteClicked)

    def pushButtonAddClicked(self):
        self.setAdd()

        if self.qdialog.exec_() == QDialog.Accepted:
            pycnoId = self.ui.lineEditRingId.text()
            pycnoWeight = self.ui.lineEditWeightRing.text()
            pycnoValM = self.ui.lineEditDiameterRing.text()
            pycnoValN = self.ui.lineEditThickRing.text()
            currentTime = self.currentTime()
            query = QSqlQuery()
            query.prepare(
                    "INSERT INTO tPycnometer (ROWID, idPycno, weightPycno, valMPycno, valNPycno, datePycno)"
                    "VALUES (?, ?, ?, ?, ?, ?)"
            )
            query.bindValue(0, None)
            query.bindValue(1, pycnoId)
            query.bindValue(2, pycnoWeight)
            query.bindValue(3, pycnoValM)
            query.bindValue(4, pycnoValN)
            query.bindValue(5, str(currentTime))
            query.exec_()
            self.loadPycnometer()

    def pushButtonUpdateClicked(self):
        self.setAdd()

        pycnoId = self.pycno.tableWidget.item(self.pycno.tableWidget.currentRow(), 0).text()
        rowId = self.getRowId(pycnoId)
        pycnoWeight = self.pycno.tableWidget.item(self.pycno.tableWidget.currentRow(), 1).text()
        pycnoValM = self.pycno.tableWidget.item(self.pycno.tableWidget.currentRow(), 2).text()
        pycnoValN = self.pycno.tableWidget.item(self.pycno.tableWidget.currentRow(), 3).text()

        self.ui.lineEditRingId.setText(pycnoId)
        self.ui.lineEditWeightRing.setText(pycnoWeight)
        self.ui.lineEditDiameterRing.setText(pycnoValM)
        self.ui.lineEditThickRing.setText(pycnoValN)

        self.ui.lineEditWeightRing.textChanged.connect(lambda x: float(pycnoWeight))
        self.ui.lineEditDiameterRing.textChanged.connect(lambda x: float(pycnoValM))
        self.ui.lineEditThickRing.textChanged.connect(lambda x: float(pycnoValN))

        if self.qdialog.exec_() == QDialog.Accepted:
            pycnoId = self.ui.lineEditRingId.text()
            pycnoWeight = self.ui.lineEditWeightRing.text()
            pycnoValM = self.ui.lineEditDiameterRing.text()
            pycnoValN = self.ui.lineEditThickRing.text()
            currentTime = self.currentTime()
            query = QSqlQuery()
            query.exec_(
                '''
                    UPDATE tPycnometer
                    SET idPycno = '%s', weightPycno = '%s', valMPycno = '%s', valNPycno = '%s', datePycno = '%s'
                    WHERE ROWID = %d
                ''' %
                (
                pycnoId,
                pycnoWeight,
                pycnoValM,
                pycnoValN,
                currentTime,
                rowId
                )
            )
            self.loadPycnometer()

    def pushButtonDeleteClicked(self):
        valIdPycno = self.pycno.tableWidget.item(self.pycno.tableWidget.currentRow(), 0).text()
        rowId = self.getRowId(valIdPycno)
        query = QSqlQuery()
        query.exec_(
            'DELETE FROM tPycnometer WHERE ROWID = %d' % rowId
        )
        self.loadPycnometer()

    def loadPycnometer(self):
        self.pycno.tableWidget.clear()
        self.pycno.tableWidget.setRowCount(self.getRowCount())
        columnHeaders = ['No. Pycno', 'Weight (gr)', 'valM (-)', 'valN (-)', 'Date (-)']
        numberColumn = len(columnHeaders)
        self.pycno.tableWidget.setColumnCount(numberColumn)
        self.pycno.tableWidget.setHorizontalHeaderLabels(columnHeaders)
        self.setColTableWidget()

        query = QSqlQuery()
        row = 0
        query.exec_('VACUUM')
        query.exec_('SELECT * FROM tPycnometer')
        while query.next():
            for i in range(numberColumn):
                item = QTableWidgetItem()
                item.setText(str(query.value(i)))
                self.pycno.tableWidget.setItem(row, i, item)
            row += 1

    def getRowId(self, idPycno):
        query = QSqlQuery()
        query.exec_('SELECT ROWID, * from tPycnometer WHERE idPycno = %d' % int(idPycno))
        query.next()
        rowId = query.value(0)
        return rowId

    def getRowCount(self):
        query = QSqlQuery()
        query.exec_('SELECT COUNT(*) FROM tPycnometer')
        query.next()
        rowCount = query.value(0)
        return rowCount

    def connectDb(self):
        db = QSqlDatabase.addDatabase('QSQLITE')
        db.setDatabaseName('./Database/dbLab')
        if db.open():
            print(db.isOpen())
        else:
            print('error')
            sys.exit(1)

    def setAdd(self):
        self.qdialog = QtWidgets.QDialog()
        self.ui = Ui_addPycnometer()
        self.ui.setupUi(self.qdialog)
        self.qdialog.show()

    def currentTime(self):
        return datetime.date.today()

    def setColTableWidget(self):
        self.pycno.tableWidget.setColumnWidth(0, 80)
        self.pycno.tableWidget.setColumnWidth(1, 100)
        self.pycno.tableWidget.setColumnWidth(2, 80)
        self.pycno.tableWidget.setColumnWidth(3, 80)
        self.pycno.tableWidget.setColumnWidth(4, 80)
        self.pycno.tableWidget.horizontalHeader().setStretchLastSection(True)

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

    main = Pycnometer()
    main.show()

    app.exec_()


import socket
import subprocess
import zlwLog

def get_local_ip():
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    try:
        s.connect(('8.8.8.8', 1))
        locale_ip = s.getsockname()[0]
    except:
        locale_ip = ''
    finally:
        s.close()
    return locale_ip

# 服务端，执行命令端
def start_server(IP):
    log = zlwLog.logging_setting()
    while 1:
        # 创建socket对象
        servers = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        # 将socket绑定到指定的地址和端口号
        servers.bind((IP, 6565))
        # 监听客户端链接操作
        servers.listen(1)
        log.info('等待用户接入....')
        client_socket, client_address = servers.accept()
        log.info('用户{}已接入'.format(client_address))
        data = client_socket.recv(1024)
        # 没有数据返回
        if not data:
            log.info('用户{}已关闭连接'.format(client_address))
            servers.close()
            continue
        try:
            result = subprocess.run(data.decode().split(), stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=5)
            cmds = ''
            for c in result.args: cmds += str(c) + ' '
            cmds = "[" + cmds + "]"
            log.info("用户{}-输入: {},输出: ->\n{}".format(client_address,cmds,result.stdout.decode('utf-8')))
            client_socket.sendall(result.stdout)
            servers.close()
        except subprocess.TimeoutExpired:
            log.error('此命令可能是一个终端命令，等待执行完成超过5s自动已自动退出！！！')
            client_socket.sendall('此命令可能是一个终端命令，等待执行完成超过5s自动已自动退出！！！'.encode())
            servers.close()
            continue
        except FileNotFoundError:
            log.error('命令错误，请查正重试！！')
            client_socket.sendall('命令错误，请查正重试！！'.encode())
            servers.close()
            continue

# 按间距中的绿色按钮以运行脚本。
if __name__ == '__main__':
    start_server(get_local_ip())


import pickle
import streamlit as st
from newspaper import Article
import re
import nltk
from nltk import word_tokenize
from nltk.corpus import stopwords
from nltk.stem import PorterStemmer
from sklearn.feature_extraction.text import TfidfVectorizer

nltk.download('punkt')
nltk.download('stopwords')

# Load the logistic regression model
filename = 'logistic_regression_model.pkl'
loaded_model = pickle.load(open(filename, 'rb'))

# Load the TF-IDF vectorizer
filename2 = 'tfidf_vectorizer.pkl'
tfidf_vectorizer = pickle.load(open(filename2, 'rb'))

# Initialize the Porter stemmer
stemmer = PorterStemmer()

# Load the set of English stopwords
stop_words = set(stopwords.words('english'))

def preprocess_text(text):
    """
    Preprocess the text by tokenizing, removing stopwords, and performing stemming.
    """
    # Tokenize the text
    tokens = nltk.word_tokenize(text)

    # Remove stop words and perform stemming
    processed_text = [stemmer.stem(word) for word in tokens if word.lower() not in stop_words]

    # Join the processed words back into a single string
    processed_text = ' '.join(processed_text)

    return processed_text

def summarize(url):
    # Retrieve the news article from the given URL, display its details, summary, and sentiment analysis.
    try:
        article = Article(url)
        article.download()
        article.parse()
        article.nlp()

        # Display the article details
        st.subheader('Article Details')
        st.write('Title:', article.title)
        st.write('Authors:', ', '.join(article.authors))
        st.write('Publication Date:', str(article.publish_date))

        # Display the article summary
        st.subheader('Summary')
        st.write(article.summary)

        # Perform sentiment analysis on the article summary
        st.subheader('Sentiment Analysis')
        preprocessed_text = preprocess_text(article.summary)  # Preprocess the news summary
        X_new_tfidf = tfidf_vectorizer.transform([preprocessed_text])  # Transform the preprocessed text using TF-IDF vectorizer
        y_pred = loaded_model.predict(X_new_tfidf)  # Use the loaded model to make predictions
        st.write('Sentiment:', y_pred[0])

    except:
        # Display "Invalid URL" message
        st.error('Invalid URL')

# Create the main Streamlit app
def main():
    # Set the page title
    st.title("News Summarizer")

    # URL Input
    url = st.text_input('Enter the URL of the news article')

    # Summarize Button
    if st.button('Summarize'):
        if url:
            summarize(url)
        else:
            st.warning('Please enter a URL.')

if __name__ == '__main__':
    main()


import unittest
from gerel.genome.edge import Edge
from gerel.genome.node import Node
import itertools
from gerel.genome.factories import dense, minimal, copy, from_genes
import numpy as np

class TestGenomeFactories(unittest.TestCase):
    def setUp(self):
        # reset innovation number
        Node.innov_iter = itertools.count()
        Edge.innov_iter = itertools.count()
        Node.registry = {}
        Edge.registry = {}

    def test_dense_factory(self):
        from gerel.algorithms.RES.population import RESPopulation
        from gerel.algorithms.RES.mutator import RESMutator
        from gerel.populations.genome_seeders import curry_genome_seeder

        genome = dense(
            input_size=1,
            output_size=1,
            layer_dims=[4]
        )

        weights_len = len(genome.edges) + len(genome.nodes)
        init_mu = np.random.uniform(-1, 1, weights_len)

        mutator = RESMutator(
            initial_mu=init_mu,
            std_dev=0.1,
            alpha=0.1
        )

        seeder = curry_genome_seeder(
            mutator=mutator,
            seed_genomes=[genome]
        )

        RESPopulation(
            population_size=1,
            genome_seeder=seeder
        )

    def test_minimal_factory(self):
        g = minimal(input_size=2, output_size=3, depth=5)

        # Check correct nodes
        self.assertEqual(len(g.inputs), 2)
        self.assertEqual(len(g.nodes), 1)
        self.assertEqual(len(g.outputs), 3)
        for node in g.inputs:
            self.assertEqual(node.layer_num, 0)
        for node in g.outputs:
            self.assertEqual(node.layer_num, len(g.layers) - 1)
        self.assertEqual(len(g.layers), 7)

        # check central connecting node edges
        self.assertEqual(
            g.layer_edges_in(layer_num=6),
            g.layer_edges_out(layer_num=1)
        )
        self.assertEqual(
            g.layer_edges_in(layer_num=1),
            g.layer_edges_out(layer_num=0)
        )

    def test_copy_factory(self):
        g = minimal()
        n2 = g.add_node(3)
        g.add_edge(g.layers[0][0], n2)
        g.add_edge(n2, g.outputs[0])
        g_copy = copy(g)
        self.assertNotEqual(g_copy, g)
        for node_copy, node in zip(g_copy.nodes, g.nodes):
            self.assertEqual(node_copy.innov, node.innov)

        for layer_copy, layer in zip(g_copy.layers, g.layers):
            self.assertEqual(len(layer_copy), len(layer))
            for node_copy, node in zip(layer_copy, layer):
                self.assertNotEqual(node_copy, node)
                self.assertEqual(node_copy.innov, node.innov)
                self.assertEqual(len(node_copy.edges_in), len(node.edges_in))
                self.assertEqual(len(node_copy.edges_out), len(node.edges_out))

        for edge_copy, edge in zip(g_copy.edges, g.edges):
            self.assertNotEqual(edge_copy, edge)
            self.assertEqual(edge_copy.innov, edge.innov)

    def test_from_genes_constructor(self):
        g = minimal(input_size=2, output_size=3, depth=5)
        n2 = g.add_node(4)
        g.add_edge(g.layers[0][0], n2)
        g.add_edge(n2, g.outputs[0])
        n2 = g.add_node(3)
        g.add_edge(g.layers[0][1], n2)
        g.add_edge(n2, g.outputs[2])
        n2 = g.add_node(3)
        g.add_edge(g.layers[0][0], n2)
        g.add_edge(n2, g.outputs[2])

        edges = [e.to_reduced_repr for e in g.edges]
        nodes = [n.to_reduced_repr for n in g.nodes]
        g_2 = from_genes(
            nodes,
            edges,
            input_size=2,
            output_size=3,
            depth=5)

        self.assertEqual(
            [[n.to_reduced_repr for n in layer] for layer in g_2.layers],
            [[n.to_reduced_repr for n in layer] for layer in g.layers]
        )

        self.assertEqual(
            [edge.to_reduced_repr for edge in g_2.edges],
            [edge.to_reduced_repr for edge in g.edges]
        )


from azure.core.credentials import AzureKeyCredential
from azure.ai.formrecognizer import FormRecognizerClient
import os

form_recognizer_client = FormRecognizerClient(endpoint="https://<>.cognitiveservices.azure.com/", credential=AzureKeyCredential("<key>"))

def recognize_content(filename):
    with open(filename, "rb") as source:
        poller = form_recognizer_client.begin_recognize_content(form=source)
    form_pages = poller.result()

    aer_selection = []
    #page = form_pages[0]
    for page in form_pages:
        for table in page.tables:
            for cell in table.cells:
                print("Cell[{}][{}] has text '{}'".format(
                    cell.row_index,
                    cell.column_index,
                    cell.text
                ))
                if cell.field_elements:
                    for element in cell.field_elements:
                        if element.kind == "selectionMark":
                            print("...Checkbox in cell is '{}' and has confidence of {}".format(
                                element.state, element.confidence
                            ))
                            if element.state == "selected" and element.confidence > 0.8:
                                aer_selection.append(cell.text)
        print("nAER Selection: {}".format(aer_selection))

filepath = "Path to Folder that contains documents"
for file in os.listdir(filepath):
    print("filename:" + file)
    recognize_content(file)


def solution(begin, target, words):
    global answer,result

    if target not in words:
        return 0
    answer = 21e8
    used = [0]*len(words)
    result = 0
    def dfs(change):
        global result,answer
        if change == target:
            if result < answer:
                answer = result
            return
        for i in range(len(words)):
            cnt = 0
            for j in range(len(change)):
                if used[i] == 0:
                    if change[j] != words[i][j]:
                        cnt += 1
            if cnt == 1:
                used[i] = 1
                result += 1
                dfs(words[i])
                used[i] = 0
                result -= 1
    dfs(begin)
    return answer


import re
from flask import request, jsonify, url_for, g
from app import db
from app.api import bp
from app.api.auth import token_auth
from app.api.errors import bad_request
from app.models import Houses, Gardens, Buildings, Houseitems, Choices, Customers, Villages, Labels, Contracts
from flask_babel import gettext as _
from datetime import datetime
from sqlalchemy import func
import time
import math

@bp.route('/dashboard', methods=['GET'])
@token_auth.login_required
def get_charts_data():
	'''返回图书记录集合，分页'''

	customers = Customers.query.join(Villages, Customers.village_id == Villages.id).with_entities(func.count(Customers.id), Villages.name).group_by(Villages.name).all()
	customers_pin_chart = {
		'series': [],
		'chartoptions_labels': []
	}
	for c in customers:
		customers_pin_chart['series'].append(c[0])
		customers_pin_chart['chartoptions_labels'].append(c[1])

	houses_bar = Houses.query\
		.join(Houseitems, Houses.houseitem_id == Houseitems.id)\
		.join(Buildings, Houses.building_id == Buildings.id)\
		.join(Gardens, Buildings.garden_id == Gardens.id)\
		.with_entities(func.count(Houses.id), Gardens.short_name, Buildings.name).group_by(Gardens.short_name, Buildings.name).all()

	houses_bar_chart = {
		'series_data': [],
		'chartoptions_xaxis_categories': []
	}

	for h in houses_bar:
		houses_bar_chart['series_data'].append(h[0])
		houses_bar_chart['chartoptions_xaxis_categories'].append([h[1], h[2] + '幢'])

	houses_bar_stack = Houses.query\
		.join(Houseitems, Houses.houseitem_id == Houseitems.id)\
		.join(Buildings, Houses.building_id == Buildings.id)\
		.join(Gardens, Buildings.garden_id == Gardens.id)\
		.with_entities(func.count(Houses.id), Gardens.short_name, Houses.status).group_by(Gardens.short_name, Houses.status).all()

	temp_dict = {}
	for h in houses_bar_stack:
		if h[1] not in temp_dict:
			temp_dict[h[1]] = {}
		if h[2] == 0:
			temp_dict[h[1]]['free'] = h[0]
		if h[2] == 1:
			temp_dict[h[1]]['occupied'] = h[0]

	houses_bar_stack_chart = {
		'series_data_01': [],
		'series_data_02': [],
		'chartoptions_xaxis_categories': []
	}

	for i in temp_dict:
		if 'free' in temp_dict[i]:
			houses_bar_stack_chart['series_data_01'].append(temp_dict[i]['free'])
		else:
			houses_bar_stack_chart['series_data_01'].append(0)

		if 'occupied' in temp_dict[i]:
			houses_bar_stack_chart['series_data_02'].append(temp_dict[i]['occupied'])
			# total = temp_dict[i]['free'] + temp_dict[i]['occupied']
		else:
			houses_bar_stack_chart['series_data_02'].append(0)

		# houses_bar_stack_chart['chartoptions_xaxis_categories'].append(i + '共 ' + str(total) + ' 套')
		houses_bar_stack_chart['chartoptions_xaxis_categories'].append(i)

	houses = Houses.query.with_entities(func.count(Houses.id), Houses.check_flag).group_by(Houses.check_flag).all()
	labels = Labels.query.with_entities(func.count(Labels.id), Labels.check_flag).group_by(Labels.check_flag).all()
	customers01 = Customers.query.filter(Customers.batch_code=='01').with_entities(func.count(Customers.id), Customers.check_flag).group_by(Customers.check_flag).all()
	# customers02 = Customers.query.filter(Customers.batch_code=='02').with_entities(func.count(Customers.id), Customers.check_flag).group_by(Customers.check_flag).all()
	# customers03 = Customers.query.filter(Customers.batch_code=='03').with_entities(func.count(Customers.id), Customers.check_flag).group_by(Customers.check_flag).all()

	labels_check_in_chart = {
		'series_data_01': [],
		'series_data_02': [],
		'chartoptions_xaxis_categories': []
	}

	customers_check_in_chart = {
		'series_data_01': [],
		'series_data_02': [],
		'chartoptions_xaxis_categories': []
	}

	for h in houses:
		if h[1] == 0:
			labels_check_in_chart['series_data_01'].append(h[0])
		else:
			labels_check_in_chart['series_data_02'].append(h[0])

	for l in labels:
		if l[1] == 0:
			labels_check_in_chart['series_data_01'].append(l[0])
		else:
			labels_check_in_chart['series_data_02'].append(l[0])

	for c in customers01:
		if c[1] == 0:
			customers_check_in_chart['series_data_01'].append(c[0])
		else:
			customers_check_in_chart['series_data_02'].append(c[0])

	# for c in customers02:
	# 	if c[1] == 0:
	# 		customers_check_in_chart['series_data_01'].append(c[0])
	# 	else:
	# 		customers_check_in_chart['series_data_02'].append(c[0])

	# for c in customers03:
	# 	if c[1] == 0:
	# 		customers_check_in_chart['series_data_01'].append(c[0])
	# 	else:
	# 		customers_check_in_chart['series_data_02'].append(c[0])

	labels_check_in_chart['chartoptions_xaxis_categories'] = ['房源', '号签']
	customers_check_in_chart['chartoptions_xaxis_categories'] = ['户主01']

	customers = Customers.query.filter(Customers.is_done == 1).order_by(Customers.last_update).all()

	cusotmers_dict = {}
	for c in customers:
		k = (round(c.last_update.timestamp()//60 * 60, 0) + 28800)* 1000 		#8小时时差
		print(k)
		if k not in cusotmers_dict:
			cusotmers_dict[k] = 0
		cusotmers_dict[k] += 1

	cusotmers_list = []
	for i in cusotmers_dict:
		cusotmers_list.append([i, cusotmers_dict[i]])

	# contracts = Contracts.query.order_by(Contracts.create_at).all()

	# cusotmers_dict = {}
	# for c in contracts:
	# 	k = (round(c.last_update.timestamp()//60 * 60, 0) + 28800)* 1000 		#8小时时差
	# 	print(k)
	# 	if k not in cusotmers_dict:
	# 		cusotmers_dict[k] = 0
	# 	cusotmers_dict[k] += 1

	# cusotmers_list = []
	# for i in cusotmers_dict:
	# 	cusotmers_list.append([i, cusotmers_dict[i]])

	customers_stock_chart = {
		'data': cusotmers_list
	}

	# 房源状态统计
	houses = Houses.query.all()
	temp_house_status_chart = {}
	for h in houses:
		garden_id = h.houseitem.building.garden_id
		if garden_id not in temp_house_status_chart:
			temp_house_status_chart[garden_id] = {}
		if h.houseitem.area < 65:
			if 65 not in temp_house_status_chart[garden_id]:
				temp_house_status_chart[garden_id][65] =  {}
			if h.status not in temp_house_status_chart[garden_id][65]:
				temp_house_status_chart[garden_id][65][h.status] = 0
			temp_house_status_chart[garden_id][65][h.status] += 1

		elif h.houseitem.area < 80:
			if 80 not in temp_house_status_chart[garden_id]:
				temp_house_status_chart[garden_id][80] = {}
			if h.status not in temp_house_status_chart[garden_id][80]:
				temp_house_status_chart[garden_id][80][h.status] = 0
			temp_house_status_chart[garden_id][80][h.status] += 1

		elif h.houseitem.area < 90:
			if 90 not in temp_house_status_chart[garden_id]:
				temp_house_status_chart[garden_id][90] = {}
			if h.status not in temp_house_status_chart[garden_id][90]:
				temp_house_status_chart[garden_id][90][h.status] = 0
			temp_house_status_chart[garden_id][90][h.status] += 1

		elif h.houseitem.area < 100:
			if 100 not in temp_house_status_chart[garden_id]:
				temp_house_status_chart[garden_id][100] = {}
			if h.status not in temp_house_status_chart[garden_id][100]:
				temp_house_status_chart[garden_id][100][h.status] = 0
			temp_house_status_chart[garden_id][100][h.status] += 1

		elif h.houseitem.area < 110:
			if 110 not in temp_house_status_chart[garden_id]:
				temp_house_status_chart[garden_id][110] = {}
			if h.status not in temp_house_status_chart[garden_id][110]:
				temp_house_status_chart[garden_id][110][h.status] = 0
			temp_house_status_chart[garden_id][110][h.status] += 1

		else:
			if 120 not in temp_house_status_chart[garden_id]:
				temp_house_status_chart[garden_id][120] = {}
			if h.status not in temp_house_status_chart[garden_id][120]:
				temp_house_status_chart[garden_id][120][h.status] = 0
			temp_house_status_chart[garden_id][120][h.status] += 1

	print(temp_house_status_chart)

	house_status_chart = {
		'series_data_01': [],
		'series_data_02': [],
		'chartoptions_xaxis_categories': []
	}

	for garden_id in temp_house_status_chart:
		if garden_id == 1:
			garden_flag = 'H2'
		elif garden_id == 2:
			garden_flag = 'H3'
		else:
			garden_flag = 'X'
		for area in temp_house_status_chart[garden_id]:
			for status in temp_house_status_chart[garden_id][area]:
				key = str(garden_flag) + '_' + str(area)
				if key not in house_status_chart['chartoptions_xaxis_categories']:
					house_status_chart['chartoptions_xaxis_categories'].append(key)
				if status == 0:
					house_status_chart['series_data_01'].append(temp_house_status_chart[garden_id][area][status])
				else:
					house_status_chart['series_data_02'].append(temp_house_status_chart[garden_id][area][status])

	data = {
		'customers_pin_chart': customers_pin_chart,
		'houses_bar_chart': houses_bar_chart,
		'houses_bar_stack_chart': houses_bar_stack_chart,
		'labels_check_in_chart': labels_check_in_chart,
		'customers_check_in_chart': customers_check_in_chart,
		'customers_stock_chart': customers_stock_chart,
		'house_status_chart': house_status_chart
	}

	return jsonify(data)


# Thursday: Reading and Writing Files

from os import system
clear = lambda: system('clear')

clear()     # use it to clean the terminal output

# opening/creating and writng to a text file
f = open('test.txt', 'w+')      # open file in writing and reading mode
f.write('this is a test')
f.close()
# appending a file
f = open('test.txt','a')
f.write('\nOh my God!')
f.close()
# reading from a text file
f = open('test.txt','r')
data = f.read()
f.close()
print(data)

# opening/creating and writing to a csv file
import csv
with open('test.csv', mode='w', newline='') as f:
    writer = csv.writer(f, delimiter=';')
    writer.writerow( ['name', 'city'])
    writer.writerow( ['Craig Lou', 'Taiwan'])

# reading from csv files
with open('test.csv', mode='r') as f:
    reader = csv.reader(f, delimiter=';')
    for row in reader:
        print(row)

# 'r' It opens the file for reading only
# 'w' Opens file for writing. If file doesn't exist, it creates one
# 'x' Creates a new file. If file exist, the operation fails
# 'a' Open in append mode.  If file doesn't exist, it creates one
# 'b' Open in binary mode
# '+' Will open a file for reading and writing. Good for updating

# Thursday Exercises

# User input
number = input('What is your favorite number?: ')
f = open('fNumber.txt', 'w+')
f.write('Favorite number is {}'.format(number))
f.close()
# 3 doritos después
f = open('fnumber.txt', 'r')
data = f.read()
f.close()
print(data)

# Data Dumping
import csv
data = {
    'name': ['Dave', 'Dennis', 'Peter', 'Jess'],
    'language': ['Python', 'C', 'Java', 'Python']
}
with open('langPrg.csv', mode='w', newline='') as f:
    writer = csv.writer(f, delimiter = ';')
    writer.writerow( data.keys())

    for i in range(len(data['name'])):
        writer.writerow( [data['name'][i], data['language'][i]])

with open('langPrg.csv', mode='r') as f:
    reader = csv.reader(f, delimiter = ';')
    for row in reader:
        print(row)


#! /usr/bin/env python3
#------------------------------------------------------------------------------

import sys
import argparse
import os
import re
import subprocess
import base64
#------------------------------------------------------------------------------

def runCmd(cmd, data=None):
    if input is None:
        p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        stdout, stderr = p.communicate()
    else:
        p = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        stdout, stderr = p.communicate(input=data)

    return stdout.decode('utf-8'), stderr.decode('utf-8'), p.returncode
#------------------------------------------------------------------------------

def getDefaultIncludeDirs(cxx):
    cmd = [cxx, '-E', '-x', 'c++', '-v', '/dev/null']
    stdout, stderr, retCode = runCmd(cmd)

    m = re.findall('\n (/.*)', stderr)

    includes = []

    for x in m:
        if -1 != x.find('(framework directory)'):
            continue

        includes.append('-isystem%s' %(x))

    return includes
#------------------------------------------------------------------------------

def replaceSource(match):
    fileName = match.group(2)

    cpp = '<!-- source:%s.cpp -->\n' %(fileName)
    cpp += '```{.cpp}\n'
    cpp += open('examples/%s.cpp' %(fileName), 'r').read().strip()
    cpp += '\n```\n'
    cpp += '<!-- source-end:%s.cpp -->' %(fileName)

    return cpp
#------------------------------------------------------------------------------

def cppinsightsLink(code, std='2a', options=''):
    # currently 20 is not a thing
    if '20' == std:
        print('Replacing 20 by 2a')
        std = '2a'

    # per default use latest standard
    if '' == std:
        std = '2a'

    std = 'cpp' + std

    if options:
        options += ',' + std
    else:
        options = std

    return('https://cppinsights.io/lnk?code=%s&insightsOptions=%s&rev=1.0' %(base64.b64encode(code).decode('utf-8'), options))
#------------------------------------------------------------------------------

def replaceInsights(match, parser, args):
    cppFileName = match.group(2) + '.cpp'

    insightsPath  = args['insights']
    remainingArgs = args['args']
    defaultCppStd = '-std=%s'% (args['std'])

    defaultIncludeDirs = getDefaultIncludeDirs(args['cxx'])
    cpp = '<!-- transformed:%s -->\n' %(cppFileName)
    cpp += 'Here is the transformed code:\n'
    cpp += '```{.cpp}\n'

    cmd = [insightsPath, 'examples/%s' %(cppFileName), '--', defaultCppStd, '-m64']
    stdout, stderr, retCode = runCmd(cmd)

    cpp += stdout

    cppData = open('examples/%s' %(cppFileName), 'r').read().strip().encode('utf-8')

    cpp += '\n```\n'
    cpp += '[Live view](%s)\n' %(cppinsightsLink(cppData))
    cpp += '<!-- transformed-end:%s -->' %(cppFileName)

    return cpp
#------------------------------------------------------------------------------

def main():
    parser = argparse.ArgumentParser(description='Description of your program')
    parser.add_argument('--insights',       help='C++ Insights binary',  required=True)
    parser.add_argument('--cxx',            help='C++ compiler to used', default='/usr/local/clang-current/bin/clang++')
    parser.add_argument('--std',            help='C++ Standard to used', default='c++17')
    parser.add_argument('args', nargs=argparse.REMAINDER)
    args = vars(parser.parse_args())

    insightsPath  = args['insights']
    remainingArgs = args['args']
    defaultCppStd = '-std=%s'% (args['std'])

    print(insightsPath)
    defaultIncludeDirs = getDefaultIncludeDirs(args['cxx'])

    for f in os.listdir('.'):
        if not f.startswith('opt-') or not f.endswith('.md'):
            continue

        optionName = os.path.splitext(f)[0][4:].strip()

        data = open(f, 'r').read()

        cppFileName = 'cmdl-examples/%s.cpp' %(optionName)

        cpp = open(cppFileName, 'r').read().strip()

        data = data.replace('%s-source' %(optionName), cpp)

        cmd = [insightsPath, cppFileName, '--%s' %(optionName), '--', defaultCppStd, '-m64']
        stdout, stderr, retCode = runCmd(cmd)

        data = data.replace('%s-transformed' %(optionName), stdout)

        open(f, 'w').write(data)

    regEx = re.compile('(<!-- source:(.*?).cpp -->(.*?)<!-- source-end:(.*?) -->)', re.DOTALL)
    regExIns = re.compile('(<!-- transformed:(.*?).cpp -->(.*?)<!-- transformed-end:(.*?) -->)', re.DOTALL)

    for f in os.listdir('examples'):
        if not f.endswith('.md'):
            continue

        exampleName = os.path.splitext(f)[0].strip()

        mdFileName = os.path.join('examples', '%s.md' %(exampleName))

        mdData = open(mdFileName, 'r').read()

        mdData = regEx.sub(replaceSource, mdData)

        rpl = lambda match : replaceInsights(match, parser, args)
        mdData = regExIns.sub(rpl, mdData)

        open(mdFileName, 'w').write(mdData)

#------------------------------------------------------------------------------

sys.exit(main())
#------------------------------------------------------------------------------


# -*- coding: utf-8 -*-
"""
Created on Wed Jun  8 20:14:46 2022

@author: User
"""

import unittest
from city_functions import *

class CitiesTestCase(unittest.TestCase):
    def test_city_country(self):
        name = city_country('santiago', 'chile')
        self.assertEqual(name, "Santiago,Chile")
    def city_country(city, country, population):
        output_string = f"{city.title()}, {country.title()}"
        output_string += f" -population {population}"
        return output_string

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