#!/usr/bin/env python3

from pickletools import uint8
import cv2 as cv
import numpy as np
import apriltag
import matplotlib.pyplot as plt

class aprilTagDetector():

		def __init__(self, min_id):

				self.options = apriltag.DetectorOptions(
												families="tag36h11",
												border=1,
												nthreads=4,
												quad_decimate=1.0,
												quad_blur=0.0,
												refine_edges=True,
												refine_decode=False,
												refine_pose=True,
												debug=False,
												quad_contours=True)
				self.detector = apriltag.Detector(self.options)

				self.min_id = min_id

		def preprocess_image(self, img):

				output = cv.cvtColor(img, cv.COLOR_BGR2GRAY)

				return output

		def find_april_tag(self, img):
				gray = self.preprocess_image(img)

				detections = self.detector.detect(gray, return_image=False)

				n = len(detections)

				bbs = []
				ids = []
				for i in range(n):
						tag_id = detections[i].tag_id
						if tag_id >= self.min_id:
							xmin, ymin, xmax, ymax = self.corners_to_bbox(detections[i].corners)

							bbs.append(np.array([xmin, ymin, xmax, ymax]))
							ids.append(tag_id)

				return bbs, ids

		def corners_to_bbox(self, corners):
			x_min, y_min = np.min(corners, axis=0)
			x_max, y_max = np.max(corners, axis=0)
			return (x_min, y_min, x_max, y_max)

		def match_features(self, detections, metric_features):
				n = len(detections)
				img_features = np.array([], dtype=np.float32).reshape(2,0)
				metric_features_ret = np.array([], dtype=np.float32).reshape(4,0)

				for i in range(n):
						tag_id = detections[i].tag_id
						corners = np.transpose(detections[i].corners)

						img_features = np.hstack((img_features, corners))
						metric_features_ret = np.hstack((metric_features_ret, metric_features[:,tag_id*4:(tag_id*4)+4]))

				return img_features, metric_features_ret

def main():
		return

if __name__ == "__main__":
		main()


import requests
from thecampy import utils, models, exceptions

class client:
    def enforce_login(self):
        if not hasattr(self, 'cookie'):
            raise ValueError("로그인이 필요합니다.")

    def login(self, id, password):

        form = {
            "state": 'email-login',
            "autoLoginYn": 'N',
            "userId": id,
            "userPwd": password,
        }

        r = requests.post(
            url= utils.request_url('login/loginA.do'),
            json = True,
            data = form,
            headers = {
            'Content-Type': 'application/x-www-form-urlencoded'
            },
        )

        if (r.status_code != requests.codes.ok):
            raise exceptions.ThecampyReqError('HTTP 에러: {}'.format(r.status_code))

        self.cookie = models.Cookie(r)

        if (self.cookie.iuid == False or self.cookie.token == False):
            raise exceptions.ThecampyException('알 수 없는 에러 {}'.format(r.json()))
        else:
            print('Successfully logged in.')

        return {
            'iuid' : self.cookie.iuid,
            'token' : self.cookie.token
        }

    def add_soldier(self, soldier):
        self.enforce_login()
        form = {
            "missSoldierClassCdNm": soldier.identity, #성분 반환 (예비군인/훈련병)
            "grpCdNm": '육군',
            "missSoldierClassCd": soldier.identity_code,
            "grpCd": '0000010001',#육군
            "name": soldier.name,
            "birth" : soldier.bday,
            "enterDate" : soldier.enlist_date,
        }

        r = requests.post(
            url = utils.request_url('missSoldier/insertDirectMissSoldierA.do'),
            json = True,
            headers = {
                'Content-Type': 'application/x-www-form-urlencoded',
                'Cookie' : "{}; {}".format(self.cookie.iuid, self.cookie.token)
            },
            data = form
        )

        if (r.status_code != requests.codes.ok):
            raise exceptions.ThecampyReqError('HTTP 에러: {}'.format(r.status_code))

        ok_resultCd = ['0000', 'E001']

        if (r.json()['resultCd'] not in ok_resultCd):
            raise exceptions.ThecampyException("알 수 없는 에러: resultCd: {}".format((r.json()['resultCd'])))

        return True

    def get_soldier(self, soldier):
        self.enforce_login()
        form = {
            "name" : soldier.name,
            "birth" : soldier.bday,
            "enterDate" : soldier.enlist_date
        }

        r = requests.post(
            url = utils.request_url('main/cafeCreateCheckA.do'),
            json = True,
            headers = {
                'Content-Type': 'application/x-www-form-urlencoded',
                'Cookie' : "{}; {}".format(self.cookie.iuid, self.cookie.token)
            },
            data = form
        )

        if (r.status_code != requests.codes.ok):
            raise exceptions.ThecampyReqError('HTTP 에러: {}'.format(r.status_code))

        if not r.json():
            raise exceptions.ThecampyReqError('응답값이 없습니다.')

        if len(r.json()['listResult']) == 0:
             raise exceptions.ThecampyValueError("해당하는 훈련병을 찾을 수 없습니다.")

        if r.status_code == 200 and r.json()["resultCd"] != '9999':
            raise exceptions.ThecampyException("알 수 없는 오류")

        self.soldier_code = r.json()['listResult'][0]['traineeMgrSeq']

        soldier.add_soldier_code(self.soldier_code)

        return self.soldier_code

    def send_message(self, soldier, message):
        if soldier.identity != '예비군인/훈련병':
            raise exceptions.ThecampyValueError('예비군인/훈련병에게만 편지를 보낼 수 있습니다.')

        if not soldier.soldier_code:
            raise exceptions.ThecampyValueError('훈련병 식별코드를 받지 못하였습니다.')

        form = {
            'traineeMgrSeq' : soldier.soldier_code,
            'sympathyLetterContent': message.content,
            'sympathyLetterSubject': message.title,
            'boardDiv': 'sympathyLetter',
            'tempSaveYn': 'N',
        }

        r = requests.post(
            url = utils.request_url('consolLetter/insertConsolLetterA.do?'),
            json = True,
            headers = {
                'Content-Type': 'application/x-www-form-urlencoded',
                'Cookie' : "{}; {}".format(self.cookie.iuid, self.cookie.token)
            },
            data = form
        )

        if r.status_code == 200 and r.json()["resultCd"] == '9019':
            raise exceptions.ThecampyException("9019")
        elif r.json()["resultCd"] != '0000':
            raise exceptions.ThecampyException("알 수 없는 오류: resultCd={}".format(r.json()["resultCd"]))

        if (not r.json()):
            raise exceptions.ThecampyReqError('응답값이 없습니다.')

        return True


import sys
lines = sys.stdin.readlines()
for line in lines:
    line = line.strip().split()
    time1 = list(map(int, line[3].split(":")))
    time2 = list(map(int, line[4].split(":")))
    if time2[1] == time1[1]:
        line[3] = "{} hours".format(time2[0]-time1[0])
        line[4] = "0 minutes"
    elif time2[1] > time1[1]:
        line[3] = "{} hours".format(time2[0]-time1[0])
        line[4] = "{} minutes".format(time2[1]-time1[1])
    else:
        t1 = time1[1]-time2[1]
        line[3] = "{} hours".format(time2[0]-time1[0]-1)
        line[4] = "{} minutes".format(60 - t1)
    print(" ".join(line))


import logging
import tensorflow as tf
from cleverhans.attacks import FastGradientMethod
from cnn_gtsrb.dataset.mnist import MnistProvider
from cnn_gtsrb.cnn.model import CNNModel
#logging.basicConfig(level=logging.INFO)

tf.logging.set_verbosity(tf.logging.INFO)

fgsm_params = {'eps': 0.2, 'clip_min': 0., 'clip_max': 1.}

mnist = MnistProvider()
# mnist.dump_images()

cnn = CNNModel(
    image_size=mnist.IMAGE_SIZE,
    classes=mnist.CLASSES,
    model_name='mnist-28x28.1',
    model_dir='tmp/mnist_model-28x28.1',
    conv_layers=[32, 64],
    fc_layer=1024,
)

x, y = cnn.make_inputs()

probs = cnn.make_model(x)
cnn.start_session()
# Not necessary because adv_test will restore the model
# cnn.init_session_and_restore()

fgsm = FastGradientMethod(cnn, sess=cnn.sess)
adv_x = fgsm.generate(x, **fgsm_params)
adv_probs = cnn.make_model(adv_x)

cnn.adv_test(adv_probs, x, y, adv_x, mnist.test_data(size=5000))
# cnn.test(mnist)
cnn.end_session()

#cnn.test(2000, mnist)

# for i in range(100):
#     data, label = gtsrb.next_batch('test')
#     print(data, label)


import pyblish.api

from openpype.pipeline.publish import (
    ValidatePipelineOrder,
    PublishXmlValidationError
)
import openpype.hosts.maya.api.action
from openpype.hosts.maya.api import lib

class ValidateNodeIDs(pyblish.api.InstancePlugin):
    """Validate nodes have a Colorbleed Id.

    When IDs are missing from nodes *save your scene* and they should be
    automatically generated because IDs are created on non-referenced nodes
    in Maya upon scene save.

    """

    order = ValidatePipelineOrder
    label = 'Instance Nodes Have ID'
    hosts = ['maya']
    families = ["model",
                "look",
                "rig",
                "pointcache",
                "animation",
                "yetiRig",
                "assembly"]

    actions = [openpype.hosts.maya.api.action.SelectInvalidAction,
               openpype.hosts.maya.api.action.GenerateUUIDsOnInvalidAction]

    def process(self, instance):
        """Process all meshes"""

        # Ensure all nodes have a cbId
        invalid = self.get_invalid(instance)
        if invalid:
            names = "\n".join(
                "- {}".format(node) for node in invalid
            )
            raise PublishXmlValidationError(
                plugin=self,
                message="Nodes found without IDs: {}".format(invalid),
                formatting_data={"nodes": names}
            )

    @classmethod
    def get_invalid(cls, instance):
        """Return the member nodes that are invalid"""

        # We do want to check the referenced nodes as it might be
        # part of the end product.
        id_nodes = lib.get_id_required_nodes(referenced_nodes=True,
                                             nodes=instance[:])
        invalid = [n for n in id_nodes if not lib.get_id(n)]

        return invalid


import evn as keys
from telegram.ext import *
from telegram.ext.filters import Filters
from telegram.ext.updater import Updater
from telegram.update import Update
from telegram.ext.callbackcontext import CallbackContext
from telegram.ext.commandhandler import CommandHandler
from telegram.ext.messagehandler import MessageHandler
import responses as r
print("Bot Started...")
import os
PORT = int(os.environ.get('PORT', 5000))

def help_command(update,context):
    update.message.reply_text("""

    JUST DIE IT WILL BE HELPFULL

	""")

def handle_message(update ,context):
    text = str(update.message.text).lower()
    response = r.sample_responses(text,update)
    update.message.reply_text(response)

def error(update,context):
    print(f"Update {update} caused error {context.error}")

def start(update: Update, context: CallbackContext):
	update.message.reply_text(
		"Seri Start Athuku Yenna Solla vara???")

# def unknown(update: Update, context: CallbackContext):
	# update.message.reply_text(
		# "Sorry '%s' is not a valid command" % update.message.text)

# def unknown_text(update: Update, context: CallbackContext):
	# update.message.reply_text(
		# "Sorry I can't recognize you , you said '%s'" % update.message.text)

def main():
    updater = Updater(keys.API_KEY,use_context=True)
    dp = updater.dispatcher
    updater.dispatcher.add_handler(CommandHandler('start', start))
    updater.dispatcher.add_handler(CommandHandler('help', help_command))
    # updater.dispatcher.add_handler(MessageHandler(Filters.text, unknown))
    # updater.dispatcher.add_handler(MessageHandler(
	# Filters.command, unknown)) # Filters out unknown commands
    # Filters out unknown messages.
    # updater.dispatcher.add_handler(MessageHandler(Filters.text, unknown_text))
    dp.add_handler(MessageHandler(Filters.text,handle_message))
    dp.add_error_handler(error)

    updater.start_webhook(listen="0.0.0.0",
                          port=int(PORT),
                          url_path=keys.API_KEY)
    # updater.start_polling()
    updater.bot.setWebhook('https://hey-sad-bot.herokuapp.com/' + keys.API_KEY)
    updater.idle()

main()

# $ git add .
# $ git commit -am "make it better"
# $ git push heroku master


"""
0153. Find Minimum in Rotated Sorted Array (Medium)
https://leetcode.com/problems/find-minimum-in-rotated-sorted-array/
"""

