on3
""" Module for implementing MRU Caching
"""

from collections import deque

BaseCaching = __import__("base_caching").BaseCaching

class MRUCache(BaseCaching):
    """  MRUCache class that inherits from BaseCaching which is a caching
    system
    """

    def __init__(self):
        """ Initialization function
        """
        super().__init__()
        self.queue = deque()

    def put(self, key, item):
        """ Assigns item value to the  self.cache_data library
        """
        if key and item:
            if key in self.cache_data:
                self.queue.remove(key)
            elif self.is_full():
                self.evict()
            self.queue.append(key)
            self.cache_data[key] = item

    def get(self, key):
        """Return the value in self.cache_data which is linked to key.
        """
        if key in self.cache_data:
            self.queue.remove(key)
            self.queue.append(key)
            return self.cache_data.get(key)

    def is_full(self):
        """ Checks the lenght of items in self.cache_data is higher that
        BaseCaching.MAX_ITEMS
        """
        return len(self.cache_data) >= self.MAX_ITEMS

    def evict(self):
        """ print DISCARD: with the key discarded and following by a
        new line
        """
        popped = self.queue.pop()
        del self.cache_data[popped]
        print("DISCARD: " + str(popped))


import argparse
import asyncio
import logging
import re
from collections import deque

from .aobject import *

__all__ = ["ServerEndpoint", "ClientEndpoint"]

def endpoint(spec):
    m = re.match(r"^(unix):(.*)$", spec)
    if m: return (m[1], m[2])

    m = re.match(r"^(tcp):(?:()|\*|\[([a-fA-F0-9:]+)\]|(\d+(?:\.\d){3})|([a-zA-Z.-]+))"
                 r":(\d+)$", spec)
    if m: return (m[1], m[3] or m[4] or m[5] if m[2] is None else "localhost", int(m[6]))

    raise argparse.ArgumentTypeError("invalid format")

class ServerEndpoint(aobject, asyncio.Protocol):
    @classmethod
    def add_argument(cls, parser, name, default=None):
        metavar = name.upper().replace("_", "-")
        help    = "listen at %s, either unix:PATH or tcp:HOST:PORT" % metavar
        if default is None:
            nargs = None
        else:
            nargs = "?"
            help += " (default: %(default)s)"

        parser.add_argument(
            name, metavar=metavar, type=endpoint, nargs=nargs, default=default,
            help=help)

    async def __init__(self, name, logger, sock_addr, queue_size=None):
        assert isinstance(sock_addr, tuple)

        self.name    = name
        self._logger = logger

        proto, *proto_args = sock_addr
        loop = asyncio.get_event_loop()
        if proto == "unix":
            self.server = await loop.create_unix_server(lambda: self, *proto_args, backlog=1)
            unix_path, = proto_args
            self._log(logging.INFO, "listening at unix:%s", unix_path)
        elif proto == "tcp":
            self.server = await loop.create_server(lambda: self, *proto_args, backlog=1)
            tcp_host, tcp_port = proto_args
            self._log(logging.INFO, "listening at tcp:%s:%d", tcp_host or "*", tcp_port)
        else:
            raise ValueError("unknown protocol %s" % proto)

        self._transport     = None
        self._new_transport = None

        self._send_epoch = 0
        self._recv_epoch = 1
        self._queue      = deque()
        self._queued     = 0
        self._queue_size = queue_size
        self._future     = None

        self._buffer = None
        self._pos    = 0

        self._read_paused = False

    def _log(self, level, message, *args):
        self._logger.log(level, self.name + ": " + message, *args)

    def connection_made(self, transport):
        self._send_epoch += 1

        peername = transport.get_extra_info("peername")
        if peername:
            self._log(logging.INFO, "new connection from [%s]:%d", *peername[0:2])
        else:
            self._log(logging.INFO, "new connection")

        if self._transport is None:
            self._transport = transport
        else:
            self._log(logging.INFO, "closing old connection")
            self._transport.close()
            self._new_transport = transport

    def connection_lost(self, exc):
        peername = self._transport.get_extra_info("peername")
        if peername:
            self._log(logging.INFO, "connection from [%s]:%d lost", *peername[0:2])
        else:
            self._log(logging.INFO, "connection lost")

        self._transport, self._new_transport = self._new_transport, None
        self._queue.append(exc)
        self._check_future()

    def data_received(self, data):
        self._log(logging.TRACE, "endpoint received %d bytes", len(data))
        self._queue.append(data)
        self._queued += len(data)
        self._check_pushback()
        self._check_future()

    def _check_pushback(self):
        if self._queue_size is None:
            return
        elif not self._read_paused and self._queued >= self._queue_size:
            self._log(logging.TRACE, "queue full, pausing reads")
            self._transport.pause_reading()
            self._read_paused = True
        elif self._read_paused and self._queued < self._queue_size:
            self._log(logging.TRACE, "queue not full, resuming reads")
            self._transport.resume_reading()
            self._read_paused = False

    def _check_future(self):
        if self._queue and self._future is not None:
            item = self._queue.popleft()
            if isinstance(item, Exception):
                self._future.set_exception(item)
            else:
                self._future.set_result(item)
            self._future = None

    async def _refill(self):
        self._future = future = asyncio.Future()
        self._check_future()
        self._buffer = await future
        if self._buffer is None:
            self._buffer = b""
            self._log(logging.TRACE, "recv end-of-stream")
            self._recv_epoch += 1
            raise asyncio.CancelledError

    async def recv(self, length=0):
        data = bytearray()
        while length == 0 or len(data) < length:
            if not self._buffer:
                self._log(logging.TRACE, "recv waits for %d bytes", length - len(data))
                await self._refill()

            if length == 0:
                length = len(self._buffer)

            chunk = self._buffer[:length - len(data)]
            self._buffer = self._buffer[len(chunk):]
            self._queued -= len(chunk)
            self._check_pushback()
            data += chunk

        self._log(logging.TRACE, "recv <%s>", data.hex())
        return data

    async def recv_until(self, separator):
        separator = bytes(separator)
        data = bytearray()
        while True:
            if not self._buffer:
                self._log(logging.TRACE, "recv waits for <%s>", separator.hex())
                await self._refill()

            try:
                index = self._buffer.index(separator)
                chunk = self._buffer[:index]
                self._buffer = self._buffer[index + 1:]
                self._queued -= len(chunk)
                self._check_pushback()
                data += chunk
                break

            except ValueError:
                data += self._buffer
                self._queued -= len(self._buffer)
                self._check_pushback()
                self._buffer = None

        self._log(logging.TRACE, "recv <%s%s>", data.hex(), separator.hex())
        return data

    async def recv_wait(self):
        if not self._buffer:
            self._log(logging.TRACE, "recv wait")
            await self._refill()

    async def send(self, data):
        data = bytes(data)
        if self._send_epoch == self._recv_epoch:
            self._log(logging.TRACE, "send <%s>", data.hex())
            self._transport.write(data)
            return True
        else:
            self._log(logging.TRACE, "send to previous connection discarded")
            return False

    async def close(self):
        if self._transport:
            self._transport.close()

class ClientEndpoint(aobject, asyncio.Protocol):
    @classmethod
    def add_argument(cls, parser, name, default=None):
        metavar = name.upper().replace("_", "-")
        help    = "connect to %s, either unix:PATH or tcp:HOST:PORT" % metavar
        if default is None:
            nargs = None
        else:
            nargs = "?"
            help += " (default: %(default)s)"

        parser.add_argument(
            name, metavar=metavar, type=endpoint, nargs=nargs, default=default,
            help=help)

    # FIXME: finish this


import requests

from django.conf import settings

def update_story(story_id, story_url):
    mutation_update_query = """
        mutation($story: UpdateStoryInput!) {
            updateStory(input: $story) {
                    story {
                        id,
                        url
                    }
                }
            }
    """
    variables = """
        {{
            "story" : {{
                "id": "{story_id}",
                "clientMutationId": "{story_id}",
                "story": {{
                    "url": "{story_url}"
                }}
            }}
        }}
    """.format(story_id=story_id, story_url='https://www.dpexnetwork.org' + story_url)
    headers = {
        'Authorization': 'Bearer {}'.format(settings.COMMENT_APP_TOKEN)
    }
    response = requests.post('https://comments.genexist.com/api/graphql/',
                             json={
                                 'query': mutation_update_query,
                                 'variables': variables,
                             },
                             headers=headers
                             )
    errors = response.json().get('errors')
    if errors:
        raise Exception('Can not update story: {}'.format(errors))
    return True


import time
import datetime

from marshmallow import fields, validate, Schema, pre_load, post_dump
from flask import request

from .mixin import Mixin, NestedSchema
from .user_schema import UserSchema

class ImageJsonSchema(Schema):
    mime = fields.Str()
    data = fields.Str()

class ArtSchema(Mixin):
    aid = fields.Str()
    description = fields.Str(required=False)
    rpath = fields.Str(required=False, dump_only=True)
    status = fields.Str(
        required=False,
        dump_only=True,
        validate=validate.OneOf(["processing", "completed", "failed"]),
    )
    preimage = fields.Str(required=False, dump_only=True)
    index = fields.Int(required=False)
    width = fields.Int(required=False, dump_only=True)
    height = fields.Int(required=False, dump_only=True)
    twidth = fields.Int(required=False, dump_only=True)
    theight = fields.Int(required=False, dump_only=True)
    # is_publishing = fields.Bool(required=False, dump_only=True)

    image = fields.Nested(ImageJsonSchema, load_only=True, required=True)

    @post_dump
    def set_full_path(self, data, **kwargs):

        if not data.get("rpath"):
            return data

        r_full_path = f"https://{request.headers['Host']}{data.get('rpath')}"
        t_full_path = f"https://{request.headers['Host']}{data.get('rpath').split('.')[0]}_thumbnail.{data.get('rpath').split('.')[1]}"

        data.update({"rpath": r_full_path})
        data.update({"tpath": t_full_path})

        if data.get("created_date"):
            data.update(
                {
                    "created_date": time.mktime(
                        datetime.datetime.strptime(
                            data.get("created_date"), "%Y-%m-%d %H:%M:%S.%f"
                        ).timetuple()
                    )
                }
            )

        if data.get("updated_date"):
            data.update(
                {
                    "updated_date": time.mktime(
                        datetime.datetime.strptime(
                            data.get("updated_date"), "%Y-%m-%d %H:%M:%S.%f"
                        ).timetuple()
                    )
                }
            )

        return data

class NestedArtSchema(NestedSchema):
    arts = fields.Nested(ArtSchema, attribute="items", exclude=[], many=True)


'''
table_config
    前端通过该配置生成对应的表格头部及内容信息
    'q':作为数据库字段查询
    'title':表格标题
    'display':是否显示
    'text':{
        'tpl':html模板
        'kwargs':用于html模板参数格式化。自定义规则：@+字段取值，@@+字段取全局变量字典的值。
    }
    'attrs':html标签的属性
        {  'edit-enable': 标签是否能编辑
           'origin': 保存原始值，用于跟新值作比较
        }

motai_config
    前端通过该配置生成对应的模态对话框实现添加功能
    'title': 标题
    'display': 是否显示
    'attrs': 标签属性

search_config
    前端通过该配置生成对应的搜索框
    'name': 标签属性
    'text': 下拉框文本
    'condition_type': 输入框类型input/select

'''

