import discord
from discord.ext import commands
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.chrome.options import Options
from text_Finder import Finder
import time

client = commands.Bot(command_prefix='!')
options = webdriver.ChromeOptions()
options.add_argument("headless")
options.add_argument("log-level=3")
driver=webdriver.Chrome(r"C:/Users/athul/Downloads/chromedriver_win32/chromedriver.exe", chrome_options=options)

@client.event
async def on_ready():
    print('We have logged in as {0.user}'.format(client))

@client.command()
async def search(ctx, arg):
    counter = 370
    status = True
    while status:
        driver.get("https://api.bestbuy.com/v1/products((search=" + str(arg) +"))?apiKey=fbHpo1XU31MYqyDvPNeczIzQ&sort=onlineAvailability.asc&show=orderable,name,addToCartUrl&pageSize=24&format=json")

        avail = []
        names = []
        url = []
        stock = []
        o = 0
        ns = 0
        us = 0
        page=driver.page_source
        page = Finder.noEnd(str(page), '"products":[')
        for c, v in enumerate(str(page)):
            if page[c:c+9] == 'orderable':
                o = c + 12
            if page[c:c+4] == 'Sold':
                avail.append("Sold Out")
            elif page[c:c+9] == 'Available':
                avail.append("In Stock")

        for c, v in enumerate(str(page)):
            if page[c:c+4] == "name":
                ns = c + 7
            if page[c:c+5] == "addTo":
                names.append(str(page)[ns:c-3])

        for c, v in enumerate(str(page)):
            if page[c:c+12] == "addToCartUrl":
                us = c + 15
            if page[c:c+4] == "cart":
                url.append(str(page)[us:c+4])

        for c, v in enumerate(avail):
            stock.append("\nNAME: " + names[c] + "\nSTOCK: " + avail[c] + "\nLINK: " + url[c])

        time.sleep(2)

        if counter > 360:
            embed=discord.Embed(title="STOCK CHECKER", color=0xEC5252)
            #description="These are probably not in stock"
            for i in stock:
                embed.add_field(name="-", value=i, inline=False)
            embed.set_footer(text="We are not associated with Bestbuy")
            await ctx.send(embed=embed)
            counter = 0

        for c, v in enumerate(avail):
            if v == "In Stock":
                embed=discord.Embed(title="STOCK CHECKER", description="BUY NOW", color=0xEC5252)
                embed.add_field(name="ITEM: ", value=names[c], inline=False)
                embed.add_field(name="IN STOCK: ", value=url[c], inline=False)
                #embed.set_footer(text="If we are still pinging, the cards are still in stock")
                await ctx.send(embed=embed)
                await ctx.channel.send("@everyone")
                #check = False
                status = False

        counter += 1

client.run('ODQyMTM0Mzk3NTE1MDcxNTE4.YJw4xg.lBgTauBk_UdQowWZEgo-U9Pq6dQ')


"""New Migration

Revision ID: fd38be600b40
Revises: 7d96ebd19353
Create Date: 2023-04-09 16:19:00.475743

"""
from alembic import op
import sqlalchemy as sa

# revision identifiers, used by Alembic.
revision = 'fd38be600b40'
down_revision = '7d96ebd19353'
branch_labels = None
depends_on = None

def upgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    with op.batch_alter_table('advertisements', schema=None) as batch_op:
        batch_op.add_column(sa.Column('file_path', sa.String(length=200), nullable=False))
        batch_op.drop_column('adFilePath')

    # ### end Alembic commands ###

def downgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    with op.batch_alter_table('advertisements', schema=None) as batch_op:
        batch_op.add_column(sa.Column('adFilePath', sa.VARCHAR(length=200), nullable=False))
        batch_op.drop_column('file_path')

    # ### end Alembic commands ###


import math
class Shape:
    def area(self):
        pass

class Triangle(Shape):
    def __init__(self, base, height):
        self.base = base
        self.height = height
    def area(self):
        return 0.5 * self.base * self.height

class Circle(Shape):
    def __init__(self, radius):
        self.radius = radius
    def area(self):
        return math.pi * self.radius ** 2

class Rectangle(Shape):
    def __init__(self, length, width):
        self.length = length
        self.width = width
    def area(self):
        return self.length * self.width

while(True):
    print('1. Area of Triangle    2. Area of Circle     3. Area of Rectangle',"\n")
    choice=int(input('enter your choice'))
    if choice==1:
        b=int(input('enter base\n'))
        h = int(input('enter height\n'))
        triangle = Triangle(b, h)
        print("Area of triangle:", triangle.area())
    elif choice==2:
        r=float(input('enter the radius\n'))
        circle = Circle(r)
        print("Area of circle:", circle.area())
    elif choice==3:
        b=int(input('enter base\n'))
        l = int(input('enter length\n'))
        rectangle = Rectangle(b, l)
        print("Area of rectangle:", rectangle.area())
    else:
        print('invalid choice')
        exit(0)


"""

Classes
^^^^^^^

"""

import sys

import numpy as np

import matplotlib.pyplot as plt

from NAMDAnalyzer.helpersFunctions.objectConverters import fromSliceToArange

class ResidenceTime:
    """ This class defines methods to compute retention time of atoms
        in a certain region. This determines how fast atoms in sel2 can
        leave the vicinity of sel1.

        Some plotting methods are also available to quicly check the results.

        :arg data:       a :class:`Dataset` class instance containing
                         trajectories data
        :arg sel:        selection corresponding to analysis region
                         (with 'within' keyword')
        :arg tMax:       maximum number of frames to be used
        :arg step:       time interval between each computed frame
        :arg nbrTimeOri: number of time origins to be averaged over
                         (optional, default 20)

    """
    def __init__(self, data, sel, tMax=25, step=1, nbrTimeOri=20, frames=slice(0, None)):

        self.data       = data
        self.sel        = sel
        self.tMax       = tMax
        self.step       = step
        self.nbrTimeOri = nbrTimeOri
        self.frames     = fromSliceToArange(frames, data.nbrFrames)

        self.resTime     = None
        self.times       = None
        self.residueWise = None
        self.residues    = None

# --------------------------------------------
# Computation methods
# --------------------------------------------
    def compResidenceTime(self):
        """ For each frame in the range of tMax with given step,
            the number of atoms in selected region is computed and divided
            by the number of atoms at time origin. The result is averaged over
            multiple time origins.

            The result is stored in *resTime* attribute.

        """
        self.times = (np.arange(0, self.tMax, self.step, dtype=int)
                      * self.data.dcdFreq[0] * self.data.timestep * 1e12)
        corr       = np.zeros_like(self.times)

        deltaTime = self.frames[-1] - self.frames[0]
        oriList = self.frames[0] + ((deltaTime - self.tMax)
                   * np.random.random(self.nbrTimeOri)).astype(int)

        for idx, frame in enumerate(oriList):

            print("Processing time origin %i of %i with %i frames..."
                  % (idx + 1, oriList.size, self.tMax / self.step), end='\r')

            sel = self.data.selection(
                self.sel + " frame %i:%i:%i"
                % (frame, frame + self.tMax, self.step))

            for tIdx, keepIdx in enumerate(sel):
                corr[tIdx] += np.intersect1d(sel[0], keepIdx).size

        self.resTime = corr / corr[0]

    def compResidueWiseResidenceTime(self, dt=25):
        """ Computes, for a given time dt, the residence time for
            selected atoms around each residue in the protein.

            By default all atoms pertaining to protein are selected.
            If different proteins are present, the *segName* argument
            can be used in selection text.

            :arg dt: time step to compute residence time. Basically,
                     the number of selected molecules wihtin the given
                     region at initial time divides the number that stayed
                     within the region after a time dt (in number of frames).

            The result is stored in *residueWise* attribute

        """

        # Gets residue number list
        resSel = self.sel[self.sel.find('of ') + 3:]
        resSel = self.data.selection(resSel).getUniqueResidues()
        resSel = np.array([val for val in resSel if val.isdecimal()])

        corr = np.zeros_like(resSel, dtype=float)

        deltaTime = self.frames[-1] - self.frames[0] + 1
        oriList = self.frames[0] + ((deltaTime - self.tMax)
                   * np.random.random(self.nbrTimeOri)).astype(int)

        for resId, residue in enumerate(resSel):
            for idx, frame in enumerate(oriList):
                print("Processing time origin %i of %i for "
                      "residue %i of %i...        "
                      % (idx + 1, oriList.size, resId + 1,
                         int(resSel.size)), end='\r')

                # Processing selection text
                selText = self.sel

                selText += ' and resid %s' % residue

                sel = self.data.selection(
                    selText + " frame %i %i" % (frame, frame + dt))

                corr[resId] += np.intersect1d(sel[0], sel[1]).size

        self.residueWise    = corr / np.max(corr)
        self.residues       = resSel.astype(int)
        self.residueWise_dt = dt

# --------------------------------------------
# Plotting methods
# --------------------------------------------
    def plotResidenceTime(self):
        """ Used to quickly plot residence time. """

        fig, ax = plt.subplots()

        ax.plot(self.times, self.resTime, marker='o')
        ax.set_xlabel('Time [ps]')
        ax.set_ylabel('P(t)')

        fig.show()

    def plotResidueWiseResidenceTime(self):
        """ Used to quickly plot residue wise residence time. """

        fig, ax = plt.subplots()

        ax.bar(self.residues, self.residueWise)
        ax.set_xlabel('Residue')
        ax.set_ylabel('P(dt=%i ps)'
                      % np.ceil(self.residueWise_dt
                                * self.data.timestep
                                * self.data.dcdFreq[0] * 1e12))

        fig.show()


from django.conf.urls import patterns, include, url
from django.contrib import admin

