index
int64
0
731k
package
stringlengths
2
98
name
stringlengths
1
76
docstring
stringlengths
0
281k
code
stringlengths
4
1.07M
signature
stringlengths
2
42.8k
23,381
uvicorn.server
_serve
null
def run(self, sockets: list[socket.socket] | None = None) -> None: self.config.setup_event_loop() return asyncio.run(self.serve(sockets=sockets))
(self, sockets: Optional[list[socket.socket]] = None) -> NoneType
23,384
uvicorn.server
handle_exit
null
def handle_exit(self, sig: int, frame: FrameType | None) -> None: self._captured_signals.append(sig) if self.should_exit and sig == signal.SIGINT: self.force_exit = True else: self.should_exit = True
(self, sig: int, frame: frame | None) -> NoneType
23,397
uvicorn.main
run
null
def run( app: ASGIApplication | Callable[..., Any] | str, *, host: str = "127.0.0.1", port: int = 8000, uds: str | None = None, fd: int | None = None, loop: LoopSetupType = "auto", http: type[asyncio.Protocol] | HTTPProtocolType = "auto", ws: type[asyncio.Protocol] | WSProtocolType = "auto", ws_max_size: int = 16777216, ws_max_queue: int = 32, ws_ping_interval: float | None = 20.0, ws_ping_timeout: float | None = 20.0, ws_per_message_deflate: bool = True, lifespan: LifespanType = "auto", interface: InterfaceType = "auto", reload: bool = False, reload_dirs: list[str] | str | None = None, reload_includes: list[str] | str | None = None, reload_excludes: list[str] | str | None = None, reload_delay: float = 0.25, workers: int | None = None, env_file: str | os.PathLike[str] | None = None, log_config: dict[str, Any] | str | None = LOGGING_CONFIG, log_level: str | int | None = None, access_log: bool = True, proxy_headers: bool = True, server_header: bool = True, date_header: bool = True, forwarded_allow_ips: list[str] | str | None = None, root_path: str = "", limit_concurrency: int | None = None, backlog: int = 2048, limit_max_requests: int | None = None, timeout_keep_alive: int = 5, timeout_graceful_shutdown: int | None = None, ssl_keyfile: str | None = None, ssl_certfile: str | os.PathLike[str] | None = None, ssl_keyfile_password: str | None = None, ssl_version: int = SSL_PROTOCOL_VERSION, ssl_cert_reqs: int = ssl.CERT_NONE, ssl_ca_certs: str | None = None, ssl_ciphers: str = "TLSv1", headers: list[tuple[str, str]] | None = None, use_colors: bool | None = None, app_dir: str | None = None, factory: bool = False, h11_max_incomplete_event_size: int | None = None, ) -> None: if app_dir is not None: sys.path.insert(0, app_dir) config = Config( app, host=host, port=port, uds=uds, fd=fd, loop=loop, http=http, ws=ws, ws_max_size=ws_max_size, ws_max_queue=ws_max_queue, ws_ping_interval=ws_ping_interval, ws_ping_timeout=ws_ping_timeout, ws_per_message_deflate=ws_per_message_deflate, lifespan=lifespan, interface=interface, reload=reload, reload_dirs=reload_dirs, reload_includes=reload_includes, reload_excludes=reload_excludes, reload_delay=reload_delay, workers=workers, env_file=env_file, log_config=log_config, log_level=log_level, access_log=access_log, proxy_headers=proxy_headers, server_header=server_header, date_header=date_header, forwarded_allow_ips=forwarded_allow_ips, root_path=root_path, limit_concurrency=limit_concurrency, backlog=backlog, limit_max_requests=limit_max_requests, timeout_keep_alive=timeout_keep_alive, timeout_graceful_shutdown=timeout_graceful_shutdown, ssl_keyfile=ssl_keyfile, ssl_certfile=ssl_certfile, ssl_keyfile_password=ssl_keyfile_password, ssl_version=ssl_version, ssl_cert_reqs=ssl_cert_reqs, ssl_ca_certs=ssl_ca_certs, ssl_ciphers=ssl_ciphers, headers=headers, use_colors=use_colors, factory=factory, h11_max_incomplete_event_size=h11_max_incomplete_event_size, ) server = Server(config=config) if (config.reload or config.workers > 1) and not isinstance(app, str): logger = logging.getLogger("uvicorn.error") logger.warning("You must pass the application as an import string to enable 'reload' or " "'workers'.") sys.exit(1) if config.should_reload: sock = config.bind_socket() ChangeReload(config, target=server.run, sockets=[sock]).run() elif config.workers > 1: sock = config.bind_socket() Multiprocess(config, target=server.run, sockets=[sock]).run() else: server.run() if config.uds and os.path.exists(config.uds): os.remove(config.uds) # pragma: py-win32 if not server.started and not config.should_reload and config.workers == 1: sys.exit(STARTUP_FAILURE)
(app: Union[Type[uvicorn._types.ASGI2Protocol], Callable[[Union[uvicorn._types.HTTPScope, uvicorn._types.WebSocketScope, uvicorn._types.LifespanScope], Callable[[], Awaitable[Union[uvicorn._types.HTTPRequestEvent, uvicorn._types.HTTPDisconnectEvent, uvicorn._types.WebSocketConnectEvent, uvicorn._types._WebSocketReceiveEventBytes, uvicorn._types._WebSocketReceiveEventText, uvicorn._types.WebSocketDisconnectEvent, uvicorn._types.LifespanStartupEvent, uvicorn._types.LifespanShutdownEvent]]], Callable[[Union[uvicorn._types.HTTPResponseStartEvent, uvicorn._types.HTTPResponseBodyEvent, uvicorn._types.HTTPResponseTrailersEvent, uvicorn._types.HTTPServerPushEvent, uvicorn._types.HTTPDisconnectEvent, uvicorn._types.WebSocketAcceptEvent, uvicorn._types._WebSocketSendEventBytes, uvicorn._types._WebSocketSendEventText, uvicorn._types.WebSocketResponseStartEvent, uvicorn._types.WebSocketResponseBodyEvent, uvicorn._types.WebSocketCloseEvent, uvicorn._types.LifespanStartupCompleteEvent, uvicorn._types.LifespanStartupFailedEvent, uvicorn._types.LifespanShutdownCompleteEvent, uvicorn._types.LifespanShutdownFailedEvent]], Awaitable[NoneType]]], Awaitable[NoneType]], Callable[..., Any], str], *, host: str = '127.0.0.1', port: int = 8000, uds: Optional[str] = None, fd: Optional[int] = None, loop: Literal['none', 'auto', 'asyncio', 'uvloop'] = 'auto', http: Union[type[asyncio.protocols.Protocol], Literal['auto', 'h11', 'httptools']] = 'auto', ws: Union[type[asyncio.protocols.Protocol], Literal['auto', 'none', 'websockets', 'wsproto']] = 'auto', ws_max_size: int = 16777216, ws_max_queue: int = 32, ws_ping_interval: float | None = 20.0, ws_ping_timeout: float | None = 20.0, ws_per_message_deflate: bool = True, lifespan: Literal['auto', 'on', 'off'] = 'auto', interface: Literal['auto', 'asgi3', 'asgi2', 'wsgi'] = 'auto', reload: bool = False, reload_dirs: Union[list[str], str, NoneType] = None, reload_includes: Union[list[str], str, NoneType] = None, reload_excludes: Union[list[str], str, NoneType] = None, reload_delay: float = 0.25, workers: Optional[int] = None, env_file: Union[str, os.PathLike[str], NoneType] = None, log_config: dict[str, typing.Any] | str | None = {'version': 1, 'disable_existing_loggers': False, 'formatters': {'default': {'()': 'uvicorn.logging.DefaultFormatter', 'fmt': '%(levelprefix)s %(message)s', 'use_colors': None}, 'access': {'()': 'uvicorn.logging.AccessFormatter', 'fmt': '%(levelprefix)s %(client_addr)s - "%(request_line)s" %(status_code)s'}}, 'handlers': {'default': {'formatter': 'default', 'class': 'logging.StreamHandler', 'stream': 'ext://sys.stderr'}, 'access': {'formatter': 'access', 'class': 'logging.StreamHandler', 'stream': 'ext://sys.stdout'}}, 'loggers': {'uvicorn': {'handlers': ['default'], 'level': 'INFO', 'propagate': False}, 'uvicorn.error': {'level': 'INFO'}, 'uvicorn.access': {'handlers': ['access'], 'level': 'INFO', 'propagate': False}}}, log_level: Union[str, int, NoneType] = None, access_log: bool = True, proxy_headers: bool = True, server_header: bool = True, date_header: bool = True, forwarded_allow_ips: Union[list[str], str, NoneType] = None, root_path: str = '', limit_concurrency: Optional[int] = None, backlog: int = 2048, limit_max_requests: Optional[int] = None, timeout_keep_alive: int = 5, timeout_graceful_shutdown: Optional[int] = None, ssl_keyfile: Optional[str] = None, ssl_certfile: Union[str, os.PathLike[str], NoneType] = None, ssl_keyfile_password: Optional[str] = None, ssl_version: int = <_SSLMethod.PROTOCOL_TLS_SERVER: 17>, ssl_cert_reqs: int = <VerifyMode.CERT_NONE: 0>, ssl_ca_certs: Optional[str] = None, ssl_ciphers: str = 'TLSv1', headers: Optional[list[tuple[str, str]]] = None, use_colors: Optional[bool] = None, app_dir: Optional[str] = None, factory: bool = False, h11_max_incomplete_event_size: Optional[int] = None) -> NoneType
23,400
conexions.proxy
Proxy
null
class Proxy: # Atributos da clase ------------------------------------------------------- __ligazon: str = 'https://sslproxies.org' __sesion: Session = None __verbose: bool = False __verbosalo: bool = False __max_cons: int = 0 # ó ser 0 implica que non ten un máximo predefinido # xFCR: xuntar as cant_cons nunha soa variable __cant_cons_totais: int = 0 __cant_cons: int = 0 __cant_cons_espido: int = 0 __reintentos: int = 5 __timeout: int = 30 __cabeceira: dict[str, str] __lst_proxys: List[ProxyDTO] # Ordeados de máis velho[0] a máis novo[len()] __proxy: ProxyDTO __spinner: Halo = Halo(text='Conectando', spinner='dots') __ligazons_ip: List[str] = [ 'https://ip.me', 'https://icanhazip.com' ] # -------------------------------------------------------------------------- def __init__(self, max_cons= 0, reintentos= 5, timeout= 30, verbose=False, verbosalo= False) -> None: self.__verbose = verbose self.__verbosalo = verbosalo self.__max_cons = max_cons self.__reintentos = reintentos self.__timeout = timeout self.__lst_proxys = [] self.set_cabeceira() # Dalle valor a __cabeceira self.set_proxys() # Enche a __lst_proxys self.set_proxy() # Saca un proxy da lista e meteo como atributo # -------------------------------------------------------------------------- # Getters def get_ligazon(self) -> str: return self.__ligazon def get_sesion(self) -> Session: """ """ return self.__sesion def get_verbose(self) -> bool: return self.__verbose def get_verbosalo(self) -> bool: return self.__verbosalo def get_max_cons(self) -> int: return self.__max_cons def get_cant_cons_totais(self) -> int: return self.__cant_cons_totais def get_cant_cons(self) -> int: return self.__cant_cons def get_cant_cons_espido(self) -> int: return self.__cant_cons_espido def get_reintentos(self) -> int: return self.__reintentos def get_timeout(self) -> int: return self.__timeout def get_cabeceira(self, set_nova: Union[bool, int] = False) -> dict[str, str]: try: return self.__cabeceira finally: if set_nova: self.set_cabeceira() def get_proxys(self) -> List[ProxyDTO]: return self.__lst_proxys def get_proxy(self) -> ProxyDTO: # se se alcanzou o máximo sacar novo proxy if (self.get_max_cons() != 0) and (self.get_cant_cons() >= self.get_max_cons()): self.set_proxy() return self.__proxy def __get_proxy(self) -> dict[str, str]: try: return self.get_proxy().format() finally: self.__set_cant_cons(self.get_cant_cons()+1) self.__set_cant_cons_totais(self.get_cant_cons_totais()+1) def get_ligazons_ip(self) -> List[str]: return self.__ligazons_ip def get_spinner(self) -> Halo: return self.__spinner # Getters # # Setters def __set_ligazon(self, nova_ligazon: str) -> None: self.__ligazon = nova_ligazon def set_sesion(self, reset: Union[bool, int] = False) -> None: """ """ if reset: self.__sesion = None else: self.__sesion = requests.Session() def set_verbose(self, novo_verbose: bool) -> None: self.__verbose = novo_verbose def set_verbosalo(self, novo_verbosalo: bool) -> None: self.__verbosalo = novo_verbosalo def set_reintentos(self, novo_reintentos: int) -> None: self.__reintentos = novo_reintentos def set_max_cons(self, novo_max_cons: int) -> None: self.__max_cons = novo_max_cons def __set_cant_cons_totais(self, novo_cant_cons_totais: int) -> None: self.__cant_cons_totais = novo_cant_cons_totais def __set_cant_cons(self, novo_cant_cons: int) -> None: self.__cant_cons = novo_cant_cons def __set_cant_cons_espido(self, novo_cant_cons_espido: int) -> None: self.__cant_cons_espido = novo_cant_cons_espido def set_timeout(self, novo_timeout: int) -> None: self.__timeout = novo_timeout def set_cabeceira(self) -> None: self.__cabeceira = {'User-Agent': UserAgent().random} def set_proxys(self) -> None: """ Colle a páxina e saca toda a info sobre os proxys que contén. @entradas: Ningunha. @saidas: Ningunha. """ while True: try: pax_web = requests.get(url= self.get_ligazon(), headers= self.get_cabeceira()) except ConnectionError: pass except Exception: raise else: # se saiu todo ben sáese do bucle if pax_web.ok: pax_web.encoding = 'utf-8' break if self.get_verbose() and self.get_cant_cons_totais()>0: print(f'{__name__}: Enchendo a lista de proxys.') taboa_proxys = bs(pax_web.text, 'html.parser').find(class_='table') lst_nomes_cols_esperados = [ 'IP Address', 'Port', 'Code', 'Country', 'Anonymity', 'Google', 'Https', 'Last Checked' ] lst_nomes_cols_obtidos = taboa_proxys.thead.find_all('th') if len(lst_nomes_cols_esperados) != len(lst_nomes_cols_obtidos): raise CambioNaPaxinaErro('Modificado o número de columnas') for esperado, obtido in zip(lst_nomes_cols_esperados, lst_nomes_cols_obtidos): if esperado != obtido.text: raise CambioNaPaxinaErro('Modificado o orde ou nome das columnas') for fila in taboa_proxys.tbody: novo_proxy = ProxyDTO([atributo.text for atributo in fila.find_all('td')]) if (novo_proxy.tipo == 'elite proxy') and (novo_proxy.google == 'no') and (novo_proxy.https == 'yes'): # métoos desta forma na lista porque así vou sacando e eliminando dende atrás self.__lst_proxys.insert(0, novo_proxy) def set_proxy(self) -> None: """ Devolve un proxy e automáticamente eliminao da lista. De non ter ningún proxy que devolver, escraperá a páxina por máis. @entradas: Ningunha. @saídas: ProxyDTO - Sempre └ O proxy a usar nas conexións. """ try: self.__proxy = self.get_proxys().pop() # se a lista de proxys está baleira except IndexError: self.set_proxys() self.get_proxy() # recursion finally: self.__set_cant_cons(0) # Setters # def get_ip(self, reintentos: int = None) -> str: """ """ if reintentos == None: reintentos = self.get_reintentos() try: return requests.get(self.get_ligazons_ip()[0]).text.rstrip() except ConnectionError: return self.get_ip(reintentos-1) def get_espido (self, ligazon: str, params: dict = None, bolachas: dict = None, stream: dict = False, timeout: int = None, reintentos: int = None) -> Response: """ """ # lazy_check_types #self. if timeout == None: timeout = self.get_timeout() if reintentos == None: if self.get_verbose(): print(f'*{__name__}* Chegouse á cantidade máxima de conexións.') reintentos = self.get_reintentos() if self.get_cant_cons() >= self.get_max_cons(): self.__set_cant_cons_espido(0) reintentos = self.get_reintentos() try: if self.get_verbosalo(): self.get_spinner().start() if self.get_sesion() != None: return self.get_sesion().get(url= ligazon, params= params, headers= self.get_cabeceira(), cookies= bolachas, stream= stream, timeout= timeout) else: return requests.get(url= ligazon, params= params, headers= self.get_cabeceira(set_nova=True), cookies= bolachas, stream= stream, timeout= timeout) #except ConnectionError: except: if reintentos <= 0: if self.get_verbose(): print(f'*{__name__}* Chegouse á cantidade máxima de reintentos.') reintentos = self.get_reintentos() if self.get_verbose(): print(f'*{__name__}* Reintento nº {self.get_reintentos()+1-reintentos}.') return self.get(ligazon= ligazon, params= params, bolachas= bolachas, stream=stream, timeout= timeout, reintentos= reintentos-1) finally: self.__set_cant_cons_espido(self.get_cant_cons_espido()+1) self.__set_cant_cons_totais(self.get_cant_cons_totais()+1) if self.get_verbosalo(): self.get_spinner().stop() def get(self, ligazon: str, params: dict = None, bolachas: dict = None, stream: dict = False, timeout: int = None, reintentos: int = None) -> Response: """ """ # lazy_check_types if timeout == None: timeout = self.get_timeout() if reintentos == None: reintentos = self.get_reintentos() if (self.get_max_cons() != 0) and (self.get_cant_cons() >= self.get_max_cons()): if self.get_verbose(): print(f'{__name__}: Chegouse á cantidade máxima de conexións. Collendo novo proxy ({len(self.get_proxys())} restantes)') self.set_proxy() self.__set_cant_cons(0) reintentos = self.get_reintentos() try: if self.get_verbosalo(): self.get_spinner().start() if self.get_sesion() != None: return self.get_sesion().get(url= ligazon, params= params, proxies= self.__get_proxy(), headers= self.get_cabeceira(), cookies= bolachas, stream= stream, timeout= timeout) else: return requests.get(url= ligazon, params= params, proxies= self.__get_proxy(), headers= self.get_cabeceira(set_nova=True), cookies= bolachas, stream= stream, timeout= timeout) except: if reintentos <= 0: if self.get_verbose(): print(f'{__name__}: Chegouse á cantidade máxima de reintentos. Collendo novo proxy ({len(self.get_proxys())} restantes)') self.set_proxy() reintentos = self.get_reintentos() if self.get_verbose(): print(f'{__name__}: Reintento nº {self.get_reintentos()+1-reintentos}.') return self.get(ligazon= ligazon, params= params, bolachas= bolachas, stream=stream, timeout= timeout, reintentos= reintentos-1) finally: if self.get_verbosalo(): self.get_spinner().stop()
(max_cons=0, reintentos=5, timeout=30, verbose=False, verbosalo=False) -> None
23,401
conexions.proxy
__get_proxy
null
def __get_proxy(self) -> dict[str, str]: try: return self.get_proxy().format() finally: self.__set_cant_cons(self.get_cant_cons()+1) self.__set_cant_cons_totais(self.get_cant_cons_totais()+1)
(self) -> dict[str, str]
23,402
conexions.proxy
__set_cant_cons
null
def __set_cant_cons(self, novo_cant_cons: int) -> None: self.__cant_cons = novo_cant_cons
(self, novo_cant_cons: int) -> NoneType
23,403
conexions.proxy
__set_cant_cons_espido
null
def __set_cant_cons_espido(self, novo_cant_cons_espido: int) -> None: self.__cant_cons_espido = novo_cant_cons_espido
(self, novo_cant_cons_espido: int) -> NoneType
23,404
conexions.proxy
__set_cant_cons_totais
null
def __set_cant_cons_totais(self, novo_cant_cons_totais: int) -> None: self.__cant_cons_totais = novo_cant_cons_totais
(self, novo_cant_cons_totais: int) -> NoneType
23,405
conexions.proxy
__set_ligazon
null
def __set_ligazon(self, nova_ligazon: str) -> None: self.__ligazon = nova_ligazon
(self, nova_ligazon: str) -> NoneType
23,406
conexions.proxy
__init__
null
def __init__(self, max_cons= 0, reintentos= 5, timeout= 30, verbose=False, verbosalo= False) -> None: self.__verbose = verbose self.__verbosalo = verbosalo self.__max_cons = max_cons self.__reintentos = reintentos self.__timeout = timeout self.__lst_proxys = [] self.set_cabeceira() # Dalle valor a __cabeceira self.set_proxys() # Enche a __lst_proxys self.set_proxy() # Saca un proxy da lista e meteo como atributo
(self, max_cons=0, reintentos=5, timeout=30, verbose=False, verbosalo=False) -> NoneType
23,407
conexions.proxy
get
def get(self, ligazon: str, params: dict = None, bolachas: dict = None, stream: dict = False, timeout: int = None, reintentos: int = None) -> Response: """ """ # lazy_check_types if timeout == None: timeout = self.get_timeout() if reintentos == None: reintentos = self.get_reintentos() if (self.get_max_cons() != 0) and (self.get_cant_cons() >= self.get_max_cons()): if self.get_verbose(): print(f'{__name__}: Chegouse á cantidade máxima de conexións. Collendo novo proxy ({len(self.get_proxys())} restantes)') self.set_proxy() self.__set_cant_cons(0) reintentos = self.get_reintentos() try: if self.get_verbosalo(): self.get_spinner().start() if self.get_sesion() != None: return self.get_sesion().get(url= ligazon, params= params, proxies= self.__get_proxy(), headers= self.get_cabeceira(), cookies= bolachas, stream= stream, timeout= timeout) else: return requests.get(url= ligazon, params= params, proxies= self.__get_proxy(), headers= self.get_cabeceira(set_nova=True), cookies= bolachas, stream= stream, timeout= timeout) except: if reintentos <= 0: if self.get_verbose(): print(f'{__name__}: Chegouse á cantidade máxima de reintentos. Collendo novo proxy ({len(self.get_proxys())} restantes)') self.set_proxy() reintentos = self.get_reintentos() if self.get_verbose(): print(f'{__name__}: Reintento nº {self.get_reintentos()+1-reintentos}.') return self.get(ligazon= ligazon, params= params, bolachas= bolachas, stream=stream, timeout= timeout, reintentos= reintentos-1) finally: if self.get_verbosalo(): self.get_spinner().stop()
(self, ligazon: str, params: Optional[dict] = None, bolachas: Optional[dict] = None, stream: dict = False, timeout: Optional[int] = None, reintentos: Optional[int] = None) -> requests.models.Response
23,408
conexions.proxy
get_cabeceira
null
def get_cabeceira(self, set_nova: Union[bool, int] = False) -> dict[str, str]: try: return self.__cabeceira finally: if set_nova: self.set_cabeceira()
(self, set_nova: Union[bool, int] = False) -> dict[str, str]
23,409
conexions.proxy
get_cant_cons
null
def get_cant_cons(self) -> int: return self.__cant_cons
(self) -> int
23,410
conexions.proxy
get_cant_cons_espido
null
def get_cant_cons_espido(self) -> int: return self.__cant_cons_espido
(self) -> int
23,411
conexions.proxy
get_cant_cons_totais
null
def get_cant_cons_totais(self) -> int: return self.__cant_cons_totais
(self) -> int
23,412
conexions.proxy
get_espido
def get_espido (self, ligazon: str, params: dict = None, bolachas: dict = None, stream: dict = False, timeout: int = None, reintentos: int = None) -> Response: """ """ # lazy_check_types #self. if timeout == None: timeout = self.get_timeout() if reintentos == None: if self.get_verbose(): print(f'*{__name__}* Chegouse á cantidade máxima de conexións.') reintentos = self.get_reintentos() if self.get_cant_cons() >= self.get_max_cons(): self.__set_cant_cons_espido(0) reintentos = self.get_reintentos() try: if self.get_verbosalo(): self.get_spinner().start() if self.get_sesion() != None: return self.get_sesion().get(url= ligazon, params= params, headers= self.get_cabeceira(), cookies= bolachas, stream= stream, timeout= timeout) else: return requests.get(url= ligazon, params= params, headers= self.get_cabeceira(set_nova=True), cookies= bolachas, stream= stream, timeout= timeout) #except ConnectionError: except: if reintentos <= 0: if self.get_verbose(): print(f'*{__name__}* Chegouse á cantidade máxima de reintentos.') reintentos = self.get_reintentos() if self.get_verbose(): print(f'*{__name__}* Reintento nº {self.get_reintentos()+1-reintentos}.') return self.get(ligazon= ligazon, params= params, bolachas= bolachas, stream=stream, timeout= timeout, reintentos= reintentos-1) finally: self.__set_cant_cons_espido(self.get_cant_cons_espido()+1) self.__set_cant_cons_totais(self.get_cant_cons_totais()+1) if self.get_verbosalo(): self.get_spinner().stop()
(self, ligazon: str, params: Optional[dict] = None, bolachas: Optional[dict] = None, stream: dict = False, timeout: Optional[int] = None, reintentos: Optional[int] = None) -> requests.models.Response
23,413
conexions.proxy
get_ip
def get_ip(self, reintentos: int = None) -> str: """ """ if reintentos == None: reintentos = self.get_reintentos() try: return requests.get(self.get_ligazons_ip()[0]).text.rstrip() except ConnectionError: return self.get_ip(reintentos-1)
(self, reintentos: Optional[int] = None) -> str
23,414
conexions.proxy
get_ligazon
null
def get_ligazon(self) -> str: return self.__ligazon
(self) -> str
23,415
conexions.proxy
get_ligazons_ip
null
def get_ligazons_ip(self) -> List[str]: return self.__ligazons_ip
(self) -> List[str]
23,416
conexions.proxy
get_max_cons
null
def get_max_cons(self) -> int: return self.__max_cons
(self) -> int
23,417
conexions.proxy
get_proxy
null
def get_proxy(self) -> ProxyDTO: # se se alcanzou o máximo sacar novo proxy if (self.get_max_cons() != 0) and (self.get_cant_cons() >= self.get_max_cons()): self.set_proxy() return self.__proxy
(self) -> conexions.dto_proxy.ProxyDTO
23,418
conexions.proxy
get_proxys
null
def get_proxys(self) -> List[ProxyDTO]: return self.__lst_proxys
(self) -> List[conexions.dto_proxy.ProxyDTO]
23,419
conexions.proxy
get_reintentos
null
def get_reintentos(self) -> int: return self.__reintentos
(self) -> int
23,420
conexions.proxy
get_sesion
def get_sesion(self) -> Session: """ """ return self.__sesion
(self) -> requests.sessions.Session
23,421
conexions.proxy
get_spinner
null
def get_spinner(self) -> Halo: return self.__spinner
(self) -> halo.halo.Halo
23,422
conexions.proxy
get_timeout
null
def get_timeout(self) -> int: return self.__timeout
(self) -> int
23,423
conexions.proxy
get_verbosalo
null
def get_verbosalo(self) -> bool: return self.__verbosalo
(self) -> bool
23,424
conexions.proxy
get_verbose
null
def get_verbose(self) -> bool: return self.__verbose
(self) -> bool
23,425
conexions.proxy
set_cabeceira
null
def set_cabeceira(self) -> None: self.__cabeceira = {'User-Agent': UserAgent().random}
(self) -> NoneType
23,426
conexions.proxy
set_max_cons
null
def set_max_cons(self, novo_max_cons: int) -> None: self.__max_cons = novo_max_cons
(self, novo_max_cons: int) -> NoneType
23,427
conexions.proxy
set_proxy
Devolve un proxy e automáticamente eliminao da lista. De non ter ningún proxy que devolver, escraperá a páxina por máis. @entradas: Ningunha. @saídas: ProxyDTO - Sempre └ O proxy a usar nas conexións.
def set_proxy(self) -> None: """ Devolve un proxy e automáticamente eliminao da lista. De non ter ningún proxy que devolver, escraperá a páxina por máis. @entradas: Ningunha. @saídas: ProxyDTO - Sempre └ O proxy a usar nas conexións. """ try: self.__proxy = self.get_proxys().pop() # se a lista de proxys está baleira except IndexError: self.set_proxys() self.get_proxy() # recursion finally: self.__set_cant_cons(0)
(self) -> NoneType
23,428
conexions.proxy
set_proxys
Colle a páxina e saca toda a info sobre os proxys que contén. @entradas: Ningunha. @saidas: Ningunha.
def set_proxys(self) -> None: """ Colle a páxina e saca toda a info sobre os proxys que contén. @entradas: Ningunha. @saidas: Ningunha. """ while True: try: pax_web = requests.get(url= self.get_ligazon(), headers= self.get_cabeceira()) except ConnectionError: pass except Exception: raise else: # se saiu todo ben sáese do bucle if pax_web.ok: pax_web.encoding = 'utf-8' break if self.get_verbose() and self.get_cant_cons_totais()>0: print(f'{__name__}: Enchendo a lista de proxys.') taboa_proxys = bs(pax_web.text, 'html.parser').find(class_='table') lst_nomes_cols_esperados = [ 'IP Address', 'Port', 'Code', 'Country', 'Anonymity', 'Google', 'Https', 'Last Checked' ] lst_nomes_cols_obtidos = taboa_proxys.thead.find_all('th') if len(lst_nomes_cols_esperados) != len(lst_nomes_cols_obtidos): raise CambioNaPaxinaErro('Modificado o número de columnas') for esperado, obtido in zip(lst_nomes_cols_esperados, lst_nomes_cols_obtidos): if esperado != obtido.text: raise CambioNaPaxinaErro('Modificado o orde ou nome das columnas') for fila in taboa_proxys.tbody: novo_proxy = ProxyDTO([atributo.text for atributo in fila.find_all('td')]) if (novo_proxy.tipo == 'elite proxy') and (novo_proxy.google == 'no') and (novo_proxy.https == 'yes'): # métoos desta forma na lista porque así vou sacando e eliminando dende atrás self.__lst_proxys.insert(0, novo_proxy)
(self) -> NoneType
23,429
conexions.proxy
set_reintentos
null
def set_reintentos(self, novo_reintentos: int) -> None: self.__reintentos = novo_reintentos
(self, novo_reintentos: int) -> NoneType
23,430
conexions.proxy
set_sesion
def set_sesion(self, reset: Union[bool, int] = False) -> None: """ """ if reset: self.__sesion = None else: self.__sesion = requests.Session()
(self, reset: Union[bool, int] = False) -> NoneType
23,431
conexions.proxy
set_timeout
null
def set_timeout(self, novo_timeout: int) -> None: self.__timeout = novo_timeout
(self, novo_timeout: int) -> NoneType
23,432
conexions.proxy
set_verbosalo
null
def set_verbosalo(self, novo_verbosalo: bool) -> None: self.__verbosalo = novo_verbosalo
(self, novo_verbosalo: bool) -> NoneType
23,433
conexions.proxy
set_verbose
null
def set_verbose(self, novo_verbose: bool) -> None: self.__verbose = novo_verbose
(self, novo_verbose: bool) -> NoneType
23,437
tryme.tryme
Again
Again of :py:class:`Failure`. A handy alias of :py:class:`Failure` to indicate that an operation should be retried
class Again(Failure): """ Again of :py:class:`Failure`. A handy alias of :py:class:`Failure` to indicate that an operation should be retried """ pass
(value, message=None, start=None, end=None, count=1)
23,438
tryme.tryme
__bool__
null
def __bool__(self): # pylint: disable = no-self-use return False
(self)
23,439
tryme.tryme
__eq__
null
def __eq__(self, other): if self is other: return True elif not isinstance(other, type(self)): return NotImplemented else: return self._value == other._value
(self, other)
23,440
functools
__ge__
Return a >= b. Computed by @total_ordering from (not a < b).
def _ge_from_lt(self, other, NotImplemented=NotImplemented): 'Return a >= b. Computed by @total_ordering from (not a < b).' op_result = type(self).__lt__(self, other) if op_result is NotImplemented: return op_result return not op_result
(self, other, NotImplemented=NotImplemented)
23,441
functools
__gt__
Return a > b. Computed by @total_ordering from (not a < b) and (a != b).
def _gt_from_lt(self, other, NotImplemented=NotImplemented): 'Return a > b. Computed by @total_ordering from (not a < b) and (a != b).' op_result = type(self).__lt__(self, other) if op_result is NotImplemented: return op_result return not op_result and self != other
(self, other, NotImplemented=NotImplemented)
23,442
tryme.tryme
__init__
null
def __init__(self, value, message=None, start=None, end=None, count=1): super(Try, self).__init__(value) self._message = message self._start = start self._end = end self._count = count if (start is None and end is not None) or (end is None and start is not None): raise InvalidTryError( "The start and end argument must either be both None or not None") if type(self) is Try: raise NotImplementedError('Please use Failure or Success instead')
(self, value, message=None, start=None, end=None, count=1)
23,443
functools
__le__
Return a <= b. Computed by @total_ordering from (a < b) or (a == b).
def _le_from_lt(self, other, NotImplemented=NotImplemented): 'Return a <= b. Computed by @total_ordering from (a < b) or (a == b).' op_result = type(self).__lt__(self, other) if op_result is NotImplemented: return op_result return op_result or self == other
(self, other, NotImplemented=NotImplemented)
23,444
tryme.tryme
__lt__
Override to handle special case: Success.
def __lt__(self, monad): """Override to handle special case: Success.""" if not isinstance(monad, (Failure, Success)): fmt = "unorderable types: {} and {}'".format raise TypeError(fmt(type(self), type(monad))) if type(self) is type(monad): # same type, either both lefts or rights, compare against value return self._value < monad._value if monad: # self is Failure and monad is Success, left is less than right return True else: return False
(self, monad)
23,446
tryme.tryme
__repr__
Customize Show.
def __repr__(self): """Customize Show.""" fmt = 'Success({})' if self else 'Failure({})' return fmt.format(repr(self._value))
(self)
23,447
tryme.tryme
fail_for_error
If a Failure, write the message to stderr and exit with return code of `exit_status` Does nothing if a Success :param exit_status: (optional) the numeric exist status to return if exit is True :type exit_status: int
def fail_for_error(self, exit_status=1): ''' If a Failure, write the message to stderr and exit with return code of `exit_status` Does nothing if a Success :param exit_status: (optional) the numeric exist status to return if exit is True :type exit_status: int ''' if self.failed(): to_console(self.message, nl=True, err=True, exit_err=True, exit_status=exit_status)
(self, exit_status=1)
23,448
tryme.tryme
failed
Return a Boolean that indicates if the value is an instance of Failure >>> Failure('shit is fucked up').failed() True >>> Success('it worked!').failed() False
def failed(self): """Return a Boolean that indicates if the value is an instance of Failure >>> Failure('shit is fucked up').failed() True >>> Success('it worked!').failed() False """ return not(bool(self))
(self)
23,449
tryme.tryme
filter
If a Success, convert this to a Failure if the predicate is not satisfied. Applies predicate to the wrapped value :param predicate: a function that takes the wrapped value as its argument and returns a boolean value :rtype: :class:`Try <Try>` object :return: Try
def filter(self, predicate): ''' If a Success, convert this to a Failure if the predicate is not satisfied. Applies predicate to the wrapped value :param predicate: a function that takes the wrapped value as its argument and returns a boolean value :rtype: :class:`Try <Try>` object :return: Try ''' if self.failed(): return self else: wrapped_value = self.get() if predicate(wrapped_value): return self else: return Failure(wrapped_value)
(self, predicate)
23,450
tryme.tryme
get
Gets the Success value if this is a Success otherwise throws an exception
def get(self): '''Gets the Success value if this is a Success otherwise throws an exception''' if self.succeeded(): return self._value else: raise NoSuchElementError('You cannot call `get` on a Failure, use `get_failure` instead')
(self)
23,451
tryme.tryme
get_failure
Gets the Failure value if this is a Failure otherwise throws an exception
def get_failure(self): '''Gets the Failure value if this is a Failure otherwise throws an exception''' if self.failed(): return self._value else: raise NoSuchElementError('You cannot call `get_failure` on a Success, use `get` instead')
(self)
23,452
tryme.tryme
get_or_else
Returns the value from this Success or the given default argument if this is a Failure.
def get_or_else(self, default): '''Returns the value from this Success or the given default argument if this is a Failure.''' if self.succeeded(): return self._value else: return default
(self, default)
23,453
tryme.tryme
map
The map operation of :py:class:`Try` to Success instances Applies function to the value if and only if this is a :py:class:`Success`.
def map(self, function): """The map operation of :py:class:`Try` to Success instances Applies function to the value if and only if this is a :py:class:`Success`. """ constructor = type(self) if self.succeeded(): return constructor(function(self._value)) else: return self
(self, function)
23,454
tryme.tryme
map_failure
The map operation of :py:class:`Try` to Failure instances Applies function to the value if and only if this is a :py:class:`Success`.
def map_failure(self, function): """The map operation of :py:class:`Try` to Failure instances Applies function to the value if and only if this is a :py:class:`Success`. """ constructor = type(self) if self.failed(): return constructor(function(self._value)) else: return self
(self, function)
23,455
tryme.tryme
raise_for_error
Raise an exception if self is an instance of Failure. If the wrapped value is an instance of Exeception or one of its subclasses, it is raised directly. The the optional argument ``exception`` is specified, that type is raised with the wrapped value as its argument. Otherwise, FailureError is raised. This method has no effect is self is an instance of Success. :param exception: (optional) type of Exception to raise
def raise_for_error(self, exception=FailureError): ''' Raise an exception if self is an instance of Failure. If the wrapped value is an instance of Exeception or one of its subclasses, it is raised directly. The the optional argument ``exception`` is specified, that type is raised with the wrapped value as its argument. Otherwise, FailureError is raised. This method has no effect is self is an instance of Success. :param exception: (optional) type of Exception to raise ''' if self.succeeded(): return wrapped_value = self.get_failure() if isinstance(wrapped_value, Exception): raise wrapped_value else: raise exception(wrapped_value)
(self, exception=<class 'tryme.tryme.FailureError'>)
23,456
tryme.tryme
succeeded
Return a Boolean that indicates if the value is an instance of Success >>> Success(True).succeeded() True >>> Failure('fubar').succeeded() False
def succeeded(self): """Return a Boolean that indicates if the value is an instance of Success >>> Success(True).succeeded() True >>> Failure('fubar').succeeded() False """ return bool(self)
(self)
23,457
tryme.tryme
to_console
Write a message to the console. By convention, Success messages are written to stdout and Failure messages are written to stderr. The Failure's `cause` is written to stderr while the string repesentation of the Success's _value is written. :param message: the message to print :param err: (optional) if set to true the file defaults to ``stderr`` instead of ``stdout``. :param nl: (optional) if set to `True` (the default) a newline is printed afterwards. :param exit_err: (optional) if set to True, exit the running program with a non-zero exit code :param exit_status: (optional) the numeric exist status to return if exit is True
def to_console(self, nl=True, exit_err=False, exit_status=1): ''' Write a message to the console. By convention, Success messages are written to stdout and Failure messages are written to stderr. The Failure's `cause` is written to stderr while the string repesentation of the Success's _value is written. :param message: the message to print :param err: (optional) if set to true the file defaults to ``stderr`` instead of ``stdout``. :param nl: (optional) if set to `True` (the default) a newline is printed afterwards. :param exit_err: (optional) if set to True, exit the running program with a non-zero exit code :param exit_status: (optional) the numeric exist status to return if exit is True ''' if self.succeeded(): to_console(self.message, nl=nl) else: to_console(self.message, nl=nl, err=True, exit_err=exit_err, exit_status=exit_status)
(self, nl=True, exit_err=False, exit_status=1)
23,458
tryme.tryme
update
Update the Try with new properties but the same value. Returns a new :class:`Failure` or :py:class:`Success` and does not actually update in place. :param message: (optional) message to output to console if to_console is called. If None, a string representation of the contained value is output. Defaults to ``None`` :param start: (optional) start time for the operation, in seconds since the UNIX epoch `time.time()` is typically used for this value. Defaults to ``None``. :type start: int :param end: (optional) end time for the operation, in seconds since the UNIX epoch ``time.time()`` is typically used for this value. Defaults to ``None``. :type end: int :param count: (optional) number of times the operation has been executed. Defaults to ``1`` :type end: int
def update(self, message=None, start=None, end=None, count=1): ''' Update the Try with new properties but the same value. Returns a new :class:`Failure` or :py:class:`Success` and does not actually update in place. :param message: (optional) message to output to console if to_console is called. If None, a string representation of the contained value is output. Defaults to ``None`` :param start: (optional) start time for the operation, in seconds since the UNIX epoch `time.time()` is typically used for this value. Defaults to ``None``. :type start: int :param end: (optional) end time for the operation, in seconds since the UNIX epoch ``time.time()`` is typically used for this value. Defaults to ``None``. :type end: int :param count: (optional) number of times the operation has been executed. Defaults to ``1`` :type end: int ''' if (start is None and end is not None) or (end is None and start is not None): raise InvalidTryError( "The start and end argument must either be both None or not None") message = message or self._message # start = start or self._start does not work because start may == 0 and is therefore falsey if start is None: start = self._start if end is None: end = self._end if count is None: count = self._count constructor = type(self) return constructor(self._value, message=message, start=start, end=end, count=count)
(self, message=None, start=None, end=None, count=1)
23,459
tryme.tryme
Failure
Failure of :py:class:`Try`.
class Failure(Try): """Failure of :py:class:`Try`.""" def __bool__(self): # pylint: disable = no-self-use return False __nonzero__ = __bool__
(value, message=None, start=None, end=None, count=1)
23,481
tryme.tryme
Maybe
A wrapper for values that be None >>> Some(42) Some(42) >>> Some([1, 2, 3]) Some([1, 2, 3]) >>> Some(Nothing) Some(Nothing) >>> Some(Some(2)) Some(Some(2)) >>> isinstance(Some(1), Maybe) True >>> isinstance(Nothing, Maybe) True >>> saving = 100 >>> spend = lambda cost: Nothing if cost > saving else Some(saving - cost) >>> spend(90) Some(10) >>> spend(120) Nothing >>> safe_div = lambda a, b: Nothing if b == 0 else Some(a / b) >>> safe_div(12.0, 6) Some(2.0) >>> safe_div(12.0, 0) Nothing Map operation with ``map``. Not that map only applies a function if the object is an instance of Some. In the case of a Some, ``map`` returns the transformed value inside a Some. No action is taken for a Nothing. >>> inc = lambda n: n + 1 >>> Some(0) Some(0) >>> Some(0).map(inc) Some(1) >>> Some(0).map(inc).map(inc) Some(2) >>> Nothing.map(inc) Nothing Comparison with ``==``, as long as what's wrapped inside are comparable. >>> Some(42) == Some(42) True >>> Some(42) == Nothing False >>> Nothing == Nothing True
class Maybe(Monad, Ord): """A wrapper for values that be None >>> Some(42) Some(42) >>> Some([1, 2, 3]) Some([1, 2, 3]) >>> Some(Nothing) Some(Nothing) >>> Some(Some(2)) Some(Some(2)) >>> isinstance(Some(1), Maybe) True >>> isinstance(Nothing, Maybe) True >>> saving = 100 >>> spend = lambda cost: Nothing if cost > saving else Some(saving - cost) >>> spend(90) Some(10) >>> spend(120) Nothing >>> safe_div = lambda a, b: Nothing if b == 0 else Some(a / b) >>> safe_div(12.0, 6) Some(2.0) >>> safe_div(12.0, 0) Nothing Map operation with ``map``. Not that map only applies a function if the object is an instance of Some. In the case of a Some, ``map`` returns the transformed value inside a Some. No action is taken for a Nothing. >>> inc = lambda n: n + 1 >>> Some(0) Some(0) >>> Some(0).map(inc) Some(1) >>> Some(0).map(inc).map(inc) Some(2) >>> Nothing.map(inc) Nothing Comparison with ``==``, as long as what's wrapped inside are comparable. >>> Some(42) == Some(42) True >>> Some(42) == Nothing False >>> Nothing == Nothing True """ @classmethod def from_value(cls, value): """Wraps ``value`` in a :class:`Maybe` monad. Returns a :class:`Some` if the value is evaluated as true. :data:`Nothing` otherwise. """ return cls.unit(value) if value else Nothing def get(self): '''Return the wrapped value if this is Some otherwise throws an exception''' if self.is_empty(): raise NoSuchElementError('You cannot call `get` on Nothing') else: return self._value def get_or_else(self, default): '''Returns the value from this Some or the given default argument otherwise.''' if self.is_empty(): return default else: return self._value def filter(self, predicate): ''' Returns Some(value) if this is a Some and the value satisfies the given predicate. :param predicate: a function that takes the wrapped value as its argument and returns a boolean value :rtype: :class:`Maybe <Maybe>` object :return: Maybe ''' if self.is_empty(): return self else: wrapped_value = self.get() if predicate(wrapped_value): return self else: return Nothing def map(self, function): """The map operation of :class:`Maybe`. Applies function to the value if and only if this is a :class:`Some`. """ constructor = type(self) return self and constructor(function(self._value)) def is_empty(self): '''Returns true, if this is None, otherwise false, if this is Some.''' return self is Nothing def is_defined(self): '''Returns true, if this is Some, otherwise false, if this is Nothing.''' return self is not Nothing def __bool__(self): return self is not Nothing __nonzero__ = __bool__ def __repr__(self): """Customized Show.""" if self is Nothing: return 'Nothing' else: return 'Some({})'.format(repr(self._value)) def __iter__(self): if self is not Nothing: yield self._value
(value)
23,482
tryme.tryme
__bool__
null
def __bool__(self): return self is not Nothing
(self)
23,486
tryme.tryme
__init__
null
def __init__(self, value): self._value = value
(self, value)
23,487
tryme.tryme
__iter__
null
def __iter__(self): if self is not Nothing: yield self._value
(self)
23,489
tryme.tryme
__lt__
null
def __lt__(self, other): if self is other: return False elif isinstance(other, type(self)): return self._value < other._value else: fmt = "unorderable types: {} and {}'".format raise TypeError(fmt(type(self), type(other)))
(self, other)
23,491
tryme.tryme
__repr__
Customized Show.
def __repr__(self): """Customized Show.""" if self is Nothing: return 'Nothing' else: return 'Some({})'.format(repr(self._value))
(self)
23,492
tryme.tryme
filter
Returns Some(value) if this is a Some and the value satisfies the given predicate. :param predicate: a function that takes the wrapped value as its argument and returns a boolean value :rtype: :class:`Maybe <Maybe>` object :return: Maybe
def filter(self, predicate): ''' Returns Some(value) if this is a Some and the value satisfies the given predicate. :param predicate: a function that takes the wrapped value as its argument and returns a boolean value :rtype: :class:`Maybe <Maybe>` object :return: Maybe ''' if self.is_empty(): return self else: wrapped_value = self.get() if predicate(wrapped_value): return self else: return Nothing
(self, predicate)
23,493
tryme.tryme
get
Return the wrapped value if this is Some otherwise throws an exception
def get(self): '''Return the wrapped value if this is Some otherwise throws an exception''' if self.is_empty(): raise NoSuchElementError('You cannot call `get` on Nothing') else: return self._value
(self)
23,494
tryme.tryme
get_or_else
Returns the value from this Some or the given default argument otherwise.
def get_or_else(self, default): '''Returns the value from this Some or the given default argument otherwise.''' if self.is_empty(): return default else: return self._value
(self, default)
23,495
tryme.tryme
is_defined
Returns true, if this is Some, otherwise false, if this is Nothing.
def is_defined(self): '''Returns true, if this is Some, otherwise false, if this is Nothing.''' return self is not Nothing
(self)
23,496
tryme.tryme
is_empty
Returns true, if this is None, otherwise false, if this is Some.
def is_empty(self): '''Returns true, if this is None, otherwise false, if this is Some.''' return self is Nothing
(self)
23,497
tryme.tryme
map
The map operation of :class:`Maybe`. Applies function to the value if and only if this is a :class:`Some`.
def map(self, function): """The map operation of :class:`Maybe`. Applies function to the value if and only if this is a :class:`Some`. """ constructor = type(self) return self and constructor(function(self._value))
(self, function)
23,515
tryme.tryme
Stop
Stop of :py:class:`Success`. A handy alias of :py:class:`Success` to indicate that an operation should **not** be retried
class Stop(Success): """ Stop of :py:class:`Success`. A handy alias of :py:class:`Success` to indicate that an operation should **not** be retried """ pass
(value, message=None, start=None, end=None, count=1)
23,516
tryme.tryme
__bool__
null
def __bool__(self): # pylint: disable = no-self-use return True
(self)
23,536
tryme.tryme
Success
Success of :py:class:`Try`.
class Success(Try): """Success of :py:class:`Try`.""" def __bool__(self): # pylint: disable = no-self-use return True
(value, message=None, start=None, end=None, count=1)
23,557
tryme.tryme
Try
A wrapper for operations that may fail Represents values/computations with two possibilities. :param value: value to contain :param message: (optional) message to output to console if to_console is called. If None, a string representation of the contained value is output. Defaults to ``None`` :param start: (optional) start time for the operation, in seconds since the UNIX epoch `time.time()` is typically used for this value. Defaults to ``None``. :type start: int :param end: (optional) end time for the operation, in seconds since the UNIX epoch ``time.time()`` is typically used for this value. Defaults to ``None``. :type end: int :param count: (optional) number of times the operation has been executed. Defaults to ``1`` :type end: int Usage:: >>> Success(42) Success(42) >>> Success([1, 2, 3]) Success([1, 2, 3]) >>> Failure('Error') Failure('Error') >>> Success(Failure('Error')) Success(Failure('Error')) >>> isinstance(Success(1), Try) True >>> isinstance(Failure(None), Try) True >>> saving = 100 >>> insolvent = Failure('I am insolvent') >>> spend = lambda cost: insolvent if cost > saving else Success(saving - cost) >>> spend(90) Success(10) >>> spend(120) Failure('I am insolvent') Map operation with ``map``, applies function to value only if it is a Success and returns a Success >>> inc = lambda n: n + 1 >>> Success(0) Success(0) >>> Success(0).map(inc) Success(1) >>> Success(0).map(inc).map(inc) Success(2) >>> Failure(0).map(inc) Failure(0) Comparison with ``==``, as long as they are the same type and what's wrapped inside are comparable. >>> Failure(42) == Failure(42) True >>> Success(42) == Success(42) True >>> Failure(42) == Success(42) False A :py:class:`Failure` is less than a :py:class:`Success`, or compare the two by the values inside if thay are of the same type. >>> Failure(42) < Success(42) True >>> Success(0) > Failure(100) True >>> Failure('Error message') > Success(42) False >>> Failure(100) > Failure(42) True >>> Success(-2) < Success(-1) True
class Try(Monad, Ord): """A wrapper for operations that may fail Represents values/computations with two possibilities. :param value: value to contain :param message: (optional) message to output to console if to_console is called. If None, a string representation of the contained value is output. Defaults to ``None`` :param start: (optional) start time for the operation, in seconds since the UNIX epoch `time.time()` is typically used for this value. Defaults to ``None``. :type start: int :param end: (optional) end time for the operation, in seconds since the UNIX epoch ``time.time()`` is typically used for this value. Defaults to ``None``. :type end: int :param count: (optional) number of times the operation has been executed. Defaults to ``1`` :type end: int Usage:: >>> Success(42) Success(42) >>> Success([1, 2, 3]) Success([1, 2, 3]) >>> Failure('Error') Failure('Error') >>> Success(Failure('Error')) Success(Failure('Error')) >>> isinstance(Success(1), Try) True >>> isinstance(Failure(None), Try) True >>> saving = 100 >>> insolvent = Failure('I am insolvent') >>> spend = lambda cost: insolvent if cost > saving else Success(saving - cost) >>> spend(90) Success(10) >>> spend(120) Failure('I am insolvent') Map operation with ``map``, applies function to value only if it is a Success and returns a Success >>> inc = lambda n: n + 1 >>> Success(0) Success(0) >>> Success(0).map(inc) Success(1) >>> Success(0).map(inc).map(inc) Success(2) >>> Failure(0).map(inc) Failure(0) Comparison with ``==``, as long as they are the same type and what's wrapped inside are comparable. >>> Failure(42) == Failure(42) True >>> Success(42) == Success(42) True >>> Failure(42) == Success(42) False A :py:class:`Failure` is less than a :py:class:`Success`, or compare the two by the values inside if thay are of the same type. >>> Failure(42) < Success(42) True >>> Success(0) > Failure(100) True >>> Failure('Error message') > Success(42) False >>> Failure(100) > Failure(42) True >>> Success(-2) < Success(-1) True """ def __init__(self, value, message=None, start=None, end=None, count=1): super(Try, self).__init__(value) self._message = message self._start = start self._end = end self._count = count if (start is None and end is not None) or (end is None and start is not None): raise InvalidTryError( "The start and end argument must either be both None or not None") if type(self) is Try: raise NotImplementedError('Please use Failure or Success instead') def map(self, function): """The map operation of :py:class:`Try` to Success instances Applies function to the value if and only if this is a :py:class:`Success`. """ constructor = type(self) if self.succeeded(): return constructor(function(self._value)) else: return self def map_failure(self, function): """The map operation of :py:class:`Try` to Failure instances Applies function to the value if and only if this is a :py:class:`Success`. """ constructor = type(self) if self.failed(): return constructor(function(self._value)) else: return self def get(self): '''Gets the Success value if this is a Success otherwise throws an exception''' if self.succeeded(): return self._value else: raise NoSuchElementError('You cannot call `get` on a Failure, use `get_failure` instead') def get_failure(self): '''Gets the Failure value if this is a Failure otherwise throws an exception''' if self.failed(): return self._value else: raise NoSuchElementError('You cannot call `get_failure` on a Success, use `get` instead') def get_or_else(self, default): '''Returns the value from this Success or the given default argument if this is a Failure.''' if self.succeeded(): return self._value else: return default def succeeded(self): """Return a Boolean that indicates if the value is an instance of Success >>> Success(True).succeeded() True >>> Failure('fubar').succeeded() False """ return bool(self) def failed(self): """Return a Boolean that indicates if the value is an instance of Failure >>> Failure('shit is fucked up').failed() True >>> Success('it worked!').failed() False """ return not(bool(self)) @property def message(self): ''' Return the message for the Try. If the ``message`` argument was provided to the constructor that value is returned. Otherwise the string representation of the contained value is returened ''' if self._message is not None: return self._message else: return str(self._value) @property def start(self): ''' Start time of the operation in seconds since the UNIX epoch if specified in the constructor or with the ``update`` method, ``None`` otherwise ''' return self._start @property def end(self): ''' End time of the operation in seconds since the UNIX epoch if specified in the constructor or with the ``update`` method, ``None`` otherwise ''' return self._end @property def elapsed(self): ''' End time of the operation in seconds since the UNIX epoch if the start and end arguments were specified in the constructor or with the ``update`` method, ``None`` otherwise ''' if self._end is None and self._start is None: return None return self.end - self.start @property def count(self): '''Number of times the operation has been tried''' return self._count def update(self, message=None, start=None, end=None, count=1): ''' Update the Try with new properties but the same value. Returns a new :class:`Failure` or :py:class:`Success` and does not actually update in place. :param message: (optional) message to output to console if to_console is called. If None, a string representation of the contained value is output. Defaults to ``None`` :param start: (optional) start time for the operation, in seconds since the UNIX epoch `time.time()` is typically used for this value. Defaults to ``None``. :type start: int :param end: (optional) end time for the operation, in seconds since the UNIX epoch ``time.time()`` is typically used for this value. Defaults to ``None``. :type end: int :param count: (optional) number of times the operation has been executed. Defaults to ``1`` :type end: int ''' if (start is None and end is not None) or (end is None and start is not None): raise InvalidTryError( "The start and end argument must either be both None or not None") message = message or self._message # start = start or self._start does not work because start may == 0 and is therefore falsey if start is None: start = self._start if end is None: end = self._end if count is None: count = self._count constructor = type(self) return constructor(self._value, message=message, start=start, end=end, count=count) def to_console(self, nl=True, exit_err=False, exit_status=1): ''' Write a message to the console. By convention, Success messages are written to stdout and Failure messages are written to stderr. The Failure's `cause` is written to stderr while the string repesentation of the Success's _value is written. :param message: the message to print :param err: (optional) if set to true the file defaults to ``stderr`` instead of ``stdout``. :param nl: (optional) if set to `True` (the default) a newline is printed afterwards. :param exit_err: (optional) if set to True, exit the running program with a non-zero exit code :param exit_status: (optional) the numeric exist status to return if exit is True ''' if self.succeeded(): to_console(self.message, nl=nl) else: to_console(self.message, nl=nl, err=True, exit_err=exit_err, exit_status=exit_status) def fail_for_error(self, exit_status=1): ''' If a Failure, write the message to stderr and exit with return code of `exit_status` Does nothing if a Success :param exit_status: (optional) the numeric exist status to return if exit is True :type exit_status: int ''' if self.failed(): to_console(self.message, nl=True, err=True, exit_err=True, exit_status=exit_status) def raise_for_error(self, exception=FailureError): ''' Raise an exception if self is an instance of Failure. If the wrapped value is an instance of Exeception or one of its subclasses, it is raised directly. The the optional argument ``exception`` is specified, that type is raised with the wrapped value as its argument. Otherwise, FailureError is raised. This method has no effect is self is an instance of Success. :param exception: (optional) type of Exception to raise ''' if self.succeeded(): return wrapped_value = self.get_failure() if isinstance(wrapped_value, Exception): raise wrapped_value else: raise exception(wrapped_value) def filter(self, predicate): ''' If a Success, convert this to a Failure if the predicate is not satisfied. Applies predicate to the wrapped value :param predicate: a function that takes the wrapped value as its argument and returns a boolean value :rtype: :class:`Try <Try>` object :return: Try ''' if self.failed(): return self else: wrapped_value = self.get() if predicate(wrapped_value): return self else: return Failure(wrapped_value) def __lt__(self, monad): """Override to handle special case: Success.""" if not isinstance(monad, (Failure, Success)): fmt = "unorderable types: {} and {}'".format raise TypeError(fmt(type(self), type(monad))) if type(self) is type(monad): # same type, either both lefts or rights, compare against value return self._value < monad._value if monad: # self is Failure and monad is Success, left is less than right return True else: return False def __repr__(self): """Customize Show.""" fmt = 'Success({})' if self else 'Failure({})' return fmt.format(repr(self._value))
(value, message=None, start=None, end=None, count=1)
23,577
tryme.tryme
retry
Function that wraps a callable with a retry loop. The callable should only return :class:Failure, :class:Success, or raise an exception. This function can be used as a decorator or directly wrap a function. This method returns a a result object which is an instance of py:class:`Success` or py:class:`Failure`. This function updates the result with the time of the first attempt, the time of the last attempt, and the total count of attempts :param acallable: object that can be called :type acallable: function :param timeout: (optional) maximum period, in seconds, to wait until an individual try succeeds. Defaults to ``300`` seconds. :type timeout: int :param delay: (optional) delay between retries in seconds. Defaults to ``5`` seconds. :type delay: int :param status_callback: (optional) callback to invoke after each retry, is passed the result as an argument. Defaults to ``None``. :type status_callback: function Usage:: >>> deadline = time.time() + 300 >>> dinner_iterator = iter([False, False, True]) >>> def dinner_is_ready(): ... return next(dinner_iterator) >>> breakfast_iterator = iter([False, False, True]) >>> def breakfast_is_ready(): ... return next(breakfast_iterator) >>> @retry ... def wait_for_dinner(): ... if dinner_is_ready(): ... return Success("Ready!") ... else: ... return Failure("not ready yet") >>> result = wait_for_dinner() # doctest: +SKIP >>> result # doctest: +SKIP Success("Ready!") >>> result.elapsed # doctest: +SKIP 8 >>> result.count # doctest: +SKIP 3 >>> @retry ... def wait_for_breakfast(): ... if breakfast_is_ready(): ... return Success("Ready!") ... else: ... return Failure("not ready yet") >>> result = wait_for_breakfast() # doctest: +SKIP Success("Ready!") >>> result.elapsed # doctest: +SKIP 8 >>> result.count # doctest: +SKIP 3 The names py:class:`Success` and py:class:`Failure` do not always map well to operations that need to be retried. The subclasses py:class:`Stop` and py:class:`Again` can be more intuitive.:: >>> breakfast_iterator = iter([False, False, True]) >>> def breakfast_is_ready(): ... return next(breakfast_iterator) >>> @retry ... def wait_for_breakfast(): ... if breakfast_is_ready(): ... return Stop("Ready!") ... else: ... return Again("not ready yet")
def retry(*args, **kwargs): ''' Function that wraps a callable with a retry loop. The callable should only return :class:Failure, :class:Success, or raise an exception. This function can be used as a decorator or directly wrap a function. This method returns a a result object which is an instance of py:class:`Success` or py:class:`Failure`. This function updates the result with the time of the first attempt, the time of the last attempt, and the total count of attempts :param acallable: object that can be called :type acallable: function :param timeout: (optional) maximum period, in seconds, to wait until an individual try succeeds. Defaults to ``300`` seconds. :type timeout: int :param delay: (optional) delay between retries in seconds. Defaults to ``5`` seconds. :type delay: int :param status_callback: (optional) callback to invoke after each retry, is passed the result as an argument. Defaults to ``None``. :type status_callback: function Usage:: >>> deadline = time.time() + 300 >>> dinner_iterator = iter([False, False, True]) >>> def dinner_is_ready(): ... return next(dinner_iterator) >>> breakfast_iterator = iter([False, False, True]) >>> def breakfast_is_ready(): ... return next(breakfast_iterator) >>> @retry ... def wait_for_dinner(): ... if dinner_is_ready(): ... return Success("Ready!") ... else: ... return Failure("not ready yet") >>> result = wait_for_dinner() # doctest: +SKIP >>> result # doctest: +SKIP Success("Ready!") >>> result.elapsed # doctest: +SKIP 8 >>> result.count # doctest: +SKIP 3 >>> @retry ... def wait_for_breakfast(): ... if breakfast_is_ready(): ... return Success("Ready!") ... else: ... return Failure("not ready yet") >>> result = wait_for_breakfast() # doctest: +SKIP Success("Ready!") >>> result.elapsed # doctest: +SKIP 8 >>> result.count # doctest: +SKIP 3 The names py:class:`Success` and py:class:`Failure` do not always map well to operations that need to be retried. The subclasses py:class:`Stop` and py:class:`Again` can be more intuitive.:: >>> breakfast_iterator = iter([False, False, True]) >>> def breakfast_is_ready(): ... return next(breakfast_iterator) >>> @retry ... def wait_for_breakfast(): ... if breakfast_is_ready(): ... return Stop("Ready!") ... else: ... return Again("not ready yet") ''' # if used as a decorator without arguments `@retry`, the first argument is # is the decorated function # If used as a decorator with keyword arguments, say `@retry(timeout=900)` # the args are empty and the decorated function is supplied sometime later # as the argument to the decorator. Confusing! acallable = None if len(args) > 0: acallable = args[0] if acallable is not None: return retry_wrapper(acallable, **kwargs) else: def decorator(func): return retry_wrapper(func, **kwargs) return decorator
(*args, **kwargs)
23,578
tryme.tryme
tick_counter
null
def tick_counter(column_limit=80): counter = Counter() def write_tick(log): sys.stdout.write('.') counter.increment() # if we have reached the max # of columns, write a newline and reset the counter if counter.count == column_limit: sys.stdout.write(os.linesep) counter.reset() sys.stdout.flush() return write_tick
(column_limit=80)
23,579
tryme.tryme
to_console
Write a message to the console :param message: the message to print :param err: (optional) if set to true the file defaults to ``stderr`` instead of ``stdout``. :param nl: (optional) if set to `True` (the default) a newline is printed afterwards. :param exit_err: (optional) if set to True, exit the running program with a non-zero exit code :param exit_status: (optional) the numeric exist status to return if exit is True
def to_console(message=None, nl=True, err=False, exit_err=False, exit_status=1): ''' Write a message to the console :param message: the message to print :param err: (optional) if set to true the file defaults to ``stderr`` instead of ``stdout``. :param nl: (optional) if set to `True` (the default) a newline is printed afterwards. :param exit_err: (optional) if set to True, exit the running program with a non-zero exit code :param exit_status: (optional) the numeric exist status to return if exit is True ''' if err: stream = sys.stderr else: stream = sys.stdout stream.write(message) if nl: stream.write(os.linesep) stream.flush() if exit_err: sys.exit(exit_status)
(message=None, nl=True, err=False, exit_err=False, exit_status=1)
23,580
tryme.tryme
try_out
Executes a callable and wraps a raised exception in a Failure class. If an exception was not raised, a Success is returned. If the keyword argument ``exception`` is not None, only wrap the specified exception. Raise all other exceptions. The stacktrace related to the exception is added to the wrapped exception as the `stracktrace` property :param callable: A callable reference, should return a value other than None :rtype Try: a Success or Failure
def try_out(callable, exception=None): ''' Executes a callable and wraps a raised exception in a Failure class. If an exception was not raised, a Success is returned. If the keyword argument ``exception`` is not None, only wrap the specified exception. Raise all other exceptions. The stacktrace related to the exception is added to the wrapped exception as the `stracktrace` property :param callable: A callable reference, should return a value other than None :rtype Try: a Success or Failure ''' if exception is None: catch_exception = Exception else: catch_exception = exception try: return Success(callable()) except catch_exception as e: stacktrace = _get_stacktrace() e.stacktrace = stacktrace return Failure(e)
(callable, exception=None)
23,582
panphon.featuretable
FeatureTable
null
class FeatureTable(object): TRIE_LEAF_MARKER = None def __init__(self, feature_set='spe+'): bases_fn, weights_fn = feature_sets[feature_set] self.weights = self._read_weights(weights_fn) self.segments, self.seg_dict, self.names = self._read_bases(bases_fn, self.weights) self.seg_regex = self._build_seg_regex() self.seg_trie = self._build_seg_trie() self.longest_seg = max([len(x) for x in self.seg_dict.keys()]) self.xsampa = xsampa.XSampa() @staticmethod def normalize(data): return unicodedata.normalize('NFD', data) def _read_bases(self, fn, weights): fn = pkg_resources.resource_filename(__name__, fn) segments = [] with open(fn, 'rb') as f: reader = csv.reader(f, encoding='utf-8') header = next(reader) names = header[1:] for row in reader: ipa = FeatureTable.normalize(row[0]) vals = [{'-': -1, '0': 0, '+': 1}[x] for x in row[1:]] vec = Segment(names, {n: v for (n, v) in zip(names, vals)}, weights=weights) segments.append((ipa, vec)) seg_dict = dict(segments) return segments, seg_dict, names def _read_weights(self, weights_fn): weights_fn = pkg_resources.resource_filename(__name__, weights_fn) with open(weights_fn, 'rb') as f: reader = csv.reader(f, encoding='utf-8') next(reader) weights = [float(x) for x in next(reader)] return weights def _build_seg_regex(self): segs = sorted(self.seg_dict.keys(), key=lambda x: len(x), reverse=True) return re.compile(r'(?P<all>{})'.format('|'.join(segs))) def _build_seg_trie(self): trie = {} for seg in self.seg_dict.keys(): node = trie for char in seg: if char not in node: node[char] = {} node = node[char] node[self.TRIE_LEAF_MARKER] = None return trie def fts(self, ipa, normalize=True): if normalize: ipa = FeatureTable.normalize(ipa) if ipa in self.seg_dict: return self.seg_dict[ipa] else: return None def longest_one_seg_prefix(self, word, normalize=True): """Return longest Unicode IPA prefix of a word Args: word (unicode): input word as Unicode IPA string normalize (bool): whether the word should be pre-normalized Returns: unicode: longest single-segment prefix of `word` in database """ if normalize: word = FeatureTable.normalize(word) last_found_length = 0 node = self.seg_trie for pos in range(len(word) + 1): if pos == len(word) or word[pos] not in node: return word[:last_found_length] node = node[word[pos]] if self.TRIE_LEAF_MARKER in node: last_found_length = pos + 1 def ipa_segs(self, word, normalize=True): """Returns a list of segments from a word Args: word (unicode): input word as Unicode IPA string normalize (bool): whether to pre-normalize the word Returns: list: list of strings corresponding to segments found in `word` """ if normalize: word = FeatureTable.normalize(word) return self._segs(word, include_invalid=False, normalize=normalize) def validate_word(self, word, normalize=True): """Returns True if `word` consists exhaustively of valid IPA segments Args: word (unicode): input word as Unicode IPA string normalize (bool): whether to pre-normalize the word Returns: bool: True if `word` can be divided exhaustively into IPA segments that exist in the database """ return not self._segs(word, include_valid=False, include_invalid=True, normalize=normalize) def word_fts(self, word, normalize=True): """Return a list of Segment objects corresponding to the segments in word. Args: word (unicode): word consisting of IPA segments normalize (bool): whether to pre-normalize the word Returns: list: list of Segment objects corresponding to word """ return [self.fts(ipa, False) for ipa in self.ipa_segs(word, normalize)] def word_array(self, ft_names, word, normalize=True): """Return a nparray of features namd in ft_name for the segments in word Args: ft_names (list): strings naming subset of features in self.names word (unicode): word to be analyzed normalize (bool): whether to pre-normalize the word Returns: ndarray: segments in rows, features in columns as [-1, 0, 1] """ return numpy.array([s.numeric(ft_names) for s in self.word_fts(word, normalize)]) def bag_of_features(self, word, normalize=True): """Return a vector in which each dimension is the number of times a feature-value pair occurs in the word Args: word (unicode): word consisting of IPA segments normalize (bool): whether to pre-normalize the word Returns: array: array of integers corresponding to a bag of feature-value pair counts """ word_features = self.word_fts(word, normalize) features = [v + f for f in self.names for v in ['+', '0', '-']] bag = collections.OrderedDict() for f in features: bag[f] = 0 vdict = {-1: '-', 0: '0', 1: '+'} for w in word_features: for (f, v) in w.items(): bag[vdict[v] + f] += 1 return numpy.array(list(bag.values())) def seg_known(self, segment, normalize=True): """Return True if `segment` is in segment <=> features database Args: segment (unicode): consonant or vowel normalize (bool): whether to pre-normalize the segment Returns: bool: True, if `segment` is in the database """ if normalize: segment = FeatureTable.normalize(segment) return segment in self.seg_dict def segs_safe(self, word, normalize=True): """Return a list of segments (as strings) from a word Characters that are not valid segments are included in the list as individual characters. Args: word (unicode): word as an IPA string normalize (bool): whether to pre-normalize the word Returns: list: list of Unicode IPA strings corresponding to segments in `word` """ if normalize: word = FeatureTable.normalize(word) return self._segs(word, include_invalid=True, normalize=normalize) def _segs(self, word, *, include_valid=True, include_invalid, normalize): if normalize: word = FeatureTable.normalize(word) segs = [] while word: m = self.longest_one_seg_prefix(word, False) if m: if include_valid: segs.append(m) word = word[len(m):] else: if include_invalid: segs.append(word[0]) word = word[1:] return segs def filter_segs(self, segs, normalize=True): """Given list of strings, return only those which are valid segments Args: segs (list): list of IPA Unicode strings normalize (bool): whether to pre-normalize the segments Return: list: list of IPA Unicode strings identical to `segs` but with invalid segments filtered out """ return list(filter(lambda seg: self.seg_known(seg, normalize), segs)) def filter_string(self, word, normalize=True): """Return a string like the input but containing only legal IPA segments Args: word (unicode): input string to be filtered normalize (bool): whether to pre-normalize the word (and return a normalized string) Returns: unicode: string identical to `word` but with invalid IPA segments absent """ return ''.join(self.ipa_segs(word, normalize)) def fts_intersection(self, segs, normalize=True): """Return a Segment object containing the features shared by all segments Args: segs (list): IPA segments normalize (bool): whether to pre-normalize the segments Returns: Segment: the features shared by all segments in segs """ return reduce(lambda a, b: a & b, [self.fts(s, normalize) for s in self.filter_segs(segs, normalize)]) def fts_match_all(self, fts, inv, normalize=True): """Return `True` if all segments in `inv` matches the features in fts Args: fts (dict): a dictionary of features inv (list): a collection of IPA segments represented as Unicode strings normalize (bool): whether to pre-normalize the segments Returns: bool: `True` if all segments in `inv` matches the features in `fts` """ return all([self.fts(s, normalize) >= fts for s in inv]) def fts_match_any(self, fts, inv, normalize=True): """Return `True` if any segments in `inv` matches the features in fts Args: fts (dict): a dictionary of features inv (list): a collection of IPA segments represented as Unicode strings normalize (bool): whether to pre-normalize the segments Returns: bool: `True` if any segments in `inv` matches the features in `fts` """ return any([self.fts(s, normalize) >= fts for s in inv]) def fts_contrast(self, fs, ft_name, inv, normalize=True): """Return `True` if there is a segment in `inv` that contrasts in feature `ft_name`. Args: fs (dict): feature specifications used to filter `inv`. ft_name (str): name of the feature where contrast must be present. inv (list): collection of segments represented as Unicode strings. normalize (bool): whether to pre-normalize the segments Returns: bool: `True` if two segments in `inv` are identical in features except for feature `ft_name` """ inv_segs = filter(lambda x: x >= fs, map(lambda seg: self.fts(seg, normalize), inv)) for a in inv_segs: for b in inv_segs: if a != b: if a.differing_specs(b) == [ft_name]: return True return False def fts_count(self, fts, inv, normalize=True): """Return the count of segments in an inventory matching a given feature mask. Args: fts (dict): feature mask given as a set of (value, feature) tuples inv (list): inventory of segments (as Unicode IPA strings) normalize (bool): whether to pre-normalize the segments Returns: int: number of segments in `inv` that match feature mask `fts` """ return len(list(filter(lambda s: self.fts(s, normalize) >= fts, inv))) def match_pattern(self, pat, word, normalize=True): """Implements fixed-width pattern matching. Matches just in case pattern is the same length (in segments) as the word and each of the segments in the pattern is a featural subset of the corresponding segment in the word. Matches return the corresponding list of feature sets; failed matches return None. Args: pat (list): pattern consisting of a sequence of feature dicts word (unicode): a Unicode IPA string consisting of zero or more segments normalize (bool): whether to pre-normalize the word Returns: list: corresponding list of feature dicts or, if there is no match, None """ segs = self.word_fts(word, normalize) if len(pat) != len(segs): return None else: if all([s >= p for (s, p) in zip(segs, pat)]): return segs def match_pattern_seq(self, pat, const, normalize=True): """Implements limited pattern matching. Matches just in case pattern is the same length (in segments) as the constituent and each of the segments in the pattern is a featural subset of the corresponding segment in the word. Args: pat (list): pattern consisting of a list of feature dicts, e.g. [{'voi': 1}] const (list): a sequence of Unicode IPA strings consisting of zero or more segments. normalize (bool): whether to pre-normalize the segments Returns: bool: `True` if `const` matches `pat` """ segs = [self.fts(s, normalize) for s in const] if len(pat) != len(segs): return False else: return all([s >= p for (s, p) in zip(segs, pat)]) def all_segs_matching_fts(self, ft_mask): """Return segments matching a feature mask, a dict of features Args: ft_mask (list): feature mask dict, e.g. {'voi': -1, 'cont': 1}. Returns: list: segments matching `ft_mask`, sorted in reverse order by length """ matching_segs = [ipa for (ipa, fts) in self.segments if fts >= ft_mask] return sorted(matching_segs, key=lambda x: len(x), reverse=True) def compile_regex_from_str(self, pat): """Given a string describing features masks for a sequence of segments, return a compiled regex matching the corresponding strings. Args: pat (str): feature masks, each enclosed in square brackets, in which the features are delimited by any standard delimiter. Returns: Pattern: regular expression pattern equivalent to `pat` """ s2n = {'-': -1, '0': 0, '+': 1} seg_res = [] for mat in re.findall(r'\[[^]]+\]+', pat): ft_mask = {k: s2n[v] for (v, k) in re.findall(r'([+-])(\w+)', mat)} segs = self.all_segs_matching_fts(ft_mask) seg_res.append('({})'.format('|'.join(segs))) regexp = ''.join(seg_res) return re.compile(regexp) def segment_to_vector(self, seg, normalize=True): """Given a Unicode IPA segment, return a list of feature specificiations in canonical order. Args: seg (unicode): IPA consonant or vowel normalize: whether to pre-normalize the segment Returns: list: feature specifications ('+'/'-'/'0') in the order from `FeatureTable.names` """ return self.fts(seg, normalize).strings() def word_to_vector_list(self, word, numeric=False, xsampa=False, normalize=True): """Return a list of feature vectors, given a Unicode IPA word. Args: word (unicode): string in IPA (or X-SAMPA, provided `xsampa` is True) numeric (bool): if True, return features as numeric values instead of strings xsampa (bool): whether the word is in X-SAMPA instead of IPA normalize: whether to pre-normalize the word (applies to IPA only) Returns: list: a list of lists of '+'/'-'/'0' or 1/-1/0 """ if xsampa: word = self.xsampa.convert(word) segs = self.word_fts(word, normalize or xsampa) if numeric: tensor = [x.numeric() for x in segs] else: tensor = [x.strings() for x in segs] return tensor
(feature_set='spe+')
23,583
panphon.featuretable
__init__
null
def __init__(self, feature_set='spe+'): bases_fn, weights_fn = feature_sets[feature_set] self.weights = self._read_weights(weights_fn) self.segments, self.seg_dict, self.names = self._read_bases(bases_fn, self.weights) self.seg_regex = self._build_seg_regex() self.seg_trie = self._build_seg_trie() self.longest_seg = max([len(x) for x in self.seg_dict.keys()]) self.xsampa = xsampa.XSampa()
(self, feature_set='spe+')
23,584
panphon.featuretable
_build_seg_regex
null
def _build_seg_regex(self): segs = sorted(self.seg_dict.keys(), key=lambda x: len(x), reverse=True) return re.compile(r'(?P<all>{})'.format('|'.join(segs)))
(self)
23,585
panphon.featuretable
_build_seg_trie
null
def _build_seg_trie(self): trie = {} for seg in self.seg_dict.keys(): node = trie for char in seg: if char not in node: node[char] = {} node = node[char] node[self.TRIE_LEAF_MARKER] = None return trie
(self)
23,586
panphon.featuretable
_read_bases
null
def _read_bases(self, fn, weights): fn = pkg_resources.resource_filename(__name__, fn) segments = [] with open(fn, 'rb') as f: reader = csv.reader(f, encoding='utf-8') header = next(reader) names = header[1:] for row in reader: ipa = FeatureTable.normalize(row[0]) vals = [{'-': -1, '0': 0, '+': 1}[x] for x in row[1:]] vec = Segment(names, {n: v for (n, v) in zip(names, vals)}, weights=weights) segments.append((ipa, vec)) seg_dict = dict(segments) return segments, seg_dict, names
(self, fn, weights)
23,587
panphon.featuretable
_read_weights
null
def _read_weights(self, weights_fn): weights_fn = pkg_resources.resource_filename(__name__, weights_fn) with open(weights_fn, 'rb') as f: reader = csv.reader(f, encoding='utf-8') next(reader) weights = [float(x) for x in next(reader)] return weights
(self, weights_fn)
23,588
panphon.featuretable
_segs
null
def _segs(self, word, *, include_valid=True, include_invalid, normalize): if normalize: word = FeatureTable.normalize(word) segs = [] while word: m = self.longest_one_seg_prefix(word, False) if m: if include_valid: segs.append(m) word = word[len(m):] else: if include_invalid: segs.append(word[0]) word = word[1:] return segs
(self, word, *, include_valid=True, include_invalid, normalize)
23,589
panphon.featuretable
all_segs_matching_fts
Return segments matching a feature mask, a dict of features Args: ft_mask (list): feature mask dict, e.g. {'voi': -1, 'cont': 1}. Returns: list: segments matching `ft_mask`, sorted in reverse order by length
def all_segs_matching_fts(self, ft_mask): """Return segments matching a feature mask, a dict of features Args: ft_mask (list): feature mask dict, e.g. {'voi': -1, 'cont': 1}. Returns: list: segments matching `ft_mask`, sorted in reverse order by length """ matching_segs = [ipa for (ipa, fts) in self.segments if fts >= ft_mask] return sorted(matching_segs, key=lambda x: len(x), reverse=True)
(self, ft_mask)
23,590
panphon.featuretable
bag_of_features
Return a vector in which each dimension is the number of times a feature-value pair occurs in the word Args: word (unicode): word consisting of IPA segments normalize (bool): whether to pre-normalize the word Returns: array: array of integers corresponding to a bag of feature-value pair counts
def bag_of_features(self, word, normalize=True): """Return a vector in which each dimension is the number of times a feature-value pair occurs in the word Args: word (unicode): word consisting of IPA segments normalize (bool): whether to pre-normalize the word Returns: array: array of integers corresponding to a bag of feature-value pair counts """ word_features = self.word_fts(word, normalize) features = [v + f for f in self.names for v in ['+', '0', '-']] bag = collections.OrderedDict() for f in features: bag[f] = 0 vdict = {-1: '-', 0: '0', 1: '+'} for w in word_features: for (f, v) in w.items(): bag[vdict[v] + f] += 1 return numpy.array(list(bag.values()))
(self, word, normalize=True)
23,591
panphon.featuretable
compile_regex_from_str
Given a string describing features masks for a sequence of segments, return a compiled regex matching the corresponding strings. Args: pat (str): feature masks, each enclosed in square brackets, in which the features are delimited by any standard delimiter. Returns: Pattern: regular expression pattern equivalent to `pat`
def compile_regex_from_str(self, pat): """Given a string describing features masks for a sequence of segments, return a compiled regex matching the corresponding strings. Args: pat (str): feature masks, each enclosed in square brackets, in which the features are delimited by any standard delimiter. Returns: Pattern: regular expression pattern equivalent to `pat` """ s2n = {'-': -1, '0': 0, '+': 1} seg_res = [] for mat in re.findall(r'\[[^]]+\]+', pat): ft_mask = {k: s2n[v] for (v, k) in re.findall(r'([+-])(\w+)', mat)} segs = self.all_segs_matching_fts(ft_mask) seg_res.append('({})'.format('|'.join(segs))) regexp = ''.join(seg_res) return re.compile(regexp)
(self, pat)
23,592
panphon.featuretable
filter_segs
Given list of strings, return only those which are valid segments Args: segs (list): list of IPA Unicode strings normalize (bool): whether to pre-normalize the segments Return: list: list of IPA Unicode strings identical to `segs` but with invalid segments filtered out
def filter_segs(self, segs, normalize=True): """Given list of strings, return only those which are valid segments Args: segs (list): list of IPA Unicode strings normalize (bool): whether to pre-normalize the segments Return: list: list of IPA Unicode strings identical to `segs` but with invalid segments filtered out """ return list(filter(lambda seg: self.seg_known(seg, normalize), segs))
(self, segs, normalize=True)
23,593
panphon.featuretable
filter_string
Return a string like the input but containing only legal IPA segments Args: word (unicode): input string to be filtered normalize (bool): whether to pre-normalize the word (and return a normalized string) Returns: unicode: string identical to `word` but with invalid IPA segments absent
def filter_string(self, word, normalize=True): """Return a string like the input but containing only legal IPA segments Args: word (unicode): input string to be filtered normalize (bool): whether to pre-normalize the word (and return a normalized string) Returns: unicode: string identical to `word` but with invalid IPA segments absent """ return ''.join(self.ipa_segs(word, normalize))
(self, word, normalize=True)
23,594
panphon.featuretable
fts
null
def fts(self, ipa, normalize=True): if normalize: ipa = FeatureTable.normalize(ipa) if ipa in self.seg_dict: return self.seg_dict[ipa] else: return None
(self, ipa, normalize=True)
23,595
panphon.featuretable
fts_contrast
Return `True` if there is a segment in `inv` that contrasts in feature `ft_name`. Args: fs (dict): feature specifications used to filter `inv`. ft_name (str): name of the feature where contrast must be present. inv (list): collection of segments represented as Unicode strings. normalize (bool): whether to pre-normalize the segments Returns: bool: `True` if two segments in `inv` are identical in features except for feature `ft_name`
def fts_contrast(self, fs, ft_name, inv, normalize=True): """Return `True` if there is a segment in `inv` that contrasts in feature `ft_name`. Args: fs (dict): feature specifications used to filter `inv`. ft_name (str): name of the feature where contrast must be present. inv (list): collection of segments represented as Unicode strings. normalize (bool): whether to pre-normalize the segments Returns: bool: `True` if two segments in `inv` are identical in features except for feature `ft_name` """ inv_segs = filter(lambda x: x >= fs, map(lambda seg: self.fts(seg, normalize), inv)) for a in inv_segs: for b in inv_segs: if a != b: if a.differing_specs(b) == [ft_name]: return True return False
(self, fs, ft_name, inv, normalize=True)
23,596
panphon.featuretable
fts_count
Return the count of segments in an inventory matching a given feature mask. Args: fts (dict): feature mask given as a set of (value, feature) tuples inv (list): inventory of segments (as Unicode IPA strings) normalize (bool): whether to pre-normalize the segments Returns: int: number of segments in `inv` that match feature mask `fts`
def fts_count(self, fts, inv, normalize=True): """Return the count of segments in an inventory matching a given feature mask. Args: fts (dict): feature mask given as a set of (value, feature) tuples inv (list): inventory of segments (as Unicode IPA strings) normalize (bool): whether to pre-normalize the segments Returns: int: number of segments in `inv` that match feature mask `fts` """ return len(list(filter(lambda s: self.fts(s, normalize) >= fts, inv)))
(self, fts, inv, normalize=True)
23,597
panphon.featuretable
fts_intersection
Return a Segment object containing the features shared by all segments Args: segs (list): IPA segments normalize (bool): whether to pre-normalize the segments Returns: Segment: the features shared by all segments in segs
def fts_intersection(self, segs, normalize=True): """Return a Segment object containing the features shared by all segments Args: segs (list): IPA segments normalize (bool): whether to pre-normalize the segments Returns: Segment: the features shared by all segments in segs """ return reduce(lambda a, b: a & b, [self.fts(s, normalize) for s in self.filter_segs(segs, normalize)])
(self, segs, normalize=True)
23,598
panphon.featuretable
fts_match_all
Return `True` if all segments in `inv` matches the features in fts Args: fts (dict): a dictionary of features inv (list): a collection of IPA segments represented as Unicode strings normalize (bool): whether to pre-normalize the segments Returns: bool: `True` if all segments in `inv` matches the features in `fts`
def fts_match_all(self, fts, inv, normalize=True): """Return `True` if all segments in `inv` matches the features in fts Args: fts (dict): a dictionary of features inv (list): a collection of IPA segments represented as Unicode strings normalize (bool): whether to pre-normalize the segments Returns: bool: `True` if all segments in `inv` matches the features in `fts` """ return all([self.fts(s, normalize) >= fts for s in inv])
(self, fts, inv, normalize=True)
23,599
panphon.featuretable
fts_match_any
Return `True` if any segments in `inv` matches the features in fts Args: fts (dict): a dictionary of features inv (list): a collection of IPA segments represented as Unicode strings normalize (bool): whether to pre-normalize the segments Returns: bool: `True` if any segments in `inv` matches the features in `fts`
def fts_match_any(self, fts, inv, normalize=True): """Return `True` if any segments in `inv` matches the features in fts Args: fts (dict): a dictionary of features inv (list): a collection of IPA segments represented as Unicode strings normalize (bool): whether to pre-normalize the segments Returns: bool: `True` if any segments in `inv` matches the features in `fts` """ return any([self.fts(s, normalize) >= fts for s in inv])
(self, fts, inv, normalize=True)
23,600
panphon.featuretable
ipa_segs
Returns a list of segments from a word Args: word (unicode): input word as Unicode IPA string normalize (bool): whether to pre-normalize the word Returns: list: list of strings corresponding to segments found in `word`
def ipa_segs(self, word, normalize=True): """Returns a list of segments from a word Args: word (unicode): input word as Unicode IPA string normalize (bool): whether to pre-normalize the word Returns: list: list of strings corresponding to segments found in `word` """ if normalize: word = FeatureTable.normalize(word) return self._segs(word, include_invalid=False, normalize=normalize)
(self, word, normalize=True)
23,601
panphon.featuretable
longest_one_seg_prefix
Return longest Unicode IPA prefix of a word Args: word (unicode): input word as Unicode IPA string normalize (bool): whether the word should be pre-normalized Returns: unicode: longest single-segment prefix of `word` in database
def longest_one_seg_prefix(self, word, normalize=True): """Return longest Unicode IPA prefix of a word Args: word (unicode): input word as Unicode IPA string normalize (bool): whether the word should be pre-normalized Returns: unicode: longest single-segment prefix of `word` in database """ if normalize: word = FeatureTable.normalize(word) last_found_length = 0 node = self.seg_trie for pos in range(len(word) + 1): if pos == len(word) or word[pos] not in node: return word[:last_found_length] node = node[word[pos]] if self.TRIE_LEAF_MARKER in node: last_found_length = pos + 1
(self, word, normalize=True)
23,602
panphon.featuretable
match_pattern
Implements fixed-width pattern matching. Matches just in case pattern is the same length (in segments) as the word and each of the segments in the pattern is a featural subset of the corresponding segment in the word. Matches return the corresponding list of feature sets; failed matches return None. Args: pat (list): pattern consisting of a sequence of feature dicts word (unicode): a Unicode IPA string consisting of zero or more segments normalize (bool): whether to pre-normalize the word Returns: list: corresponding list of feature dicts or, if there is no match, None
def match_pattern(self, pat, word, normalize=True): """Implements fixed-width pattern matching. Matches just in case pattern is the same length (in segments) as the word and each of the segments in the pattern is a featural subset of the corresponding segment in the word. Matches return the corresponding list of feature sets; failed matches return None. Args: pat (list): pattern consisting of a sequence of feature dicts word (unicode): a Unicode IPA string consisting of zero or more segments normalize (bool): whether to pre-normalize the word Returns: list: corresponding list of feature dicts or, if there is no match, None """ segs = self.word_fts(word, normalize) if len(pat) != len(segs): return None else: if all([s >= p for (s, p) in zip(segs, pat)]): return segs
(self, pat, word, normalize=True)