table_config = [
                {'q': None,  # 数据库查询字段
                 'title': '',  # 标题
                 'display': True,  # 是否显示
                 'text': {  # 内容
                     'tpl': '<input type="checkbox" value="{n1}">',
                     'kwargs': {'n1': '@id'} #用于tpl格式化
                 },
                 'attrs': {'nid': '@id'},  # 标签的属性
                 },

                {'q': 'id',
                 'title': 'ID',
                 'display': True,
                 'text': {
                     'tpl': '{n1}',
                     'kwargs': {'n1': '@id'}
                 },
                 'attrs': { 'id': '@id'},
                 },
                {
                    'q':'username',
                    'title':'用户名',
                    'display':True,
                    'text':{
                        'tpl':'{n1}',
                        'kwargs':{'n1':'@username'}
                    },
                    'attrs': {'k2': '@username'},
                },
                {
                    'q': 'userinfo__nickname',
                    'title': '昵称',
                    'display': True,
                    'text': {
                        'tpl': '{n1}',
                        'kwargs': {'n1': '@userinfo__nickname'}
                    },
                    'attrs': {'edit-enable': 'true', 'origin':'@userinfo__nickname', 'name':'userinfo__nickname'},
                },
                {
                    'q': 'email',
                    'title': '邮箱',
                    'display': True,
                    'text': {
                        'tpl': '{n1}',
                        'kwargs': {'n1': '@email'}
                    },
                    'attrs': {'edit-enable': 'true',  'origin':'@email', 'name':'email'},
                },

            ]

motai_config = [
                {
                    'title': '用户名',
                    'display': True,
                    'attrs': {'type':'input', 'class': 'form-control', 'name':'username'},
                },
                {
                    'title': '密码',
                    'display': True,
                    'attrs': { 'type': 'input', 'class': 'form-control', 'name': 'password'},
                },
                {
                    'title': '昵称',
                    'display': True,
                    'attrs': {'edit-enable': 'true', 'origin': '@nickname', 'name': 'nickname','type':'input','class': 'form-control'},
                },
                {
                    'title': '邮箱',
                    'display': True,
                    'attrs': {'edit-enable': 'true', 'origin': '@email', 'name': 'email','type':'input', 'class': 'form-control'},
                },

            ]

search_config = [
                {'name': 'id', 'text': 'ID', 'condition_type': 'input'},
                {'name': 'username__contains', 'text': '用户名', 'condition_type': 'input'},
            ]


# 링크드리스트 데이터 사이에 데이터를 추가
class Node:
    def __init__(self,data,next=None):
            self.data =data
            self.next = next

def add(data):
    node = head
    # 마지막 노드를 찾는 반복문
    while node.next:
        node = node.next
    # 마지막 노드에 새로운 노드의 주소값을 가리키도록 함
    node.next = Node(data)

node1 = Node(1)
node2 = Node(2)
node1.next = node2
head = node1

for index in range(3, 11):
    add(index)

node3 = Node(1.5)

node = head
search = True
while search:
    if node.data == 1:
        search = False
    else:
        node = node.next

node_next = node.next
node.next = node3
node3.next = node_next

node = head
while node.next:
    print(node.data)
    node = node.next

링크드리스트/2. 링크드리스트.py

2. 링크드리스트.py


import os
from uuid import uuid4
import undetected_chromedriver as uc
from selenium import webdriver
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.keys import Keys
import polars as pl
from selenium.webdriver.common.by import By
from bot.constants import IMPLEMENTED
from selenium.common.exceptions import NoSuchElementException,StaleElementReferenceException,ElementNotInteractableException
import logging
from selenium.webdriver.support import expected_conditions
import time

class UcChromeDriver(uc.Chrome):
    """"
    Description:
    This class is a wrapper for the undetected_chromedriver package but with basic options

    """

    def __init__(self)->None:

        options = webdriver.ChromeOptions()

        options.add_argument('--log-level=1')
        # Adding argument to disable the AutomationControlled flag
        options.add_argument("--disable-blink-features=AutomationControlled")

        # Exclude the collection of enable-automation switches
        options.add_experimental_option("excludeSwitches", ["enable-automation"])

        # Turn-off userAutomationExtension
        options.add_experimental_option("useAutomationExtension", False)

        self.driver = uc.Chrome(executable_path="chromedriver",chrome_options=options)

        # driver.set_window_size(1920,1080)

    def get_driver(self):
        return self.driver

class Bot:
    """
    Description:
    """
    def __init__(self,
                 website:str,
                 job_title:str="Data Scientist",
                 search_location:str="Paris",
                 ) -> None:

        if website not in list(IMPLEMENTED.keys()):
            raise NotImplementedError(f"{website} not implemented yet")

        self.job_title = job_title
        self.search_location = search_location

        self.website = website

        self.driver = UcChromeDriver().get_driver()
        self.driver.implicitly_wait(5)

        self.CONSTANTS = IMPLEMENTED[website]
        self.wait = WebDriverWait(self.driver, 5,poll_frequency=0.2)

    def find_element_try(self,element=None,verbose=False,*args,**kwargs):
        """
        Description:
        This method will try to find an element and return None if it fails"""
        try:
           if element:
               return element.find_element(*args,**kwargs)
           return self.driver.find_element(*args,**kwargs)
        except NoSuchElementException as e:
            if verbose:
                print(e)
            return None

    def save_offers(self,offers,schema=None):
        """"
        Description:
        This method will save the offers in parquet format"""
        if offers:
            if offers[0]["job_title"]:
                try:
                    pl.DataFrame(
                        offers,
                        schema=schema
                    ).write_parquet(f"{self.CONSTANTS['DATA_PATH']}/{self.website}_{uuid4()}.parquet")
                except Exception as e:
                    print(offers)
                    print(e)

    def get_offers_off_page(self):
        """
        Description:
        This method will get the offers on the page and return a list of offers"""

        # self.wait.until(EC.visibility_of_all_elements_located(self.CONSTANTS["LIST_PAGE_OFFERS"]))

        return self.wait.until(EC.visibility_of_all_elements_located(self.CONSTANTS["LIST_PAGE_OFFERS"]))

    def search_job(self):
        """

        Description:
        This method will search the job title in the search bar and click on the search button"""

        self.driver.get(self.CONSTANTS["START_URL"])

        search_bar = self.wait.until(EC.visibility_of_element_located(tuple(self.CONSTANTS["SEARCH_BAR"].values()) ))

        webdriver.ActionChains(self.driver).move_to_element(search_bar).click().perform()

        webdriver.ActionChains(self.driver).send_keys(self.job_title).perform()
        # self.driver.find_element(**self.CONSTANTS["SEARCH_BAR"])
        location  = self.driver.find_element(**self.CONSTANTS["SEARCH_LOCATION"])

        location.send_keys(Keys.CONTROL + "a")
        location.send_keys(Keys.DELETE)
        location.clear()

        webdriver.ActionChains(self.driver).move_to_element(location).click().perform()

        # self.search_location=""
        location.send_keys(self.search_location)
        location.send_keys(Keys.ENTER)

        self.page = 1

        self.offers = []

class IndeedBot(Bot):
    """
    Description:
    This class is a bot that will scrap the indeed website and save the data in parquet forma
    """

    def __init__(self,
                 *args,
                 **kwargs
                 ) -> None:
        """
        Description:
        This method is the constructor of the class
        Parameters:
        job_title: str
        This parameter is the job title that will be searched
        @TODO: Add a parameter to choose the location
        """
        super().__init__("indeed",
                          *args,
                        **kwargs)

    def run(self):
        """
        Description:
        This method is the main method of the class, it will run the bot and save the data in parquet format
        @TODO : Add a method to save the data in a database
        @TODO : Implement logging
        """
        self.search_job()

        while self.page:

            if self.page != 1:
                self.driver.get(self.page.get_attribute('href'))
                webdriver.ActionChains(self.driver).send_keys(Keys.ESCAPE).perform()

            result_list = self.get_offers_off_page()
            self.go_trough_offers(result_list)
            self.next_page()
            self.save_offers(self.offers)
            # page = None
        self.driver.quit()
        print("Done")

    def next_page(self):
        """
        Description:
        This method will find the next page button"""
        self.page = self.find_element_try(**self.CONSTANTS["NEXT_PAGE"])

    def go_trough_offers(self,result_list):
        """
        Description:
        This method will go trough the offers and save the data in a list of dict"""

        for offer in result_list:

                offer_dict= dict()
                for i in ("job_title","id","company","text","salary_range"):
                    offer_dict[i]=None
                try:
                    os.listdir(self.CONSTANTS["DATA_PATH"])
                    list_fetch_ids = pl.scan_parquet(f'{self.CONSTANTS["DATA_PATH"]}/*.parquet').filter(pl.col("text").is_not_null()).select(pl.col("id").unique()).collect().to_series()

                except FileNotFoundError as e :
                    list_fetch_ids = []
                try:

                    offer_dict['id'] = offer.find_element(**self.CONSTANTS["OFFER_ID"]).get_attribute('id')
                    if offer_dict['id']  not in list_fetch_ids:

                        offer_dict["job_title"] =offer.find_element(**self.CONSTANTS["OFFER_TITLE"]).text
                        offer_dict["company"] = offer.find_element(**self.CONSTANTS["OFFER_COMPANY"]).text
                        webdriver.ActionChains(self.driver).move_to_element(offer).click(offer ).perform()
                        text_offer =self.driver.find_element(*self.CONSTANTS["OFFER_TEXT"])
                        offer_dict["text"] = text_offer.text
                        offer_dict["salary_range"] = offer.find_element(**self.CONSTANTS["OFFER_SALARY"]).text
                        self.offers.append(offer_dict)

                except Exception as e:
                    print(offer_dict.get("id",None))
                    print(e)