urlpatterns = patterns('',
                       # Examples:
                       # url(r'^blog/', include('blog.urls')),
                       url(r'^$', 'login.views.landing', name='landing'),
                       url(r'^home/$', 'login.views.home', name='home'),
                       url(r'^account/$', 'login.views.account', name='account'),
                       url(r'^goals/$', 'login.views.goals', name='goals'),
                       url(r'^signup/$', 'login.views.signup', name='signup'),
                       url(r'^guide/$', 'login.views.guide', name='guide'),
                       # Purposefully redirecting to home
                       url(r'^profile/$', 'login.views.home', name='profile'),
                       url(r'^ATMs/$', 'login.views.ATMs', name='ATMs'),
                       url(r'^collection/$', 'login.views.collection', name='collection'),
                       url(r'^.*/?logout[/w]?$', 'login.views.logout', name = 'logout'),
                       url(r'^parent/$', 'login.views.parent', name='parent'),
                       url(r'^references/$', 'login.views.references', name='references'),
                       url(r'^404/$', 'login.views.http404', name='404'),
                       url(r'^admin/', include(admin.site.urls)),

)
# Default 404 and 403 code override
handler404 = 'login.views.http404'
handler403 = 'login.views.http403'


"""
Demonstrates how to use the `ChatInterface` and `PanelCallbackHandler` to create a
chatbot to talk to your Pandas DataFrame. This is heavily inspired by the
[LangChain `chat_pandas_df` Reference Example](https://github.com/langchain-ai/streamlit-agent/blob/main/streamlit_agent/chat_pandas_df.py).
"""
from __future__ import annotations

from pathlib import Path
from textwrap import dedent

import pandas as pd
import panel as pn
import param
import requests
from langchain.agents import AgentType
from langchain.chat_models import ChatOpenAI
from langchain_experimental.agents.agent_toolkits import create_pandas_dataframe_agent

from panel_chat_examples import EnvironmentWidgetBase

pn.extension("perspective")

PENGUINS_URL = (
    "https://raw.githubusercontent.com/mwaskom/seaborn-data/master/penguins.csv"
)
PENGUINS_PATH = Path(__file__).parent / "penguins.csv"
if not PENGUINS_PATH.exists():
    response = requests.get(PENGUINS_URL)
    PENGUINS_PATH.write_text(response.text)

FILE_DOWNLOAD_STYLE = """
.bk-btn a {
    padding: 0px;
}
.bk-btn-group > button, .bk-input-group > button {
    font-size: small;
}
"""

class Environment(EnvironmentWidgetBase):
    """Will be asking the user for the API Key if not set as environment variable"""

    OPENAI_API_KEY = param.String()

class AgentConfig(param.Parameterized):
    """Configuration used for the Pandas Agent"""

    user = param.String("Pandas Agent")
    avatar = param.String("🐼")

    show_chain_of_thought = param.Boolean(default=False)

    def _get_agent_message(self, message: str) -> pn.chat.ChatMessage:
        return pn.chat.ChatMessage(message, user=self.user, avatar=self.avatar)

class AppState(param.Parameterized):
    data = param.DataFrame()

    llm = param.Parameter(constant=True)
    pandas_df_agent = param.Parameter(constant=True)

    config: AgentConfig = param.ClassSelector(class_=AgentConfig)
    environ: Environment = param.ClassSelector(class_=Environment, constant=True)

    def __init__(
        self, config: AgentConfig | None = None, environ: Environment | None = None
    ):
        if not config:
            config = AgentConfig()
        if not environ:
            environ = Environment()
        super().__init__(config=config, environ=environ)

    @param.depends("environ.OPENAI_API_KEY", on_init=True, watch=True)
    def _reset_llm(self):
        with param.edit_constant(self):
            if self.environ.OPENAI_API_KEY:
                self.llm = ChatOpenAI(
                    temperature=0,
                    model="gpt-3.5-turbo-0613",
                    api_key=self.environ.OPENAI_API_KEY,
                    streaming=True,
                )
            else:
                self.llm = None

    @param.depends("llm", "data", on_init=True, watch=True)
    def _reset_pandas_df_agent(self):
        with param.edit_constant(self):
            if not self.error_message:
                self.pandas_df_agent = create_pandas_dataframe_agent(
                    self.llm,
                    self.data,
                    verbose=True,
                    agent_type=AgentType.OPENAI_FUNCTIONS,
                    handle_parsing_errors=True,
                )
            else:
                self.pandas_df_agent = None

    @property
    def error_message(self):
        if not self.llm and self.data is None:
            return dedent(
                """\
                Please provide your `OPENAI_API_KEY`, **upload a `.csv` file**
                and click the **send** button."""
            )
        if not self.llm:
            return "Please provide your `OPENAI_API_KEY`."
        if self.data is None:
            return "Please **upload a `.csv` file** and click the **send** button."
        return ""

    @property
    def welcome_message(self):
        return dedent(
            f"""
            I'm your LangChain Pandas DataFrame Agent.

            I execute LLM generated Python code under the hood - this can be bad if
            the `llm` generated Python code is harmful. Use cautiously!

            {self.error_message}"""
        ).strip()

    async def callback(self, contents, user, instance):
        if isinstance(contents, pd.DataFrame):
            self.data = contents
            instance.active = 1
            message = self.config._get_agent_message(
                dedent(
                    """You can ask me anything about the data. For example 'how many
                    species are there?'"""
                )
            )
            return message

        if self.error_message:
            message = self.config._get_agent_message(self.error_message)
            return message

        if self.config.show_chain_of_thought:
            langchain_callbacks = [
                pn.chat.langchain.PanelCallbackHandler(instance=instance)
            ]
        else:
            langchain_callbacks = []

        response = await self.pandas_df_agent.arun(
            contents, callbacks=langchain_callbacks
        )
        message = self.config._get_agent_message(response)
        return message

state = AppState()

chat_interface = pn.chat.ChatInterface(
    widgets=[
        pn.widgets.FileInput(name="Upload"),
        pn.widgets.TextInput(name="Message", placeholder="Send a message"),
    ],
    renderers=pn.pane.Perspective,
    callback=state.callback,
    callback_exception="verbose",
    show_rerun=False,
    show_undo=False,
    show_clear=False,
    min_height=400,
)
chat_interface.send(
    state.welcome_message,
    user=state.config.user,
    avatar=state.config.avatar,
    respond=False,
)

download_button = pn.widgets.FileDownload(
    PENGUINS_PATH,
    button_type="primary",
    button_style="outline",
    height=30,
    width=335,
    stylesheets=[FILE_DOWNLOAD_STYLE],
)

layout = pn.template.MaterialTemplate(
    title="🦜 LangChain - Chat with Pandas DataFrame",
    main=[chat_interface],
    sidebar=[
        download_button,
        "#### Agent Settings",
        state.config.param.show_chain_of_thought,
    ],
)

if state.environ.variables_not_set:
    layout.sidebar.append(state.environ)

layout.servable()


from collections import deque
N = int(input())
graph = [list(map(int, input().split())) for _ in range(N)]

# 방문 유무 확인
visited = [[False]*3 for _ in range(N)]

# 오른쪽만 가능
dx = [1,0]

# 아래만 가능
dy = [0,1]

def bfs(x, y):

  q = deque()
  q.append([x,y])

  while q:
    x, y = q.popleft()
    # 쪨리가 현재 밟고 있는 칸의 숫자를 인출
    step = graph[x][y]

    # 끝점이 -1이므로 -1로 도달하면 성공
    if graph[x][y] == -1:
      return True
    for move in range(2):
      # 쩰리가 현재 밟고 있는 숫자를 인출하고 이동수에 곱해서 이동
      nx = x+dx[move]*step
      ny = y+dy[move]*step

       # 주어진 범위를 벗어나는 경우 무시
  	   # x, y의 범위가 0,0보다 작아지거나, 주어진 matrix의 크기를 초과하는 경우
      if nx < 0 or nx >= N or ny < 0 or ny >= N:
        continue

      # 방문하지 않았을경우만
      if not visited[nx][ny]:
      	# 방문으로 수정
        visited[nx][ny] = True
        # 아직 우리가 찾는 조건(graph[x][y] == -1)이 아니므로 q에 담아주고 다시 반복
        q.append([nx, ny])

if bfs(0,0):
    print('HaruHaru')
else:
    print('Hing')


#! /usr/bin/env python3

# code2.py

filename1 = 'data1.txt'
filename2 = 'data2.txt'

def main():
    data1 = dict()
    data2 = dict()

    with open(filename1) as file1:
        for line in file1:
            parts = line.rstrip().split(':')
            key = parts[0]
            value = parts[1]
            if key in data1:
                data1[key].append(value)
            else:
                data1[key] = [value]

    with open(filename2) as file2:
        for line in file2:
            parts = line.rstrip().split(':')
            key = parts[0]
            value = parts[1]
            if key in data2:
                data2[key].append(value)
            else:
                data2[key] = [value]

    for key in data1:
        if key in data2:
            values = (data1[key] + data2[key])
            values_str = ','.join(values)
            print(f"{key}:{values_str}")
    return data1, data2

if __name__ == "__main__":
  d1, d2 =  main()


import os
import tqdm
import numpy as np
from pathlib import Path
from PIL import Image

clsID_to_trID = {
    0: 255,
    1: 0,
    2: 1,
    3: 2,
    4: 3,
    5: 4,
    6: 5,
    7: 6,
    8: 7,
    9: 8,
    10: 9,
    11: 10,
    12: 11,
    13: 12,
    14: 13,
    15: 14,
    16: 15,
    17: 16,
    18: 17,
    19: 18,
    20: 19,
    255: 255,
}

clsID_to_trID_w_background = clsID_to_trID.copy()
clsID_to_trID_w_background[0] = 20

def convert_to_trainID(
    maskpath, out_mask_dir, is_train, clsID_to_trID=clsID_to_trID, suffix="",
):
    mask = np.array(Image.open(maskpath))
    mask = np.vectorize(clsID_to_trID.get)(mask).astype(np.uint8)

    seg_filename = (
        os.path.join(out_mask_dir, "train" + suffix, os.path.basename(maskpath))
        if is_train
        else os.path.join(out_mask_dir, "val" + suffix, os.path.basename(maskpath))
    )
    if len(np.unique(mask)) == 1 and (np.unique(mask)[0] == 255 or np.unique(mask)[0] == 20):
        # ignore images with only background
        return
    Image.fromarray(mask).save(seg_filename, "PNG")