class Solution:
    def findMin(self, nums: list[int]) -> int:
        left, right = 0, len(nums) - 1
        while left < right:
            mid = (left + right) // 2
            if nums[mid] > nums[right]:
                left = mid + 1
            else:
                right = mid
        return nums[left]  # or nums[right]

def main():
    s = Solution()
    nums = [3, 4, 5, 1, 2]
    print(f"Input: {nums} \nOutput: {s.findMin(nums)}")
    nums = [4, 5, 6, 7, 0, 1, 2]
    print(f"Input: {nums} \nOutput: {s.findMin(nums)}")
    nums = [11, 13, 15, 17]
    print(f"Input: {nums} \nOutput: {s.findMin(nums)}")

if __name__ == "__main__":
    main()


from unittest import IsolatedAsyncioTestCase
from aries_cloudagent.tests import mock

from ....core.in_memory import InMemoryProfile

from ...base import BaseLedger
from ...multiple_ledger.base_manager import (
    BaseMultipleLedgerManager,
    MultipleLedgerManagerError,
)
from ...indy import IndySdkLedger, IndySdkLedgerPool

from ..ledger_requests_executor import IndyLedgerRequestsExecutor

class TestIndyLedgerRequestsExecutor(IsolatedAsyncioTestCase):
    async def asyncSetUp(self):
        self.profile = InMemoryProfile.test_profile()
        self.context = self.profile.context
        setattr(self.context, "profile", self.profile)
        self.profile.settings["ledger.ledger_config_list"] = [
            {
                "id": "test_prod_1",
                "pool_name": "test_prod_1",
                "is_production": True,
                "genesis_transactions": "genesis_transactions",
            }
        ]
        self.ledger = IndySdkLedger(
            IndySdkLedgerPool("test_prod_1", checked=True), self.profile
        )
        self.profile.context.injector.bind_instance(
            BaseMultipleLedgerManager,
            mock.MagicMock(
                extract_did_from_identifier=mock.MagicMock(
                    return_value="WgWxqztrNooG92RXvxSTWv"
                ),
                lookup_did_in_configured_ledgers=mock.CoroutineMock(
                    return_value=("test_prod_1", self.ledger)
                ),
                get_ledger_inst_by_id=mock.CoroutineMock(return_value=self.ledger),
            ),
        )
        self.profile.context.injector.bind_instance(BaseLedger, self.ledger)
        self.indy_ledger_requestor = IndyLedgerRequestsExecutor(self.profile)

    async def test_get_ledger_for_identifier(self):
        (
            ledger_id,
            ledger_inst,
        ) = await self.indy_ledger_requestor.get_ledger_for_identifier(
            "WgWxqztrNooG92RXvxSTWv:2:schema_name:1.0", 0
        )
        assert ledger_id == "test_prod_1"
        assert ledger_inst.pool.name == "test_prod_1"

    async def test_get_ledger_inst(self):
        ledger_inst = await self.indy_ledger_requestor.get_ledger_inst("test_prod_1")
        assert ledger_inst

    async def test_get_ledger_for_identifier_is_digit(self):
        ledger_id, ledger = await self.indy_ledger_requestor.get_ledger_for_identifier(
            "123", 0
        )
        assert ledger_id is None
        assert ledger == self.ledger

    async def test_get_ledger_for_identifier_x(self):
        self.profile.context.injector.bind_instance(
            BaseMultipleLedgerManager,
            mock.MagicMock(
                extract_did_from_identifier=mock.MagicMock(
                    return_value="WgWxqztrNooG92RXvxSTWv"
                ),
                lookup_did_in_configured_ledgers=mock.CoroutineMock(
                    side_effect=MultipleLedgerManagerError
                ),
            ),
        )
        self.indy_ledger_requestor = IndyLedgerRequestsExecutor(self.profile)
        ledger_id, ledger = await self.indy_ledger_requestor.get_ledger_for_identifier(
            "WgWxqztrNooG92RXvxSTWv:2:schema_name:1.0", 0
        )
        assert ledger_id is None
        assert ledger == self.ledger

    async def test_get_ledger_for_identifier_mult_ledger_not_set(self):
        self.profile.settings["ledger.ledger_config_list"] = None
        self.indy_ledger_requestor = IndyLedgerRequestsExecutor(self.profile)
        ledger_id, ledger = await self.indy_ledger_requestor.get_ledger_for_identifier(
            "WgWxqztrNooG92RXvxSTWv:2:schema_name:1.0", 0
        )
        assert ledger_id is None
        assert ledger == self.ledger

    async def test_get_ledger_for_identifier_mult_ledger_not_cached(self):
        (
            ledger_id,
            ledger_inst,
        ) = await self.indy_ledger_requestor.get_ledger_for_identifier(
            "GUTK6XARozQCWxqzPSUr4g", 4
        )
        assert ledger_id == "test_prod_1"
        assert ledger_inst.pool.name == "test_prod_1"


lines = []
with open('inputs/day2.txt') as f:
    lines = f.readlines()

x = 0
y = 0
aim = 0
direction = ""
units = 0
count = 0
for line in lines:
    line = line.split()
    direction = line[0]
    units = int(line[1])
    if (direction == "forward"):
        x += units
        y += units*aim
    elif (direction == "up"):
        aim -= units
    elif (direction == "down"):
        aim += units
    else:
        print("error")
    count += 1

answer = x*y
print(answer)


import math

from intersections import Intersection, Intersections
from point import Point
from shape import Shape

class Sphere(Shape):
    def __init__(self,
                 center=Point(),
                 radius=1.0,
                 transform=None,
                 material=None):
        super().__init__(transform=transform, material=material)
        self.center = center
        self.radius = radius

    @property
    def center(self):
        return self._center

    @center.setter
    def center(self, value):
        self._center = Point(x=value.x, y=value.y, z=value.z) \
            if value else Point(x=0, y=0, z=0)

    @property
    def radius(self):
        return self._radius

    @radius.setter
    def radius(self, value):
        self._radius = value

    def _intersect(self, ray):
        """
        Override base class method to provide sphere-specific method for
        computing intersection with ray and sphere.

        This method should not be called directly.  Instead, call the public
        intersect method defined in the Shape class.

        :param ray: The ray we use to compute intersections.
        :return: Intersections, the set of Intersection objects representing
            the intersections between the provided ray and this sphere.
        """
        # To understand how to compute the intersection of a ray with this
        # sphere, it might be helpful to read this lesson,
        # https://tinyurl.com/tuhcnx7, on the Analytical
        # Solution for Ray-Sphere Intersection.  This Wikipedia page is also
        # helpful for understanding solving the problem for a sphere that is
        # not at the center: https://tinyurl.com/u57fouv
        #
        # TL;DR
        #
        # By taking the equation of a sphere with radius, r, and center, c, any
        # point, p, on the sphere satisfies the equation:
        #
        #        2    2
        # (p - c)  = r
        #
        # The equation of any point on the ray with origin O and direction D:
        #
        # p = O + tD
        #
        # you can substitute the equation for a point on the ray into the
        # equation for the sphere to get:
        #
        #             2    2
        # |O + Dt - c|  = r
        #
        #             2    2
        # |O + Dt - c|  - r  = 0
        #
        #               2    2
        # |(O - c) + Dt|  - r  = 0
        #
        #        2                 2 2    2
        # (O - c)  + 2D(O - c)t + D t  - r  = 0
        #
        # and finally get to a quadratic in the form f(x) = ax^2 + bx + c
        #
        #  2 2                       2    2
        # D t  + 2D(O - c)t + (O - c)  - r = 0
        #
        #      2
        # a = D
        #
        # b = 2 * D * (O - c)
        #
        #            2    2                        2
        # c = (O - c)  - r  = (O - c) * (O - c) - r
        #
        # Note: (O - c) is the ray from the center of the sphere to the origin
        # of the ray.  When the sphere is centered on the origin, the c
        # component disappears.
        #
        # From there we can use our favorite, the quadratic formula,
        #
        #              2
        # -b +/- sqrt(b - 4ac)
        # --------------------
        #        2a
        #
        # and more specifically the discriminant d = (b  - 4ac) to determine how
        # many solutions there are:
        #
        # d < 0 - no solutions
        # d = 0 - 1 solution
        # d > 0 - 2 solutions
        #
        # and then the solution(s) if any exist.
        #
        # Phew.  That is a lot of explaining, but I wanted to make sure that I
        # understood what the code in the book was doing.

        # Create a vector from the center of this sphere to the origin of the
        # ray
        sphere_to_ray = ray.origin - self._center

        # Compute the a, b, and c coefficients for the quadratic equation
        # described above:
        a = ray.direction.dot_product(ray.direction)
        b = 2 * ray.direction.dot_product(sphere_to_ray)
        c = sphere_to_ray.dot_product(sphere_to_ray) - self._radius**2

        # Now compute the discriminant to determine if we even have solutions.
        discriminant = b**2 - 4 * a * c
        if discriminant < 0:
            return Intersections()

        i1 = Intersection(time=(-b - math.sqrt(discriminant)) / (2 * a),
                          shape=self)
        i2 = Intersection(time=(-b + math.sqrt(discriminant)) / (2 * a),
                          shape=self)

        return Intersections(i1, i2)

    def _normal_at(self, position):
        """
        Override base class method to provide sphere-specific method for
        computing normal at the point specified.

        This method should not be called directly.  Instead, call the public
        normal_at method defined in the Shape class.

        :param position: The position on the sphere for which the normal is
            to be computed.
        :return: Vector, the normal at the point provided.
        """
        return position - Point(x=0, y=0, z=0)


#!/usr/local/bin/python3

import speech_recognition as sr
import os
from gtts import gTTS
import datetime
import warnings
import calendar
import random
import wikipedia
import time
import tkinter
from PIL import Image, ImageTk, ImageSequence
import sys
import subprocess