class GlassdoorBot(Bot):
    """
    Description:
    This class is a bot that will scrap the glassdoor website and save the data in parquet forma
    """

    def __init__(self,
                 *args,
                 **kwargs
                 ) -> None:
        """
        Description:
        This method is the constructor of the class
        Parameters:
        job_title: str
        This parameter is the job title that will be searched
        """
        super().__init__("glassdoor",
                          *args,
                        **kwargs)

    def run(self):
        self.search_job()
        while self.page:

            if self.page != 1:
                # self.driver.get(self.page.get_attribute('href'))
                webdriver.ActionChains(self.driver).send_keys(Keys.ESCAPE).perform()

            result_list = self.get_offers_off_page_glassdoor()
            self.go_trough_offers(result_list)
            self.next_page()
            # s
            # self.save_offers(self.offers,schema=schema)
            # page = None
        schema = dict(
                job_title=pl.Utf8(),
                id=pl.Utf8(),
                company=pl.Utf8(),
                text=pl.Utf8(),
                salary_range=pl.Utf8(),
                location=pl.Utf8(),
                age=pl.Utf8(),
                company_rating=pl.Utf8(),
                company_info=pl.Utf8(),
                is_easy_apply=pl.Utf8(),
                salary_range_provenance=pl.Utf8()

            )
        self.save_offers(self.offers,schema=schema)
        self.driver.quit()
        print("Done")
    def get_offers_off_page_glassdoor(self):

        """
        Description:
        This method will get the offers on the page and return a list of offers"""

        # self.wait.until(EC.visibility_of_all_elements_located(self.CONSTANTS["LIST_PAGE_OFFERS"]))
        offers= self.wait.until(EC.visibility_of_all_elements_located(self.CONSTANTS["LIST_PAGE_OFFERS"]))
        offer_list = []
        for offer in offers:
            ignored_exceptions=(NoSuchElementException,StaleElementReferenceException,)
            o = WebDriverWait(self.driver, 10,ignored_exceptions=ignored_exceptions).until(expected_conditions.visibility_of(offer
                                                                                )).get_attribute('data-id')

            offer_list.append(o)

        return offer_list
    def next_page(self):
        """
        Description:
        This method will find the next page button"""
        self.page = self.driver.find_element(**self.CONSTANTS["NEXT_PAGE"])
        if self.page:
            webdriver.ActionChains(self.driver).move_to_element(self.page ).click(self.page ).perform()
        else:
            print("No more pages")

    def go_trough_offers(self,result_list):
        """
        Description:
        This method will go trough the offers and save the data in a list of dict"""
        self.count = 0
        for c,offer in enumerate(result_list):

            self.count = c + 1

            offer_dict= dict()
            for i in ("job_title","id","company","text","salary_range","location","age","company_rating","company_info","is_easy_apply","salary_range_provenance"):
                offer_dict[i]=None
            try:
                os.listdir(self.CONSTANTS["DATA_PATH"])
                list_fetch_ids = pl.scan_parquet(f'{self.CONSTANTS["DATA_PATH"]}/*.parquet').filter(pl.col("text").is_not_null()).select(pl.col("id").unique()).collect().to_series()

            except FileNotFoundError as e :
                list_fetch_ids = []

            offer_dict['id'] = offer

            if offer_dict['id']  not in list_fetch_ids:

                # offer_dict["job_title"] =offer.find_element(**self.CONSTANTS["OFFER_TITLE"]).text
                offer_xpath = f"//li[@data-id='{offer_dict['id']}']"
                location_xpath = f"//li[@data-id='{offer_dict['id']}']" + self.CONSTANTS["OFFER_LOCATION"]["value"]
                age_xpath = f"//li[@data-id='{offer_dict['id']}']" + self.CONSTANTS["OFFER_AGE"]["value"]
                company_rating_xpath = f"//li[@data-id='{offer_dict['id']}']" + self.CONSTANTS["COMPANY_RATING"]["value"]
                company_info_xpath = f"//li[@data-id='{offer_dict['id']}']" + self.CONSTANTS["COMPANY_INFO"]["value"]
                is_easy_apply_xpath = f"//li[@data-id='{offer_dict['id']}']" + self.CONSTANTS["OFFER_IS_EASY_APPLY"]["value"]

                salary_range_provenance_xpath = f"//li[@data-id='{offer_dict['id']}']" + self.CONSTANTS["OFFER_SALARY_PROVENANCE"]["value"]
                salary_range_xpath = f"//li[@data-id='{offer_dict['id']}']" + self.CONSTANTS["OFFER_SALARY"]["value"]
                job_title_xpath = f"//li[@data-id='{offer_dict['id']}']" + self.CONSTANTS["OFFER_JOB_TITLE"]["value"]

                ignored_exceptions=(NoSuchElementException,StaleElementReferenceException,)
                offer_element = WebDriverWait(self.driver, 10,ignored_exceptions=ignored_exceptions).until(expected_conditions.visibility_of_element_located((By.XPATH,offer_xpath)
                                                                                ))

                webdriver.ActionChains(self.driver).move_to_element(offer_element).click(offer_element ).perform()
                webdriver.ActionChains(self.driver).send_keys(Keys.ESCAPE).perform()

                offer_dict["location"] = self.find_element_try(by=By.XPATH,value=location_xpath)
                offer_dict["age"] = self.find_element_try(by=By.XPATH,value=age_xpath)

                offer_dict["salary_range_provenance"] = self.find_element_try(by=By.XPATH,value=salary_range_provenance_xpath)

                offer_dict["job_title"] = self.find_element_try(**self.CONSTANTS["OFFER_JOB_TITLE"])
                #takes too much time
                offer_dict["company_rating"] = self.find_element_try(**self.CONSTANTS['COMPANY_RATING'])
                #takes too much time
                offer_dict["company_info"] = self.find_element_try(**self.CONSTANTS["COMPANY_INFO"])
                offer_dict["is_easy_apply"] = self.find_element_try(**self.CONSTANTS["OFFER_IS_EASY_APPLY"])
                offer_dict["text"] = self.find_element_try(**self.CONSTANTS["OFFER_TEXT"])
                offer_dict["company"] = self.find_element_try(**self.CONSTANTS["OFFER_COMPANY"])
                offer_dict["salary_range"] = self.find_element_try(by=By.XPATH,value=salary_range_xpath)

                for i in offer_dict:
                    if type(offer_dict[i])==uc.webelement.WebElement:
                        offer_dict[i] = offer_dict[i].text

                self.offers.append(offer_dict)

                if c % 5 == 0 :
                    schema = dict(
                        job_title=pl.Utf8(),
                        id=pl.Utf8(),
                        company=pl.Utf8(),
                        text=pl.Utf8(),
                        salary_range=pl.Utf8(),
                        location=pl.Utf8(),
                        age=pl.Utf8(),
                        company_rating=pl.Utf8(),
                        company_info=pl.Utf8(),
                        is_easy_apply=pl.Utf8(),
                        salary_range_provenance=pl.Utf8()

                    )
                    self.save_offers(self.offers,schema=schema)

class LinkedinBot(Bot):
    """
    Description:
    This class is a bot that will scrap the glassdoor website and save the data in parquet forma
    """

    def __init__(self,
                 *args,
                 **kwargs
                 ) -> None:
        """
        Description:
        This method is the constructor of the class
        Parameters:
        job_title: str
        This parameter is the job title that will be searched
        """
        super().__init__("linkedin",
                          *args,
                        **kwargs)

    def get_offers_off_page_linkedin(self):

        """
        Description:
        This method will get the offers on the page and return a list of offers"""

        # self.wait.until(EC.visibility_of_all_elements_located(self.CONSTANTS["LIST_PAGE_OFFERS"]))
        offers= self.wait.until(EC.visibility_of_all_elements_located(self.CONSTANTS["LIST_PAGE_OFFERS"]))
        offer_list = []
        for offer in offers:
            ignored_exceptions=(NoSuchElementException,StaleElementReferenceException,)
            o = WebDriverWait(self.driver, 10,ignored_exceptions=ignored_exceptions).until(expected_conditions.visibility_of(offer
                                                                                ))

            offer_list.append(o)

        return offer_list

    def run(self):
        self.search_job()
        schema = dict(
                        job_title=pl.Utf8(),
                        id=pl.Utf8(),
                        company=pl.Utf8(),
                        location=pl.Utf8(),
                        age=pl.Utf8(),
                        date=pl.Utf8(),
                        date_parsed=pl.Float64(),
                        benefits=pl.Utf8(),
                        text=pl.Utf8(),
                        candidates=pl.Utf8(),
                    )
        while True:

            if not self.find_element_try(by=By.CLASS_NAME,value="infinite-scroller__show-more-button"):
                # Comment: if there is no more offers to load, stop
                break

            result_list = self.get_offers_off_page_linkedin()

            ids_to_pass = pl.read_parquet('linkedin_data/linkedin*.parquet').select("id").unique().to_series().to_list()

            result_list_filtered = list(filter(
                lambda x: x.get_attribute("data-entity-urn") not in ids_to_pass,result_list
            ))

            if not result_list_filtered :

                webdriver.ActionChains(self.driver).move_to_element(result_list[-1]).scroll_to_element(result_list[-1]).scroll_by_amount(delta_x=0,delta_y=100).perform()
                next_button =   self.find_element_try(by=By.CLASS_NAME,value="infinite-scroller__show-more-button")
                time.sleep(2)

                if next_button:
                    try:
                        webdriver.ActionChains(self.driver).move_to_element(next_button).click(next_button).perform()
                    except  ElementNotInteractableException as e:
                        continue

                continue

            for offer in result_list_filtered:
                offer_dict = {}
                offer_dict["job_title"] = offer.find_element(**self.CONSTANTS["OFFER_JOB_TITLE"]).text
                offer_dict["id"] = offer.get_attribute("data-entity-urn")
                offer_dict["company"] = offer.find_element(**self.CONSTANTS["OFFER_COMPANY"]).text
                offer_dict["location"] = offer.find_element(**self.CONSTANTS["OFFER_LOCATION"]).text

                offer_dict["age"] = self.find_element_try(offer,**self.CONSTANTS["OFFER_AGE"])
                if not offer_dict["age"]:
                    offer_dict["age"] = self.find_element_try(offer,**self.CONSTANTS["OFFER_AGE_NEW"])

                if offer_dict["age"]:
                    offer_dict["age"],offer_dict["date"]= offer_dict["age"].text,offer_dict["age"].get_attribute("datetime")

                offer_dict["date_parsed"] = time.time()

                offer_dict["benefits"] = self.find_element_try(offer,**self.CONSTANTS["OFFER_BENEFITS"])
                if offer_dict["benefits"]:
                    offer_dict["benefits"]= offer_dict["benefits"].text

                webdriver.ActionChains(self.driver).move_to_element(offer).click(offer).perform()
                time.sleep(2)
                offer_dict["text"] = self.driver.find_element(*self.CONSTANTS["OFFER_TEXT"]).text
                offer_dict["candidates"] = self.driver.find_element(**self.CONSTANTS["OFFER_CANDIDATES"]).text
                self.offers.append(offer_dict)

                print(offer_dict)
                # s
                # self.save_offers(self.offers,schema=schema)
                # page = None

            self.save_offers(self.offers,schema=schema)

        print("Done")
        time.sleep(60)
        self.driver.quit()


def postorder(root):
    if root == None:
        return []
    stack = []
    postorder = []
    stack.append(root)
    visited = set()
    visited.add(root)
    while len(stack) > 0:
        curr = stack[-1]
        currCh = curr.children[::-1]
        if len(currCh) > 0:
            chToVisit = [not ch in visited for ch in currCh]
            if any(chToVisit):
                for i in range(len(currCh)):
                    if chToVisit[i]:
                        visited.add(currCh[i])
                        stack.append(currCh[i])
            else:
                stack.pop()
                postorder.append(curr.val)
        else:
            stack.pop()
            postorder.append(curr.val)
    return postorder


import os
import shutil
import easyocr

# Create an EasyOCR reader object
reader = easyocr.Reader(['en'])

# Set paths for input and output folders
input_folder = 'x'
output_folder = 'y'

# Create output folder if it does not exist
if not os.path.exists(output_folder):
    os.makedirs(output_folder)