def download_dataset(ds_path):
    """
    Downloads the dataset
    """
    print('Downloading dataset...')
    # Downloading images
    os.system('wget http://host.robots.ox.ac.uk/pascal/VOC/voc2012/VOCtrainval_11-May-2012.tar')
    os.system(f'tar -xvf VOCtrainval_11-May-2012.tar -C {ds_path.parent.parent}')
    os.system(f'rm VOCtrainval_11-May-2012.tar')
    # Downloading annotations
    os.system('wget https://www.dropbox.com/s/oeu149j8qtbs1x0/SegmentationClassAug.zip')
    os.system('unzip SegmentationClassAug.zip -d ' + str(ds_path))
    os.system('rm SegmentationClassAug.zip')

def main():
    dataset_dir = Path(os.getenv("DETECTRON2_DATASETS", "datasets"))
    voc_path = dataset_dir / "VOCdevkit" / "VOC2012"

    if not voc_path.exists():
        download_dataset(voc_path)

    out_mask_dir = voc_path / "annotations_detectron2"

    for name in ["val"]:
        os.makedirs((out_mask_dir / name), exist_ok=True)
        os.makedirs((out_mask_dir / (name + '_bg')), exist_ok=True)

        val_list = [
            os.path.join(voc_path, "SegmentationClassAug", f + ".png")
            for f in np.loadtxt(os.path.join(voc_path, "ImageSets/Segmentation/val.txt"), dtype=np.str).tolist()
        ]

        for file in tqdm.tqdm(val_list):
            convert_to_trainID(file, out_mask_dir, is_train=False)
            convert_to_trainID(file, out_mask_dir, is_train=False,
                               clsID_to_trID=clsID_to_trID_w_background, suffix="_bg")

if __name__ == "__main__":
    main()


n = int(input())
arr = list(map(int, input().split()))

arr.sort(reverse=True)

num = arr[0]
mem_cnt = 0
g_cnt = 0
i = 0

for i in arr:
  if num == mem_cnt:
    num = i
    g_cnt += 1
    mem_cnt = 1
  else:
    mem_cnt += 1

print(g_cnt+1)

이코테/모험가길드.py


# Definition for singly-linked list.
from typing import Optional

class ListNode:
    def __init__(self, x):
        self.val = x
        self.next = None

class Solution:
    def hasCycle(self, head: Optional[ListNode]) -> bool:
        if not head:
            return False

        slow = head
        fast = head.next

        while slow != fast:
            if fast is None or fast.next is None:
                return False
            fast = fast.next.next
            slow = slow.next
        return True


import json
import time
import tempfile
import botocore

from boto3.dynamodb.conditions import Key
from boto3.dynamodb.types import TypeDeserializer
from sys import maxsize
import cloud.shortuuid as shortuuid

def get_boto3_session(credentials):
    import boto3
    bundle = credentials['aws']
    access_key = bundle['access_key']
    secret_key = bundle['secret_key']
    region_name = bundle.get('region', 'ap-northeast-2')
    session = boto3.Session(
        aws_access_key_id=access_key,
        aws_secret_access_key=secret_key,
        region_name=region_name,
    )
    return session

class APIGateway:
    stage_name = 'prod_aws_interface'

    def __init__(self, boto3_session):
        self.region = boto3_session.region_name
        self.client = boto3_session.client('apigateway')
        self.lambda_client = boto3_session.client('lambda')
        self.iam_client = IAM(boto3_session)

    def get_rest_api_id(self, rest_api_name):
        rest_api_id = None
        apis = self.get_rest_apis().get('items', [])
        for api in apis:
            if api['name'] == rest_api_name:
                rest_api_id = api['id']
                break
        if not rest_api_id:
            response = self.create_rest_api(rest_api_name)
            rest_api_id = response['id']
        return rest_api_id

    def delete_rest_api_by_name(self, rest_api_name):
        try:
            rest_api_id = self.get_rest_api_id(rest_api_name)
            response = self.client.delete_rest_api(
                restApiId=rest_api_id
            )
            return response
        except BaseException as ex:
            print(ex)
            return None

    def get_root_resource_id(self, rest_api_id):
        resources = self.get_resources(rest_api_id).get('items', [])
        parent_id = None
        for res in resources:
            if res['path'] == '/':
                parent_id = res['id']
        return parent_id

    def get_lambda_function_resource_id(self, rest_api_id, lambda_func_name):
        resources = self.get_resources(rest_api_id).get('items', [])
        resource_id = None
        for res in resources:
            if res.get('pathPart') == lambda_func_name:
                resource_id = res['id']
        return resource_id

    def get_rest_api_url(self, cloud_api_name):
        base_url = 'https://{}.execute-api.{}.amazonaws.com/{}/{}'
        api_id = self.get_rest_api_id(cloud_api_name)
        region = self.region
        stage = self.stage_name
        url = base_url.format(api_id, region, stage, cloud_api_name)
        return url

    def connect_with_lambda(self, cloud_api_name, lambda_func_name):
        aws_region = self.region
        api_client = self.client
        aws_lambda = self.lambda_client

        # Find existing rest api
        rest_api_id = self.get_rest_api_id(cloud_api_name)
        root_resource_id = self.get_root_resource_id(rest_api_id)
        resource_id = self.get_lambda_function_resource_id(rest_api_id, lambda_func_name)

        stage_name = self.stage_name

        if not resource_id:
            resource_id = api_client.create_resource(
                restApiId=rest_api_id,
                parentId=root_resource_id,  # resource id for the Base API path
                pathPart=lambda_func_name
            )['id']

        self.put_method(rest_api_id, resource_id, 'POST')

        lambda_version = aws_lambda.meta.service_model.api_version

        aws_account_id = self.iam_client.get_account_id()

        uri_data = {
            "aws-region": aws_region,
            "api-version": lambda_version,
            "aws-acct-id": aws_account_id,
            "lambda-function-name": lambda_func_name,
        }
        uri = self.get_uri(uri_data)

        integration_response_param = {
            'method.response.header.Access-Control-Allow-Headers': '\'Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token,X-Requested-With\'',
            'method.response.header.Access-Control-Allow-Methods': '\'POST,OPTIONS\'',
            'method.response.header.Access-Control-Allow-Origin': '\'*\''
        }
        method_response_param = {
            'method.response.header.Access-Control-Allow-Headers': False,
            'method.response.header.Access-Control-Allow-Origin': False,
            'method.response.header.Access-Control-Allow-Methods': False,
            'method.response.header.X-Requested-With': False,
        }

        # create integration
        self.put_integration(rest_api_id, resource_id, 'POST', uri)
        self.put_integration_response(rest_api_id, resource_id, 'POST')
        self.put_method_response(rest_api_id, resource_id, 'POST', method_response_param)

        uri_data['aws-api-id'] = rest_api_id
        post_source_arn = self.get_source_arn(uri_data, 'POST')

        print('put_permission post'.center(80, '-'))
        self.put_permission(lambda_func_name, post_source_arn)

        # CORS OPTION
        self.put_method(rest_api_id, resource_id, 'OPTIONS')
        self.put_method_response(rest_api_id, resource_id, 'OPTIONS', method_response_param)
        self.put_integration(rest_api_id, resource_id, 'OPTIONS', uri)
        self.put_integration_response(rest_api_id, resource_id, 'OPTIONS', integration_response_param)

        print('create_deployment'.center(80, '-'))
        api_client.create_deployment(
            restApiId=rest_api_id,
            stageName=stage_name,
        )

    def put_method(self, rest_api_id, resource_id, method_type, auth_type='NONE'):
        try:
            response = self.client.put_method(
                restApiId=rest_api_id,
                resourceId=resource_id,
                httpMethod=method_type,
                authorizationType=auth_type,
                apiKeyRequired=False,
            )
        except BaseException as ex:
            print(ex)
            return None
        return response

    def put_method_response(self, rest_api_id, resource_id, method_type, response_parameters=dict()):
        try:
            response = self.client.put_method_response(
                restApiId=rest_api_id,
                resourceId=resource_id,
                httpMethod=method_type,
                statusCode="200",
                responseParameters=response_parameters,
            )
        except BaseException as ex:
            response = None
            print(ex)
        return response

    def get_uri(self, uri_data):
        uri = "arn:aws:apigateway:{aws-region}:lambda:path/{api-version}/functions/arn:aws:lambda:{aws-region}:" \
               "{aws-acct-id}:function:{lambda-function-name}/invocations".format(**uri_data)
        return uri

    def put_integration(self, rest_api_id, resource_id, method_type, uri):
        integration_resp = self.client.put_integration(
            restApiId=rest_api_id,
            resourceId=resource_id,
            httpMethod=method_type,
            type="AWS",
            integrationHttpMethod=method_type,
            uri=uri,
        )
        return integration_resp

    def put_integration_response(self, rest_api_id, resource_id, method_type, response_parameters=dict()):
        response = self.client.put_integration_response(
            restApiId=rest_api_id,
            resourceId=resource_id,
            httpMethod=method_type,
            statusCode="200",
            selectionPattern=".*",
            responseParameters=response_parameters,
        )
        return response

    def get_source_arn(self, uri_data, method_type):
        method_type = 'POST'
        arn = "arn:aws:execute-api:{aws-region}:{aws-acct-id}:{aws-api-id}/*/" + method_type + "/{lambda-function-name}"
        arn = arn.format(**uri_data)
        return arn

    def put_permission(self, lambda_func_name, source_arn):
        statement_id = 'state{}'.format(lambda_func_name)

        try:
            _ = self.lambda_client.remove_permission(
                FunctionName=lambda_func_name,
                StatementId=statement_id,
            )
        except Exception:
            print('Failed to remove permissions for {}'.format(lambda_func_name))
            pass

        try:
            self.lambda_client.add_permission(
                FunctionName=lambda_func_name,
                StatementId=statement_id,
                Action="lambda:InvokeFunction",
                Principal="apigateway.amazonaws.com",
                SourceArn=source_arn
            )
        except Exception:
            raise Exception('Failed to put permissions for {}'.format(lambda_func_name))

    def get_method(self, rest_api_id, resource_id, method_type='POST'):
        response = self.client.get_method(
            restApiId=rest_api_id,
            resourceId=resource_id,
            httpMethod=method_type
        )
        return response

    def get_rest_apis(self):
        response = self.client.get_rest_apis(
            limit=100
        )
        return response

    def create_rest_api(self, api_name):
        response = self.client.create_rest_api(
            name=api_name,
            endpointConfiguration={
                'types': [
                    'EDGE'
                ]
            }
        )
        return response

    def create_resource(self, rest_api_id, parent_id, path_part):
        response = self.client.create_resource(
            restApiId=rest_api_id,
            parentId=parent_id,
            pathPart=path_part
        )
        return response

    def get_resources(self, rest_api_id):
        response = self.client.get_resources(
            restApiId=rest_api_id,
            limit=100,
        )
        return response

    def delete_rest_api(self, rest_api_id):
        return self.client.delete_rest_api(
            restApiId=rest_api_id
        )

    def get_method_response(self, rest_api_id, resource_id, method_type, status_code):
        response = self.client.get_method_response(
            restApiId=rest_api_id,
            resourceId=resource_id,
            httpMethod=method_type,
            statusCode=status_code
        )
        return response