class Mery(object):
	def __init__(self):

		self.language = "en"

		warnings.filterwarnings("ignore")

		# self.root = tkinter.Tk()
		# self.canvas = tkinter.Canvas(self.root, width=250, height=230, background="black")
		# self.sequence = [ImageTk.PhotoImage(img.resize(((300),(220))))
		# 					for img in ImageSequence.Iterator(
		# 							Image.open(
		# 							r'/Users/Ismael/Desktop/AI-Project/brain1.gif'))]
		# self.image = self.canvas.create_image(125,125, image=self.sequence[0])

	def Listener(self):

		AudioReader = sr.Recognizer()

		with sr.Microphone() as source:
			audio = AudioReader.listen(source)
			# prindasht ("I'm Listening")

			data = ""
			try:
				data = AudioReader.recognize_google(audio)
				print ("you said: " + data)

			except sr.UnknownValueError:
				print ("waiting for audio...")

			except sr.RequestError as e:
				print ("Service error from Google Speech Recognition, check internet connection " + e)

			return data

	def CallBack(self):
		WakeWords = ["mary", "hey mary", "mery", "married", "marrieds", "he married", "ameri", "amari", "marry"]
		MeryHeard = False

		text = OneTrueMery.Listener()
		text = text.lower()
		for phrase in WakeWords:
			if phrase in text:
				MeryHeard = True

		if MeryHeard:

			OneTrueMery.Response("Yes Sir?",self.language)

			return "succes"

	def Response(self,text,language):

		TtS = gTTS(text = text, lang = language, slow=False)
		#Text to Speech

		TtS.save("TextToResponse.mp3")

		os.system("afplay TextToResponse.mp3")

		# subprocess.call(('/usr/bin/osascript', '-e',  'tell application "Music" to pause',))

	def getDate(self):

		month_names = [

		"January", "February", "March"
		, "April", "May", "June", "July"
		, "August", "September", "October"
		, "November", "December"]

		ordinal_numbers = [

		"1st", "2nd", "3rd", "4rd", "5th", "6th", "7th", "8th", "9th", "10th",
		"11th", "12th", "13th", "14th", "15th", "16th", "17th", "18th", "19th", "20th",
		"21st", "22nd", "23rd", "24th", "25th", "26th", "27th", "28th", "29th", "30th", "31st"]

		Now = datetime.datetime.now()

		My_day = datetime.datetime.today()

		Weekday = calendar.day_name[My_day.weekday()]

		Month_num = Now.month

		Day_num = Now.day

		return "Today is: " + Weekday + " " + month_names[Month_num - 1] + " the " + ordinal_numbers[Day_num - 1] + "."

	def getInfo(self, audio2):
		try:
			sentence = audio2.split(" ")
			filtered = []
			for word in sentence:
				if word == "look" or word == "up" or word == "search":
					pass
				else:
					filtered.append(sentence[sentence.index(word)])

			filteredWord = " ".join(filtered)
			wikInfo = wikipedia.summary(filteredWord, sentences=2)
			OneTrueMery.Response("Here's what I found: " + wikInfo,self.language)

		except:
			OneTrueMery.Response("I didn't understand what you want me to search",self.language)

	def OpenApp(self, audio2):

		try:
			AudioList = audio2.split(" ")
			Grammar = []
			counter = 1

			for word in AudioList:
				if word == "open" or word == "Open":
					pass
				else:
					for letter in word:
						if word.index(letter) == 0 and counter == 1:
							x = letter.upper()
							Grammar.append(x)
							counter+=1
						elif word.index(letter) == 0 and counter == 2:
							x = letter.upper()
							Grammar.append("\\")
							Grammar.append(" ")
							Grammar.append(x)
						else:
							x = letter
							Grammar.append(x)

			CorrectedGrammar = "".join(Grammar)
			os.system("open -a " + CorrectedGrammar)
			OneTrueMery.Response("Opening " + CorrectedGrammar,self.language)
		except:
			OneTrueMery.Response("I didn't recognize the application.",self.language)

	def CloseApp(self, audio2):
		try:
			AudioList = audio2.split(" ")
			Grammar = []
			counter = 1

			for word in AudioList:
				if word == "close" or word == "Close":
					pass
				else:
					for letter in word:
						if word.index(letter) == 0 and counter == 1:
							x = letter.upper()
							Grammar.append(x)
							counter+=1
						elif word.index(letter) == 0 and counter == 2:
							x = letter.upper()
							Grammar.append(" ")
							Grammar.append(x)
						else:
							x = letter
							Grammar.append(x)

			CorrectedGrammar = "".join(Grammar)
			# AppPID = os.system("pgrep " + CorrectedGrammar)
			OneTrueMery.Response("Closing " + CorrectedGrammar,self.language)
			subprocess.call(('/usr/bin/osascript', '-e',  "tell application "+ "\"" +CorrectedGrammar+ "\"" +" to quit",))
			# os.system("pkill -x " + CorrectedGrammar)

		except:
			OneTrueMery.Response("I didn't recognize the application.",self.language)

	def AI(self):

		while True:

			audio2 = OneTrueMery.Listener()

			if "open" in audio2:
				OneTrueMery.OpenApp(audio2)

			if "look up" in audio2 or "search" in audio2:
				OneTrueMery.getInfo(audio2)

			if "play" in audio2 or "play music" in audio2 or "music please" in audio2:
				subprocess.call(('/usr/bin/osascript', '-e',  'tell application "Music" to play',))

			if "date" in audio2:
				OneTrueMery.Response(OneTrueMery.getDate(),self.language)

			if "stop music" in audio2 or "stop" in audio2 or "silence" in audio2 or  "quiet" in audio2:
				subprocess.call(('/usr/bin/osascript', '-e',  'tell application "Music" to pause',))

			if "next" in audio2 or "track" in audio2 or "next song" in audio2 or "next track" in audio2:
				subprocess.call(('/usr/bin/osascript', '-e',  'tell application "Music" to next track',))

			if "previous"  in audio2 or "previous song" in audio2 or "previous track" in audio2:
				subprocess.call(('/usr/bin/osascript', '-e',  'tell application "Music" to previous track',))

			if "thanks mary" in audio2 or "thanks" in audio2:
				OneTrueMery.Response("sure thing. goodbye",self.language)
				pid = os.system("ps a | grep AI_animation")
				os.system("kill -9 " + str(pid))
				# break
				sys.exit()
			if "close" in audio2:
				OneTrueMery.CloseApp(audio2)

			if "nothing" in audio2 or "nevermind" in audio2:
				OneTrueMery.Response("alright then",self.language)
				pid = os.system("ps | grep AI_animation.py")
				os.system("kill -9 " + str(pid))
				# break
				sys.exit()

			if "goodbye" in audio2 or "exit" in audio2:
				OneTrueMery.Response("Goodbye",self.language)
				pid = os.system("ps | grep AI_animation.py")
				os.system("kill -9 " + str(pid))
				sys.exit()

			else:
				pass

	# def Animate(self,counter):
	# 	self.canvas.itemconfig(self.image, image=self.sequence[counter])
	# 	self.root.after(20, lambda: OneTrueMery.Animate((counter+1) % len(self.sequence)))

	# def Exit(self):

	# 	self.root.destroy()
	# 	sys.exit()

	# def Miscelaneous(self):
	# 	self.canvas.pack(fill=tkinter.BOTH, expand=True)
	# 	label = tkinter.Label(self.root, text="Mery [Isma's Personal AI]", background="black", foreground="white").pack(fill=tkinter.BOTH, expand=True, side="left")
	# 	button = tkinter.Button(self.root, text="exit",font="bold", highlightbackground="black",command=OneTrueMery.Exit).pack(fill=tkinter.BOTH,side=tkinter.BOTTOM)

	# def Pop(self):
	# 		OneTrueMery.Miscelaneous()
	# 		OneTrueMery.Animate(1)
	# 		self.root.mainloop()

OneTrueMery = Mery()
thingy = "none"
subprocess.Popen("python3 AI_animation.py",shell=True)

while True:

	if thingy == "succes":

		OneTrueMery.AI()

	else:

		thingy = OneTrueMery.CallBack()

#"Done"


from openpyxl import load_workbook
import numpy as np
import pandas as pd

df_orderform = pd.read_excel('orderform.xlsx')
df_sf = pd.read_excel('SF.xlsx')
df_sf_local = pd.read_excel('SF_local.xlsx')

found_code = False
df_result_sf = pd.DataFrame()
df_result_sf_local = pd.DataFrame()

for row_orderform in df_orderform.itertuples():
    #print(row_orderform[2])
    temp_sf = df_sf[df_sf['code'].str.upper() == row_orderform[2]]
    if len(temp_sf) > 0:
        #temp_code['orderform_price'] = sheet_orderform.cell(row_orderform, 4).value
        df_result_sf = pd.concat([df_result_sf, temp_sf], ignore_index=True)
    else:
        temp_sf_local = df_sf_local[df_sf_local['code'].str.upper() == row_orderform[2]]
        if len(temp_sf_local) > 0:
            df_result_sf_local = pd.concat([df_result_sf_local, temp_sf_local], ignore_index=True)

print(df_result_sf)
df_result_sf.to_excel('sf_code_price.xlsx', sheet_name='sheet1')
df_result_sf_local.to_excel('sf_code_local_price.xlsx', sheet_name='sheet1')


#!/usr/bin/python3
# Time: 2019/07/09 4:17 PM
# About:

import PySimpleGUI as sg

layout = [
    [sg.Text("please tell me something about you:")],
    [sg.Text('Name', size=(15, 1)), sg.Input('name')],
    [sg.Text('Address', size=(15, 1)), sg.Input('Address')],
    [sg.Text('Phone', size=(15, 1)), sg.Input('Phone')],
    [sg.Submit(), sg.Cancel()]
]

window = sg.Window("First GUI window").Layout(layout)
button, values = window.Read()

print(button, values[0], values[1], values[2])


from flask import Blueprint, render_template

from app import rule_translator

frontend_bp = Blueprint('frontend', __name__)

@frontend_bp.route('/')
def index():
    """
    Response the index page HTML

    :return:
    """
    lang_codes = {}
    for lang_code in rule_translator.rules.keys():
        lang_codes[lang_code] = rule_translator.rules[lang_code]['meta']['language_name']
    return render_template('index.html', lang_codes=lang_codes)


import ml_utils
import tensorflow as tf

if __name__ == "__main__":
    model=tf.keras.models.load_model('mortgage_doc_identifier_v5')
    sample_file = input('Enter the folder location of your source packet files: ')
    output_path = input('Enter the folder location where you want to store your processed packet files: ')

    doc_df=ml_utils.doc_to_dataframe(sample_file, output_path)
    ml_utils.ml_sort_data(doc_df, 512, model)


from app.models import db, Reward, environment, SCHEMA
from sqlalchemy.sql import text
from datetime import date