# Loop through files in input folder
for file_name in os.listdir(input_folder):
    # Check if file is an image
    if file_name.endswith('.png') or file_name.endswith('.jpg') or file_name.endswith('.jpeg'):
        # Construct full path for input and output files
        input_path = os.path.join(input_folder, file_name)
        output_path = os.path.join(output_folder, file_name)
        # Read image using EasyOCR
        results = reader.readtext(input_path)
        # Define keywords to search for in the text
        keywords = ['Device name', 'Processor', 'Installed RAM', 'Device ID', 'System type']
        # Create a dictionary to store the extracted information
        info = {}
        # Loop through the results and extract relevant information
        for i, result in enumerate(results):
            for keyword in keywords:
                if keyword in result[1]:
                    # Extract value after the keyword and store in dictionary
                    value = results[i+1][1].strip()
                    info[keyword] = value
        # Print extracted information

        if info=={}:
            shutil.move(input_path, 'delete')
            continue

        with open('data.txt', 'a') as f:
            f.write(f'File: {file_name}\n'
            f'Device Name: {info.get("Device name", "")}\n'
            f'Processor: {info.get("Processor", "")}\n'
            f'Installed RAM: {info.get("Installed RAM", "")}\n'
            f'Device ID: {info.get("Device ID", "")}\n'
            f'System Type: {info.get("System type", "")}\n'
            f'//////////////////////////////////////////////////////////////////////\n\n')

        print(info)

        # Move input file to output folder

        shutil.move(input_path, output_path)


#! /usr/bin/env python3

from os import path
from multiprocessing.pool import ThreadPool
import multiprocessing
import os
import logging
import yaml
import psutil
import argparse
import subprocess
import re
import glob
import time
import sys
import shlex

OVERRIDE_FIELDS = ['verifiers', 'memory', 'time-limit', 'memory-limit', 'skip']
APPEND_FIELDS = ['flags', 'checkbpl', 'checkout']

LANGUAGES = {'c': {'*.c'},
             'cargo': {'Cargo.toml'},
             'cplusplus': {'*.cpp'},
             'rust': {'*.rs'},
             'llvm-ir': {"*.ll"}}

def bold(text):
    return '\033[1m' + text + '\033[0m'

def red(text, log_file):
    if log_file:
        return text
    else:
        return '\033[0;31m' + text + '\033[0m'

def green(text, log_file):
    if log_file:
        return text
    else:
        return '\033[0;32m' + text + '\033[0m'

def get_result(output):
    if re.search(r'SMACK timed out', output):
        return 'timeout'
    elif re.search(r'SMACK found no errors', output):
        return 'verified'
    elif re.search(r'SMACK found an error', output):
        return 'error'
    else:
        return 'unknown'

def merge(metadata, yamldata):
    for key in OVERRIDE_FIELDS:
        if key in yamldata:
            metadata[key] = yamldata[key]

    for key in APPEND_FIELDS:
        if key in yamldata:
            if key in metadata:
                metadata[key] += yamldata[key]
            else:
                metadata[key] = yamldata[key]

def metadata(file):
    m = {}
    prefix = []

    for d in path.dirname(file).split('/'):
        prefix += [d]
        yaml_file = path.join(*(prefix + ['config.yml']))
        if path.isfile(yaml_file):
            with open(yaml_file, "r") as f:
                data = yaml.safe_load(f)
                merge(m, data)

    with open(file, "r") as f:
        for line in f.readlines():

            match = re.search(r'@skip', line)
            if match:
                m['skip'] = True

            match = re.search(r'@flag (.*)', line)
            if match:
                m['flags'] += shlex.split(match.group(1).strip())

            match = re.search(r'@expect (.*)', line)
            if match:
                m['expect'] = match.group(1).strip()

            match = re.search(r'@checkbpl (.*)', line)
            if match:
                m['checkbpl'].append(match.group(1).strip())

            match = re.search(r'@checkout (.*)', line)
            if match:
                m['checkout'].append(match.group(1).strip())

    if not m['skip']:
        if 'expect' not in m:
            print(red("WARNING: @expect MISSING IN %s" % file, None))
            m['expect'] = 'verified'

        if not m['expect'] in ['verified', 'error', 'timeout', 'unknown']:
            print(red("WARNING: unexpected @expect annotation '%s'" %
                      m['expect'], None))

    return m

# integer constants
PASSED = 0
TIMEDOUT = 1
UNKNOWN = 2
FAILED = -1

def process_test(
        cmd,
        test,
        memory,
        verifier,
        expect,
        checkbpl,
        checkout,
        log_file):
    """
    This is the worker function for each process. This function process the
    supplied test and returns a tuple containing  indicating the test results.

    :return: A tuple with the
    """
    str_result = "{0:>20}\n".format(test)
    str_result += "{0:>20} {1:>10}    :".format(memory, verifier)

    t0 = time.time()
    p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
                         universal_newlines=True)
    out, err = p.communicate()
    elapsed = time.time() - t0
    status = 0

    bplfile = cmd[cmd.index('-bpl') + 1]
    with open(os.devnull, 'w') as devnull:
        for f in checkbpl:
            with open(bplfile) as bpl:
                checker = subprocess.Popen(
                    shlex.split(f), stdin=bpl, stdout=devnull, stderr=devnull)
                checker.wait()
                status = status or checker.returncode

        for f in checkout:
            checker = subprocess.Popen(
                shlex.split(f),
                stdin=subprocess.PIPE,
                stdout=devnull,
                stderr=devnull)
            checker.communicate(input=out.encode())
            status = status or checker.returncode

    # get the test results
    result = get_result(out + err)
    if result == expect and status == 0:
        str_result += green('PASSED ', log_file)
    elif result == 'timeout':
        str_result += red('TIMEOUT', log_file)
    elif result == 'unknown':
        str_result += red('UNKNOWN', log_file)
    else:
        str_result += red('FAILED ', log_file)

    str_result += '  [%.2fs]' % round(elapsed, 2)
    return str_result

passed = failed = timeouts = unknowns = 0

def tally_result(result):
    """
    Tallies the result of each worker. This will only be called by the main
    thread.
    """
    # log the info
    logging.info(result)

    global passed, failed, timeouts, unknowns
    if "PASSED" in result:
        passed += 1
    elif "FAILED" in result:
        failed += 1
    elif "TIMEOUT" in result:
        timeouts += 1
    elif "UNKNOWN" in result:
        unknowns += 1

def get_extensions(languages):
    languages = list(languages.split(','))
    extensions = set()
    for language in languages:
        extensions |= LANGUAGES[language]
    return extensions

def get_tests(folder, extensions):
    tests = []
    for ext in extensions:
        tests_path = path.dirname(__file__)
        tests.extend(glob.glob(path.join(tests_path, folder, ext)))
    tests.sort()
    return tests

def main():
    """
    Main entry point for the test suite.
    """
    t0 = time.time()
    num_cpus = multiprocessing.cpu_count()
    mem_total = psutil.virtual_memory().total / (1024 * 1024)

    # configure the CLI
    parser = argparse.ArgumentParser()
    parser.add_argument(
        "--exhaustive",
        help="check all configurations on all examples",
        action="store_true")
    parser.add_argument(
        "--all-configs",
        help="check all configurations per example",
        action="store_true")
    parser.add_argument(
        "--all-examples",
        help="check all examples",
        action="store_true")
    parser.add_argument("--folder", action="store", default="**/**", type=str,
                        help="sets the regressions folder to run")
    parser.add_argument(
        "--threads",
        action="store",
        dest="n_threads",
        default=num_cpus,
        type=int,
        help='''execute regressions using the selected number of threads in
                parallel''')
    parser.add_argument(
        "--log",
        action="store",
        dest="log_level",
        default="DEBUG",
        type=str,
        help="sets the logging level (DEBUG, INFO, WARNING)")
    parser.add_argument(
        "--output-log",
        action="store",
        dest="log_path",
        type=str,
        help="sets the output log path. (std out by default)")
    parser.add_argument(
        "--languages",
        action="store",
        default="c",
        choices=list(
            LANGUAGES.keys()),
        help='''Comma separated list of langauges to test. C[c],C++[cplusplus],
                Rust[rust]''')
    args = parser.parse_args()

    if args.exhaustive:
        args.all_examples = True
        args.all_configs = True

    extensions = get_extensions(args.languages)
    tests = get_tests(args.folder, extensions)

    # configure the logging
    log_format = ''
    log_level = logging.DEBUG

    # add more log levels later (if needed)
    if args.log_level.upper() == "INFO":
        log_level = logging.INFO
    elif args.log_level.upper() == "WARNING":
        log_level = logging.WARNING

    # if the user supplied a log path, write the logs to that file.
    # otherwise, write the logs to std out.
    if args.log_path:
        logging.basicConfig(
            filename=args.log_path,
            format=log_format,
            level=log_level)
    else:
        logging.basicConfig(format=log_format, level=log_level)

    logging.debug("Creating Pool with '%d' Workers" % args.n_threads)
    p = ThreadPool(processes=args.n_threads)

    try:
        # start the tests
        logging.info("Running regression tests...")

        # start processing the tests.

        results = []
        for test in tests:
            # get the meta data for this test
            meta = metadata(test)

            if meta['memory-limit'] > mem_total:
                continue

            if meta['skip'] is True:
                continue

            if meta['skip'] is not False and not args.all_examples:
                continue

            # build up the subprocess command
            cmd = ['smack', test]
            cmd += ['--time-limit', str(meta['time-limit'])]
            cmd += meta['flags']

            for memory in meta['memory'][:100 if args.all_configs else 1]:
                cmd += ['--mem-mod=' + memory]

                for verifier in (meta['verifiers']
                                     [:100 if args.all_configs else 1]):
                    name = path.splitext(path.basename(test))[0]
                    cmd += ['--verifier=' + verifier]
                    cmd += ['-bc', "%s-%s-%s.bc" % (name, memory, verifier)]
                    cmd += ['-bpl', "%s-%s-%s.bpl" % (name, memory, verifier)]
                    r = p.apply_async(
                        process_test,
                        args=(
                            cmd[:],
                            test,
                            memory,
                            verifier,
                            meta['expect'],
                            meta['checkbpl'],
                            meta['checkout'],
                            args.log_path,
                        ),
                        callback=tally_result)
                    results.append(r)

        # keep the main thread active while there are active workers
        for r in results:
            r.wait()

    except KeyboardInterrupt:
        logging.debug("Caught KeyboardInterrupt, terminating workers")
        p.terminate()  # terminate any remaining workers
        p.join()
    else:
        logging.debug("Quitting normally")
        # close the pool. this prevents any more tasks from being submitted.
        p.close()
        p.join()  # wait for all workers to finish their tasks

    # log the elapsed time
    elapsed_time = time.time() - t0
    logging.info(' ELAPSED TIME [%.2fs]' % round(elapsed_time, 2))

    # log the test results
    logging.info(' PASSED count: %d' % passed)
    logging.info(' FAILED count: %d' % failed)
    logging.info(' TIMEOUT count: %d' % timeouts)
    logging.info(' UNKNOWN count: %d' % unknowns)

    # if there are any failed tests or tests that timed out, set the system
    # exit code to a failure status
    if timeouts > 0 or failed > 0 or unknowns > 0:
        sys.exit(1)

if __name__ == "__main__":
    main()


from django.shortcuts import render, redirect, get_object_or_404
from .models import TodoItem
from django.http import HttpResponse, HttpResponseRedirect
from django.urls import reverse
from django.contrib import messages
from django.contrib.auth.decorators import login_required

def home(request):
    list_tasks = TodoItem.objects.all()

    context = {
        'tasks':list_tasks,
    }

    return render(request, "index.html", context=context)