class DynamoDB:
    def __init__(self, boto3_session):
        self.client = boto3_session.client('dynamodb')
        self.resource = boto3_session.resource('dynamodb')

    def init_table(self, table_name):
        self.create_table(table_name)
        # self.update_table(table_name, index={
        #     'hash_key': 'partition',
        #     'hash_key_type': 'S',
        #     'sort_key': 'creationDate',
        #     'sort_key_type': 'N'
        # })
        # self.update_table(table_name, index={
        #     'hash_key': 'invertedQuery',
        #     'hash_key_type': 'S',
        #     'sort_key': 'creationDate',
        #     'sort_key_type': 'N'
        # })

    def create_table(self, table_name):
        try:
            response = self.client.create_table(
                AttributeDefinitions=[
                    {
                        'AttributeName': 'id',
                        'AttributeType': 'S'
                    }, {
                        'AttributeName': 'partition',
                        'AttributeType': 'S'
                    }, {
                        'AttributeName': 'invertedQuery',
                        'AttributeType': 'S'
                    }, {
                        'AttributeName': 'creationDate',
                        'AttributeType': 'N'
                    }
                ],
                TableName=table_name,
                KeySchema=[
                    {
                        'AttributeName': 'id',
                        'KeyType': 'HASH'
                    },
                ],
                BillingMode='PAY_PER_REQUEST',
                StreamSpecification={
                    'StreamEnabled': True,
                    'StreamViewType': 'KEYS_ONLY'
                },
                GlobalSecondaryIndexes=[
                    {
                        'IndexName': 'partition-creationDate',
                        'KeySchema': [
                            {
                                'AttributeName': 'partition',
                                'KeyType': 'HASH'
                            }, {
                                'AttributeName': 'creationDate',
                                'KeyType': 'RANGE'
                            },
                        ],
                        'Projection': {
                            'ProjectionType': 'ALL'
                        }
                    }, {
                        'IndexName': 'invertedQuery-creationDate',
                        'KeySchema': [
                            {
                                'AttributeName': 'invertedQuery',
                                'KeyType': 'HASH'
                            }, {
                                'AttributeName': 'creationDate',
                                'KeyType': 'RANGE'
                            },
                        ],
                        'Projection': {
                            'ProjectionType': 'ALL'
                        }
                    },
                ]
            )
            print('CREATING TABLE...')
            self.client.get_waiter('table_exists').wait(TableName=table_name)
            return response
        except Exception as ex:
            print(ex)
            return None

    def update_table(self, table_name, index):
        attr_updates = []
        index_updates = []
        hash_key = index['hash_key']
        hash_key_type = index['hash_key_type']
        sort_key = index.get('sort_key', None)
        sort_key_type = index.get('sort_key_type', None)
        key_schema = [
            {
                'AttributeName': hash_key,
                'KeyType': 'HASH'
            }
        ]
        if sort_key:
            index_name = hash_key + '-' + sort_key
            key_schema.append({
                'AttributeName': sort_key,
                'KeyType': 'RANGE'
            })
        else:
            index_name = hash_key
        index_create = {
            'Create': {
                'IndexName': index_name,
                'KeySchema': key_schema,
                'Projection': {
                    'ProjectionType': 'ALL'
                }
            }
        }
        hash_key_update = {
            'AttributeName': hash_key,
            'AttributeType': hash_key_type
        }
        index_updates.append(index_create)
        attr_updates.append(hash_key_update)
        if sort_key:
            sort_key_update = {
                'AttributeName': sort_key,
                'AttributeType': sort_key_type
            }
            attr_updates.append(sort_key_update)

        while True:
            try:
                response = self.client.update_table(
                    AttributeDefinitions=attr_updates,
                    TableName=table_name,
                    GlobalSecondaryIndexUpdates=index_updates
                )
                return response
            except Exception as e:
                print(e)
                return e

    def delete_table(self, name):
        try:
            response = self.client.delete_table(
                TableName=name
            )
            return response
        except BaseException as ex:
            print(ex)
            return None

    def create_partition(self, table_name, partition):
        item = {
            'name': partition
        }
        response = self.put_item(table_name, 'partition-list', item, partition, indexing=False)
        return response

    def get_partition(self, table_name, partition):
        response = self.get_item(table_name, partition)
        return response.get('Item', None)

    def delete_partition(self, table_name, partition):
        return self.delete_item(table_name, partition)

    def get_partitions(self, table_name):
        return self.get_items_in_partition(table_name, 'partition-list', limit=maxsize)

    def delete_item(self, table_name, item_id):
        item = self.get_item(table_name, item_id)
        partition = item.get('Item', {}).get('partition', None)
        if not partition:
            print('It cannot be removed. table_name: {}, item_id: {}'.format(table_name, item_id))
            return False
        response = self.client.delete_item(
            TableName=table_name,
            Key={
                'id': {
                    'S': item_id
                }
            }
        )
        self._add_item_count(table_name, '{}-count'.format(partition), value_to_add=-1)
        self._delete_inverted_query(table_name, item_id)
        return response

    def get_item(self, table_name, item_id):
        table = self.resource.Table(table_name)
        item = table.get_item(Key={
            'id': item_id
        })
        return item

    def put_item(self, table_name, partition, item, item_id=None, creation_date=None, indexing=True):
        if not item_id:
            item_id = str(shortuuid.uuid())
        if not creation_date:
            creation_date = int(time.time())
        table = self.resource.Table(table_name)
        item['id'] = item_id
        item['creationDate'] = creation_date
        item['partition'] = partition
        response = table.put_item(
            Item=item,
        )
        self._add_item_count(table_name, '{}-count'.format(partition))
        if indexing:
            self._delete_inverted_query(table_name, item_id)
            self._put_inverted_query(table_name, partition, item)
        return response

    def get_items(self, table_name, item_ids):
        keys = list([{'id': {'S': item_id}} for item_id in item_ids])
        response = self.client.batch_get_item(
            RequestItems={
                table_name: {
                    'Keys': keys,
                    'ConsistentRead': True
                }
            }
        )
        type_deserializer = TypeDeserializer()
        items = response['Responses'][table_name]
        for item in items:
            for key, value in item.items():
                value = type_deserializer.deserialize(value)
                item[key] = value

        return {'Items': items}

    def get_items_in_partition(self, table_name, partition, start_key=None, limit=100, reverse=False):
        scan_index_forward = not reverse
        index_name = 'partition-creationDate'
        table = self.resource.Table(table_name)
        self.get_items_eq_hash_key(table_name, index_name, 'partition', partition, start_key, limit)
        if not limit:
            limit = maxsize
        if start_key:
            response = table.query(
                IndexName=index_name,
                Limit=limit,
                ConsistentRead=False,
                ExclusiveStartKey=start_key,
                KeyConditionExpression=Key('partition').eq(partition),
                ScanIndexForward=scan_index_forward,
            )
        else:
            response = table.query(
                IndexName=index_name,
                Limit=limit,
                ConsistentRead=False,
                KeyConditionExpression=Key('partition').eq(partition),
                ScanIndexForward=scan_index_forward,
            )
        return response

    def get_inverted_queries(self, table_name, partition, field, operand, operation, start_key=None, limit=100, reverse=False):
        if operation == 'in' or operation == 'eq':
            hash_key_name = 'invertedQuery'
            sort_key_name = 'creationDate'
            hash_key = '{}-{}-{}-{}'.format(partition, field, operand, operation)
            index_name = '{}-{}'.format(hash_key_name, sort_key_name)
            response = self.get_items_eq_hash_key(table_name, index_name, hash_key_name, hash_key, start_key, limit, reverse)
            return response
        else:
            raise BaseException('an operation is must be <in> or <eq>')

    def get_items_eq_hash_key(self, table_name, index_name, hash_key_name, hash_key_value,
                              start_key=None, limit=100, reverse=False):
        key_expression = Key(hash_key_name).eq(hash_key_value)
        response = self.get_items_with_key_expression(table_name, index_name, key_expression, start_key, limit, reverse)
        return response

    def get_items_with_key_expression(self, table_name, index_name, key_expression,
                                      start_key=None, limit=100, reverse=False):
        scan_index_forward = not reverse
        table = self.resource.Table(table_name)
        if start_key:
            response = table.query(
                IndexName=index_name,
                Limit=limit,
                ConsistentRead=False,
                ExclusiveStartKey=start_key,
                KeyConditionExpression=key_expression,
                ScanIndexForward=scan_index_forward,
            )
        else:
            response = table.query(
                IndexName=index_name,
                Limit=limit,
                ConsistentRead=False,
                KeyConditionExpression=key_expression,
                ScanIndexForward=scan_index_forward,
            )
        return response

    def update_item(self, table_name, item_id, item):
        table = self.resource.Table(table_name)
        update_date = int(time.time())
        item['id'] = item_id
        item['_update_date'] = update_date
        response = table.put_item(
            TableName=table_name,
            Item=item,
        )
        partition = item.get('partition')
        self._delete_inverted_query(table_name, item_id)
        self._put_inverted_query(table_name, partition, item)
        return response

    def _put_item_count(self, table_name, count_id, value):
        response = self.put_item(table_name, 'meta_info', {'count': value}, item_id=count_id)
        return response

    def _add_item_count(self, table_name, count_id, value_to_add=1):
        response = self.client.update_item(
            ExpressionAttributeNames={
                '#A': 'count',
            },
            ExpressionAttributeValues={
                ':v': {
                    'N': str(value_to_add),
                }
            },
            Key={
                'id': {
                    'S': count_id,
                }
            },
            ReturnValues='ALL_NEW',
            TableName=table_name,
            UpdateExpression='ADD #A :v',
        )
        return response

    def get_item_count(self, table_name, count_id):
        response = self.get_item(table_name, count_id)
        return response

    def _eq_operands(self, value):
        value = str(value)
        return [value]

    def _put_inverted_query(self, table_name, partition, item):
        table = self.resource.Table(table_name)
        item_id = item.get('id')
        creation_date = item.get('creationDate', int(time.time()))
        with table.batch_writer() as batch:
            for field, value in item.items():
                for operand in self._eq_operands(value):
                    self._put_inverted_query_field(batch, partition, field, operand, 'eq', item_id, creation_date)

    def _put_inverted_query_field(self, table, partition, field, operand, operation, item_id, creation_date):
        _invertedQuery = '{}-{}-{}-{}'.format(partition, field, operand, operation)
        query = {
            'id': 'query-{}'.format(shortuuid.uuid()),
            'partition': 'index-{}'.format(item_id),
            'invertedQuery': _invertedQuery,
            'creationDate': creation_date,
            'item_id': item_id,
        }
        response = table.put_item(
            Item=query,
        )
        return response

    def _delete_inverted_query(self, table_name, item_id):
        table = self.resource.Table(table_name)
        items = self.get_items_in_partition(table_name, 'index-{}'.format(item_id), limit=maxsize).get('Items', [])
        with table.batch_writer() as batch:
            for item in items:
                inverted_query_id = item.get('id', None)
                batch.delete_item(
                    Key={
                        'id': inverted_query_id
                    }
                )