def seed_rewards():
    reward1 = Reward(
        projectId=1,
        name='Early Bird Special',
        description='Be among the first to get the game at a special price!',
        price=35,
        est_delivery=date(2024, 5, 1),
        quantity=100,
    )

    reward2 = Reward(
        projectId=1,
        name='Enchanting Art Print',
        description="Receive a stunning art print inspired by the game's artwork.",
        price=50,
        est_delivery=date(2024, 6, 1),
        quantity=50,
    )

    reward3 = Reward(
        projectId=1,
        name="Collector's Edition",
        description="Get the deluxe collector's edition with exclusive content",
        price=75,
        est_delivery=date(2024, 7, 1),
        quantity=30,
    )

    reward4 = Reward(
        projectId=1,
        name='Game + Expansion Pack',
        description='Get the base game and the first expansion pack bundled together!',
        price=60,
        est_delivery=date(2024, 8, 1),
        quantity=60,
    )

    reward5 = Reward(
        projectId=2,
        name='VR Explorer Pack',
        description='Embark on your VR adventure with this essential starter pack!',
        price=40,
        est_delivery=date(2024, 9, 1),
        quantity=100,
    )

    reward6 = Reward(
        projectId=2,
        name='Exclusive In-Game Pet',
        description='Receive an adorable virtual pet companion in the game!',
        price=25,
        est_delivery=date(2024, 9, 1),
        quantity=200,
    )

    reward7 = Reward(
        projectId=2,
        name='VIP Access',
        description='Gain VIP status and enjoy early access and special in-game perks!',
        price=75,
        est_delivery=date(2024, 8, 5),
        quantity=50,
    )

    reward8 = Reward(
        projectId=2,
        name='Limited Edition Poster',
        description='Decorate your gaming space with a limited edition poster featuring game artwork.',
        price=30,
        est_delivery=date(2024, 9, 5),
        quantity=75,
    )

    reward9 = Reward(
        projectId=3,
        name='Explorer Pack',
        description='Start your cosmic journey with this essential explorer pack!',
        price=35,
        est_delivery=date(2023, 9, 1),
        quantity=150,
    )

    reward10 = Reward(
        projectId=3,
        name='Limited Edition Game Board',
        description='Get a unique limited edition game board with exclusive artwork.',
        price=50,
        est_delivery=date(2023, 9, 5),
        quantity=100,
    )

    reward11 = Reward(
        projectId=3,
        name='Galactic Commander Pack',
        description='Command the galaxy with this deluxe commander pack!',
        price=75,
        est_delivery=date(2023, 9, 1),
        quantity=75,
    )

    reward12 = Reward(
        projectId=3,
        name='Custom Alien Species',
        description='Create and name your own alien species featured in the game.',
        price=100,
        est_delivery=date(2023, 8, 5),
        quantity=25,
    )

    reward61 = Reward(
        projectId=4,
        name="Starter Spellbook",
        description="Begin your journey into arcane alchemy with this starter spellbook!",
        price=20,
        est_delivery=date(2023, 12, 1),
        quantity=200,
    )

    reward62 = Reward(
        projectId=4,
        name="Collector's Edition Card Set",
        description="Own a collector's edition set of magical cards with unique artwork.",
        price=40,
        est_delivery=date(2023, 11, 15),
        quantity=100,
    )

    reward63 = Reward(
        projectId=4,
        name="Master Alchemist Kit",
        description="Become a master alchemist with this deluxe kit of rare ingredients and tools.",
        price=70,
        est_delivery=date(2023, 11, 1),
        quantity=50,
    )

    reward64 = Reward(
        projectId=4,
        name="Custom Spell Card",
        description="Design your own spell card and add it to the game!",
        price=100,
        est_delivery=date(2023, 10, 25),
        quantity=30,
    )

    reward13 = Reward(
        projectId=5,
        name="Beta Tester Access",
        description="Be one of the first to explore the cybernetic world as a beta tester!",
        price=15,
        est_delivery=date(2024, 1, 15),
        quantity=300,
    )

    reward14 = Reward(
        projectId=5,
        name="Digital Art Collection",
        description="Receive a collection of stunning digital art inspired by Cybernetica.",
        price=30,
        est_delivery=date(2023, 12, 31),
        quantity=100,
    )

    reward15 = Reward(
        projectId=5,
        name="Ultimate Cybernetic Upgrade",
        description="Enhance your VR experience with the ultimate cybernetic hardware upgrade.",
        price=100,
        est_delivery=date(2023, 12, 15),
        quantity=50,
    )

    reward16 = Reward(
        projectId=5,
        name="Exclusive In-Game Character",
        description="Unlock an exclusive in-game character with unique abilities!",
        price=50,
        est_delivery=date(2023, 12, 1),
        quantity=75,
    )

    reward17 = Reward(
        projectId=6,
        name="Dragon Tamer's Starter Kit",
        description="Begin your journey as a dragon tamer with this essential starter kit!",
        price=20,
        est_delivery=date(2024, 1, 15),
        quantity=200,
    )

    reward18 = Reward(
        projectId=6,
        name="Limited Edition Art Book",
        description="Own a limited edition art book featuring stunning illustrations from Dragons Dominion.",
        price=35,
        est_delivery=date(2023, 12, 31),
        quantity=100,
    )

    reward19 = Reward(
        projectId=6,
        name="Legendary Dragon Figurine",
        description="Receive an intricately crafted figurine of a legendary dragon from the game.",
        price=75,
        est_delivery=date(2023, 12, 15),
        quantity=50,
    )

    reward20 = Reward(
        projectId=6,
        name="Custom Character Illustration",
        description="Get a custom character illustration of yourself as a hero in Dragons Dominion.",
        price=50,
        est_delivery=date(2023, 12, 1),
        quantity=75,
    )

    reward21 = Reward(
        projectId=7,
        name="Virtual Dive Certification",
        description="Get certified as a virtual diver and gain access to exclusive in-game content.",
        price=30,
        est_delivery=date(2024, 1, 15),
        quantity=150,
    )

    reward22 = Reward(
        projectId=7,
        name="Ocean Explorer's Bundle",
        description="Receive a bundle of ocean-themed VR experiences, including AquaVenture.",
        price=50,
        est_delivery=date(2023, 12, 31),
        quantity=100,
    )

    reward23 = Reward(
        projectId=7,
        name="DeepSea Diver's Kit",
        description="Get equipped with a virtual deep-sea diving kit for immersive exploration.",
        price=75,
        est_delivery=date(2023, 12, 15),
        quantity=50,
    )

    reward24 = Reward(
        projectId=7,
        name="Underwater Photography Course",
        description="Join a virtual underwater photography course and capture stunning aquatic moments.",
        price=40,
        est_delivery=date(2023, 12, 1),
        quantity=75,
    )

    reward25 = Reward(
        projectId=8,
        name="QuantumX Developer Kit",
        description="Get your hands on the QuantumX developer kit and start experimenting with quantum computing.",
        price=250,
        est_delivery=date(2024, 1, 15),
        quantity=50,
    )

    reward26 = Reward(
        projectId=8,
        name="QuantumX Quantum Simulator",
        description="Receive access to the QuantumX quantum simulator for virtual quantum experiments.",
        price=100,
        est_delivery=date(2024, 1, 31),
        quantity=100,
    )

    reward27 = Reward(
        projectId=8,
        name="QuantumX Masterclass",
        description="Join a virtual masterclass on quantum computing with leading experts in the field.",
        price=150,
        est_delivery=date(2024, 2, 15),
        quantity=30,
    )

    reward28 = Reward(
        projectId=8,
        name="QuantumX Research Grant",
        description="Receive a research grant to support your quantum computing research project.",
        price=500,
        est_delivery=date(2024, 3, 31),
        quantity=10,
    )

    reward29 = Reward(
        projectId=9,
        name="LunaLens Basic Kit",
        description="Get the LunaLens Basic Kit and start experiencing augmented reality in a whole new way.",
        price=199,
        est_delivery=date(2024, 2, 28),
        quantity=100,
    )

    reward30 = Reward(
        projectId=9,
        name="LunaLens Pro Edition",
        description="Upgrade to the LunaLens Pro Edition for advanced AR capabilities and exclusive content.",
        price=299,
        est_delivery=date(2024, 3, 15),
        quantity=50,
    )

    reward31 = Reward(
        projectId=9,
        name="LunaLens Developer Kit",
        description="Receive the LunaLens Developer Kit for creating your own augmented reality experiences.",
        price=499,
        est_delivery=date(2024, 4, 1),
        quantity=30,
    )

    reward32 = Reward(
        projectId=9,
        name="LunaLens Exclusive Access",
        description="Get exclusive early access to LunaLens updates and features.",
        price=99,
        est_delivery=date(2024, 3, 31),
        quantity=200,
    )

    reward33 = Reward(
        projectId=10,
        name="SkyHawk Explorer Pack",
        description="Get the SkyHawk Explorer Pack and start your aerial adventures with our AI-powered drone.",
        price=499,
        est_delivery=date(2024, 3, 15),
        quantity=100,
    )

    reward34 = Reward(
        projectId=10,
        name="SkyHawk Pro Pack",
        description="Upgrade to the SkyHawk Pro Pack for advanced features and extended flight time.",
        price=799,
        est_delivery=date(2024, 3, 31),
        quantity=50,
    )

    reward35 = Reward(
        projectId=10,
        name="SkyHawk Autonomous Flight Kit",
        description="Receive the SkyHawk Autonomous Flight Kit to experience fully autonomous drone flights.",
        price=1199,
        est_delivery=date(2024, 4, 15),
        quantity=30,
    )

    reward36 = Reward(
        projectId=10,
        name="SkyHawk Exclusive Access",
        description="Get exclusive early access to SkyHawk software updates and new features.",
        price=99,
        est_delivery=date(2024, 4, 5),
        quantity=200,
    )

    reward37 = Reward(
        projectId=11,
        name="EcoCharge Essential Pack",
        description="Get the EcoCharge Essential Pack and start charging your devices sustainably with our solar-powered charger.",
        price=79,
        est_delivery=date(2024, 4, 15),
        quantity=100,
    )

    reward38 = Reward(
        projectId=11,
        name="EcoCharge Ultimate Pack",
        description="Upgrade to the EcoCharge Ultimate Pack for additional solar panels and faster charging.",
        price=129,
        est_delivery=date(2024, 4, 30),
        quantity=50,
    )

    reward39 = Reward(
        projectId=11,
        name="EcoCharge Solar Backpack",
        description="Receive the EcoCharge Solar Backpack, a backpack with built-in solar panels to charge your devices on the go.",
        price=149,
        est_delivery=date(2024, 5, 15),
        quantity=30,
    )

    reward40 = Reward(
        projectId=11,
        name="EcoCharge Eco-Warrior Bundle",
        description="Become an eco-warrior with this bundle, including multiple EcoCharge sets and a tree planted in your name.",
        price=299,
        est_delivery=date(2024, 5, 5),
        quantity=20,
    )

    reward41 = Reward(
        projectId=12,
        name="EcoStyle Essential Collection",
        description="Get the EcoStyle Essential Collection, featuring eco-friendly clothing items made from sustainable materials.",
        price=99,
        est_delivery=date(2024, 7, 15),
        quantity=100,
    )

    reward42 = Reward(
        projectId=12,
        name="EcoStyle Premium Collection",
        description="Upgrade to the EcoStyle Premium Collection, with exclusive, high-quality eco-friendly fashion pieces.",
        price=149,
        est_delivery=date(2024, 7, 30),
        quantity=50,
    )

    reward43 = Reward(
        projectId=12,
        name="EcoStyle Sustainable Accessories",
        description="Accessorize sustainably with our EcoStyle Sustainable Accessories, including bags, hats, and more.",
        price=49,
        est_delivery=date(2024, 8, 15),
        quantity=30,
    )

    reward44 = Reward(
        projectId=12,
        name="EcoStyle Eco-Chic Wardrobe",
        description="Revamp your wardrobe sustainably with the EcoStyle Eco-Chic Wardrobe, a complete collection of eco-friendly fashion.",
        price=249,
        est_delivery=date(2024, 8, 5),
        quantity=20,
    )

    reward45 = Reward(
        projectId=13,
        name="UrbanThreads Classic Tee",
        description="Get the UrbanThreads Classic Tee, a comfortable and stylish addition to your streetwear collection.",
        price=39,
        est_delivery=date(2024, 8, 1),
        quantity=100,
    )

    reward46 = Reward(
        projectId=13,
        name="UrbanThreads Hoodie",
        description="Upgrade your street style with the UrbanThreads Hoodie, a cozy and fashionable choice for any season.",
        price=69,
        est_delivery=date(2024, 8, 15),
        quantity=75,
    )

    reward47 = Reward(
        projectId=13,
        name="UrbanThreads Exclusive Caps",
        description="Complete your streetwear look with UrbanThreads Exclusive Caps, available in various urban-inspired designs.",
        price=29,
        est_delivery=date(2024, 8, 10),
        quantity=50,
    )

    reward48 = Reward(
        projectId=13,
        name="UrbanThreads Streetwear Bundle",
        description="Upgrade your entire wardrobe with the UrbanThreads Streetwear Bundle, featuring a range of streetwear essentials.",
        price=149,
        est_delivery=date(2024, 8, 20),
        quantity=30,
    )

    reward49 = Reward(
        projectId=14,
        name="Epic Tales: Book 1 - The Quest Begins",
        description="Get the first book in the 'Epic Tales' series and start your journey into the world of epic fantasy.",
        price=19,
        est_delivery=date(2024, 11, 1),
        quantity=200,
    )

    reward50 = Reward(
        projectId=14,
        name="Epic Tales: Collector's Edition Set",
        description="Collect all books in the 'Epic Tales' series with this special collector's edition set. Dive deep into the fantasy realms.",
        price=99,
        est_delivery=date(2024, 11, 15),
        quantity=100,
    )

    reward51 = Reward(
        projectId=14,
        name="Epic Tales: Exclusive Art Prints",
        description="Decorate your walls with exclusive art prints inspired by 'Epic Tales' and bring the fantasy world to life.",
        price=29,
        est_delivery=date(2024, 11, 10),
        quantity=150,
    )

    reward52 = Reward(
        projectId=14,
        name="Epic Tales: Author's Q&A Session",
        description="Join an exclusive live Q&A session with the author of 'Epic Tales' and dive deeper into the creative process.",
        price=49,
        est_delivery=date(2024, 11, 20),
        quantity=50,
    )

    reward53 = Reward(
        projectId=15,
        name="Cookbook Chronicles: Digital Edition",
        description="Get a digital copy of 'Cookbook Chronicles' and explore culinary delights from around the world.",
        price=12,
        est_delivery=date(2024, 11, 15),
        quantity=500,
    )

    reward54 = Reward(
        projectId=15,
        name="Cookbook Chronicles: Hardcover Collector's Edition",
        description="Own a collector's edition hardcover of 'Cookbook Chronicles' filled with mouthwatering recipes and beautiful illustrations.",
        price=49,
        est_delivery=date(2024, 11, 20),
        quantity=300,
    )

    reward55 = Reward(
        projectId=15,
        name="Cookbook Chronicles: Exclusive Cooking Class",
        description="Join an exclusive online cooking class hosted by renowned chefs featured in the book and learn culinary secrets.",
        price=89,
        est_delivery=date(2024, 11, 25),
        quantity=100,
    )

    reward56 = Reward(
        projectId=15,
        name="Cookbook Chronicles: Signed Copy + Personal Recipe",
        description="Receive a signed copy of 'Cookbook Chronicles' along with a personalized recipe card from the author.",
        price=29,
        est_delivery=date(2024, 11, 18),
        quantity=200,
    )

    reward57 = Reward(
        projectId=16,
        name="Whodunit Mysteries: Digital Collection",
        description="Get a digital collection of the entire 'Whodunit Mysteries' series and dive into a world of suspense and intrigue.",
        price=20,
        est_delivery=date(2024, 12, 10),
        quantity=500,
    )

    reward58 = Reward(
        projectId=16,
        name="Whodunit Mysteries: Exclusive Collector's Set",
        description="Own an exclusive collector's set of the 'Whodunit Mysteries' series, including hardcovers, posters, and more.",
        price=99,
        est_delivery=date(2024, 12, 15),
        quantity=300,
    )

    reward59 = Reward(
        projectId=16,
        name="Whodunit Mysteries: Personalized Detective Kit",
        description="Receive a personalized detective kit with clues, props, and puzzles to immerse yourself in the world of mysteries.",
        price=149,
        est_delivery=date(2024, 12, 18),
        quantity=100,
    )

    reward60 = Reward(
        projectId=16,
        name="Whodunit Mysteries: Virtual Author Q&A",
        description="Join a virtual Q&A session with the author of 'Whodunit Mysteries' and ask questions about the series.",
        price=29,
        est_delivery=date(2024, 12, 12),
        quantity=200,
    )

# PROJECT 1
    db.session.add(reward1)
    db.session.add(reward2)
    db.session.add(reward3)
    db.session.add(reward4)
# PROJECT 2
    db.session.add(reward5)
    db.session.add(reward6)
    db.session.add(reward7)
    db.session.add(reward8)
# PROJECT 3
    db.session.add(reward9)
    db.session.add(reward10)
    db.session.add(reward11)
    db.session.add(reward12)