@login_required
def task_details(request, id):
    desp = TodoItem.objects.get(pk=id)

    context = {
        'desp':desp,
    }

    return render(request, "task_details.html", context=context)

@login_required
def remove_task(request,id):
    task = get_object_or_404(TodoItem, pk=id)
    task.delete()
    return redirect("home")

@login_required
def edit_task(request,id):
    task = TodoItem.objects.get(pk=id)

    context = {
        'task': task
    }
    return render(request,"edit_task.html", context=context)

@login_required
def update_task(request,id):

    task = TodoItem.objects.get(pk=id)

    if request.POST.get('is_completed', False) == "on":
        task.task_name = request.POST['task_name']
        task.complete_task()
        task.save()

    return redirect('home')

@login_required
def create_task(request):

       #https://stackoverflow.com/questions/57288652/save-html-form-data-in-database-django?rq=1

    if request.method == 'POST':

        task_name = request.POST['task_name']
        due_date = request.POST['due_date']

        TodoItem.objects.create(task_name=task_name, due_date=due_date, )

        return redirect('create_task')
    else:
        return render(request,'create_task.html')


#!/usr/bin/python3
import matplotlib
matplotlib.use('Agg')
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
import os
import sys

Request = sys.argv[1]
Area = sys.argv[2]
ToDay = sys.argv[3]

Node_Scale = [100,200,300,400,500,600,700,800,900,1000]

plt.figure(figsize=(6,6))

DIR="result/" + str(ToDay) +"/"+str(Area)+"area/"+str(Request)+"requests/"

Result = []
for i in Node_Scale:
    fp = open(DIR + str(i) + "_" + str(Request) + ".txt")
    R_lines = fp.readlines()
    rows = len(R_lines)-1
    average = float(R_lines[rows].strip('\n'))
    average = int(average)
    Result.append(average)

plt.xlabel('Node Scale')
plt.ylabel('Throughput')
# Charging Scale => 1
lines = plt.plot(Node_Scale,Result,'bo')
plt.setp(lines, color='r', linewidth=2.0)
lines = plt.plot(Node_Scale,Result)
plt.setp(lines, color='r', linewidth=2.0)

# r_patch = mpatches.Patch(color='r', label='1 node')
# g_patch = mpatches.Patch(color='g', label='2 node')
# b_patch = mpatches.Patch(color='b', label='4 node')
# plt.legend(handles=[r_patch,g_patch,b_patch])

out_path = DIR+"/Result.png"
plt.savefig(out_path)
plt.close()


'''
 Desenvolva um aplicativo que leia o salário e o sexo de vários funcionários.
No final, mostre o total de salários pagos aos homens e o total pago às
mulheres. O programa vai perguntar ao usuário se ele quer continuar ou não
sempre que ler os dados de um funcionário.'''
print(f'>>>>>>>>>>>>>Extrato Salarial>>>>>>>>>>>>>')
salarios_homens = 0
salarios_mulheres = 0
while True:
    print('.............Dados.............')
    sexo = input('Digite seu sexo(m/f): ')
    if sexo == 'm':
        salario = int(input('Digite o seu salário: '))
        salarios_homens += salario
    elif sexo == 'f':
        salario = int(input('Digite o seu salário: '))
        salarios_mulheres += salario
    else:
        print('Sexo inválido para o cadastro.Tente novamente!')
    opcao = input('Deseja continuar(s/n)?: ')
    if opcao in 'nNAOnaoNnãoNão':
        break
print(f'O total de salários pagos aos homens é R${salarios_homens}, já o de mulheres é R${salarios_mulheres}')


"""tables v2

Revision ID: b2700d350e48
Revises: 2c203d99df15
Create Date: 2023-03-16 15:46:02.454764

"""
from alembic import op
import sqlalchemy as sa

# revision identifiers, used by Alembic.
revision = 'b2700d350e48'
down_revision = '2c203d99df15'
branch_labels = None
depends_on = None

def upgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.create_table('classroom',
    sa.Column('index', sa.Integer(), nullable=False),
    sa.Column('class_id', sa.String(), nullable=True),
    sa.Column('student_id', sa.Integer(), nullable=True),
    sa.Column('sem', sa.Integer(), nullable=True),
    sa.Column('elective_type', sa.String(), nullable=True),
    sa.PrimaryKeyConstraint('index')
    )
    # ### end Alembic commands ###

def downgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.drop_table('classroom')
    # ### end Alembic commands ###


Matrix = [["0110", "1010", "1010", "1100", "0110", "1100"],
          ["0101", "0110", "1000", "0111", "1001", "0001"],
          ["0011", "1001", "0110", "1001", "0010", "1100"],
          ["0110", "1010", "1011", "1110", "1010", "1101"],
          ["0101", "0110", "1000", "0101", "0110", "1001"],
          ["0011", "1011", "1010", "1001", "0011", "1000"]]
# a  6 by 6 matrix with each row numbered 0-5
# defines each position's possible movement directions
# at position 0, 0, you can't go north, you can go east, you can go south, you can't go west
class Maze:
    def __init__(self):
        self.x = 0
        self.y = 0
        self.position = Matrix[self.x][self.y]
    def check(self):
        if self.position[0] == "1":
            print("You can GO NORTH.")
        if self.position[1] == "1":
            print("You can GO EAST.")
        if self.position[2] == "1":
            print("You can GO SOUTH.")
        if self.position[3] == "1":
            print("You can GO WEST.")
        # say where you can go
    def movement(self, move):
        self.x
        self.y
        self.position
        if move == "GO NORTH" and self.position[0] == "1":
        # if you said go north and you can go north
            self.y = self.y - 1
            # move the y coordinate 1 north
            self.position = Matrix[self.x][self.y]
            # set your position
            print("You are now at " + str(self.x) + ", " + str(self.y))
            # say your new position
        elif move == "GO EAST" and self.position[1] == "1":
            self.x = self.x + 1
            self.position = Matrix[self.x][self.y]
            print("You are now at " + str(self.x) + ", " + str(self.y))
        elif move == "GO SOUTH" and self.position[2] == "1":
            self.y = self.y + 1
            self.position = Matrix[self.x][self.y]
            print("You are now at " + str(self.x) + ", " + str(self.y))
        elif move == "GO WEST" and self.position[3] == "1":
            self.x = self.x - 1
            self.position = Matrix[self.x][self.y]
            print("You are now at " + str(self.x) + ", " + str(self.y))

if __name__ == "__main__":
    maze = Maze()
    print("Welcome to The Maze. Your objective is to reach 5, 5.")
    print("You are now at " + str(maze.x) + ", " + str(maze.y))
    game = "inProgress"
    # say where you start
    while game == "inProgress":
        maze.check()
        move = input()
        maze.movement(move);
        if maze.x == 5 and maze.y == 5:
        # if you get to the bottom right corner
            print("Congrats! You won!")
            game = "won"
            # you won
            break
            # end program


# -*- coding: utf-8 -*-
import multiprocessing
import os
import shutil
import shutilwhich
import io

import subprocess32 as subprocess

from oasislmf.model_preparation.oed import ALLOCATE_TO_ITEMS_BY_PREVIOUS_LEVEL_ALLOC_ID
from oasislmf.utils.exceptions import OasisException
from oasislmf.utils.log import oasis_log
from oasislmf.model_execution.bash import genbash

RUNTYPE_GROUNDUP_LOSS = 'gul'
RUNTYPE_INSURED_LOSS = 'il'

WAIT_PROCESSING_SWITCHES = {
    'full_uncertainty_aep': '-F',
    'wheatsheaf_aep': '-W',
    'sample_mean_aep': '-S',
    'full_uncertainty_oep': '-f',
    'wheatsheaf_oep': '-w',
    'sample_mean_oep': '-s',
    'wheatsheaf_mean_aep': '-M',
    'wheatsheaf_mean_oep': '-m',
}

def print_command(command_file, cmd):
    """
    Writes the supplied command to the end of the generated script

    :param cmd: The command to append
    """
    with io.open(command_file, "a", encoding='utf-8') as myfile:
        myfile.writelines(cmd + "\n")

def create_workfolders(runtype, analysis_settings, filename):
    summaries = analysis_settings.get('{}_summaries'.format(runtype))
    if not summaries:
        return

    for summary in summaries:
        if 'id' in summary:
            summary_set = summary['id']
            if summary.get('lec_output'):
                print_command(filename, "md work\\{}_S{}_summaryleccalc".format(runtype, summary_set))

            if summary.get('aalcalc'):
                print_command(filename, 'md work\\{}_S{}_summaryaalcalc'.format(runtype, summary_set))

def il(analysis_settings, max_process_id, filename):
    for process_id in range(1, max_process_id + 1):
        do_any(RUNTYPE_INSURED_LOSS, analysis_settings, process_id, filename)

    for process_id in range(1, max_process_id + 1):
        do_summarycalcs(RUNTYPE_INSURED_LOSS, analysis_settings, process_id, filename)

    for process_id in range(1, max_process_id + 1):
        do_tees(RUNTYPE_INSURED_LOSS, analysis_settings, process_id, filename)

    for process_id in range(1, max_process_id + 1):
        do_reps(RUNTYPE_INSURED_LOSS, analysis_settings, process_id, filename)

def do_gul(analysis_settings, max_process_id, filename):
    for process_id in range(1, max_process_id + 1):
        do_any(RUNTYPE_GROUNDUP_LOSS, analysis_settings, process_id, filename)

    for process_id in range(1, max_process_id + 1):
        do_summarycalcs(RUNTYPE_GROUNDUP_LOSS, analysis_settings, process_id, filename)

    for process_id in range(1, max_process_id + 1):
        do_tees(RUNTYPE_GROUNDUP_LOSS, analysis_settings, process_id, filename)

    for process_id in range(1, max_process_id + 1):
        do_reps(RUNTYPE_GROUNDUP_LOSS, analysis_settings, process_id, filename)

def do_any(runtype, analysis_settings, process_id, filename=''):
    summaries = analysis_settings.get('{}_summaries'.format(runtype))
    if not summaries:
        return

    for summary in summaries:
        if 'id' in summary:
            summary_set = summary['id']

            if summary.get("summarycalc"):
                cmd = 'summarycalctocsv -s'
                if process_id == 1:
                    cmd = 'summarycalctocsv'

                print_command(
                    filename,
                    '{3} < fifo\\{0}_S{1}_summarysummarycalc_P{2} > work\\kat\\{0}_S{1}_summarycalc_P{2}'.format(
                        runtype, summary_set, process_id, cmd
                    )
                )

        print_command(filename, '')

def do_reps(runtype, analysis_settings, process_id, filename=''):
    summaries = analysis_settings.get('{}_summaries'.format(runtype))
    if not summaries:
        return

    for summary in summaries:
        if 'id' in summary:
            summary_set = summary['id']
            if summary.get('eltcalc'):
                cmd = 'eltcalc -s'
                if process_id == 1:
                    cmd = 'eltcalc'

                print_command(
                    filename,
                    "{3} < fifo\\{0}_S{1}_summaryeltcalc_P{2} > work\\kat\\{0}_S{1}_eltcalc_P{2}".format(
                        runtype, summary_set, process_id, cmd
                    )
                )

            if summary.get('pltcalc'):
                cmd = 'pltcalc -s'
                if process_id == 1:
                    cmd = 'pltcalc'

                print_command(
                    filename,
                    '{3} < fifo\\{0}_S{1}_summarypltcalc_P{2} > work\\kat\\{0}_S{1}_pltcalc_P{2}'.format(
                        runtype, summary_set, process_id, cmd
                    )
                )

        print_command(filename, '')