class Lambda:
    def __init__(self, boto3_session):
        self.client = boto3_session.client('lambda')

    def create_function(self, name, description, runtime, role_arn, handler, zip_file):
        response = self.client.create_function(
            FunctionName=name,
            Runtime=runtime,
            Role=role_arn,
            Handler=handler,
            Code={
                'ZipFile': zip_file
            },
            Description=description,
            Timeout=128,
            MemorySize=1024,
            Publish=True,
            TracingConfig={
                'Mode': 'Active'
            },
        )
        return response

    def update_function_code(self, name, zip_file):
        response = self.client.update_function_code(
            FunctionName=name,
            ZipFile=zip_file,
            Publish=True
        )
        return response

    def delete_function(self, name):
        try:
            response = self.client.delete_function(
                FunctionName=name,
            )
            return response
        except BaseException as ex:
            print(ex)
            return None

    def invoke_function(self, name, payload_bytes):
        response = self.client.invoke(
            FunctionName=name,
            InvocationType='RequestResponse',
            Payload=payload_bytes,
        )
        return response

class S3:
    def __init__(self, boto3_session):
        self.client = boto3_session.client('s3')
        self.resource = boto3_session.resource('s3')
        self.region = boto3_session.region_name

    @classmethod
    def to_dns_name(cls, bucket_name):
        def f(c):
            if c.isupper():
                return 'c.{}'.format(c.lower())
            else:
                return c
        bucket_name = [f(c) for c in bucket_name]
        bucket_name = ''.join(bucket_name)
        return bucket_name

    def init_bucket(self, bucket_name):
        try:
            self.create_bucket(bucket_name)
            print('create_bucket success')
        except Exception as ex:
            print(ex)

    def create_bucket(self, bucket_name):
        bucket_name = self.to_dns_name(bucket_name)
        response = self.client.create_bucket(
            ACL='private',
            Bucket=bucket_name,
            CreateBucketConfiguration={
                'LocationConstraint': self.region
            },
        )
        return response

    def upload_bin(self, bucket_name, file_name, binary):
        bucket_name = self.to_dns_name(bucket_name)
        with tempfile.TemporaryFile() as tmp:
            tmp.write(binary)
            tmp.seek(0)
            response = self.client.upload_fileobj(tmp, bucket_name, file_name)
            return response

    def delete_bin(self, bucket_name, file_name):
        bucket_name = self.to_dns_name(bucket_name)
        return self.resource.Object(bucket_name, file_name).delete()

    def download_bin(self, bucket_name, file_name):
        bucket_name = self.to_dns_name(bucket_name)
        try:
            with tempfile.NamedTemporaryFile() as data:
                self.client.download_fileobj(bucket_name, file_name, data)
                data.seek(0)
                return data.read()
        except botocore.exceptions.ClientError as e:
            if e.response['Error']['Code'] == "404":
                print("The object does not exist.")
                return None
            else:
                raise

    def delete_bucket(self, bucket_name):
        try:
            response = self.client.delete_bucket(
                Bucket=bucket_name
            )
            return response
        except BaseException as ex:
            print(ex)
            return None

class IAM:
    policy_arns = [
        'arn:aws:iam::aws:policy/AWSLambdaExecute',
        'arn:aws:iam::aws:policy/AmazonDynamoDBFullAccess',
        'arn:aws:iam::aws:policy/AmazonS3FullAccess',
        'arn:aws:iam::aws:policy/AWSXrayFullAccess',
    ]

    def __init__(self, boto3_session):
        self.client = boto3_session.client('iam')
        self.resource = boto3_session.resource('iam')

    def create_role_and_attach_policies(self, role_name):
        self.create_role(role_name)
        self.attach_policies(role_name, self.policy_arns)
        return self.get_role_arn(role_name)

    def get_role_arn(self, role_name):
        role = self.resource.Role(role_name)
        role_arn = role.arn
        return role_arn

    def delete_role(self, role_name):
        try:
            response = self.client.delete_role(
                RoleName=role_name
            )
            return response
        except BaseException as ex:
            print(ex)
            return None

    def create_role(self, role_name):
        assume_role_policy_document = {
            "Version": "2012-10-17",
            "Statement": [
                {
                    "Effect": "Allow",
                    "Principal": {
                        "Service": "lambda.amazonaws.com"
                    },
                    "Action": "sts:AssumeRole"
                }
            ]
        }
        assume_role_policy_document = json.dumps(assume_role_policy_document)
        try:
            response = self.client.create_role(
                Path='/',
                RoleName=role_name,
                AssumeRolePolicyDocument=assume_role_policy_document,
            )
        except:
            print('Already have a role', role_name)
            return None
        return response

    def attach_policies(self, role_name, policy_arns):
        for policy_arn in policy_arns:
            self.attach_policy(role_name, policy_arn)

    def attach_policy(self, role_name, policy_arn):
        try:
            response = self.client.attach_role_policy(
                RoleName=role_name,
                PolicyArn=policy_arn
            )
        except Exception as e:
            print('Failed to attach policy: {} by: {}'.format(role_name, e))
            return None
        return response

    def detach_all_policies(self, role_name):
        for policy_arn in self.policy_arns:
            self.detach_policy(role_name, policy_arn)

    def detach_policy(self, role_name, policy_arn):
        try:
            response = self.client.detach_role_policy(
                RoleName=role_name,
                PolicyArn=policy_arn
            )
            return response
        except BaseException as ex:
            print(ex)
            return None

    def get_account_id(self):
        account_id = self.resource.CurrentUser().arn.split(':')[4]
        return account_id

class CostExplorer:
    def __init__(self, boto3_session):
        self.client = boto3_session.client('ce', 'us-east-1')

    def get_cost_and_usage(self, start, end):
        response = self.client.get_cost_and_usage(
            TimePeriod={
                'Start': start,
                'End': end
            },
            Granularity='MONTHLY',
            Metrics=['AmortizedCost'],
            GroupBy=[
                {
                    'Type': 'DIMENSION',
                    'Key': 'SERVICE'
                },
            ],
        )
        return response

    def get_cost(self, start, end):
        response = self.client.get_cost_and_usage(
            TimePeriod={
                'Start': start,
                'End': end
            },
            Granularity='MONTHLY',
            Metrics=['BLENDED_COST']
        )
        return response


from requests import exceptions, get
import logging

def __downloadFilings(cik: str) -> list:
    """Function to download the XML text of listings pages for a given CIK
    from the EDGAR database.

    Arguments:
        cik {str} -- Target CIK.

    Returns:
        list -- List of page XML, comprising full listing metadata for CIK.
    """

    idx = 0  # Current page index
    end = False  # Flags for loop
    count = 100  # Number of results per page (limited by SEC)

    # Text indicating next page exists
    next_page_text = 'rel="next" type="application/atom+xml" />'

    pages = []

    while not end:
        # Making request
        page_text = __makeRequest(cik=cik, start_idx=idx, count=count)
        end = (page_text.find(next_page_text) == -1)  # Update end flag
        idx += count  # Increment index for next page
        pages.append(page_text)  # Save page text

    return pages