# PROJECT 5
    db.session.add(reward13)
    db.session.add(reward14)
    db.session.add(reward15)
    db.session.add(reward16)
# PROJECT 6
    db.session.add(reward17)
    db.session.add(reward18)
    db.session.add(reward19)
    db.session.add(reward20)
# PROJECT 7
    db.session.add(reward21)
    db.session.add(reward22)
    db.session.add(reward23)
    db.session.add(reward24)
#  PROJECT 8
    db.session.add(reward25)
    db.session.add(reward26)
    db.session.add(reward27)
    db.session.add(reward28)
# PROJECT 9
    db.session.add(reward29)
    db.session.add(reward30)
    db.session.add(reward31)
    db.session.add(reward32)
# PROJECT 10
    db.session.add(reward33)
    db.session.add(reward34)
    db.session.add(reward35)
    db.session.add(reward36)
# PROJECT 11
    db.session.add(reward37)
    db.session.add(reward38)
    db.session.add(reward39)
    db.session.add(reward40)
# PROJECT 12
    db.session.add(reward41)
    db.session.add(reward42)
    db.session.add(reward43)
    db.session.add(reward44)
# PROJECT 13
    db.session.add(reward45)
    db.session.add(reward46)
    db.session.add(reward47)
    db.session.add(reward48)
# PROJECT 14
    db.session.add(reward49)
    db.session.add(reward50)
    db.session.add(reward51)
    db.session.add(reward52)
# PROJECT 15
    db.session.add(reward53)
    db.session.add(reward54)
    db.session.add(reward55)
    db.session.add(reward56)
# PROJECT 16
    db.session.add(reward57)
    db.session.add(reward58)
    db.session.add(reward59)
    db.session.add(reward60)
# PROJECT 4
    db.session.add(reward61)
    db.session.add(reward62)
    db.session.add(reward63)
    db.session.add(reward64)

    db.session.commit()

def undo_rewards():
    if environment == "production":
        db.session.execute(f"TRUNCATE table {SCHEMA}.rewards RESTART IDENTITY CASCADE;")
    else:
        db.session.execute(text("DELETE FROM rewards"))

    db.session.commit()


#! /usr/bin/env python3

import re
import sys

from advent import Inputs

source = Inputs(2018).get(20).text.strip()
sys.setrecursionlimit(10000)

#source = '^ESSWWN(E|NNENN(EESS(WNSE|)SSS|WWWSSSSE(SW|NNNE)))$'
#source = '^WSSEESWWWNW(S|NENNEEEENN(ESSSSW(NWSW|SSEN)|WSWWN(E|WWS(E|SS))))$'
source = open('20-1.txt').read().strip()

class Alternatives:
    def __init__(self):
        self.branches = [Sequence()]

    def branch(self):
        self.branches.append(Sequence())

    def add(self, element):
        self.branches[-1].add(element)

    def __len__(self):
        lengths = [len(b) for b in self.branches]
        l = max(lengths) // (1 if min(lengths) > 0 else 2)
        print(lengths, '->', l)
        return l

class Sequence:
    def __init__(self):
        self.elements = []

    def add(self, element):
        self.elements.append(element)

    def __len__(self):
        return sum(len(e) for e in self.elements)

stack = [Sequence()]
for char in source[1:-1]:
    if char in 'NESW':
        stack[-1].add(char)
    elif char == '(':
        a = Alternatives()
        stack[-1].add(a)
        stack.append(a)
    elif char == '|':
        stack[-1].branch()
    elif char == ')':
        stack.pop()

print("Part one:", max(map(len, stack)))


import numpy as np
from numba import jit
import tensorflow as tf
from tensorflow.keras import models, layers, regularizers

@jit(nopython=True)
def normalize_map(imap):
    temp_map = np.zeros(imap.shape)
    for j in range(imap.shape[-1]):
        temp = (imap[...,j]-np.mean(imap[...,j]))/np.std(imap[...,j])
        temp_map[...,j] = temp

    return temp_map

#A helper function that stores a bunch of models I've been playing around with. Notable Kosiba is a model following
#Kosiba 2020 (https://arxiv.org/abs/2006.05998) who had good success training it on x-ray+ optical data
def make_model(model_type = 'simple_cnn', input_shape = (342,342,5), degree = 5):

    if model_type == 'simple_cnn':
        model = models.Sequential()
        model.add(layers.Conv2D(32, (3, 3), activation='relu', input_shape=input_shape))
        model.add(layers.MaxPooling2D((2, 2)))
        model.add(layers.Conv2D(64, (3, 3), activation='relu'))
        model.add(layers.MaxPooling2D((2, 2)))
        model.add(layers.Conv2D(64, (3, 3), activation='relu'))
        model.add(layers.Flatten())
        model.add(layers.Dense(64, activation='relu'))
        model.add(layers.Dense(2))
    elif model_type == 'resnet':
        model = tf.keras.applications.ResNet50(include_top=True,
        weights= None,
        input_shape = input_shape,
        classes = 2)
    elif model_type == 'pretrained':
        model = tf.keras.applications.ResNet50(include_top=False,
        weights= 'imagenet',
        input_shape = input_shape_rgb,
        classes = 2)

    elif model_type == 'inception_v2':
        base_model = tf.keras.applications.InceptionResNetV2(include_top = False,
                input_shape = input_shape,
                weights= 'imagenet'
                )
        base_model.trainable = False

    elif model_type == 'hyper':
        def train_test_model(hparams):
            model = models.Sequential()
            model.add(layers.Conv2D(32, (3, 3), activation='relu', input_shape=input_shape))
            model.add(layers.MaxPooling2D((2, 2)))
            model.add(layers.Conv2D(64, (3, 3), activation='relu'))
            model.add(layers.MaxPooling2D((2, 2)))
            model.add(layers.Dropout(hparams[HP_DROPOUT]))
            model.add(layers.Conv2D(64, (3, 3), activation='relu'))
            model.add(layers.Flatten())
            model.add(layers.Dense(hparams[HP_NUM_UNITS], activation='relu'))
            model.add(layers.Dense(2))
            model.compile(
              optimizer=hparams[HP_OPTIMIZER],
              loss='sparse_categorical_crossentropy',
              metrics=['accuracy'],
          )

            model.fit(train_dataset, epochs=10)
            _, accuracy = model.evaluate(test_dataset)
            return accuracy

    elif model_type == 'test':
        model = models.Sequential([
        layers.Conv2D(16, 3, padding='same', activation='relu',
               input_shape=input_shape),
        layers.MaxPooling2D(),
        layers.Dropout(0.2),
        layers.Conv2D(32, 3, padding='same', activation='relu'),
        layers.MaxPooling2D(),
        layers.Conv2D(64, 3, padding='same', activation='relu'),
        layers.MaxPooling2D(),
        layers.Dropout(0.2),
        layers.Flatten(),
        layers.Dense(512, activation='relu'),
        layers.Dense(2)])

    elif model_type == 'deep_few_filters':
        model = models.Sequential()
        #model.add(layers.experimental.preprocessing.Rescaling(1./all_max, input_shape=input_shape))
        model.add(layers.Conv2D(2, (3, 3), activation='relu', input_shape=input_shape))
        model.add(layers.MaxPooling2D((2, 2)))
        j = 0
        for j in range(degree):
            model.add(layers.Conv2D(4, (3, 3), activation='relu'))
            model.add(layers.ZeroPadding2D((1,1)))
            #model.add(layers.MaxPooling2D((2, 2)))
            j +=1
        model.add(layers.Conv2D(8, (3, 3), activation='relu'))
        model.add(layers.Flatten())
        model.add(layers.Dense(16, activation='relu'))
        model.add(layers.Dense(2))

    elif model_type == 'dropout':
        model = models.Sequential()
        model.add(layers.Conv2D(32, (3, 3), kernel_regularizer=regularizers.l2(0.0001), activation='relu', input_shape=input_shape))
        layers.Dropout(0.5),
        model.add(layers.AveragePooling2D((2, 2)))
        model.add(layers.Conv2D(64, (3, 3), kernel_regularizer=regularizers.l2(0.0001), activation='relu'))
        layers.Dropout(0.5),
        model.add(layers.AveragePooling2D((2, 2)))
        model.add(layers.Conv2D(64, (3, 3), kernel_regularizer=regularizers.l2(0.0001), activation='relu'))
        layers.Dropout(0.5),
        model.add(layers.Flatten())
        model.add(layers.Dense(64, activation='relu'))
        model.add(layers.Dense(2))

    elif model_type == 'kosiba':
        model = models.Sequential()
        model.add(layers.Conv2D(64, (3, 3), activation='relu', input_shape=input_shape))
        model.add(layers.MaxPooling2D((2, 2), strides=(2,2)))
        for i in range(degree):
            model.add(layers.Conv2D(32, (3, 3), activation='relu'))
            model.add(layers.MaxPooling2D((2, 2), strides=(2,2)))
        model.add(layers.Flatten())
        model.add(layers.Dense(256, activation='relu', kernel_regularizer=regularizers.l1(0.0001)))
        layers.Dropout(0.65)

        model.add(layers.Dense(2))
    model.summary()
    if model_type == 'kosiba':
        lr_schedule = tf.keras.optimizers.schedules.InverseTimeDecay(
              0.0001,
              decay_steps=348/10*1000,
              decay_rate=1e-6,
              staircase=False)
        opt = tf.keras.optimizers.SGD(
                learning_rate=0.01, momentum=0.9, nesterov = True, name='SGD')
        model.compile(optimizer=opt,
                  loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
                  metrics=['accuracy'])
    else:
        model.compile(optimizer='Adam',
              loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
              metrics=['accuracy'])
    return model

class feature_model:

    def __init__(self, train, comp, w_y = False):
        self.w_y = w_y
        self.train = clean_inputs(train)
        self.comp = clean_inputs(comp)

    def clean_inputs(data_tensor):
        flags = []
        for i in range(data_tensor.shape[0]):
            if np.any(np.isnan(data_tensor[i,...])):
                flags.append(i)
        data_tensor = np.delete(data_tensor, flags, axis = 0)


import numpy as np
from skimage import io, transform, measure
from torch.utils.data import Dataset, DataLoader
import os

class DataProcessor(object):
    """ Class to process raw images, masks and footprints to generate and save network inputs and labels as .npy files.
    Saves data as [C x H x W] as per Pytorch ordering.
        -> C = [R, G, B, Mask, Footprint]
    """
    def __init__(self):
        self.masks = np.array([])
        self.footprints = np.array([])
        self.images = np.array([])
        self.train_data = None
        self.val_data = None
        self.filenames = None

    def load_raw_data(self, path, image_size=(288,512)):
        filenames = os.listdir(path+"ground_masks/masks/")
        filenumber = len(filenames)

        masks = np.zeros([filenumber, image_size[0], image_size[1]], dtype=int)
        footprints = np.zeros_like(masks)
        images = np.zeros([filenumber, image_size[0], image_size[1], 3]) # number of files x h x w x RGB

        index = 0
        for name in filenames:
            mask = np.load(path+"ground_masks/masks/"+name)
            footprint = np.load(path+"ground_footprints/footprints/"+name)
            image = io.imread(path+"/ground_frames/"+name[:-4]+".jpg") / 255

            masks[index] = mask
            footprints[index] = footprint
            images[index] = image

            index += 1

        # Save file name ordering for reconstruction later
        self.filenames = np.array([filenames])

        # if len(self.masks)!=0:  # if data in train_masks then add to it
        #     self.masks = np.concatenate((self.masks, masks), axis=0)
        #     self.footprints = np.concatenate((self.footprints, footprints), axis=0)
        #     self.images = np.concatenate((self.images, images), axis=0)
        # else:  # otherwise set explicitly
        self.masks = masks
        self.footprints = footprints
        self.images = images

    def shuffle_data(self):
        ordering = np.random.permutation(len(self.train_data))
        self.train_data = self.train_data[ordering]

    def valitdation_split(self, val_fraction):
        self.shuffle_data()
        self.val_data = self.train_data[:int(round(val_fraction * len(self.train_data)))]
        self.train_data = self.train_data[int(round(val_fraction * len(self.train_data))):]

    def prepare_data(self, output_shape):

        size = len(self.masks)
        # Initialise
        masks = np.zeros([size, output_shape[0], output_shape[1]], dtype=int)
        footprints = np.zeros([size, output_shape[0], output_shape[1]], dtype=float)
        images = np.zeros([size, output_shape[0], output_shape[1], 3])
        for i in range(size):
            # Loop and resize to output_shape
            masks[i] = transform.resize(self.masks[i], output_shape=output_shape, preserve_range=True)
            footprints[i] = transform.resize(self.footprints[i], output_shape=output_shape, preserve_range=True)
            images[i] = transform.resize(self.images[i], output_shape=output_shape, preserve_range=True)

        masks = np.expand_dims(masks, -1)
        footprints = np.expand_dims((footprints > 0.5).astype(int), -1)
        self.train_data = np.concatenate((images, masks, footprints), axis=-1)
        self.train_data = np.transpose(self.train_data, [0,3,1,2]) # for pytorch style inputs (batch x C x H x W)

    def save_data(self, path, val_path=None):
        index = len(os.listdir(path))
        for i in range(len(self.train_data)):
            np.save(path + "data_" + str(i+index), self.train_data[i])

        if val_path:
            index = len(os.listdir(val_path))
            for i in range(len(self.val_data)):
                np.save(val_path + "data_" + str(i + index), self.val_data[i])