def do_summarycalcs(runtype, analysis_settings, process_id, filename):

    summaries = analysis_settings.get('{}_summaries'.format(runtype))
    if not summaries:
        return

    summarycalc_switch = '-f'
    if runtype == RUNTYPE_GROUNDUP_LOSS:
        summarycalc_switch = '-g'

    summarycalc_directory_switch = ""

    cmd = 'summarycalc {} {}'.format(summarycalc_switch, summarycalc_directory_switch)
    for summary in summaries:
        if 'id' in summary:
            summary_set = summary['id']
            cmd = '{0} -{1} fifo\\{2}_S{1}_summary_P{3}'.format(cmd, summary_set, runtype, process_id)

    cmd = '{0} < {1}fifo\\{2}_P{3}'.format(cmd, '', runtype, process_id)
    print_command(filename, cmd)

def do_tees(runtype, analysis_settings, process_id, filename):
    summaries = analysis_settings.get('{}_summaries'.format(runtype))
    if not summaries:
        return

    for summary in summaries:
        if 'id' in summary:
            summary_set = summary['id']
            cmd = 'copy fifo\\{}_S{}_summary_P{}'.format(runtype, summary_set, process_id)

            if summary.get('eltcalc'):
                c = '{} fifo\\{}_S{}_summaryeltcalc_P{}'.format(cmd, runtype, summary_set, process_id)
                print_command(filename, c)

            if summary.get('pltcalc'):
                c = '{} fifo\\{}_S{}_summarypltcalc_P{}'.format(cmd, runtype, summary_set, process_id)
                print_command(filename, c)

            if summary.get('summarycalc'):
                c = '{} fifo\\{}_S{}_summarysummarycalc_P{}'.format(cmd, runtype, summary_set, process_id)
                print_command(filename, c)

            if summary.get('aalcalc'):
                c = '{} work\\{}_S{}_summaryaalcalc\\P{}.bin'.format(cmd, runtype, summary_set, process_id)
                print_command(filename, c)

            if summary.get('lec_output'):
                c = '{} work\\{}_S{}_summaryleccalc\\P{}.bin'.format(cmd, runtype, summary_set, process_id)
                print_command(filename, c)

            print_command(filename, '')

def run_batch(
    max_process_id,
    analysis_settings,
    num_reinsurance_iterations,
    fifo_tmp_dir,
    mem_limit,
    alloc_rule,
    filename,
    _get_getmodel_cmd,
    custom_args={}
):
    # remove the file if it already exists
    if os.path.exists(filename):
        os.remove(filename)

    aux_file, _ = os.path.splitext(filename)
    aux_file += ".txt"
    if os.path.exists(aux_file):
        os.remove(aux_file)

    print_command(filename, 'md work\\kat')
    gul_threshold = analysis_settings.get('gul_threshold', 0)
    number_of_samples = analysis_settings.get('number_of_samples', 0)

    use_random_number_file = ''
    if 'model_settings' in analysis_settings and analysis_settings['model_settings'].get('use_random_number_file'):
        use_random_number_file = '123'

    if 'gul_output' in analysis_settings:
        gul_output = analysis_settings['gul_output']
        create_workfolders(RUNTYPE_GROUNDUP_LOSS, analysis_settings, filename)

    if 'il_output' in analysis_settings:
        il_output = analysis_settings['il_output']
        create_workfolders(RUNTYPE_INSURED_LOSS, analysis_settings, filename)

    for process_id in range(1, max_process_id + 1):
        if gul_output and il_output:
            getmodel_args = {
                'number_of_samples'      : number_of_samples,
                'gul_threshold'          : gul_threshold,
                'use_random_number_file' : use_random_number_file,
                'coverage_output'        : '{}fifo\\gul_P{}'.format("", process_id),
                'item_output'            : '-',
                'process_id'             : process_id,
                'max_process_id'         : max_process_id
            }
            getmodel_cmd = _get_getmodel_cmd(**getmodel_args)
            main_cmd = '{1} | fmcalc -a {2} > {3}fifo\\il_P{0} '.format(
                process_id, getmodel_cmd,
                alloc_rule,
                "")
            print_command(aux_file, main_cmd)
        else:
            if gul_output and 'gul_summaries' in analysis_settings:
                getmodel_args = {
                    'number_of_samples'      : number_of_samples,
                    'gul_threshold'          : gul_threshold,
                    'use_random_number_file' : use_random_number_file,
                    'coverage_output'        : '{}fifo\\gul_P{}'.format("", process_id),
                    'item_output'            : '',
                    'process_id'             : process_id,
                    'max_process_id'         : max_process_id
                }
                main_cmd = _get_getmodel_cmd(**getmodel_args)
                print_command(aux_file, main_cmd)

            if il_output  and 'il_summaries' in analysis_settings:
                getmodel_args = {
                    'number_of_samples'      : number_of_samples,
                    'gul_threshold'          : gul_threshold,
                    'use_random_number_file' : use_random_number_file,
                    'coverage_output'        : '',
                    'item_output'            : '-',
                    'process_id'             : process_id,
                    'max_process_id'         : max_process_id
                }
                getmodel_cmd = _get_getmodel_cmd(**getmodel_args)
                main_cmd = '{1} | fmcalc -a {2} > {3}fifo\\il_P{0} '.format(
                    process_id, getmodel_cmd,
                    alloc_rule,
                    "")
                print_command(aux_file, main_cmd)

    print_command(filename, 'rush {} < ' + aux_file)
    print_command(filename, '')

    if gul_output:
        print_command(filename, '')
        print_command(filename, 'REM --- Do ground up loss computes ---')
        print_command(filename, '')
        do_gul(analysis_settings, max_process_id, filename)

    if il_output:
        print_command(filename, '')
        print_command(filename, 'REM --- Do insured loss computes ---')
        print_command(filename, '')
        il(analysis_settings, max_process_id, filename)

    do_post_wait_processing(RUNTYPE_INSURED_LOSS, analysis_settings, filename)
    do_post_wait_processing(RUNTYPE_GROUNDUP_LOSS, analysis_settings, filename)

    if il_output:
        print_command(filename, '')
        print_command(filename, 'REM --- Do insured loss kats ---')
        print_command(filename, '')
        do_kats(RUNTYPE_INSURED_LOSS, analysis_settings, max_process_id, filename)

    if gul_output:
        print_command(filename, '')
        print_command(filename, 'REM --- Do ground up loss kats ---')
        print_command(filename, '')
        do_kats(RUNTYPE_GROUNDUP_LOSS, analysis_settings, max_process_id, filename)

def do_post_wait_processing(runtype, analysis_settings, filename):
    if '{}_summaries'.format(runtype) not in analysis_settings:
        return

    for summary in analysis_settings['{}_summaries'.format(runtype)]:
        if "id" in summary:
            summary_set = summary['id']
            if summary.get('aalcalc'):
                cmd = 'aalcalc -K{}_S{}_summaryaalcalc'.format(
                    runtype,
                    summary_set
                )

                cmd = '{} > output\\{}_S{}_aalcalc.csv'.format(cmd, runtype, summary_set)
                print_command(filename, cmd)

            if summary.get('lec_output'):
                leccalc = summary.get('leccalc', {})
                cmd = 'leccalc {} -K{}_S{}_summaryleccalc'.format(
                    '-r' if leccalc.get('return_period_file') else '',
                    runtype,
                    summary_set
                )

                for option, active in sorted(leccalc['outputs'].items()):
                    if active:
                        switch = WAIT_PROCESSING_SWITCHES.get(option, '')
                        cmd = '{} {} output/{}_S{}_leccalc_{}.csv'.format(cmd, switch, runtype, summary_set,
                                                                            option)

                print_command(filename, cmd)

def do_kats(runtype, analysis_settings, max_process_id, filename):
    summaries = analysis_settings.get('{}_summaries'.format(runtype))
    if not summaries:
        return False

    anykats = False
    for summary in summaries:
        if 'id' in summary:
            summary_set = summary['id']

            if summary.get('eltcalc'):
                anykats = True

                cmd = 'kat'
                for process_id in range(1, max_process_id + 1):
                    cmd = '{} work/kat/{}_S{}_eltcalc_P{}'.format(cmd, runtype, summary_set, process_id)

                cmd = '{} > output/{}_S{}_eltcalc.csv'.format(cmd, runtype, summary_set)
                print_command(filename, cmd)

            if summary.get('pltcalc'):
                anykats = True

                cmd = 'kat'
                for process_id in range(1, max_process_id + 1):
                    cmd = '{} work/kat/{}_S{}_pltcalc_P{}'.format(cmd, runtype, summary_set, process_id)

                cmd = '{} > output/{}_S{}_pltcalc.csv'.format(cmd, runtype, summary_set)
                print_command(filename, cmd)

            if summary.get("summarycalc"):
                anykats = True

                cmd = 'kat'
                for process_id in range(1, max_process_id + 1):
                    cmd = '{} work/kat/{}_S{}_summarycalc_P{}'.format(cmd, runtype, summary_set, process_id)

                cmd = '{} > output/{}_S{}_summarycalc.csv'.format(cmd, runtype, summary_set)
                print_command(filename, cmd)

    return anykats

@oasis_log()
def run(
    analysis_settings,
    number_of_processes=-1,
    num_reinsurance_iterations=0,
    ktools_mem_limit=False,
    set_alloc_rule=ALLOCATE_TO_ITEMS_BY_PREVIOUS_LEVEL_ALLOC_ID,
    fifo_tmp_dir=True,
    run_debug=None,
    filename='run_ktools.sh'
):
    if os.name == 'nt':
        filename = 'run_ktools.bat'

    if number_of_processes == -1:
        number_of_processes = multiprocessing.cpu_count()

    custom_gulcalc_cmd = "EarthquakeDamage"

    # Check for custom gulcalc
    if shutil.which(custom_gulcalc_cmd):

        def custom_get_getmodel_cmd(
            number_of_samples,
            gul_threshold,
            use_random_number_file,
            coverage_output,
            item_output,
            process_id,
            max_process_id,
            **kwargs):

            cmd = "{} -m {} -n {} -a {} -p {} -S{}".format(
                custom_gulcalc_cmd,
                process_id,
                max_process_id,
                os.path.abspath("analysis_settings.json"),
                ".",
                number_of_samples)
            if coverage_output != '':
                cmd = '{} -c {}'.format(cmd, coverage_output)
            if item_output != '':
                cmd = '{} -i {}'.format(cmd, item_output)

            return cmd

        if os.name == 'nt':
            run_batch(
                number_of_processes,
                analysis_settings,
                num_reinsurance_iterations=num_reinsurance_iterations,
                fifo_tmp_dir=fifo_tmp_dir,
                mem_limit=ktools_mem_limit,
                alloc_rule=set_alloc_rule,
                filename=filename,
                _get_getmodel_cmd=custom_get_getmodel_cmd,
            )
        else:
            genbash(
                number_of_processes,
                analysis_settings,
                num_reinsurance_iterations=num_reinsurance_iterations,
                fifo_tmp_dir=fifo_tmp_dir,
                mem_limit=ktools_mem_limit,
                alloc_rule=set_alloc_rule,
                filename=filename,
                _get_getmodel_cmd=custom_get_getmodel_cmd,
            )
    else:
        genbash(
            number_of_processes,
            analysis_settings,
            num_reinsurance_iterations=num_reinsurance_iterations,
            fifo_tmp_dir=fifo_tmp_dir,
            mem_limit=ktools_mem_limit,
            alloc_rule=set_alloc_rule,
            filename=filename
        )

    try:

        if os.name != 'nt':
            subprocess.check_call(['bash', filename])
        else:
            subprocess.check_call([filename])
    except subprocess.CalledProcessError as e:
        raise OasisException('Error running ktools: {}'.format(str(e)))