def __makeRequest(cik: str, start_idx: int, count: int, retry: bool=False) \
    -> str:
    """Function to make a request to the EDGAR system to retrieve XML with
    listings for a given CIK.

    Arguments:
        cik {str} -- Target CIK.
        start_idx {int} -- Start index (for pagination).
        count {int} -- Count of results per page.

    Keyword Arguments:
        retry {bool} -- Flag for auto-retry (default: {False}).

    Raises:
        exceptions.RetryError -- Raised if the request retry fails.

    Returns:
        str -- Page text with XML listing metadata for the target CIK.
    """

    base_url = 'https://sec.gov/cgi-bin/browse-edgar'

    # Building parameters for request wit hticker
    # Note: Order of parameters here is important; null params are
    #       necessary cuz the SEC is silly
    params = {
        'action': 'getcompany',
        'CIK': cik,
        'type': '',
        'dateb': '',
        'owner': 'exclude',
        'start': start_idx,
        'count': count,
        'output': 'atom'
    }

    # Making request
    r = get(url=base_url, params=params)

    # Retry request if it fails; raise Exception if it still doesn't work
    if (not r.ok) and (not retry):
        logging.warn('Listings request failed for CIK {0}. Trying again...'
                     .format(cik))
        return __makeRequest(cik=cik, start_idx=start_idx, count=count,
                             retry=True)
    elif not r.ok:
        logging.error('Listings request failed for CIK {0}'.format(cik))
        raise exceptions.RetryError('Listings request retry failed for CIK {0}'
                                    .format(cik))

    return r.text


from random import randint
import random

print("WELCOME TO THE GUESSING GAME")
print("THINKING BETWEEN 1 TO 100")

def makeaguess(chance,num,attempt):

    if chance == num:
          print("you have guessed it right!!")
    elif chance > num:
          print("too high")
          return attempt-1
    elif chance < num:
          print("too low")
          return attempt - 1

def levels():
  level=input("Pick a level 'easy' or 'hard':")
  if level=="easy":
      return 10
  else:
      return 5

num = random.randint(1,100)
attempt = levels()
chance = 0
while chance!= num:
  print(f"You have {attempt} attempts remaining to guess the number.")
  chance = int(input("make a guess:"))
  attempt= makeaguess(chance, num, attempt)
  if attempt == 0:
      print("You've run out of guesses, you lose.")
      break
  elif chance != num:
      print("Guess again.")


import tensorflow as tf

from constant_params import window_size

class EvolEncoder2(tf.keras.layers.Layer):
    def __init__(self,
                 num_species=200,
                 pairwise_type='none',
                 weighting_schema='spe'):
        super(EvolEncoder2, self).__init__()

        self.num_species = num_species
        self.pairwise_type = pairwise_type
        self.weighting_schema = weighting_schema

    def build(self, input_shape):
        if self.weighting_schema == 'spe':
            self.W = self.add_weight(
                name='species_weights',
                shape=(1, self.num_species),
                initializer=tf.keras.initializers.Constant(0.0),
                trainable=True)
            '''
            self.B = self.add_weight(
                name='b',
                shape=[],
                initializer=tf.keras.initializers.Constant(0.0),
                trainable=False)
            '''
        elif self.weighting_schema == 'none':
            self.W = tf.constant(1.0 / self.num_species,
                                 shape=(1, self.num_species),
                                 dtype=tf.float32)
        else:
            raise NotImplementedError(
                f'weighting_schema {weighting_schema} NotImplementedError')

    def call(self, x):
        shape = tf.shape(x)
        B, L, N = shape[0], shape[1], shape[2] // 2
        center_pos = window_size // 2
        A = 21 + 1  #alphabet size
        A = 21

        ww = x[:, :, 200:]
        w = x[:, 0, 200:]
        x = x[:, :, :200]
        if self.weighting_schema == 'spe':
            #W = self.B * w / 100.0 + self.W  #+ tf.cast(tf.less(w, 0.01),
            #          tf.float32) * -1e12
            W = tf.nn.softmax(self.W, axis=-1)
        else:
            W = self.W

        #tf.print(self.B, self.W)
        #x = tf.where(tf.less(ww, 0.01), 21.0, x)
        x = tf.one_hot(tf.cast(x, tf.int32), depth=A, axis=-1)

        #W, (batch, 1, 1, species)
        #x, (batch, len, species, 21)
        #output, (batch, len, 1, 21)
        x1 = tf.matmul(W[:, tf.newaxis, tf.newaxis], x)

        #pairwise
        if self.pairwise_type == 'fre':
            x2 = tf.matmul(x[:, center_pos:center_pos + 1, :, :, tf.newaxis],
                           x[:, :, :, tf.newaxis])
            x2 = tf.reshape(x2, (B, L, N, A * A))
            x2 = tf.matmul(W, x2)
            x2 = tf.squeeze(x2, axis=2)
        elif self.pairwise_type == 'cov':
            #numerical stability
            #(batch_size, window_size, 192, A)
            x2 = x - x1
            x2 = tf.sqrt(W[:, tf.newaxis, :, tf.newaxis]) * x2
            x2 = tf.transpose(x2, perm=(0, 2, 1, 3))
            x2_t = tf.reshape(x2, shape=(B, N, L * A))
            #left(batch_size, 192, A)
            #right(batch_size, 192, L * A)
            #result(batch-size, A, L * A)
            x2 = tf.matmul(x2[:, :, center_pos], x2_t, transpose_a=True)
            x2 = tf.reshape(x2, (B, A, L, A))
            x2 = tf.transpose(x2, (0, 2, 1, 3))
            x2 = tf.reshape(x2, (B, L, A * A))
            norm = tf.sqrt(
                tf.reduce_sum(tf.square(x2), keepdims=True, axis=-1) + 1e-12)
            x2 = tf.concat([x2, norm], axis=-1)
        elif self.pairwise_type == 'cov_all':
            #(batch, len, species, 21)
            x2 = x - x1
            #(batch, species, len, 21)
            x2 = tf.transpose(x2, perm=(0, 2, 1, 3))
            #(batch, species, len * 21)
            x2 = tf.reshape(x2, shape=(B, N, L * A))
            x2 = tf.sqrt(W[:, :, tf.newaxis]) * x2
            x2 = tf.matmul(x2, x2, transpose_a=True)
            x2 = tf.reshape(x2, (B, L, A, L, A))
            x2 = tf.transpose(x2, perm=(0, 1, 3, 2, 4))
            x2 = tf.reshape(x2, (B, L, L, A * A))
            norm = tf.sqrt(
                tf.reduce_sum(tf.square(x2), keepdims=True, axis=-1) + 1e-12)
            x2 = tf.concat([x2, norm], axis=-1)
        elif self.pairwise_type == 'inv_cov':
            x2 = x - x1
            x2 = tf.transpose(x2, perm=(0, 2, 1, 3))
            x2 = tf.reshape(x2, shape=(B, N, L * A))
            x2 = tf.sqrt(W[:, :, tf.newaxis]) * x2
            x2 = tf.matmul(x2, x2, transpose_a=True)
            x2 += tf.eye(L * A) * 0.01
            x2 = tf.linalg.inv(x2)
            x2 = tf.reshape(x2, (B, L, A, L, A))
            x2 = tf.transpose(x2, perm=(0, 1, 3, 2, 4))
            x2 = x2[:, center_pos]
            x2 = tf.reshape(x2, (B, L, A * A))

        elif self.pairwise_type == 'none':
            x2 = None
        else:
            raise NotImplementedError(
                f'pairwise_type {self.pairwise_type} not implemented')

        x1 = tf.squeeze(x1, axis=2)

        return x1, x2