import tkinter as tk

#define
root = tk.Tk()

#create title
root.title('First GUI')

#add icon on windwo
root.iconbitmap('./Resources/Section2/thinking.ico')

#set the window size
root.geometry('250x700')

#want to change windw size (x,y)
root.resizable(0,0)

#colors str or hex
root.config(bg='blue')

#2nd window
top = tk.Toplevel()
top.title('2nd Window')
top.config(bg='green')
top.geometry('200x200+500+50')

#create
root.mainloop()


from DateTime import DateTime
from pkg_resources import get_distribution
from pkg_resources import parse_version
from plone.dexterity.utils import createContentInContainer
from plone.restapi.interfaces import ISerializeToJson
from plone.restapi.interfaces import ISerializeToJsonSummary
from plone.restapi.testing import PLONE_RESTAPI_DX_INTEGRATION_TESTING
from plone.uuid.interfaces import IMutableUUID
from Products.CMFCore.utils import getToolByName
from zope.component import getMultiAdapter

import unittest

HAS_PLONE_6 = parse_version(
    get_distribution("Products.CMFPlone").version
) >= parse_version("6.0.0a1")

class TestCatalogSerializers(unittest.TestCase):
    layer = PLONE_RESTAPI_DX_INTEGRATION_TESTING

    def setUp(self):
        self.app = self.layer["app"]
        self.portal = self.layer["portal"]
        self.request = self.portal.REQUEST
        self.catalog = getToolByName(self.portal, "portal_catalog")

        # /plone/my-folder
        self.folder = createContentInContainer(self.portal, "Folder", title="My Folder")

        # /plone/my-folder/my-document
        self.doc = createContentInContainer(
            self.folder,
            "Document",
            creation_date=DateTime(2015, 12, 31, 23, 45),
            title="My Document",
        )

        IMutableUUID(self.doc).set("77779ffa110e45afb1ba502f75f77777")
        self.doc.reindexObject()

    def test_lazy_cat_serialization_empty_resultset(self):
        # Force an empty resultset (Products.ZCatalog.Lazy.LazyCat)
        lazy_cat = self.catalog(path="doesnt-exist")
        results = getMultiAdapter((lazy_cat, self.request), ISerializeToJson)()

        self.assertDictEqual(
            {"@id": "http://nohost", "items": [], "items_total": 0}, results
        )

    @unittest.skipUnless(HAS_PLONE_6, "Since Plone 6 the Plone site is indexed ...")
    def test_lazy_map_serialization(self):
        # Test serialization of a Products.ZCatalog.Lazy.LazyMap
        lazy_map = self.catalog()
        results = getMultiAdapter((lazy_map, self.request), ISerializeToJson)()

        self.assertEqual(results["@id"], "http://nohost")
        self.assertEqual(results["items_total"], 3)
        self.assertEqual(3, len(results["items"]))

    @unittest.skipIf(HAS_PLONE_6, "... before it was not")
    def test_lazy_map_serialization_plone5(self):
        # Test serialization of a Products.ZCatalog.Lazy.LazyMap
        lazy_map = self.catalog()
        results = getMultiAdapter((lazy_map, self.request), ISerializeToJson)()

        self.assertEqual(results["@id"], "http://nohost")
        self.assertEqual(results["items_total"], 2)
        self.assertEqual(2, len(results["items"]))

    def test_lazy_map_serialization_with_fullobjects(self):
        # Test serialization of a Products.ZCatalog.Lazy.LazyMap
        lazy_map = self.catalog(path="/plone/my-folder/my-document")
        results = getMultiAdapter((lazy_map, self.request), ISerializeToJson)(
            fullobjects=True
        )

        self.assertEqual(results["@id"], "http://nohost")
        self.assertEqual(results["items_total"], 1)
        self.assertEqual(1, len(results["items"]))
        result_item = results["items"][0]

        expected = {
            "@id": "http://nohost/plone/my-folder/my-document",
            "@type": "Document",
            "changeNote": "",
            "contributors": [],
            "creators": ["test_user_1_"],
            "description": "",
            "effective": None,
            "exclude_from_nav": False,
            "expires": None,
            "id": "my-document",
            "is_folderish": False,
            "language": "",
            "layout": "document_view",
            "parent": {
                "@id": "http://nohost/plone/my-folder",
                "@type": "Folder",
                "type_title": "Folder",
                "description": "",
                "review_state": "private",
                "title": "My Folder",
            },
            "relatedItems": [],
            "review_state": "private",
            "rights": "",
            "subjects": [],
            "table_of_contents": None,
            "text": None,
            "title": "My Document",
            "version": "current",
        }
        self.assertEqual(result_item, {**result_item, **expected})

    def test_brain_summary_representation(self):
        lazy_map = self.catalog(path="/plone/my-folder/my-document")
        brain = lazy_map[0]
        result = getMultiAdapter((brain, self.request), ISerializeToJsonSummary)()
        self.assertEqual(
            {
                "@id": "http://nohost/plone/my-folder/my-document",
                "@type": "Document",
                "title": "My Document",
                "type_title": "Page",
                "description": "",
                "review_state": "private",
            },
            result,
        )


'''Soal 1
A = himpunan (set) bilangan genap antara 1 dan 20.
B = himpunan (set) bilangan ganjil antara 1 dan 20.
C = himpunan (set) bilangan negatif lebih dari -10.
D = himpunan (set) bilangan prima antara 1 dan 20.
E = himpunan (set) bilangan komposit antara 1 dan 20.
'''
'''Bilangan genap & ganjil'''

alist = []
blist = []
for a in range(1,20):
    if a % 2==0:
        alist.append(a)
    elif a%2!=0:
        blist.append(a)

'''bilangan negatif lebih dari -10'''
clist=(range(-10,0))
'''bilangan prima'''
def prima1(num):
   if num > 1:
       for i in range(2,num):
           if (num % i) == 0:
               return False
               break
       else:
           return True
D = set (filter(prima1,range (20)))
'''bilangan komposit'''
elist=[]
for a in range(2,20):
    if a not in D:
        elist.append(a)

A = set(alist)
B = set(blist)
C = set(clist)
D = set (filter(prima1,range (20)))
E = set (elist)

'''Jawaban:
a. A ∪ B ∪ C ∪ D ∪ E
b. (A ∩ B) ∪ (D ∩ E)
c. (A ∪ B) ∩ (D ∪ E)
d. (A ∪ B) - (D ∪ E)
e. (A ∪ B ∪ C) - (A ∩ E)
'''
print ('a.jawab:'); print (A|B|C|D|E)
print ('b.jawab:');print ((A&B)|(D&E))
print ('c.jawab:');print ((A|B) & (D|E))
print ('d.jawab:');print ((A|B)-(D|E))
print ('e.jawab:');print ((A|B|C)-(A&E))


from django.contrib.auth.models import User
from django.db import models
from django.utils.html import mark_safe
from django.core.urlresolvers import reverse
from django.core.exceptions import ObjectDoesNotExist

from ckeditor.fields import RichTextField
from bs4 import BeautifulSoup
from PIL import Image
import html, datetime, logging

logger = logging.getLogger('main')

class UpImages(models.Model):
    image = models.ImageField(blank=False, upload_to='images/%Y/%m/%d/', max_length=250)
    uploaded_by = models.ForeignKey(User, null=True, on_delete=models.SET_NULL)
    image_title = models.CharField(blank=True, max_length=255, verbose_name='Τίτλος')
    upload_date = models.DateTimeField('Ημερομηνία Ανάρτησης', default=datetime.datetime.now)

    def thumbnail(self):
        return u'' % self.image.url
    thumbnail.short_description = 'Εικόνα'
    thumbnail.allow_tags = True

    def __str__(self):
        return self.image_title

    def save(self, *args, **kwargs):
        # Setting image title and reducing image quality.
        self.image_title = (self.image.path).split('/')[-1].split('.')[0]
        super(UpImages, self).save(*args, **kwargs)
        imagepath = self.image.path
        image = Image.open(imagepath)
        image.save(imagepath, "JPEG", quality=30)

    class Meta:
        verbose_name = "Εικόνα"
        verbose_name_plural = "Εικόνες"
        ordering = ['-upload_date']

class Category(models.Model):
    name = models.CharField('Όνομα Κατηγορίας', max_length=100, blank=False)
    def __str__(self):
        return self.name
    class Meta:
        verbose_name = "Κατηγορία"
        verbose_name_plural =  "Κατηγορίες"

class Posts(models.Model):
    STATUS_CHOICES = (
        ('p', 'Δημοσιευμένο'),
        ('d', 'Πρόχειρο'),
    )
    text = RichTextField("Κείμενο", blank=False)
    pub_date = models.DateField('Ημερομηνία Ανάρτησης', default=datetime.date.today, null=True, blank=True)
    image = models.ForeignKey(UpImages, on_delete=models.SET_NULL,null=True, blank=True, verbose_name='Εικόνα')
    title = models.CharField('Τίτλος' ,max_length=255, null=True, blank=True)
    author = models.ForeignKey(User, on_delete=models.SET_NULL, verbose_name='Αρθρογράφος', null=True, blank=True)
    category = models.ForeignKey(Category,default=0, on_delete=models.SET_NULL, null=True, blank=True, verbose_name='Κατηγορία')
    status = models.CharField('Κατάσταση', max_length=1, choices=STATUS_CHOICES, default='d')
    viewcount = models.IntegerField('Αριθμός Προβολών', default=0)

    def thumbnail(self):
        if self.image:
            return u'' % self.image.image.url
        return "Δεν υπάρχει φωτογραφία"
    thumbnail.short_description = 'Εικόνα Κειμένου'
    thumbnail.allow_tags = True

    def show_link(self):
        return ' Προβολή Άρθρου ' % self.get_absolute_url()
    show_link.allow_tags = True
    show_link.short_description = "-"

    def __str__(self):
        if self.title:
            return self.title
        return "Δεν υπάρχει τίτλος"

    def get_absolute_url(self):
        return reverse('main:articles', args=(self.id,))
    class Meta:
        verbose_name_plural = "Δημοσιεύσεις"
        verbose_name = "Δημοσίευση"
        ordering = ['-pub_date']

class BodyText(models.Model):
    text = models.TextField('Κείμενο', blank=False)
    author = models.CharField('Ποίος Το Είπε', blank=False, max_length=255)
    active = models.BooleanField(verbose_name='Ενεργό', default=False)
    pub_date = models.DateTimeField('Ημερομηνία Αρχικής Δημοσίευσης', default=datetime.datetime.now)

    def activate(self):
        # This is used to activate a quote through the changelist
        return " Ενεργοποίηση  "
    activate.allow_tags = True
    activate.short_description = "Ενεργοίηση Παραφοράς"

    def save(self, *args, **kwargs):
        if self.active == True:
            try:
                current_active = BodyText.objects.get(active=True)
                if self != current_active:
                    current_active.active = False;
                    current_active.save()
            except BodyText.DoesNotExist:
                pass
        super(BodyText, self).save(*args, **kwargs)

    class Meta:
        verbose_name_plural = "Παραφορές"
        verbose_name = "Παραφορά"

# Avoid circular imports
from .utils import truncate

class Bios(models.Model):
    def get_number():
        num = Bios.objects.count()
        if num:
            return num + 1
        # Case : no objects are present in the db.
        # Then return 1.
        return 1
    author_name = models.CharField(max_length=50, blank=False, verbose_name="Όνομα")
    author_cv   = models.TextField(blank=False, verbose_name="Βιογραφικό")
    position    = models.IntegerField(verbose_name="Αριθμός Θέσης", default=get_number)
    minified_cv = models.CharField(max_length=255, blank=True, verbose_name="Βιογραφικό")

    def __str__(self):
        return self.author_name
    def save(self, *args, **kwargs):
        if not self.pk:
            try:
                curr_bios = Bios.objects.get(position=self.position)
                curr_bios.position = Bios.get_number()
                curr_bios.save()
            except ObjectDoesNotExist:
                pass
        self.minified_cv = truncate(self.author_cv)
        super(Bios, self).save(*args, **kwargs)
    class Meta:
        ordering = ["position",]
        verbose_name = "Βιογραφικό"
        verbose_name_plural = "Βιογραφικά"