# REFERENCE
	# 293. Flip Game
	# https://leetcode.com/problems/flip-game/description/

# DESCRIPTION
	# You are playing the following Flip Game with your friend: Given a string that contains only these two characters: + and -,
  # you and your friend take turns to flip two consecutive "++" into "--".
  # The game ends when a person can no longer make a move and therefore the other person will be the winner.
  # Write a function to compute all possible states of the string after one valid move.

# EXAMPLE
  # Input: s = "++++"
  # Output:
  # [
  #   "--++",
  #   "+--+",
  #   "++--"
  # ]

# SOLUTION
class Solution:
    def generatePossibleNextMoves(self, s):
        """
        :type s: str
        :rtype: List[str]
        """
        l = list(s)
        res = []

        # Other Cases
        for i in range(0, len(l)-1):
            temp = ""
            if l[i] == l[i+1] and l[i] == "+":
                if l[i] == "+":
                    temp = s[:i] + "--" + s[i+2:]
                res.append(temp)
        return res

s = Solution()
print(s.generatePossibleNextMoves("++++"))


from flask import Flask, request
from twilio.twiml.messaging_response import MessagingResponse
from twilio.rest import Client
from p2000_bot import run_p2000_bot
from decouple import config

# Your Twilio Account SID and Auth Token
account_sid = config('TWILIO_ACCOUNT_SID')
auth_token = config('TWILIO_AUTH_TOKEN')

# Initialize Twilio client
client = Client(account_sid, auth_token)

# Create a Flask app
app = Flask(__name__)

@app.route('/webhook', methods=['POST'])
def webhook():
    # Get the incoming message data from Twilio
    message_body = request.values.get('Body', '')
    sender_number = request.values.get('From', '')

    # Process the incoming message
    # create regex that checks for 'p2000' in message_body

    if message_body == 'P2000' or message_body == 'p':
        run_p2000_bot()
        return 'Standard P2000 messages sent'
    if 'P2000' in message_body:
        # get all characters after 'P2000'
        city = message_body[6:]
        run_p2000_bot(city)
        return f'P2000 messages sent for {city}'
    else:
        response = MessagingResponse()
        response.message('Unknown command. Please send "P2000" to get the latest P2000 messages.')
        return str(response)

if __name__ == "__main__":
    app.run(debug=True, port=5005)


"""
PRACTICE -> Search a Word in a 2D Grid of characters
https://www.geeksforgeeks.org/search-a-word-in-a-2d-grid-of-characters/

Dada uma grade 2D de caracteres e uma palavra, encontre todas as ocorrências dessa palavra na grade. Uma palavra
pode ser correspondida nas 8 direções a qualquer momento. Diz-se que a palavra é encontrada em uma direção
se todos os caracteres corresponderem nessa direção (não na forma de zig-zag).
As 8 direções são: Horizontalmente à esquerda, Horizontalmente à direita, Verticalmente para cima e
4 direções em diagonal.

Source: Microsoft Interview Question.

Input:  grid[][] = {"GEEKSFORGEEKS",
                    "GEEKSQUIZGEEK",
                    "IDEQAPRACTICE"};
        word = "GEEKS"

Output: pattern found at 0, 0
        pattern found at 0, 8
        pattern found at 1, 0

Explanation: 'GEEKS' can be found as prefix of 1st 2 rows and suffix of first row

Input:  grid[][] = {"GEEKSFORGEEKS",
                    "GEEKSQUIZGEEK",
                    "IDEQAPRACTICE"};
        word = "EEE"

Output: pattern found at 0, 2
        pattern found at 0, 10
        pattern found at 2, 2
        pattern found at 2, 12

Explanation: EEE can be found in first row twice at index 2 and index 10and in second row at 2 and 12
"""

class GFG:

    def __init__(self):
        self.R = None
        self.C = None
        self.dir = [[-1, 0], [1, 0], [1, 1], [1, -1], [-1, -1], [0, 1], [0, -1]]

        # This function searches in all 8-direction from point(row, col) in grid[][]

    def search2D(self, grid, row, col, word):

        # If first character of word doesn't match with the given starting point in grid.
        if grid[row][col] != word[0]:
            return False

        # Search word in all 8 directions starting from (row, col)
        for x, y in self.dir:

            # Initialize starting point for current direction
            rd, cd = row + x, col + y
            flag = True

            # First character is already checked, match remaining characters
            for k in range(1, len(word)):

                # If out of bound or not matched, break
                if (0 <= rd < self.R and
                        0 <= cd < self.C and
                        word[k] == grid[rd][cd]):

                    # Moving in particular direction
                    rd += x
                    cd += y
                else:
                    flag = False
                    break

            # If all character matched, then value of flag must be false
            if flag:
                return True
        return False

    # Searches given word in a given matrix in all 8 directions
    def patternSearch(self, grid, word):

        # Rows and columns in given grid
        self.R = len(grid)
        self.C = len(grid[0])

        # Consider every point as starting point and search given word
        for row in range(self.R):
            for col in range(self.C):
                if self.search2D(grid, row, col, word):
                    print("pattern found at " +
                          str(row) + ', ' + str(col))

                # Driver Code

if __name__ == '__main__':
    grid = ["GEEKSFORGEEKS",
            "GEEKSQUIZGEEK",
            "IDEQAPRACTICE"]

    gfg = GFG()
    gfg.patternSearch(grid, 'GEEKS')
    print('')
    gfg.patternSearch(grid, 'EEE')

# This code is contributed by Yezheng Li


from flask import Blueprint

posts = Blueprint( 'posts', __name__ )

from flask import escape, request, render_template, url_for, flash, redirect

from flask import current_app

from flask_blog import db, bcrypt, mail

from ..models import User, Post
from .forms import PostCreationForm, PostChangeForm

from flask_login import login_user, logout_user, current_user, login_required

from sqlalchemy import desc

from datetime import datetime

""" For pagination of posts """
from flask_paginate import Pagination

@posts.route('/posts_detail/<int:post_id>')
def posts_detail(post_id):
    post = Post.query.get(post_id)
    user_id = request.args.get( 'user_id', type=int )

    if post is None:
        flash(f'Post does not exist','info')
        return redirect(url_for('posts.posts_list'))

    return render_template('posts/posts_detail.html',post=post, user_id = user_id, title="Post details" )

""" creation of posts """
@posts.route('/posts_create', methods=['GET','POST'])
@login_required
def posts_create():
    form = PostCreationForm()
    if form.validate_on_submit():
        post = Post(user_id=current_user.id, title=form.title.data,content=form.content.data)
        db.session.add(post)
        db.session.commit()

        flash(f'Post created','success')
        return redirect(url_for('posts.posts_list'))

    return render_template('posts/posts_create.html',title='Post creation',form=form)

""" changing of posts """
@posts.route('/posts_change/<int:post_id>', methods=['GET','POST'])
@login_required
def posts_change(post_id):

    post = Post.query.get(post_id)

    if post and current_user == post.author:
        form = PostChangeForm(obj=post)

        if form.validate_on_submit():
            post.title = form.title.data
            post.content = form.content.data
            post.date_changed = datetime.utcnow()

            db.session.commit()

            flash(f'Post changed','success')
            return redirect(url_for('posts.posts_list'))

        return render_template('posts/posts_change.html',title='Post update',form=form)

    return redirect(url_for('posts.posts_list'))

""" deletion of posts """
@posts.route('/posts_delete/<int:post_id>', methods=['GET','POST'])
@login_required
def posts_delete(post_id):

    post = Post.query.get(post_id)

    if post and current_user == post.author:
        if request.method == 'POST':

            db.session.delete(post)
            db.session.commit()

            flash(f'Post deleted','success')
            return redirect(url_for('posts.posts_list'))

    return render_template('posts/posts_delete.html',title='Post deletion',post=post)

@posts.route('/')
@posts.route('/home')
@posts.route('/Home')
def posts_list():

    posts = db.session.query(Post).order_by(desc(Post.date_changed))

    """ FILTERING BY user_id """
    user_id = request.args.get( 'user_id', type=int, default=0 )
    user = User.query.get( user_id ) ## get parameter &user_id=<int>, defaults to 0 (NONE)
    if user_id and not user:
        flash("No user with such id exists", 'info')
    elif user:
        posts = posts.filter_by( author = user )

    """ PAGINATION """
    per_page = 3 ## show <int> entries per page
    page = int( request.args.get('page', type=int, default=1) ) ## get parameter &page=<int>, defaults to 1 (first page)
    pagination = Pagination( page=page, per_page=per_page, total=posts.count(), record_name='posts', css_framework='bootstrap4') ## the pagination html objects

    posts = posts.paginate(page=page, per_page=per_page)
    return render_template('home.html', posts=posts.items, pagination=pagination, user=user, title="Posts" )


"""Module for Controlling Grace Robot
"""

import time
from .control import MultiMotorCtrl
from .utils import ROSClient, sys_dict