class MultiHeadAttention(tf.keras.layers.Layer):
    def __init__(self,
                 d_model,
                 num_heads,
                 attn_score_type='add',
                 use_pairwise=False):
        super(MultiHeadAttention, self).__init__()
        self.num_heads = num_heads
        self.d_model = d_model

        assert d_model % self.num_heads == 0

        self.depth = d_model // num_heads

        self.wq = tf.keras.layers.Dense(d_model)
        self.wk = tf.keras.layers.Dense(d_model)
        self.wv = tf.keras.layers.Dense(d_model)

        self.out_proj = tf.keras.layers.Dense(d_model)

        self.attn_score_type = attn_score_type

        self.use_pairwise = use_pairwise
        self.use_kv_bias = True
        self.use_position_bias = True

        if self.use_pairwise:
            self.w_pairwise = tf.keras.layers.Dense(d_model)

    def build(self, input_shape):

        if self.use_position_bias:
            self.position_bias = self.add_weight(
                name='position_bias',
                shape=(1, 1, 1, window_size),
                dtype=tf.float32,
                trainable=True,
                initializer=tf.keras.initializers.Zeros())

        if self.attn_score_type == 'nn':
            self.agg_v = self.add_weight(
                name='agg_v',
                shape=(1, self.num_heads, 1, self.depth * 3),
                dtype=tf.float32,
                initializer=tf.keras.initializers.GlorotUniform(),
                trainable=True)

        if self.attn_score_type == 'add':
            self.agg_v = self.add_weight(
                name='agg_v',
                shape=(1, self.num_heads, 1, self.depth),
                dtype=tf.float32,
                initializer=tf.keras.initializers.GlorotUniform(),
                trainable=True)

        if self.use_pairwise and self.attn_score_type == 'dot':
            self.agg_pairwise = self.add_weight(
                name='agg_pairwise',
                shape=(1, self.num_heads, 1, self.depth),
                dtype=tf.float32,
                initializer=tf.keras.initializers.GlorotUniform(),
                trainable=True)
        '''
        self.attention_bias = self.add_weight(
            name='attention_bias',
            shape=(1, self.num_heads, 1, 1),
            dtype=tf.float32,
            initializer=tf.keras.initializers.Zeros(),
            trainable=True)
        '''

        if self.use_kv_bias:
            self.bias_k = self.add_weight(
                name='bias_k',
                shape=(1, 1, self.d_model),
                initializer=tf.keras.initializers.GlorotUniform())
            self.bias_v = self.add_weight(
                name='bias_v',
                shape=(1, 1, self.d_model),
                initializer=tf.keras.initializers.GlorotUniform())

            if self.use_position_bias:
                self.bias_position_bias = self.add_weight(
                    name='bias_position_bias',
                    shape=(1, 1, 1, 1),
                    initializer=tf.keras.initializers.Zeros())

            if self.use_pairwise:
                self.bias_pairwise = self.add_weight(
                    name='bias_pairwise',
                    shape=(1, 1, self.d_model),
                    initializer=tf.keras.initializers.GlorotUniform())

    def call(self, x, pairwise=None, mask=None):
        q, k, v = x
        if self.use_position_bias:
            if self.use_kv_bias:
                position_bias = tf.concat(
                    [self.position_bias, self.bias_position_bias], axis=3)
            else:
                position_bias = self.position_bias

            #position_bias = tf.tile(self.position_bias,
            #                        [1, self.num_heads, 1, 1])

        if self.use_pairwise:
            assert (pairwise is not None)

        shape = tf.shape(k)
        batch_size, neighbor_size = shape[0], shape[1]

        #q, k, v = x1d[:, :1], x1d, x1d

        #set query only for center position
        q = self.wq(q)  # (batch_size, 1, d_model)
        k = self.wk(k)  # (batch_size, neighbor_size, d_model)
        v = self.wv(v)  # (batch_size, neighbor_size, d_model)

        #if self.use_position_bias:
        #    position_bias = 0.5 * (position_bias +
        #                           tf.reverse(position_bias, axis=(3, )))

        if self.use_pairwise:
            pairwise = self.w_pairwise(pairwise)

        if self.use_kv_bias:
            #add bias along the sequence
            k = tf.concat([k, tf.tile(self.bias_k, (batch_size, 1, 1))],
                          axis=1)  #(batch_size, tgt_len + 1, embed_dim)
            v = tf.concat([v, tf.tile(self.bias_v, (batch_size, 1, 1))],
                          axis=1)  #(batch_size, tgt_len + 1, embed_dim)
            if mask is not None:
                mask = tf.pad(mask, paddings=[[0, 0], [0, 1]])

            if self.use_pairwise:
                pairwise = tf.concat(
                    [
                        pairwise,
                        tf.tile(self.bias_pairwise, (batch_size, 1, 1))
                    ],
                    axis=1)  #(batch_size, tgt_len + 1, embed_dim)

        #input=(batch_size, len, embed_dim)
        #output=(batch_size, num_heads, len, depth)
        def _split_heads(x):
            x = tf.reshape(x, (batch_size, -1, self.num_heads, self.depth))
            x = tf.transpose(x, (0, 2, 1, 3))
            return x

        v = _split_heads(v)

        #scaled-dot attention
        if self.attn_score_type == 'dot':
            q = _split_heads(q)
            k = _split_heads(k)

            #(batch_size, num_heads, 1, neighbor_size)
            attention_logits = tf.matmul(q, k, transpose_b=True)

            if self.use_pairwise:
                #dot_pairwies (1,num_hedas, 1, depth)
                #pairwise(batch_size, num_heads, seq_len, depth)
                pairwise = _split_heads(pairwise)
                pairwise = tf.nn.tanh(pairwise)
                pairwise_attention = tf.matmul(self.agg_pairwise,
                                               pairwise,
                                               transpose_b=True)
                #batch_size, seq_len, num_heads
                attention_logits += pairwise_attention

        elif self.attn_score_type == 'nn':
            q = _split_heads(q)
            k = _split_heads(k)
            s = [tf.tile(q, [1, 1, tf.shape(k)[2], 1]), k]
            if self.use_pairwise:
                pairwise = _split_heads(pairwise)
                s.append(pairwise)
            s = tf.concat(s, axis=-1)  #(batch_size, num_heads, len, depth*3)
            s = tf.matmul(self.agg_v, s,
                          transpose_b=True)  #(batch_size, num_heads, 1, len)
            attention_logits = tf.nn.leaky_relu(s)

        elif self.attn_score_type == 'add':  #additive attention
            '''
            s = q + k
            if self.use_pairwise:
                s += pairwise
            s = tf.nn.tanh(s)
            s = _split_heads(s)
            attention_logits = tf.matmul(self.agg_v, s, transpose_b=True)
            '''
            s = q + k
            if self.use_pairwise:
                s += pairwise
            s = _split_heads(s)
            s = tf.matmul(self.agg_v, s, transpose_b=True)
            attention_logits = tf.nn.leaky_relu(s)
            #attention_logits = tf.nn.tanh(s)

        else:
            raise NotImplementedError(
                f'{attn_score_type} not NotImplementedError')

        attention_logits /= tf.math.sqrt(tf.cast(self.depth, tf.float32))

        if self.use_position_bias:
            attention_logits += position_bias

        attention_logits = tf.squeeze(attention_logits, axis=2)

        #mask, (batch_size, 1, neighbor_size)
        if mask is not None:
            attention_logits += (mask[:, tf.newaxis] * -1e12)

        attention_weights = tf.nn.softmax(
            attention_logits,
            axis=-1)  # (batch_size, num_heads,  neighbor_size)

        #(batch_size,num_heads,1,depth)
        attention_weights = attention_weights[:, :, tf.newaxis]

        scaled_attention = tf.squeeze(tf.matmul(
            attention_weights, v), axis=2)  # (batch_size, num_heads,  depth)

        concat_attention = tf.reshape(
            scaled_attention,
            (batch_size, self.d_model))  # (batch_size, d_model)

        output = self.out_proj(concat_attention)
        #output = concat_attention
        return output


import re

file = open("data.txt")
text = file.read()

# emails = re.findall(r'\w+@\w+\.\w+', text)
emails = re.findall(r'(?:\w+\.)*\w+@(?:\w+\.)+\w+', text)

for email in emails:
    print(email)

for match in  re.finditer(r'((?:\w+\.)*\w+)@((?:\w+\.)+\w+)', text):
    print("email:{}, name:{}, domain:{}".format(
        match.group(), match.group(1), match.group(2)
    ))


import sqlite3

DATABASE_PATH = "/Users/nick/Dropbox/lab_notebook/projects_and_data/mnc/analysis_and_data/patch_clamp/data/summary_data/spiking_201912-202001/patch_data_batch.db"

def persistent_connection_to_db(path):
    """returns a connection object for the `path` to a database"""
    return sqlite3.connect(path)

def add_to_db(path, query_string):
    """uses a context manager to open a connection to database at `path` and execute
    query in `query_string`. Returns a 0 for success or a 1 for failure."""
    try:
        con = sqlite3.connect(path)
        with con:
            con.execute(query_string)
        con.close()
        return 0
    except Exception as e:
        print(f"Failed to execute. Query: {query_string}\n with error:\n{e}")
        con.close()
        return 1

def add_to_db_parameterized(path, query_string, data):
    """uses a context manager to open a connection to database at `path` and execute
    query in `query_string`. Returns a 0 for success or a 1 for failure."""
    try:
        con = sqlite3.connect(path)
        with con:
            con.execute(query_string, data)
        con.close()
        return 0
    except Exception as e:
        print(f"Failed to execute. Query: {query_string}\n with error:\n{e}")
        con.close()
        return 1

def get_paths_for_protocol(path_to_db, prot):
    """returns a list of paths from metadata which matching the protocol `prot` and
    `include` is `yes` or `maybe`"""
    query = "SELECT fpath FROM metadata WHERE protocol = ? AND (include = 'yes' OR include = 'maybe')"
    try:
        con = sqlite3.connect(path_to_db)
        con.row_factory = sqlite3.Row
        with con:
            things = con.execute(query, (prot,)).fetchall()
        con.close()
        return sorted([s["fpath"] for s in things])
    except Exception as e:
        print(f"Failed to execute. Query: {query}\n with error:\n{e}")
        con.close()
        return 1

def sql_data_as_dict(path_to_db: str, select_query: str) -> list:
    """Returns data from an query as a list of dicts."""
    try:
        con = sqlite3.connect(path_to_db)
        con.row_factory = sqlite3.Row
        things = con.execute(select_query).fetchall()
        unpacked = [{k: item[k] for k in item.keys()} for item in things]
        return unpacked
    except Exception as e:
        print(f"Failed to execute. Query: {select_query}\n with error:\n{e}")
        return []
    finally:
        con.close()

def list_of_ints_to_str(list_of_ints):
    return ",".join([str(i) for i in list_of_ints])

def list_of_floats_to_str(list_of_floats):
    return ",".join([str(i) for i in list_of_floats])

def str_list_to_list_floats(str_list):
    if not str_list:
        return []
    return [float(i) for i in str_list.split(",")]

def str_list_to_list_ints(str_list):
    if not str_list:
        return []
    return [int(i) for i in str_list.split(",")]


import os
import cv2
import json
import time
import random
import string
import filetype
import numpy as np
import pandas as pd
from functools import wraps

from config import logger

def msgwrap(func):
    @wraps(func)
    def wrap(*args, **kwargs):
        ret = {
            'succeed':0,
            'message':'succeed',
        }
        try:
            result = func(*args, **kwargs)
            if type(result) is dict:
                ret.update(result)
        except Exception as e:
            logger.exception(e)
            ret = {
                'succeed':1,
                'message':str(e),
            }
        logger.debug('message : {}'.format(ret))
        return json.dumps(ret).encode('utf-8')
    return wrap

def gen_random_string(length=8, *, number=True, abc=True, upper_case=False, lower_case=False):
    charset = ''
    if number:
        charset += string.digits
    if abc:
        if upper_case==lower_case:
            charset += string.ascii_letters
        elif upper_case:
            charset += string.ascii_uppercase
        elif lower_case:
            charset += string.ascii_lowercase
    return ''.join(random.choice(charset) for _ in range(length))

def get_type(filepath=None, data=None):
    try:
        if filepath is not None:
            ans = filetype.guess_mime(filepath)
            logger.debug('filetype guess: {} {}'.format(filepath, ans))
            if ans is None:
                if filepath[-5:] == '.json':
                    with open(filepath, 'r') as f:
                        data = json.load(f)
                    if type(data) == list:
                        return 'Sequence'
                    return "Graph"
                elif filepath[-4:] == '.mat':
                    return 'Graph'
                elif filepath[-4:] == '.csv':
                    return "DataFrame"
                return "Text"
            if ans.find('image') != -1:
                return "Image"
            if ans.find('video') != -1:
                return 'Video'
            if ans.find('audio') != -1:
                return 'Audio'
        raise NotImplementedError
    except Exception as e:
        logger.exception('Guess Type Error : {} {}'.format(filepath, e))