# Overring User's str method
def user_str_patch(self):
    return self.first_name

User.__str__ = user_str_patch


##### controller
# it starts the processes, and managing the space on device suspend them

import psutil
import os
import time
import sys

DB_BASE_PATH = os.path.join(os.getcwd(), 'DB', 'WOW')

print('Truncating DB objects...')
# Truncate DB file content
try:
    for dirname, dirnames, filenames in os.walk(DB_BASE_PATH):
        if dirname.__contains__('data'):
            continue
        print(dirname)
        for filename in filenames:
            try:
                if filename.endswith('.json'):
                    file_path = os.path.join(dirname, filename)
                    os.truncate(file_path, 0)
            except os.error as err:
                print(str(err) + ' -- line: ' + str(sys.exc_info()[-1].tb_lineno))
except os.error as err:
    print(str(err) + ' -- line: ' + str(sys.exc_info()[-1].tb_lineno))
    time.sleep(60)
print('...DONE --> usage: ' + str(psutil.disk_usage('.')[-1]))


n = int(input())

price = 0

a = list(map(int, input().split()))

for i in range(n-2):
    temp = a[i]
    maxnum = min(a[i],a[i+1],a[i+2])
    if maxnum!=0:
        price += maxnum*7
        a[i] -= maxnum
        a[i+1] -= maxnum
        a[i+2] -= maxnum
    maxnum = min(a[i],a[i+1])
    if maxnum!=0:
        price += maxnum*5
        a[i] -= maxnum
        a[i+1] -= maxnum
    price += a[i]*3
    a[i] = 0
    if a[i+2] < a[i+1]:
        tmp = min(temp, a[i+1]-a[i+2])
        price -= tmp*2
        a[i+2] += tmp
    print(a)

maxnum = min(a[n-2],a[n-1])
if maxnum!=0:
    price += maxnum*5
    a[i] -= maxnum
    a[i+1] -= maxnum

price += sum(a)*3
print(price)


from itertools import count

houses = []
for x in range(5000000):
    houses.append(0)

for i in range(1, len(houses)):
    for j in range(i, min(len(houses), 50 * i + 1), i):
        houses[j] += i * 11

for n,gifts in enumerate(houses):
    if gifts >= 34000000:
        print('Answer:', n)
        exit()


#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import os
import re
import sys
import time
import json
import socket
import shutil
import logging
import argparse
import subprocess
import logging.handlers
from urllib.parse import urlsplit

import requests

try:
    from config import *
except ImportError:
    from default_config import *

elogger = logging.getLogger('stderr')
ologger = logging.getLogger('stdout')

def main():
    """python3 unblockgw.py [-h]
"""
    elogger.debug("")
    elogger.debug(" ".join(sys.argv))
    Gateway.execute(sys.argv[1:])