class Grace(object):

    def __init__(self, degrees=True) -> None:
        self.ros = ROSClient()
        self.l_eye_pan = MultiMotorCtrl(self.ros.ros_client, ['EyeTurnLeft'], degrees)
        self.r_eye_pan = MultiMotorCtrl(self.ros.ros_client, ['EyeTurnRight'], degrees)
        self.lr_eyes_tilt = MultiMotorCtrl(self.ros.ros_client, ['EyesUpDown'], degrees)
        self.lr_eyes_pan = MultiMotorCtrl(self.ros.ros_client, ['EyeTurnLeft', 'EyeTurnRight'], degrees)
        self.l_eye_pan_tilt = MultiMotorCtrl(self.ros.ros_client, ['EyeTurnLeft', 'EyesUpDown'], degrees)
        self.r_eye_pan_tilt = MultiMotorCtrl(self.ros.ros_client, ['EyeTurnRight', 'EyesUpDown'], degrees)
        self.lr_eyes_pan_tilt = MultiMotorCtrl(self.ros.ros_client, ['EyeTurnLeft', 'EyeTurnRight', 'EyesUpDown'], degrees)
        self.reset_eyes()

    def move_left_eye(self, angles: tuple):
        """Moves the left eye motor with pan and/or tilt values.

        Pan only: angles = (pan, None)
        Tilt only: angles = (None, tilt)
        Pan and Tilt: angles = (pan, tilt)

        Angles (tuple): (pan, tilt)
        """
        if angles[0] is None:
            self.lr_eyes_tilt.move([angles[1]])
        elif angles[1] is None:
            self.l_eye_pan.move([angles[0]])
        else:
            self.l_eye_pan_tilt.move(list(angles))
        angles = self.state
        return (angles[0], angles[2])

    def move_right_eye(self, angles: tuple):
        """Moves the right eye motor with pan and/or tilt values.

        Pan only: angles = (pan, None)
        Tilt only: angles = (None, tilt)
        Pan and Tilt: angles = (pan, tilt)

        Angles (tuple): (pan, tilt)
        """
        if angles[0] is None:
            self.lr_eyes_tilt.move([angles[1]])
        elif angles[1] is None:
            self.r_eye_pan.move([angles[0]])
        else:
            self.r_eye_pan_tilt.move(list(angles))
        angles = self.state
        return (angles[1], angles[2])

    def move_both_eyes(self, angles: tuple):
        """Moves both the left and right eye motors with pan and/or tilt values.

        Left Right Pan and Tilt: angles = (l_eye_pan, r_eye_pan, tilt)
        Left Right Pan only: angles = (l_eye_pan, r_eye_pan, None)

        Angles (tuple): (l_eye_pan, r_eye_pan, tilt)
        """
        if angles[0] is None:
            self.move_right_eye((angles[1],angles[2]))
        elif angles[1] is None:
            self.move_left_eye((angles[0],angles[2]))
        elif angles[2] is None:
            self.lr_eyes_pan.move([angles[0],angles[1]])
        else:
            self.lr_eyes_pan_tilt.move(list(angles))
        angles = self.state
        return angles

    def rel_move_left_eye(self, delta: tuple):
        temp = self._state
        if delta[0]==0:
            angles = self.move_left_eye((None, temp[2]+delta[1]))
        elif delta[1]==0:
            angles = self.move_left_eye((temp[0]+delta[0], None))
        else:
            angles = self.move_left_eye((temp[0]+delta[0], temp[2]+delta[1]))
        return angles

    def rel_move_right_eye(self, delta: tuple):
        temp = self._state
        if delta[0]==0:
            angles = self.move_right_eye((None, temp[2]+delta[1]))
        elif delta[1]==0:
            angles = self.move_right_eye((temp[1]+delta[0], None))
        else:
            angles = self.move_right_eye((temp[1]+delta[0], temp[2]+delta[1]))
        return angles

    def rel_move_both_eyes(self, delta: tuple):
        temp = self._state
        if delta[0]==0:
            self.rel_move_right_eye((delta[1], delta[2]))
        elif delta[1]==0:
            self.rel_move_left_eye((delta[0], delta[2]))
        elif delta[2]==0:
            self.move_both_eyes((temp[0]+delta[0], temp[1]+delta[1], None))
        else:
            self.move_both_eyes((temp[0]+delta[0], temp[1]+delta[1], temp[2]+delta[2]))
        angles = self.state
        return (angles[0], angles[1], angles[2])

    def direct_move_left_eye(self, angles: tuple):
        """Directly moves the left eye motor with pan and/or tilt values.

        Pan only: angles = (pan, None)
        Tilt only: angles = (None, tilt)
        Pan and Tilt: angles = (pan, tilt)

        Return: None
        """
        if angles[0] is None:
            self.lr_eyes_tilt.direct_move([angles[1]])
        elif angles[1] is None:
            self.l_eye_pan.direct_move([angles[0]])
        else:
            self.l_eye_pan_tilt.direct_move(list(angles))

    def slow_move_left_eye_pan(self, angle, step_size, time_interval):  # TODO: Extend slow movements to tilt motor
        """Slowly moves the left eye motor with pan values.

        Args:
            angle (float): target angle
            step_size (float): amplitude resolution
            time_interval (float): time duration in between two consecutive motor commands
        """
        self.l_eye_pan.slow_move([angle], step_size, time_interval, num_repeat=1)
        time.sleep(0.75)
        angles = self.state
        return (angles[0], angles[2])

    def slow_centering_eyes(self):
        angles = self.slow_move_left_eye_pan(angle=0, step_size=0.0879, time_interval=0.015)
        return angles

    def reset_eyes(self):
        angles = self.move_both_eyes((0, 0, 0))
        return angles

    @property
    def state(self):
        temp = self.lr_eyes_pan_tilt.state
        angles = (temp[0]['actual'], temp[1]['actual'], temp[2]['actual'])
        ctr = 1
        while(None in angles or any(filter(lambda x: (x>75 or x<-75), angles))):
            temp = self.lr_eyes_pan_tilt.state
            angles = (temp[0]['actual'], temp[1]['actual'], temp[2]['actual'])
            if ctr == 100:
                raise(Exception("Motor state timeout. Servo motors erroneous output"))
            else:
                ctr+=1
        self._state = angles
        return self._state

    @property
    def state_with_time(self):
        temp = self.lr_eyes_pan_tilt.state
        angles = (temp[0]['actual'], temp[1]['actual'], temp[2]['actual'])
        if None in angles:
            while(not None in angles):
                temp = self.lr_eyes_pan_tilt.state
                angles = (temp[0]['actual'], temp[1]['actual'], temp[2]['actual'])
                print('Repeat')
        self._state = angles
        return self._state, temp['timestamp']

if __name__ == "__main__":
    # Initialization
    grace = Grace(degrees=True)

    # Left Eye Control
    state = grace.move_left_eye((-19, -19))
    print(state)

    # Right Eye Control
    state = grace.move_right_eye((-19, None))
    print(state)

    # Both Eyes Control
    state = grace.reset_eyes()
    print(state)


import requests
import logging
from aws_requests_auth.aws_auth import AWSRequestsAuth

from base.config import config

logging.info('Connecting AWS ElasticSearch %s', config.ES_URI)
auth = AWSRequestsAuth(aws_access_key=config.AWS_ES_ACCESS_KEY,
                                  aws_secret_access_key=config.AWS_ES_SECRET_KEY,
                                  aws_host=config.ES_URI,
                                  aws_region=config.ES_REGION,
                                  aws_service='es')

def get_settings():
    url = "https://" + config.ES_URI + '/_cat/allocation?v'
    headers = {"Content-Type": "application/json"}
    response = requests.get(url, auth=auth, headers=headers)
    print(response.status_code)
    print(response.headers)
    return response.content

print(get_settings())


from django.urls import path
from api.views import ProjectDetailView, TaskDetailView, ProjectUpdateView, TaskUpdateView, ProjectDeleteView, TaskDeleteView

urlpatterns = [
    path('project/<int:pk>', ProjectDetailView.as_view()),
    path("task/<int:pk>", TaskDetailView.as_view()),
    path('project/<int:pk>/update', ProjectUpdateView.as_view()),
    path('task/<int:pk>/update', TaskUpdateView.as_view()),
    path('project/<int:pk>/delete', ProjectDeleteView.as_view()),
    path('task/<int:pk>/delete', TaskDeleteView.as_view())
]


from scripts.models.pos_unet.unet_parts import *
from scripts.models.pos_unet.PositionalEncoding import PositionalEncoding

class UNet_Pos(nn.Module):
    def __init__(self, n_channels, n_classes,in_height,in_width, bilinear=False):
        super(UNet_Pos, self).__init__()
        self.n_channels = n_channels
        self.n_classes = n_classes
        self.bilinear = bilinear

        self.inc = DoubleConv(n_channels, 64)
        self.pos=PositionalEncoding(64,in_height,in_width)
        self.down1 = Down(64, 128)
        self.down2 = Down(128, 256)
        self.down3 = Down(256, 512)
        factor = 2 if bilinear else 1
        self.down4 = Down(512, 1024 // factor)
        self.up1 = Up(1024, 512 // factor, bilinear)
        self.up2 = Up(512, 256 // factor, bilinear)
        self.up3 = Up(256, 128 // factor, bilinear)
        self.up4 = Up(128, 64, bilinear)

        self.outc = OutConv(64, n_classes)

    def forward(self, x):
        x1 = self.inc(x)
        mask=self.pos(x1)
        x2 = self.down1(x1)
        x3 = self.down2(x2)
        x4 = self.down3(x3)
        x5 = self.down4(x4)
        x = self.up1(x5, x4)
        x = self.up2(x, x3)
        x = self.up3(x, x2)
        x = self.up4(x, x1)
        mask_x=mask*x
        logits = self.outc(mask_x)
        return logits
    def get_mask(self,x):
        x1 = self.inc(x)
        mask=self.pos(x1)
        return mask

    def forward_without_mask(self,x):
        x1 = self.inc(x)
        x2 = self.down1(x1)
        x3 = self.down2(x2)
        x4 = self.down3(x3)
        x5 = self.down4(x4)
        x = self.up1(x5, x4)
        x = self.up2(x, x3)
        x = self.up3(x, x2)
        x = self.up4(x, x1)
        logits = self.outc(x)
        return logits


# Author: Viktor Mamontov
# Print a list of non-repeated elements from random list

from random import randint as rnd

rnd_list = [rnd(1, 15) for i in range(20)]
print(rnd_list)  # show random list compared to the resulted one

my_list = [i for i in rnd_list if rnd_list.count(i) == 1]
print(my_list)


import requests
from typing import List

class Tesco:
    """The Tesco wrapper object
    """

    def __init__(self, key:str) -> None:
        """init

        Args:
            key (str): The API key
        """

        self.key = key

    def grocery_search(self, query:str, offset:int=0, limit:int=10) -> List:
        """Searches grocery items stocked by Tescolabs

        ```
        Args:
            query (str): The search query
            offset (int, optional): The offset used for pagination. Defaults to 0.
            limit (int, optional): The number of results to return. Defaults to 10.

        Returns:
            List: List of products
        ```
        """

        params:dict = {
            "query": query,
            "offset": offset,
            "limit": limit
        }
        headers:dict = {
            "Ocp-Apim-Subscription-Key": self.key
        }
        base:str = "https://dev.tescolabs.com/grocery/products/"

        r = requests.get(base, params=params, headers=headers)

        return r.json()["uk"]["ghs"]["products"]["results"]

    def product_data(self, gtin:str="", tpnb:str="", tpnc:str="", catid:str="") -> List:
        """Gets information about a product

        ```
        Args:
            gtin (str, optional): The gtin of the product. Defaults to "".
            tpnb (str, optional): The tpnb of the product. Defaults to "".
            tpnc (str, optional): The tpnc of the product. Defaults to "".
            catid (str, optional): The catid of the product. Defaults to "".

        Returns:
            List: The information about the product
        ```
        """

        params:dict = {
            "gtin": gtin,
            "tpnb": tpnb,
            "tpnc": tpnc,
            "catid": catid
        }
        cleaned_params:dict = {k: v for k, v in params.items() if v is not ""}
        headers:dict = {
            "Ocp-Apim-Subscription-Key": self.key
        }
        base:str = "https://dev.tescolabs.com/product/"

        r = requests.get(base, params=cleaned_params, headers=headers)

        return r.json()["products"]


#Crea/Presenta  la forma que creas más conveniente para describir
#cuántos alumnos hay por grados.

import pandas as pd

students = students = pd.read_csv("clean_students_complete.csv", index_col=0)
students.drop(students.columns[0], axis=1, inplace=True)

fig1 = students["grade"].value_counts().plot(kind="bar").get_figure()
fig1.savefig("Actividad18\\graficaPorGrado")