def safepath(path):
    # TODO : change replace
    path = path.replace('..', '')
    path = path.lstrip('/')
    path = path.replace('/', os.path.sep)
    return path

def sample_data(data, type_=None, num=10):
    if type_ == 'path':
        type_ = get_type(data)
        if type_ == 'DataFrame':
            data = pd.read_csv(data, nrows=10)
        elif type_ == 'Image':
            data = [[cv2.imread(data), os.path.basename(data)]]
        elif type_ == 'Sequence':
            with open(data, 'r') as f:
                data = json.load(f)
        elif type_ == 'Text':
            with open(data, 'r') as f:
                data = f.read()
        elif type_ == 'Graph':
            data = ''

    ret = {}
    if type_ == 'DataFrame':
        num = max(num, 0)
        index = list(data.columns)
        df = data[0:num]
        df = df.round(3)
        types = [str(df[index[j]].dtype) for j in range(len(index))]
        df = df.fillna('NaN')
        df = np.array(df).tolist()
        df = list(map(lambda x:list(map(lambda y:str(y) if len(str(y))< 16 else str(y)[:13]+'...',x)), df))
        if len(index) > 20:
            index = index[:19] + ['More...']
            df = list(map(lambda x:x[:19]+['...'], df))

        ret = {
            'type':'DataFrame',
            'shape':list(data.shape),
            'col_num':len(index),
            'col_index':index,
            'col_type':types,
            'row_num':num,
            'data': df
        }
    elif type_ == 'Image':
        savename = gen_random_string() + '.png'
        savedir = os.path.join('app', 'static', 'cache')
        if not os.path.exists(savedir):
            os.mkdir(savedir)
        filename = data[1][0]
        data = data[0][0]
        shape = list(data.shape)
        shape[0], shape[1] = shape[1], shape[0]
        resize_shape = shape[:2]
        while resize_shape[0] > 640 or resize_shape[1] > 480:
            resize_shape[0] //= 2
            resize_shape[1] //= 2
        data = cv2.resize(data, tuple(resize_shape))
        cv2.imwrite(os.path.join(savedir, savename), data)
        ret = {
            'type':'Image',
            'data':{
                'url':'static/cache/'+savename,
                'shape':shape,
            }
        }
    elif type_ == 'Graph':
        ret = {
            'type':'Graph',
            'data':data,
        }
    elif type_ == 'Video':
        ret = {
            'type':'Video',
        }
    elif type_ == 'Sequence':
        data = data[:num]
        data = list(map(str, data))
        ret = {
            'type':'Sequence',
            'len':len(data),
            'data':data,
        }
    elif type_ == 'Text':
        ret = {
            'type':'Text',
            'data':data,
        }
    else:
        raise NotImplementedError
    logger.debug('sample data {}'.format(ret))
    return ret


# local libs

from categories import Category
from items import VisitsOutsideUKItem
from utils import regex_for_registered, regex_for_amount, get_regex_pair_search

class VisitsOutsideUK(Category):
	def __init__(self):
		"""
		Visits outside the UK
		"""

		# Init the class, then set some class specific variables
		Category.__init__(self)

		# category info
		self.category_id = 5
		self.category_type = 'visits_outside_uk'
		self.category_description = 'Vists outside UK'
		self.isCurrency = True

	def do_logic(self, raw_string):
		"""
		Method performing the logic of parsing raw data into dictionary
		"""

		amount = 0
		next_id = len(self.items) + 1
		item_id = '%04d' % next_id

		# not much we can really split on
		pretty = raw_string.split(' (Registered')[0]
		registered = regex_for_registered(raw_string)

		# hold a list of lists with search pair, to then regex out the value between them
		regex_pairs = []
		regex_pairs.append(['Name of donor: ', 'Address of donor: '])
		regex_pairs.append(['Address of donor: ', 'Amount of donation '])
		regex_pairs.append(['Address of donor: ', 'Estimate of the probable value'])
		regex_pairs.append(['Destination of visit: ', 'Dates of visit: '])
		regex_pairs.append(['Destination of visit: ', 'Date of visit: '])
		regex_pairs.append(['Dates of visit: ', 'Purpose of visit: '])
		regex_pairs.append(['Date of visit: ', 'Purpose of visit: '])
		regex_pairs.append(['Purpose of visit: ', r'\(Registered '])

		amount = regex_for_amount(raw_string)

		donor = None
		address = None
		destination = None
		dates = None
		purpose = None

		for pair in regex_pairs:
			regex_search = get_regex_pair_search(pair, raw_string)

			if regex_search:
				value = regex_search.group(1)

				if 'name of donor' in pair[0].lower():
					donor = value
				elif 'address of donor' in pair[0].lower():
					address = value
				elif 'destination' in pair[0].lower():
					destination = value
				elif 'date' in pair[0].lower():
					dates = value
				elif 'dates' in pair[0].lower():
					dates = value
				elif 'purpose' in pair[0].lower():
					pretty = value

		item = VisitsOutsideUKItem(item_id, self.category_id, raw_string, pretty, registered, amount)
		item.donor = donor
		item.address = address
		item.destination = destination
		item.dates = dates

		self.items.append(item)


import sys
import ast
from graph import Graph

class InterferenceGraph:
    def __init__(self, github):
        self.graph = Graph(github)

    def get_node_register(self, name):
        return self.graph.get_node_register(name)

    def create_interference_graph(self, liveness_graph, tot_variables):
        print('----- creating interference graph -----')
        #print('variables: ', tot_variables)
        ### add register as the nodes.
        self.graph.add_node('eax', 'pink')
        self.graph.add_node('ecx', 'orange')
        self.graph.add_node('edx', 'green')
        self.graph.add_node('ebx', 'yellow')
        self.graph.add_node('esi', 'red')
        self.graph.add_node('edi', 'purple')

        self.graph.create_nodes(tot_variables)

        for node in liveness_graph.values():
            self.new_IR(node.body, node.liveness_list)

        #self.graph.draw_graph()
        return self.graph

    def new_IR(self, intermediate_ir, liveness_list):
        '''
            Algo:
              for each instruction Ik
                 if Ik is a move instruction:
                    Target interfers with all variables live after Ik, except the source variable
                 If Ik is an arthemetic op:
                    Target interfers with all variables live after Ik
                If Ik is a call:
                    caller save registers interfere with all variables live after Ik
        '''

        ##  converting  each set to a list.
        for i in range(len(liveness_list)):
            liveness_list[i] = list(liveness_list[i])
        liveness_list.reverse()
        for k in range(len(intermediate_ir)):
            instruction = intermediate_ir[k].replace(","," ").split()
            if instruction[0] == 'movl':
                if instruction[1][0] == '$':
                    for i in range(len(liveness_list[k+1])):
                        self.graph.add_edge(instruction[2], liveness_list[k+1][i])
                else:
                    ## interference with all variables live after Ik, except the source variable
                    #print("Liveness List:", liveness_list[k+1], "source:", instruction[1], "target:", instruction[2])
                    for i in range(len(liveness_list[k+1])):
                        if liveness_list[k+1][i] != instruction[1]:
                            self.graph.add_edge(instruction[2], liveness_list[k+1][i])
            elif instruction[0] == 'addl':
                for i in range(len(liveness_list[k+1])):
                    self.graph.add_edge(instruction[2], liveness_list[k+1][i])
            elif instruction[0] == 'call':
                ## caller save registers will behave as a target and interfere with all variables live after Ik. This
                # This is because the caller save registers are not preserved across function calls.
                for i in range(len(liveness_list[k+1])):
                    self.graph.add_edge('eax', liveness_list[k+1][i])
                    self.graph.add_edge('ecx', liveness_list[k+1][i])
                    self.graph.add_edge('edx', liveness_list[k+1][i])
                    for instruct in instruction[2:]:
                        self.graph.add_edge(instruct, liveness_list[k+1][i])
                    '''
                    self.graph.add_edge(instruction[2], liveness_list[k+1][i])
                    if len(instruction) >= 4:
                        self.graph.add_edge(instruction[3], liveness_list[k+1][i])
                    if len(instruction) >= 5:
                        self.graph.add_edge(instruction[4], liveness_list[k+1][i])
                    '''
            elif instruction[0] == 'sete' or instruction[0] == 'setne':
                for i in range(len(liveness_list[k+1])):
                    self.graph.add_edge('eax', liveness_list[k+1][i])
            elif instruction[0] == 'cmpl':
                if instruction[1][0] != '$':
                    for i in range(len(liveness_list[k+1])):
                        self.graph.add_edge(instruction[1], liveness_list[k+1][i])
                elif instruction[2][0] != '$':
                    for i in range(len(liveness_list[k+1])):
                        self.graph.add_edge(instruction[2], liveness_list[k+1][i])
            elif instruction[0] == 'movzbl':
                for i in range(len(liveness_list[k+1])):
                    self.graph.add_edge(instruction[2], liveness_list[k+1][i])
            elif instruction[0] == 'neg':
                for i in range(len(liveness_list[k+1])):
                    self.graph.add_edge(instruction[1], liveness_list[k+1][i])
            elif instruction[0] == 'ret':
                pass
                #for i in range(len(liveness_list[k+1])):
                #    self.graph.add_edge('eax', liveness_list[k+1][i])
            else:
                print('***** instruction not recognized *****')
                print(instruction)


a = []
b = []
c = []
n = int(input("enter thr no of elements of list:"))
for i in range(0, n):
    i = int(input("enter the {} th element of list:".format(i+1)))
    a.append(i)
print(a)
while(a != c):
    x = a[0]
    for i in a[0:]:
        if(x > i):
            continue
        else:
            x = i
    b.append(x)
    a.pop(a.index(x))

for i in range(n-1, -1, -1):
    c.append(b[i])

print("list is sorted in decending order : {}".format(b))
print("list is sorted in accendind order : {}".format(c))