class Gateway(object):

    @classmethod
    def execute(cls, raw_args):
        """python3 unblockgw.py {status,on,off,check,renew,setup,create}

Unblock CHN 网关命令：
  status                  查看代理状态
  on                      开启代理
  off                     关闭代理
  check <URL/IP/域名>     检查 <URL/IP/域名> 是否走代理
  renew                   更新规则
  setup [--no-ss]         一键配置网关 [--no-ss: 跳过配置 ss-redir]
  create                  仅生成 ipset 规则配置文件
"""
        parser = argparse.ArgumentParser(usage=cls.execute.__doc__)
        parser.add_argument(
            'cmd', choices=['status', 'on', 'off', 'check', 'renew', 'setup', 'create'])
        args = parser.parse_args(raw_args[0:1])

        if args.cmd == 'create':
            cls.cmd_create()
            return

        # 检查 iptables 和 ipset 命令是否存在
        cls.check_ipset_iptables()

        if args.cmd == 'on':
            cls.cmd_on()
        elif args.cmd == 'off':
            cls.cmd_off()
        elif args.cmd == 'status':
            cls.cmd_status()
        elif args.cmd == 'check':
            cls.cmd_check(raw_args[1:])
        elif args.cmd == 'renew':
            cls.cmd_renew()
        elif args.cmd == 'setup':
            cls.cmd_setup(raw_args[1:])

    @classmethod
    def cmd_status(cls):
        """查看 Unblock Youku Gateway 代理状态"""
        cls.check_setup()
        ss_redir_running = cls.check_ss_redir()
        if not ss_redir_running:
            ologger.info("ss-redir 未运行")
            return
        iptables_chn_exists = cls.check_iptables_chn()
        if iptables_chn_exists:
            ologger.info("已开启")
        else:
            ologger.info("已关闭")

    @classmethod
    def cmd_on(cls):
        """开启 Unblock CHN 代理"""
        cls.check_setup()
        ss_redir_running = cls.check_ss_redir()
        if not ss_redir_running:
            success = cls.start_ss_redir()
            if not success:
                ologger.error("✘ 无法启动 ss-redir")
                sys.exit(1)
        iptables_chn_exists = cls.check_iptables_chn()
        if not iptables_chn_exists:
            cls.add_iptables_chn()
        if ss_redir_running and iptables_chn_exists:
            ologger.info("已经开启")
        else:
            ologger.info("开启成功")

    @classmethod
    def cmd_off(cls):
        """关闭 Unblock CHN 代理"""
        cls.check_setup()
        iptables_chn_exists = cls.check_iptables_chn()
        if iptables_chn_exists:
            cls.delete_iptables_chn()
            ologger.info("关闭成功")
        else:
            ologger.info("已经关闭")

    @classmethod
    def cmd_check(cls, raw_args):
        """python3 unblockgw.py router check [-h] url
        检查 url 是否走 Unblock CHN 代理
        """
        parser = argparse.ArgumentParser(usage=cls.cmd_check.__doc__)
        parser.add_argument('url', help="URL / IP / 域名")
        args = parser.parse_args(raw_args)

        cls.check_setup()

        if "://" in args.url:
            domain = urlsplit(args.url).hostname
        else:
            domain = args.url.split('/')[0]
        ip = socket.gethostbyname(domain)

        cmd = "ipset test chn {}".format(ip)
        returncode = subprocess.call(
            cmd, shell=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
        if returncode == 0:
            ologger.info("{} 走代理".format(ip))
        else:
            ologger.info("{} 不走代理".format(ip))

    @classmethod
    def cmd_renew(cls):
        """更新 Unblock CHN 规则"""
        cls.check_setup()

        # 生成网关配置文件
        unblock_youku = UnblockYouku()
        cls.create_conf_files(unblock_youku.black_domains)

        # 清空 ipset 的 chn 表
        cmd = "ipset flush chn"
        subprocess.check_call(cmd, shell=True)
        elogger.info("✔ 清空 ipset 的 chn 表：{}".format(cmd))

        # 载入 ipset 规则
        headless_ipset_conf_path = os.path.join(DIR_PATH, "configs/ipset.headless.rules")
        cmd = "ipset restore < {}".format(headless_ipset_conf_path)
        subprocess.check_call(cmd, shell=True)
        elogger.info("✔ 载入 ipset 规则：{}".format(cmd))

        ologger.info("更新成功")

    @classmethod
    def cmd_setup(cls, raw_args):
        """python3 unblockgw.py router setup [-h] [--no-ss]
        Unblock CHN 一键配置网关
        """
        parser = argparse.ArgumentParser(usage=cls.cmd_setup.__doc__)
        parser.add_argument('--no-ss', action='store_true', help="跳过配置 ss-redir")
        args = parser.parse_args(raw_args)

        # 不跳过配置 ss-redir
        if not args.no_ss:
            # 配置 ss-redir
            cls.setup_ss_redir()

        # 生成网关配置文件
        unblock_youku = UnblockYouku()
        cls.create_conf_files(unblock_youku.black_domains)

        # 清空 ipset 的 chn 表
        cmd = "ipset flush"
        subprocess.check_call(cmd, shell=True)
        elogger.info("✔ 清空 ipset：{}".format(cmd))

        # 配置 ipset 和 iptables
        cls.setup_ipset_iptables()

        # 添加每日更新规则的 cron 定时任务
        cls.add_renew_cron_job()

        ologger.info("配置成功")

    @classmethod
    def cmd_create(cls):
        """仅生成 ipset 规则配置文件"""

        # 生成网关配置文件
        unblock_youku = UnblockYouku()
        cls.create_conf_files(unblock_youku.black_domains)

        ologger.info("生成配置文件成功")

    @classmethod
    def create_conf_files(cls, domains):
        """生成网关 ipset 规则配置文件"""

        # 生成 ipset 规则
        ipset_rules = []
        dnsmasq_rules = []
        if domains:
            for domain in domains:
                if re.match(r"\d+\.\d+\.\d+\.\d+", domain):  # IP
                    rule = "add chn {}".format(domain)
                    ipset_rules.append(rule)
                else:  # 域名
                    try:
                        ips = socket.gethostbyname_ex(domain)[2]
                        for ip in ips:
                            if ip not in ["127.0.0.1", "0.0.0.1"]:
                                rule = f"add chn {ip}"
                                ipset_rules.append(rule)
                    except:
                        pass
        ipset_rules = set(ipset_rules) #remove the same IPs
        # 从模板生成 ipset 规则配置文件 ipset.rules
        cls.create_ipset_conf_file(ipset_rules)

    @classmethod
    def create_ipset_conf_file(cls, ipset_rules):
        """从模板生成 ipset 规则配置文件 ipset.rules"""
        ipset_tpl_path = os.path.join(DIR_PATH, "configs/ipset.rules.tpl")
        if os.path.isfile(ipset_tpl_path):
            with open(ipset_tpl_path, 'r', encoding='utf-8') as f:
                ipset_tpl = f.read()
        else:
            ipset_tpl = "{rules}"
            with open(ipset_tpl_path, 'w', encoding='utf-8') as f:
                f.write(ipset_tpl)
            elogger.info("✔ 生成 ipset 默认配置模板文件：ipset.rules.tpl")

        # 无 ipset 规则 & 无自定义模板内容
        if (not ipset_rules) and (ipset_tpl == "{rules}"):
            return False

        if ipset_rules:
            ipset_rules = "\n".join(ipset_rules)
        else:
            ipset_rules = ""
        ipset_conf = ipset_tpl.format(rules=ipset_rules)

        # 生成包含表创建命令的 ipset 规则配置文件 ipset.rules
        ipset_conf_path = os.path.join(DIR_PATH, "configs/ipset.rules")
        with open(ipset_conf_path, 'w', encoding='utf-8') as f:
            f.write("create chn hash:ip family inet hashsize 1024 maxelem 65536\n")
            f.write(ipset_conf)

        # 生成不包含表创建命令的 ipset 规则配置文件 ipset.headless.rules
        headless_ipset_conf_path = os.path.join(DIR_PATH, "configs/ipset.headless.rules")
        with open(headless_ipset_conf_path, 'w', encoding='utf-8') as f:
            f.write(ipset_conf)

        elogger.info("✔ 生成 ipset 配置文件：ipset.rules & ipset.headless.rules")
        return True

    @classmethod
    def setup_ss_redir(cls):
        """配置 ss-redir"""

        # 生成 ss-redir 配置文件
        conf = SS_REDIR_CONF
        if conf['server'] is None:
            conf['server'] = input("Shadowsocks 服务器地址：").strip()
        if conf['server_port'] is None:
            conf['server_port'] = int(input("Shadowsocks 服务器端口：").strip())
        if conf['password'] is None:
            conf['password'] = input("Shadowsocks 密码：").strip()
        if conf['method'] is None:
            conf['method'] = input("Shadowsocks 加密方法：").strip()
        with open(SS_REDIR_CONF_PATH, 'w', encoding='utf-8') as f:
            json.dump(conf, f, indent=4)
        elogger.info("✔ 保存 ss-redir 配置文件：{}".format(SS_REDIR_CONF_PATH))

        # 启动 ss-redir
        success = cls.start_ss_redir()
        if not success:
            cmd = "{} -c {}".format(SS_REDIR_PATH, SS_REDIR_CONF_PATH)
            elogger.error("✘ 无法启动 ss-redir，请手动运行以下命令查看错误信息：\n{}".format(cmd))
            sys.exit(1)

        # 保存 ss-redir 启动命令到网关的 services-start 启动脚本中
        cmd = "{} -c {} -f {}"
        cmd = cmd.format(SS_REDIR_PATH, SS_REDIR_CONF_PATH, SS_REDIR_PID_PATH)
        comment = "# ss-redir"
        cls.append_to_script(SERVICES_START_SCRIPT_PATH, comment, cmd)
        elogger.info("✔ 保存 ss-redir 启动命令到网关的 services-start 启动脚本中：{}".format(SERVICES_START_SCRIPT_PATH))

    @classmethod
    def setup_ipset_iptables(cls):
        """配置 ipset 和 iptables"""
        # 载入 ipset 规则
        ipset_cmd = "ipset restore < {}".format(IPSET_CONF_PATH)
        try:
            subprocess.check_output(ipset_cmd, shell=True, stderr=subprocess.PIPE)
        except subprocess.CalledProcessError as e:
            if "set with the same name already exists" not in str(e.stderr):
                raise e
        elogger.info("✔ 载入 ipset 规则：{}".format(ipset_cmd))

        # 保存 ipset 载入命令到网关的 nat-start 启动脚本中
        comment = "# Load ipset rules"
        cls.append_to_script(NAT_START_SCRIPT_PATH, comment, ipset_cmd)
        elogger.info("✔ 保存 ipset 载入命令到网关的 nat-start 启动脚本中：{}".format(NAT_START_SCRIPT_PATH))

        # 添加 iptables 规则
        iptables_chn_exists = cls.check_iptables_chn()
        if not iptables_chn_exists:
            cls.add_iptables_chn()
        elogger.info("✔ 添加 iptables 规则：{}".format(ADD_IPTABLES_CHN_CMD))

        # 保存 iptables 添加规则命令到网关的 nat-start 启动脚本中
        comment = "# Redirect chn ipset to ss-redir"
        cmd = 'if [ "$(nvram get unblockgw_on)" = "True" ]; then {}; fi'
        cmd = cmd.format(ADD_IPTABLES_CHN_CMD)
        cls.append_to_script(NAT_START_SCRIPT_PATH, comment, cmd)
        elogger.info("✔ 保存 iptables 规则添加命令到启动脚本中：{}".format(NAT_START_SCRIPT_PATH))

    @classmethod
    def add_renew_cron_job(cls):
        """添加每日更新规则的 cron 定时任务"""
        renew_cmd = "0 {} * * * {} {} renew\r\n"
        unblockgw_path = os.path.realpath(__file__)
        renew_cmd = renew_cmd.format(RENEW_TIME, PYTHON3_PATH, unblockgw_path)

        # 写入定时任务到文件中
        ipset_tpl_path = os.path.join(DIR_PATH, "configs/renew_task")
        with open(ipset_tpl_path, 'w', encoding='utf-8') as f:
            f.write(renew_cmd)
        elogger.info("✔ 生成 corn 任务配置模板文件：renew_task")

        cron_cmd = "crontab configs/renew_task"
        try:
            subprocess.check_call(cron_cmd, shell=True)
        except subprocess.CalledProcessError as e:
            elogger.exception(e)
            elogger.warning("✘ 无法添加每日更新规则的定时任务，你需要手动添加以下条目到 crontab 中：\n{}".format(renew_cmd))
            return
        else:
            elogger.info("✔ 定时每日 {} 点更新规则：{}".format(RENEW_TIME, cron_cmd))

        # 保存以上定时命令到网关的 services-start 启动脚本中
        comment = "# unblockgw_renew cron job"
        cls.append_to_script(SERVICES_START_SCRIPT_PATH, comment, cron_cmd)
        elogger.info("✔ 保存定时更新规则命令到网关的 services-start 启动脚本中：{}".format(SERVICES_START_SCRIPT_PATH))

    @classmethod
    def remove_renew_cron_job(cls):
        """移除每日更新规则的 cron 定时任务"""
        cmd = "cru d unblockgw_renew"
        subprocess.check_call(cmd, shell=True)
        elogger.info("✔ 删除每日更新规则的 cron 定时任务：{}".format(cmd))

        # 从启动脚本里移除定时命令
        comment = "# unblockgw_renew cron job"
        cls.remove_from_script(SERVICES_START_SCRIPT_PATH, comment)
        elogger.info("✔ 从启动脚本里移除定时命令：{}".format(SERVICES_START_SCRIPT_PATH))

    @classmethod
    def start_ss_redir(cls):
        """启动 ss-redir"""
        cmd = "{} -c {} -f {}"
        cmd = cmd.format(SS_REDIR_PATH, SS_REDIR_CONF_PATH, SS_REDIR_PID_PATH)
        subprocess.call(cmd, shell=True)
        time.sleep(1)
        is_running = cls.check_ss_redir()
        if is_running:
            elogger.info("✔ 启动 ss-redir：{}".format(cmd))
        return is_running

    @classmethod
    def stop_ss_redir(cls):
        """停止 ss-redir"""
        with open(SS_REDIR_PID_PATH, 'r', encoding='utf-8') as f:
            pid = f.read()
        cmd = "kill {}".format(pid)
        subprocess.check_call(cmd, shell=True)
        elogger.info("✔ 停止 ss-redir：{}".format(cmd))

    @classmethod
    def check_ss_redir(cls):
        """检查 ss-redir 是否运行中"""
        with open(SS_REDIR_PID_PATH, 'r', encoding='utf-8') as f:
            pid = f.read()
        return os.path.exists("/proc/{}".format(pid))

    @classmethod
    def check_setup(cls):
        """检查网关是否配置过"""
        chn_ipset_exists = cls.check_chn_ipset()
        if not chn_ipset_exists:
            ologger.error("✘ 网关未正确配置，请先运行以下命令进行配置：\npython3 unblockgw.py setup")
            sys.exit(1)

    @classmethod
    def check_ipset_iptables(cls):
        """检查 iptables 和 ipset 命令是否存在"""
        iptables_exists = cls.check_command('iptables')
        ipset_exists = cls.check_command('ipset')
        if not (iptables_exists and ipset_exists):
            d = {'iptables': iptables_exists, 'ipset': ipset_exists}
            missing = [k for k in d if not d[k]]
            ologger.error("✘ 运行环境不支持 {} 命令".format(" 和 ".join(missing)))
            sys.exit(1)

    @classmethod
    def check_chn_ipset(cls):
        """检查 ipset 是否有 chn 表"""
        cmd = "ipset list chn"
        returncode = subprocess.call(
            cmd, shell=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
        return returncode == 0

    @classmethod
    def add_iptables_chn(cls):
        """iptables 添加 chn ipset 规则"""
        subprocess.check_call(ADD_IPTABLES_CHN_CMD, shell=True)

    @classmethod
    def delete_iptables_chn(cls):
        """iptables 删除 chn ipset 规则"""
        subprocess.check_call(DELETE_IPTABLES_CHN_CMD, shell=True)

    @classmethod
    def check_iptables_chn(cls):
        """检查 iptables 是否有 chn ipset 规则"""
        returncode = subprocess.call(
            CHECK_IPTABLES_CHN_CMD, shell=True, stderr=subprocess.DEVNULL)
        return returncode == 0

    @classmethod
    def append_to_script(cls, script_path, comment, cmd):
        """添加命令到脚本"""
        if os.path.isfile(script_path):
            with open(script_path, 'r', encoding='utf-8') as f:
                scpt = f.read()
        else:
            scpt = "#!/bin/sh\n"
        if comment not in scpt:
            scpt += "\n" + comment + "\n" + cmd + "\n"
        with open(script_path, 'w', encoding='utf-8') as f:
            f.write(scpt)
        cmd = "chmod a+rx {}".format(script_path)
        subprocess.check_call(cmd, shell=True)

    @classmethod
    def remove_from_script(cls, script_path, comment):
        """从脚本中移除命令"""
        if not os.path.isfile(script_path):
            return
        with open(script_path, 'r', encoding='utf-8') as f:
            scpt = f.read()
        pattern = r"\n" + comment + r"\n.+\n?"
        scpt = re.sub(pattern, "", scpt)
        with open(script_path, 'w', encoding='utf-8') as f:
            f.write(scpt)

    @classmethod
    def check_command(cls, command):
        """检查命令是否存在"""
        returncode = subprocess.call(
            ["which", command],
            stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
        if returncode == 0:
            return True
        else:
            return False

class UnblockYouku(object):

    def __init__(self):
        super(UnblockYouku, self).__init__()
        self.source = requests.get(UNBLOCK_YOUKU_URLSJS_URL).text
        self._black_urls = None
        self._white_urls = None
        self._black_domains = None
        self._white_domains = None

    @property
    def black_urls(self):
        """URLs 黑名单"""
        if self._black_urls is not None:
            return self._black_urls

        header_urls = self.extract('header_urls')
        redirect_urls = self.extract('redirect_urls')
        chrome_proxy_urls = self.extract('chrome_proxy_urls')
        pac_proxy_urls = self.extract('pac_proxy_urls')

        self._black_urls = header_urls + redirect_urls + chrome_proxy_urls + pac_proxy_urls
        self._black_urls = list(set(self._black_urls))
        self._black_urls.sort()

        return self._black_urls

    @property
    def white_urls(self):
        """URLs 白名单"""
        if self._white_urls is not None:
            return self._white_urls

        chrome_proxy_bypass_urls = self.extract('chrome_proxy_bypass_urls')
        pac_proxy_bypass_urls = self.extract('pac_proxy_bypass_urls')

        self._white_urls = chrome_proxy_bypass_urls + pac_proxy_bypass_urls
        self._white_urls = list(set(self._white_urls))
        self._white_urls.sort()

        return self._white_urls

    @property
    def black_domains(self):
        """域名黑名单"""
        if self._black_domains is not None:
            return self._black_domains

        self._black_domains = []
        for url in self.black_urls:
            domain = urlsplit(url).hostname
            self._black_domains.append(domain)

        self._black_domains = list(set(self._black_domains))
        self._black_domains.sort(key=lambda s: s[::-1], reverse=True)

        return self._black_domains

    @property
    def white_domains(self):
        """域名白名单"""
        if self._white_domains is not None:
            return self._white_domains

        self._white_domains = []
        for url in self.white_urls:
            domain = urlsplit(url).hostname
            self._white_domains.append(domain)

        self._white_domains = list(set(self._white_domains))
        self._white_domains.sort(key=lambda s: s[::-1], reverse=True)

        return self._white_domains

    def extract(self, name):
        """从 Unblock Youku 的 urls.js 中提取指定的 URL 列表"""
        pattern = "unblock_youku\\.{}\\s*=.+?(\\[.+?\\])".format(name)
        match = re.search(pattern, self.source, re.DOTALL)
        if not match:
            elogger.error("✘ 从 Unblock Youku 提取 {} 规则失败".format(name))
            sys.exit(1)
        s = match.group(1)
        s = s.replace("'", '"')  # 替换单引号为双引号
        s = re.sub(r"(?<!:)//.+", "", s)  # 去除注释
        s = re.sub(r",\s*\]", "\n]", s)  # 去除跟在最后一个元素后面的逗号
        urls = json.loads(s)
        return urls

def init_logging():
    """日志初始化"""

    root_logger = logging.getLogger()
    root_logger.setLevel(logging.NOTSET)

    # 输出日志到文件
    log_file_path = os.path.join(DIR_PATH, "unblockgw.log")
    formatter = logging.Formatter(
        "%(asctime)s ~ %(levelname)-8s - "
        "%(message)s",
        datefmt="%Y-%m-%d %H:%M:%S"
    )
    logfile = logging.handlers.RotatingFileHandler(
        log_file_path,
        maxBytes=10 * 1024 * 1024,
        backupCount=1
    )
    logfile.setFormatter(formatter)
    logfile.setLevel(logging.DEBUG)
    root_logger.addHandler(logfile)

    # 输出日志到控制台
    formatter = logging.Formatter("%(message)s")
    # stderr logger
    console = logging.StreamHandler(sys.stderr)
    console.setFormatter(formatter)
    console.setLevel(logging.INFO)
    elogger.addHandler(console)
    # stdout logger
    console = logging.StreamHandler(sys.stdout)
    console.setFormatter(formatter)
    console.setLevel(logging.INFO)
    ologger.addHandler(console)

    # 设置 requests 和 urllib3 日志级别
    requests_logger = logging.getLogger("requests")
    requests_logger.setLevel(logging.WARNING)
    urllib3_logger = logging.getLogger('urllib3')
    urllib3_logger.setLevel(logging.WARNING)

if __name__ == '__main__':
    try:
        init_logging()
        main()
    except Exception as error:
        elogger.exception(error)