repository_name
stringclasses
316 values
func_path_in_repository
stringlengths
6
223
func_name
stringlengths
1
134
language
stringclasses
1 value
func_code_string
stringlengths
57
65.5k
func_documentation_string
stringlengths
1
46.3k
split_name
stringclasses
1 value
func_code_url
stringlengths
91
315
called_functions
listlengths
1
156
enclosing_scope
stringlengths
2
1.48M
ofir123/py-printer
pyprinter/printer.py
get_printer
python
def get_printer(colors: bool = True, width_limit: bool = True, disabled: bool = False) -> Printer: global _printer global _colors # Make sure we can print colors if needed. colors = colors and _colors # If the printer was never defined before, or the settings have changed. if not _printer or (co...
Returns an already initialized instance of the printer. :param colors: If False, no colors will be printed. :param width_limit: If True, printing width will be limited by console width. :param disabled: If True, nothing will be printed.
train
https://github.com/ofir123/py-printer/blob/876c83b32120f3b6a7b06989b2cd9b86915d1a50/pyprinter/printer.py#L328-L343
null
import os import re import subprocess import sys from typing import List, Optional # True if printer is in QT console context. _IN_QT = None class DefaultWriter: """ A default writing stream. """ def __init__(self, output_file=None, disabled: bool = False): """ Initializes the defaul...
ofir123/py-printer
pyprinter/printer.py
_get_windows_console_width
python
def _get_windows_console_width() -> int: from ctypes import byref, windll import pyreadline out = windll.kernel32.GetStdHandle(-11) info = pyreadline.console.CONSOLE_SCREEN_BUFFER_INFO() windll.kernel32.GetConsoleScreenBufferInfo(out, byref(info)) return info.dwSize.X
A small utility function for getting the current console window's width, in Windows. :return: The current console window's width.
train
https://github.com/ofir123/py-printer/blob/876c83b32120f3b6a7b06989b2cd9b86915d1a50/pyprinter/printer.py#L346-L358
null
import os import re import subprocess import sys from typing import List, Optional # True if printer is in QT console context. _IN_QT = None class DefaultWriter: """ A default writing stream. """ def __init__(self, output_file=None, disabled: bool = False): """ Initializes the defaul...
ofir123/py-printer
pyprinter/printer.py
_in_qtconsole
python
def _in_qtconsole() -> bool: try: from IPython import get_ipython try: from ipykernel.zmqshell import ZMQInteractiveShell shell_object = ZMQInteractiveShell except ImportError: from IPython.kernel.zmq import zmqshell shell_object = zmqshell.ZMQ...
A small utility function which determines if we're running in QTConsole's context.
train
https://github.com/ofir123/py-printer/blob/876c83b32120f3b6a7b06989b2cd9b86915d1a50/pyprinter/printer.py#L368-L382
null
import os import re import subprocess import sys from typing import List, Optional # True if printer is in QT console context. _IN_QT = None class DefaultWriter: """ A default writing stream. """ def __init__(self, output_file=None, disabled: bool = False): """ Initializes the defaul...
ofir123/py-printer
pyprinter/printer.py
get_console_width
python
def get_console_width() -> int: # Assigning the value once, as frequent call to this function # causes a major slow down(ImportErrors + isinstance). global _IN_QT if _IN_QT is None: _IN_QT = _in_qtconsole() try: if _IN_QT: # QTConsole determines and handles the max line ...
A small utility function for getting the current console window's width. :return: The current console window's width.
train
https://github.com/ofir123/py-printer/blob/876c83b32120f3b6a7b06989b2cd9b86915d1a50/pyprinter/printer.py#L385-L408
null
import os import re import subprocess import sys from typing import List, Optional # True if printer is in QT console context. _IN_QT = None class DefaultWriter: """ A default writing stream. """ def __init__(self, output_file=None, disabled: bool = False): """ Initializes the defaul...
ofir123/py-printer
pyprinter/printer.py
Printer.group
python
def group(self, indent: int = DEFAULT_INDENT, add_line: bool = True) -> _TextGroup: return _TextGroup(self, indent, add_line)
Returns a context manager which adds an indentation before each line. :param indent: Number of spaces to print. :param add_line: If True, a new line will be printed after the group. :return: A TextGroup context manager.
train
https://github.com/ofir123/py-printer/blob/876c83b32120f3b6a7b06989b2cd9b86915d1a50/pyprinter/printer.py#L112-L120
null
class Printer: """ A user-friendly printer, with auxiliary functions for colors and tabs. """ DEFAULT_INDENT = 4 SEPARATOR = ':' LINE_SEP = '\n' # ANSI Color codes constants. _ANSI_COLOR_PREFIX = '\x1b' _ANSI_REGEXP = re.compile('\x1b\\[(\\d;)?(\\d+)m') _ANSI_COLOR_CODE = f'{_A...
ofir123/py-printer
pyprinter/printer.py
Printer._split_lines
python
def _split_lines(self, original_lines: List[str]) -> List[str]: console_width = get_console_width() # We take indent into account only in the inner group lines. max_line_length = console_width - len(self.LINE_SEP) - self._last_position - \ (self.indents_sum if not self._is_first_line...
Splits the original lines list according to the current console width and group indentations. :param original_lines: The original lines list to split. :return: A list of the new width-formatted lines.
train
https://github.com/ofir123/py-printer/blob/876c83b32120f3b6a7b06989b2cd9b86915d1a50/pyprinter/printer.py#L122-L179
null
class Printer: """ A user-friendly printer, with auxiliary functions for colors and tabs. """ DEFAULT_INDENT = 4 SEPARATOR = ':' LINE_SEP = '\n' # ANSI Color codes constants. _ANSI_COLOR_PREFIX = '\x1b' _ANSI_REGEXP = re.compile('\x1b\\[(\\d;)?(\\d+)m') _ANSI_COLOR_CODE = f'{_A...
ofir123/py-printer
pyprinter/printer.py
Printer.write
python
def write(self, text: str): # Default color is NORMAL. last_color = (self._DARK_CODE, 0) # We use splitlines with keepends in order to keep the line breaks. # Then we split by using the console width. original_lines = text.splitlines(True) lines = self._split_lines(origin...
Prints text to the screen. Supports colors by using the color constants. To use colors, add the color before the text you want to print. :param text: The text to print.
train
https://github.com/ofir123/py-printer/blob/876c83b32120f3b6a7b06989b2cd9b86915d1a50/pyprinter/printer.py#L181-L233
[ "def _split_lines(self, original_lines: List[str]) -> List[str]:\n \"\"\"\n Splits the original lines list according to the current console width and group indentations.\n\n :param original_lines: The original lines list to split.\n :return: A list of the new width-formatted lines.\n \"\"\"\n cons...
class Printer: """ A user-friendly printer, with auxiliary functions for colors and tabs. """ DEFAULT_INDENT = 4 SEPARATOR = ':' LINE_SEP = '\n' # ANSI Color codes constants. _ANSI_COLOR_PREFIX = '\x1b' _ANSI_REGEXP = re.compile('\x1b\\[(\\d;)?(\\d+)m') _ANSI_COLOR_CODE = f'{_A...
ofir123/py-printer
pyprinter/printer.py
Printer.write_aligned
python
def write_aligned(self, key: str, value: str, not_important_keys: Optional[List[str]] = None, is_list: bool = False, align_size: Optional[int] = None, key_color: str = PURPLE, value_color: str = GREEN, dark_key_color: str = DARK_PURPLE, dark_value_color: str = DARK_GREEN, ...
Prints keys and values aligned to align_size. :param key: The name of the property to print. :param value: The value of the property to print. :param not_important_keys: Properties that will be printed in a darker color. :param is_list: True if the value is a list of items. :par...
train
https://github.com/ofir123/py-printer/blob/876c83b32120f3b6a7b06989b2cd9b86915d1a50/pyprinter/printer.py#L244-L281
[ "def get_console_width() -> int:\n \"\"\"\n A small utility function for getting the current console window's width.\n\n :return: The current console window's width.\n \"\"\"\n # Assigning the value once, as frequent call to this function\n # causes a major slow down(ImportErrors + isinstance).\n ...
class Printer: """ A user-friendly printer, with auxiliary functions for colors and tabs. """ DEFAULT_INDENT = 4 SEPARATOR = ':' LINE_SEP = '\n' # ANSI Color codes constants. _ANSI_COLOR_PREFIX = '\x1b' _ANSI_REGEXP = re.compile('\x1b\\[(\\d;)?(\\d+)m') _ANSI_COLOR_CODE = f'{_A...
ofir123/py-printer
pyprinter/printer.py
Printer.write_title
python
def write_title(self, title: str, title_color: str = YELLOW, hyphen_line_color: str = WHITE): self.write_line(title_color + title) self.write_line(hyphen_line_color + '=' * (len(title) + 3))
Prints title with hyphen line underneath it. :param title: The title to print. :param title_color: The title text color (default is yellow). :param hyphen_line_color: The hyphen line color (default is white).
train
https://github.com/ofir123/py-printer/blob/876c83b32120f3b6a7b06989b2cd9b86915d1a50/pyprinter/printer.py#L283-L292
[ "def write_line(self, text: str = ''):\n \"\"\"\n Prints a line of text to the screen.\n Uses the write method.\n\n :param text: The text to print.\n \"\"\"\n self.write(text + self.LINE_SEP)\n" ]
class Printer: """ A user-friendly printer, with auxiliary functions for colors and tabs. """ DEFAULT_INDENT = 4 SEPARATOR = ':' LINE_SEP = '\n' # ANSI Color codes constants. _ANSI_COLOR_PREFIX = '\x1b' _ANSI_REGEXP = re.compile('\x1b\\[(\\d;)?(\\d+)m') _ANSI_COLOR_CODE = f'{_A...
ofir123/py-printer
pyprinter/table.py
Table.pretty_print
python
def pretty_print(self, printer: Optional[Printer] = None, align: int = ALIGN_CENTER, border: bool = False): if printer is None: printer = get_printer() table_string = self._get_pretty_table(indent=printer.indents_sum, align=align, border=border).get_string() if table_string != '': ...
Pretty prints the table. :param printer: The printer to print with. :param align: The alignment of the cells(Table.ALIGN_CENTER/ALIGN_LEFT/ALIGN_RIGHT) :param border: Whether to add a border around the table
train
https://github.com/ofir123/py-printer/blob/876c83b32120f3b6a7b06989b2cd9b86915d1a50/pyprinter/table.py#L44-L67
[ "def get_printer(colors: bool = True, width_limit: bool = True, disabled: bool = False) -> Printer:\n \"\"\"\n Returns an already initialized instance of the printer.\n\n :param colors: If False, no colors will be printed.\n :param width_limit: If True, printing width will be limited by console width.\n...
class Table(object): """ This class represent a table, by using rows. """ COLUMN_SIZE_LIMIT = 40 ALIGN_CENTER = 0 ALIGN_LEFT = 1 ALIGN_RIGHT = 2 _ALIGN_DICTIONARY = {ALIGN_CENTER: 'c', ALIGN_LEFT: 'l', ALIGN_RIGHT: 'r'} def __init__(self, title: str, data: List[Dict[str, str]], col...
ofir123/py-printer
pyprinter/table.py
Table.rows
python
def rows(self) -> List[List[str]]: return [list(d.values()) for d in self.data]
Returns the table rows.
train
https://github.com/ofir123/py-printer/blob/876c83b32120f3b6a7b06989b2cd9b86915d1a50/pyprinter/table.py#L70-L74
null
class Table(object): """ This class represent a table, by using rows. """ COLUMN_SIZE_LIMIT = 40 ALIGN_CENTER = 0 ALIGN_LEFT = 1 ALIGN_RIGHT = 2 _ALIGN_DICTIONARY = {ALIGN_CENTER: 'c', ALIGN_LEFT: 'l', ALIGN_RIGHT: 'r'} def __init__(self, title: str, data: List[Dict[str, str]], col...
ofir123/py-printer
pyprinter/table.py
Table.set_column_size_limit
python
def set_column_size_limit(self, column_name: str, size_limit: int): if self._column_size_map.get(column_name): self._column_size_map[column_name] = size_limit else: raise ValueError(f'There is no column named {column_name}!')
Sets the size limit of a specific column. :param column_name: The name of the column to change. :param size_limit: The max size of the column width.
train
https://github.com/ofir123/py-printer/blob/876c83b32120f3b6a7b06989b2cd9b86915d1a50/pyprinter/table.py#L83-L93
null
class Table(object): """ This class represent a table, by using rows. """ COLUMN_SIZE_LIMIT = 40 ALIGN_CENTER = 0 ALIGN_LEFT = 1 ALIGN_RIGHT = 2 _ALIGN_DICTIONARY = {ALIGN_CENTER: 'c', ALIGN_LEFT: 'l', ALIGN_RIGHT: 'r'} def __init__(self, title: str, data: List[Dict[str, str]], col...
ofir123/py-printer
pyprinter/table.py
Table._get_pretty_table
python
def _get_pretty_table(self, indent: int = 0, align: int = ALIGN_CENTER, border: bool = False) -> PrettyTable: rows = self.rows columns = self.columns # Add the column color. if self._headers_color != Printer.NORMAL and len(rows) > 0 and len(columns) > 0: # We need to copy the...
Returns the table format of the scheme, i.e.: <table name> +----------------+---------------- | <field1> | <field2>... +----------------+---------------- | value1(field1) | value1(field2) | value2(field1) | value2(field2) | value3(field1) | value3(...
train
https://github.com/ofir123/py-printer/blob/876c83b32120f3b6a7b06989b2cd9b86915d1a50/pyprinter/table.py#L95-L129
[ "def get_console_width() -> int:\n \"\"\"\n A small utility function for getting the current console window's width.\n\n :return: The current console window's width.\n \"\"\"\n # Assigning the value once, as frequent call to this function\n # causes a major slow down(ImportErrors + isinstance).\n ...
class Table(object): """ This class represent a table, by using rows. """ COLUMN_SIZE_LIMIT = 40 ALIGN_CENTER = 0 ALIGN_LEFT = 1 ALIGN_RIGHT = 2 _ALIGN_DICTIONARY = {ALIGN_CENTER: 'c', ALIGN_LEFT: 'l', ALIGN_RIGHT: 'r'} def __init__(self, title: str, data: List[Dict[str, str]], col...
ofir123/py-printer
pyprinter/table.py
Table.get_as_html
python
def get_as_html(self) -> str: table_string = self._get_pretty_table().get_html_string() title = ('{:^' + str(len(table_string.splitlines()[0])) + '}').format(self.title) return f'<center><h1>{title}</h1></center>{table_string}'
Returns the table object as an HTML string. :return: HTML representation of the table.
train
https://github.com/ofir123/py-printer/blob/876c83b32120f3b6a7b06989b2cd9b86915d1a50/pyprinter/table.py#L131-L139
[ "def get_html_string(self, **kwargs):\n\n \"\"\"Return string representation of HTML formatted version of table in current state.\n\n Arguments:\n\n start - index of first data row to include in output\n end - index of last data row to include in output PLUS ONE (list slice style)\n fields - names of...
class Table(object): """ This class represent a table, by using rows. """ COLUMN_SIZE_LIMIT = 40 ALIGN_CENTER = 0 ALIGN_LEFT = 1 ALIGN_RIGHT = 2 _ALIGN_DICTIONARY = {ALIGN_CENTER: 'c', ALIGN_LEFT: 'l', ALIGN_RIGHT: 'r'} def __init__(self, title: str, data: List[Dict[str, str]], col...
ofir123/py-printer
pyprinter/table.py
Table.get_as_csv
python
def get_as_csv(self, output_file_path: Optional[str] = None) -> str: output = StringIO() if not output_file_path else open(output_file_path, 'w') try: csv_writer = csv.writer(output) csv_writer.writerow(self.columns) for row in self.rows: csv_writer.w...
Returns the table object as a CSV string. :param output_file_path: The output file to save the CSV to, or None. :return: CSV representation of the table.
train
https://github.com/ofir123/py-printer/blob/876c83b32120f3b6a7b06989b2cd9b86915d1a50/pyprinter/table.py#L141-L158
null
class Table(object): """ This class represent a table, by using rows. """ COLUMN_SIZE_LIMIT = 40 ALIGN_CENTER = 0 ALIGN_LEFT = 1 ALIGN_RIGHT = 2 _ALIGN_DICTIONARY = {ALIGN_CENTER: 'c', ALIGN_LEFT: 'l', ALIGN_RIGHT: 'r'} def __init__(self, title: str, data: List[Dict[str, str]], col...
ofir123/py-printer
pyprinter/file_size.py
FileSize._unit_info
python
def _unit_info(self) -> Tuple[str, int]: abs_bytes = abs(self.size) if abs_bytes < 1024: unit = 'B' unit_divider = 1 elif abs_bytes < (1024 ** 2): unit = 'KB' unit_divider = 1024 elif abs_bytes < (1024 ** 3): unit = 'MB' ...
Returns both the best unit to measure the size, and its power. :return: A tuple containing the unit and its power.
train
https://github.com/ofir123/py-printer/blob/876c83b32120f3b6a7b06989b2cd9b86915d1a50/pyprinter/file_size.py#L54-L77
null
class FileSize: """ Represents a file size measured in bytes. """ MULTIPLIERS = [('kb', 1024), ('mb', 1024 ** 2), ('gb', 1024 ** 3), ('tb', 1024 ** 4), ('b', 1)] SIZE_COLORS = { 'B': Printer.YELLOW, 'KB': Printer.CYAN, 'MB': Printer.GREEN, 'GB': Printer.RED, ...
ofir123/py-printer
pyprinter/file_size.py
FileSize.pretty_print
python
def pretty_print(self, printer: Optional[Printer] = None, min_width: int = 1, min_unit_width: int = 1): unit, unit_divider = self._unit_info() unit_color = self.SIZE_COLORS[unit] # Multiply and then divide by 100 in order to have only two decimal places. size_in_unit = (self.size * 100) ...
Prints the file size (and it's unit), reserving places for longer sizes and units. For example: min_unit_width = 1: 793 B 100 KB min_unit_width = 2: 793 B 100 KB min_unit_width = 3: 793 B ...
train
https://github.com/ofir123/py-printer/blob/876c83b32120f3b6a7b06989b2cd9b86915d1a50/pyprinter/file_size.py#L208-L235
[ "def get_printer(colors: bool = True, width_limit: bool = True, disabled: bool = False) -> Printer:\n \"\"\"\n Returns an already initialized instance of the printer.\n\n :param colors: If False, no colors will be printed.\n :param width_limit: If True, printing width will be limited by console width.\n...
class FileSize: """ Represents a file size measured in bytes. """ MULTIPLIERS = [('kb', 1024), ('mb', 1024 ** 2), ('gb', 1024 ** 3), ('tb', 1024 ** 4), ('b', 1)] SIZE_COLORS = { 'B': Printer.YELLOW, 'KB': Printer.CYAN, 'MB': Printer.GREEN, 'GB': Printer.RED, ...
welchbj/sublemon
sublemon/subprocess.py
SublemonSubprocess.spawn
python
async def spawn(self): self._server._pending_set.add(self) await self._server._sem.acquire() self._subprocess = await asyncio.create_subprocess_shell( self._cmd, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE) self._began_at = datetime....
Spawn the command wrapped in this object as a subprocess.
train
https://github.com/welchbj/sublemon/blob/edbfd1ca2a0ce3de9470dfc88f8db1cadf4b6326/sublemon/subprocess.py#L49-L61
null
class SublemonSubprocess: """Logical encapsulation of a subprocess.""" def __init__(self, server: 'Sublemon', cmd: str) -> None: self._server = server self._cmd = cmd self._scheduled_at = datetime.now() self._uuid = uuid.uuid4() self._began_at: Optional[datetime] = None...
welchbj/sublemon
sublemon/subprocess.py
SublemonSubprocess.wait_done
python
async def wait_done(self) -> int: await self._done_running_evt.wait() if self._exit_code is None: raise SublemonLifetimeError( 'Subprocess exited abnormally with `None` exit code') return self._exit_code
Coroutine to wait for subprocess run completion. Returns: The exit code of the subprocess.
train
https://github.com/welchbj/sublemon/blob/edbfd1ca2a0ce3de9470dfc88f8db1cadf4b6326/sublemon/subprocess.py#L67-L78
null
class SublemonSubprocess: """Logical encapsulation of a subprocess.""" def __init__(self, server: 'Sublemon', cmd: str) -> None: self._server = server self._cmd = cmd self._scheduled_at = datetime.now() self._uuid = uuid.uuid4() self._began_at: Optional[datetime] = None...
welchbj/sublemon
sublemon/subprocess.py
SublemonSubprocess._poll
python
def _poll(self) -> None: if self._subprocess is None: raise SublemonLifetimeError( 'Attempted to poll a non-active subprocess') elif self._subprocess.returncode is not None: self._exit_code = self._subprocess.returncode self._done_running_evt.set() ...
Check the status of the wrapped running subprocess. Note: This should only be called on currently-running tasks.
train
https://github.com/welchbj/sublemon/blob/edbfd1ca2a0ce3de9470dfc88f8db1cadf4b6326/sublemon/subprocess.py#L80-L94
null
class SublemonSubprocess: """Logical encapsulation of a subprocess.""" def __init__(self, server: 'Sublemon', cmd: str) -> None: self._server = server self._cmd = cmd self._scheduled_at = datetime.now() self._uuid = uuid.uuid4() self._began_at: Optional[datetime] = None...
welchbj/sublemon
sublemon/subprocess.py
SublemonSubprocess.stdout
python
async def stdout(self) -> AsyncGenerator[str, None]: await self.wait_running() async for line in self._subprocess.stdout: # type: ignore yield line
Asynchronous generator for lines from subprocess stdout.
train
https://github.com/welchbj/sublemon/blob/edbfd1ca2a0ce3de9470dfc88f8db1cadf4b6326/sublemon/subprocess.py#L97-L101
[ "async def wait_running(self) -> None:\n \"\"\"Coroutine to wait for this subprocess to begin execution.\"\"\"\n await self._began_running_evt.wait()\n" ]
class SublemonSubprocess: """Logical encapsulation of a subprocess.""" def __init__(self, server: 'Sublemon', cmd: str) -> None: self._server = server self._cmd = cmd self._scheduled_at = datetime.now() self._uuid = uuid.uuid4() self._began_at: Optional[datetime] = None...
welchbj/sublemon
sublemon/subprocess.py
SublemonSubprocess.stderr
python
async def stderr(self) -> AsyncGenerator[str, None]: await self.wait_running() async for line in self._subprocess.stderr: # type: ignore yield line
Asynchronous generator for lines from subprocess stderr.
train
https://github.com/welchbj/sublemon/blob/edbfd1ca2a0ce3de9470dfc88f8db1cadf4b6326/sublemon/subprocess.py#L104-L108
[ "async def wait_running(self) -> None:\n \"\"\"Coroutine to wait for this subprocess to begin execution.\"\"\"\n await self._began_running_evt.wait()\n" ]
class SublemonSubprocess: """Logical encapsulation of a subprocess.""" def __init__(self, server: 'Sublemon', cmd: str) -> None: self._server = server self._cmd = cmd self._scheduled_at = datetime.now() self._uuid = uuid.uuid4() self._began_at: Optional[datetime] = None...
welchbj/sublemon
demos/from_the_readme.py
main
python
async def main(): for c in (1, 2, 4,): async with Sublemon(max_concurrency=c) as s: start = time.perf_counter() await asyncio.gather(one(s), two(s)) end = time.perf_counter() print('Limiting to', c, 'concurrent subprocess(es) took', end-start...
`sublemon` library example!
train
https://github.com/welchbj/sublemon/blob/edbfd1ca2a0ce3de9470dfc88f8db1cadf4b6326/demos/from_the_readme.py#L12-L20
[ "async def one(s: Sublemon):\n \"\"\"Spin up some subprocesses, sleep, and echo a message for this coro.\"\"\"\n shell_cmds = [\n 'sleep 1 && echo subprocess 1 in coroutine one',\n 'sleep 1 && echo subprocess 2 in coroutine one']\n async for line in s.iter_lines(*shell_cmds):\n print(l...
"""Demo from the README.""" import asyncio import time from sublemon import ( amerge, crossplat_loop_run, Sublemon) async def one(s: Sublemon): """Spin up some subprocesses, sleep, and echo a message for this coro.""" shell_cmds = [ 'sleep 1 && echo subprocess 1 in coroutine one', ...
welchbj/sublemon
demos/from_the_readme.py
one
python
async def one(s: Sublemon): shell_cmds = [ 'sleep 1 && echo subprocess 1 in coroutine one', 'sleep 1 && echo subprocess 2 in coroutine one'] async for line in s.iter_lines(*shell_cmds): print(line)
Spin up some subprocesses, sleep, and echo a message for this coro.
train
https://github.com/welchbj/sublemon/blob/edbfd1ca2a0ce3de9470dfc88f8db1cadf4b6326/demos/from_the_readme.py#L23-L29
null
"""Demo from the README.""" import asyncio import time from sublemon import ( amerge, crossplat_loop_run, Sublemon) async def main(): """`sublemon` library example!""" for c in (1, 2, 4,): async with Sublemon(max_concurrency=c) as s: start = time.perf_counter() aw...
welchbj/sublemon
demos/from_the_readme.py
two
python
async def two(s: Sublemon): subprocess_1, subprocess_2 = s.spawn( 'sleep 1 && echo subprocess 1 in coroutine two', 'sleep 1 && echo subprocess 2 in coroutine two') async for line in amerge(subprocess_1.stdout, subprocess_2.stdout): print(line.decode('utf-8'), end='')
Spin up some subprocesses, sleep, and echo a message for this coro.
train
https://github.com/welchbj/sublemon/blob/edbfd1ca2a0ce3de9470dfc88f8db1cadf4b6326/demos/from_the_readme.py#L32-L38
[ "async def amerge(*agens) -> AsyncGenerator[Any, None]:\n \"\"\"Thin wrapper around aiostream.stream.merge.\"\"\"\n xs = stream.merge(*agens)\n async with xs.stream() as streamer:\n async for x in streamer:\n yield x\n" ]
"""Demo from the README.""" import asyncio import time from sublemon import ( amerge, crossplat_loop_run, Sublemon) async def main(): """`sublemon` library example!""" for c in (1, 2, 4,): async with Sublemon(max_concurrency=c) as s: start = time.perf_counter() aw...
welchbj/sublemon
sublemon/utils.py
amerge
python
async def amerge(*agens) -> AsyncGenerator[Any, None]: xs = stream.merge(*agens) async with xs.stream() as streamer: async for x in streamer: yield x
Thin wrapper around aiostream.stream.merge.
train
https://github.com/welchbj/sublemon/blob/edbfd1ca2a0ce3de9470dfc88f8db1cadf4b6326/sublemon/utils.py#L14-L19
null
"""Asynchronous / misc utilities.""" import asyncio import contextlib import signal import sys from aiostream import stream from typing import ( Any, AsyncGenerator) def crossplat_loop_run(coro) -> Any: """Cross-platform method for running a subprocess-spawning coroutine.""" if sys.platform == 'win...
welchbj/sublemon
sublemon/utils.py
crossplat_loop_run
python
def crossplat_loop_run(coro) -> Any: if sys.platform == 'win32': signal.signal(signal.SIGINT, signal.SIG_DFL) loop = asyncio.ProactorEventLoop() else: loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) with contextlib.closing(loop): return loop.run_until_comple...
Cross-platform method for running a subprocess-spawning coroutine.
train
https://github.com/welchbj/sublemon/blob/edbfd1ca2a0ce3de9470dfc88f8db1cadf4b6326/sublemon/utils.py#L22-L32
null
"""Asynchronous / misc utilities.""" import asyncio import contextlib import signal import sys from aiostream import stream from typing import ( Any, AsyncGenerator) async def amerge(*agens) -> AsyncGenerator[Any, None]: """Thin wrapper around aiostream.stream.merge.""" xs = stream.merge(*agens) ...
welchbj/sublemon
sublemon/runtime.py
Sublemon.start
python
async def start(self) -> None: if self._is_running: raise SublemonRuntimeError( 'Attempted to start an already-running `Sublemon` instance') self._poll_task = asyncio.ensure_future(self._poll()) self._is_running = True
Coroutine to run this server.
train
https://github.com/welchbj/sublemon/blob/edbfd1ca2a0ce3de9470dfc88f8db1cadf4b6326/sublemon/runtime.py#L52-L59
[ "async def _poll(self) -> None:\n \"\"\"Coroutine to poll status of running subprocesses.\"\"\"\n while True:\n await asyncio.sleep(self._poll_delta)\n for subproc in list(self._running_set):\n subproc._poll()\n" ]
class Sublemon: """The runtime for spawning subprocesses.""" def __init__(self, max_concurrency: int=_DEFAULT_MC, poll_delta: float=_DEFAULT_PD) -> None: self._max_concurrency = max_concurrency self._poll_delta = poll_delta self._sem = asyncio.BoundedSemaphore(max_conc...
welchbj/sublemon
sublemon/runtime.py
Sublemon.stop
python
async def stop(self) -> None: if not self._is_running: raise SublemonRuntimeError( 'Attempted to stop an already-stopped `Sublemon` instance') await self.block() self._poll_task.cancel() self._is_running = False with suppress(asyncio.CancelledError): ...
Coroutine to stop execution of this server.
train
https://github.com/welchbj/sublemon/blob/edbfd1ca2a0ce3de9470dfc88f8db1cadf4b6326/sublemon/runtime.py#L61-L71
[ "async def block(self) -> None:\n \"\"\"Block until all running and pending subprocesses have finished.\"\"\"\n await asyncio.gather(\n *itertools.chain(\n (sp.wait_done() for sp in self._running_set),\n (sp.wait_done() for sp in self._pending_set)))\n" ]
class Sublemon: """The runtime for spawning subprocesses.""" def __init__(self, max_concurrency: int=_DEFAULT_MC, poll_delta: float=_DEFAULT_PD) -> None: self._max_concurrency = max_concurrency self._poll_delta = poll_delta self._sem = asyncio.BoundedSemaphore(max_conc...
welchbj/sublemon
sublemon/runtime.py
Sublemon._poll
python
async def _poll(self) -> None: while True: await asyncio.sleep(self._poll_delta) for subproc in list(self._running_set): subproc._poll()
Coroutine to poll status of running subprocesses.
train
https://github.com/welchbj/sublemon/blob/edbfd1ca2a0ce3de9470dfc88f8db1cadf4b6326/sublemon/runtime.py#L73-L78
null
class Sublemon: """The runtime for spawning subprocesses.""" def __init__(self, max_concurrency: int=_DEFAULT_MC, poll_delta: float=_DEFAULT_PD) -> None: self._max_concurrency = max_concurrency self._poll_delta = poll_delta self._sem = asyncio.BoundedSemaphore(max_conc...
welchbj/sublemon
sublemon/runtime.py
Sublemon.iter_lines
python
async def iter_lines( self, *cmds: str, stream: str='both') -> AsyncGenerator[str, None]: sps = self.spawn(*cmds) if stream == 'both': agen = amerge( amerge(*[sp.stdout for sp in sps]), amerge(*[sp.stderr for sp in sps])) ...
Coroutine to spawn commands and yield text lines from stdout.
train
https://github.com/welchbj/sublemon/blob/edbfd1ca2a0ce3de9470dfc88f8db1cadf4b6326/sublemon/runtime.py#L80-L98
[ "async def amerge(*agens) -> AsyncGenerator[Any, None]:\n \"\"\"Thin wrapper around aiostream.stream.merge.\"\"\"\n xs = stream.merge(*agens)\n async with xs.stream() as streamer:\n async for x in streamer:\n yield x\n", "def spawn(self, *cmds: str) -> List[SublemonSubprocess]:\n \"\...
class Sublemon: """The runtime for spawning subprocesses.""" def __init__(self, max_concurrency: int=_DEFAULT_MC, poll_delta: float=_DEFAULT_PD) -> None: self._max_concurrency = max_concurrency self._poll_delta = poll_delta self._sem = asyncio.BoundedSemaphore(max_conc...
welchbj/sublemon
sublemon/runtime.py
Sublemon.gather
python
async def gather(self, *cmds: str) -> Tuple[int]: subprocs = self.spawn(*cmds) subproc_wait_coros = [subproc.wait_done() for subproc in subprocs] return await asyncio.gather(*subproc_wait_coros)
Coroutine to spawn subprocesses and block until completion. Note: The same `max_concurrency` restriction that applies to `spawn` also applies here. Returns: The exit codes of the spawned subprocesses, in the order they were passed.
train
https://github.com/welchbj/sublemon/blob/edbfd1ca2a0ce3de9470dfc88f8db1cadf4b6326/sublemon/runtime.py#L100-L114
[ "def spawn(self, *cmds: str) -> List[SublemonSubprocess]:\n \"\"\"Coroutine to spawn shell commands.\n\n If `max_concurrency` is reached during the attempt to spawn the\n specified subprocesses, excess subprocesses will block while attempting\n to acquire this server's semaphore.\n\n \"\"\"\n if n...
class Sublemon: """The runtime for spawning subprocesses.""" def __init__(self, max_concurrency: int=_DEFAULT_MC, poll_delta: float=_DEFAULT_PD) -> None: self._max_concurrency = max_concurrency self._poll_delta = poll_delta self._sem = asyncio.BoundedSemaphore(max_conc...
welchbj/sublemon
sublemon/runtime.py
Sublemon.block
python
async def block(self) -> None: await asyncio.gather( *itertools.chain( (sp.wait_done() for sp in self._running_set), (sp.wait_done() for sp in self._pending_set)))
Block until all running and pending subprocesses have finished.
train
https://github.com/welchbj/sublemon/blob/edbfd1ca2a0ce3de9470dfc88f8db1cadf4b6326/sublemon/runtime.py#L116-L121
null
class Sublemon: """The runtime for spawning subprocesses.""" def __init__(self, max_concurrency: int=_DEFAULT_MC, poll_delta: float=_DEFAULT_PD) -> None: self._max_concurrency = max_concurrency self._poll_delta = poll_delta self._sem = asyncio.BoundedSemaphore(max_conc...
welchbj/sublemon
sublemon/runtime.py
Sublemon.spawn
python
def spawn(self, *cmds: str) -> List[SublemonSubprocess]: if not self._is_running: raise SublemonRuntimeError( 'Attempted to spawn subprocesses from a non-started server') subprocs = [SublemonSubprocess(self, cmd) for cmd in cmds] for sp in subprocs: async...
Coroutine to spawn shell commands. If `max_concurrency` is reached during the attempt to spawn the specified subprocesses, excess subprocesses will block while attempting to acquire this server's semaphore.
train
https://github.com/welchbj/sublemon/blob/edbfd1ca2a0ce3de9470dfc88f8db1cadf4b6326/sublemon/runtime.py#L123-L138
null
class Sublemon: """The runtime for spawning subprocesses.""" def __init__(self, max_concurrency: int=_DEFAULT_MC, poll_delta: float=_DEFAULT_PD) -> None: self._max_concurrency = max_concurrency self._poll_delta = poll_delta self._sem = asyncio.BoundedSemaphore(max_conc...
ilgarm/pyzimbra
pyzimbra/auth.py
Authenticator.authenticate
python
def authenticate(self, transport, account_name, password): if not isinstance(transport, ZimbraClientTransport): raise ZimbraClientException('Invalid transport') if util.empty(account_name): raise AuthException('Empty account name')
Authenticates account, if no password given tries to pre-authenticate. @param transport: transport to use for method calls @param account_name: account name @param password: account password @return: AuthToken if authentication succeeded @raise AuthException: if authentication fa...
train
https://github.com/ilgarm/pyzimbra/blob/c397bc7497554d260ec6fd1a80405aed872a70cc/pyzimbra/auth.py#L100-L113
[ "def empty(val):\n \"\"\"\n Checks if value is empty.\n All unknown data types considered as empty values.\n @return: bool\n \"\"\"\n if val == None:\n return True\n\n if isinstance(val,str) and len(val) > 0:\n return False\n\n return True\n" ]
class Authenticator(object): """ Authenticator provides methods to authenticate using username/password as a user or administrator or using domain key. """ __metaclass__ = abc.ABCMeta # --------------------------------------------------------------- properties domains = property(lambda sel...
ilgarm/pyzimbra
pyzimbra/zclient.py
ZimbraSoapClient.invoke
python
def invoke(self, ns, request_name, params={}, simplify=False): if self.auth_token == None: raise AuthException('Unable to invoke zimbra method') if util.empty(request_name): raise ZimbraClientException('Invalid request') return self.transport.invoke(ns, ...
Invokes zimbra method using established authentication session. @param req: zimbra request @parm params: request params @param simplify: True to return python object, False to return xml struct @return: zimbra response @raise AuthException: if authentication fails @raise ...
train
https://github.com/ilgarm/pyzimbra/blob/c397bc7497554d260ec6fd1a80405aed872a70cc/pyzimbra/zclient.py#L67-L87
[ "def empty(val):\n \"\"\"\n Checks if value is empty.\n All unknown data types considered as empty values.\n @return: bool\n \"\"\"\n if val == None:\n return True\n\n if isinstance(val,str) and len(val) > 0:\n return False\n\n return True\n", "def invoke(self, ns, request_na...
class ZimbraSoapClient(object): """ Zimbra client main class. """ __metaclass__ = abc.ABCMeta # --------------------------------------------------------------- properties transport = property(lambda self: self._transport, lambda self, v: setattr(self, '_transport', v)) ...
ilgarm/pyzimbra
pyzimbra/z/admin.py
ZimbraAdmin.get_info
python
def get_info(self, account, params={}): res = self.invoke(zconstant.NS_ZIMBRA_ADMIN_URL, sconstant.GetInfoRequest, params) return res
Gets account info. @param account: account to get info for @param params: parameters to retrieve @return: AccountInfo
train
https://github.com/ilgarm/pyzimbra/blob/c397bc7497554d260ec6fd1a80405aed872a70cc/pyzimbra/z/admin.py#L66-L77
[ "def invoke(self, ns, request_name, params={}, simplify=False):\n \"\"\"\n Invokes zimbra method using established authentication session.\n @param req: zimbra request\n @parm params: request params\n @param simplify: True to return python object, False to return xml struct\n @return: zimbra respo...
class ZimbraAdmin(ZimbraSoapClient): """ Zimbra non-privileged client. """ # ------------------------------------------------------------------ unbound def authenticate(self, account_name, password): """ Authenticates zimbra account. @param account_name: account email address...
ilgarm/pyzimbra
pyzimbra/util.py
empty
python
def empty(val): if val == None: return True if isinstance(val,str) and len(val) > 0: return False return True
Checks if value is empty. All unknown data types considered as empty values. @return: bool
train
https://github.com/ilgarm/pyzimbra/blob/c397bc7497554d260ec6fd1a80405aed872a70cc/pyzimbra/util.py#L30-L42
null
# -*- coding: utf-8 -*- """ ################################################################################ # Copyright (c) 2010, Ilgar Mashayev # # E-mail: pyzimbra@lab.az # Website: http://github.com/ilgarm/pyzimbra ################################################################################ # This file is part...
ilgarm/pyzimbra
pyzimbra/soap_soappy.py
parseSOAP
python
def parseSOAP(xml_str, rules = None): try: from cStringIO import StringIO except ImportError: from StringIO import StringIO parser = xml.sax.make_parser() t = ZimbraSOAPParser(rules = rules) parser.setContentHandler(t) e = xml.sax.handler.ErrorHandler() parser.setErrorHandle...
Replacement for SOAPpy._parseSOAP method to spoof SOAPParser.
train
https://github.com/ilgarm/pyzimbra/blob/c397bc7497554d260ec6fd1a80405aed872a70cc/pyzimbra/soap_soappy.py#L54-L81
null
# -*- coding: utf-8 -*- """ ################################################################################ # Copyright (c) 2010, Ilgar Mashayev # # E-mail: pyzimbra@lab.az # Website: http://github.com/ilgarm/pyzimbra ################################################################################ # This file is part...
ilgarm/pyzimbra
pyzimbra/soap_soappy.py
SoapHttpTransport.build_opener
python
def build_opener(self): http_handler = urllib2.HTTPHandler() # debuglevel=self.transport.debug if util.empty(self.transport.proxy_url): return urllib2.build_opener(http_handler) proxy_handler = urllib2.ProxyHandler( {self.transport.proxy_url[:4]: self.transport.proxy_ur...
Builds url opener, initializing proxy. @return: OpenerDirector
train
https://github.com/ilgarm/pyzimbra/blob/c397bc7497554d260ec6fd1a80405aed872a70cc/pyzimbra/soap_soappy.py#L138-L151
[ "def empty(val):\n \"\"\"\n Checks if value is empty.\n All unknown data types considered as empty values.\n @return: bool\n \"\"\"\n if val == None:\n return True\n\n if isinstance(val,str) and len(val) > 0:\n return False\n\n return True\n" ]
class SoapHttpTransport(SOAPpy.Client.HTTPTransport): """ Http transport using urllib2, with support for proxy authentication and more. """ # --------------------------------------------------------------- properties transport = property(lambda self: self._transport, lambda ...
ilgarm/pyzimbra
pyzimbra/soap_soappy.py
SoapHttpTransport.init_soap_exception
python
def init_soap_exception(self, exc): if not isinstance(exc, urllib2.HTTPError): return SoapException(unicode(exc), exc) if isinstance(exc, urllib2.HTTPError): try: data = exc.read() self.log.debug(data) t = SOAPpy.Parser.parseSOAP(...
Initializes exception based on soap error response. @param exc: URLError @return: SoapException
train
https://github.com/ilgarm/pyzimbra/blob/c397bc7497554d260ec6fd1a80405aed872a70cc/pyzimbra/soap_soappy.py#L154-L177
null
class SoapHttpTransport(SOAPpy.Client.HTTPTransport): """ Http transport using urllib2, with support for proxy authentication and more. """ # --------------------------------------------------------------- properties transport = property(lambda self: self._transport, lambda ...
ilgarm/pyzimbra
pyzimbra/soap_auth.py
SoapAuthenticator.authenticate_admin
python
def authenticate_admin(self, transport, account_name, password): Authenticator.authenticate_admin(self, transport, account_name, password) auth_token = AuthToken() auth_token.account_name = account_name params = {sconstant.E_NAME: account_name, sconstant.E_PASSWORD: p...
Authenticates administrator using username and password.
train
https://github.com/ilgarm/pyzimbra/blob/c397bc7497554d260ec6fd1a80405aed872a70cc/pyzimbra/soap_auth.py#L50-L77
[ "def authenticate_admin(self, transport, account_name, password):\n \"\"\"\n Authenticates administrator using username and password.\n @param transport: transport to use for method calls\n @param account_name: account name\n @param password: account password\n @return: AuthToken if authentication...
class SoapAuthenticator(Authenticator): """ Soap authenticator. """ # --------------------------------------------------------------- properties # -------------------------------------------------------------------- bound def __init__(self): Authenticator.__init__(self) self.log...
ilgarm/pyzimbra
pyzimbra/soap_auth.py
SoapAuthenticator.authenticate
python
def authenticate(self, transport, account_name, password=None): Authenticator.authenticate(self, transport, account_name, password) if password == None: return self.pre_auth(transport, account_name) else: return self.auth(transport, account_name, password)
Authenticates account using soap method.
train
https://github.com/ilgarm/pyzimbra/blob/c397bc7497554d260ec6fd1a80405aed872a70cc/pyzimbra/soap_auth.py#L80-L89
[ "def auth(self, transport, account_name, password):\n if not account_name == self.account_name:\n raise AuthException('Invalid username')\n\n if not password == self.password:\n raise AuthException('Invalid password')\n\n token = AuthToken()\n token.account_name = self.account_name\n to...
class SoapAuthenticator(Authenticator): """ Soap authenticator. """ # --------------------------------------------------------------- properties # -------------------------------------------------------------------- bound def __init__(self): Authenticator.__init__(self) self.log...
ilgarm/pyzimbra
pyzimbra/soap_auth.py
SoapAuthenticator.auth
python
def auth(self, transport, account_name, password): auth_token = AuthToken() auth_token.account_name = account_name attrs = {sconstant.A_BY: sconstant.V_NAME} account = SOAPpy.Types.stringType(data=account_name, attrs=attrs) params = {sconstant.E_ACCOUNT: account, ...
Authenticates using username and password.
train
https://github.com/ilgarm/pyzimbra/blob/c397bc7497554d260ec6fd1a80405aed872a70cc/pyzimbra/soap_auth.py#L92-L122
null
class SoapAuthenticator(Authenticator): """ Soap authenticator. """ # --------------------------------------------------------------- properties # -------------------------------------------------------------------- bound def __init__(self): Authenticator.__init__(self) self.log...
ilgarm/pyzimbra
pyzimbra/soap_auth.py
SoapAuthenticator.pre_auth
python
def pre_auth(self, transport, account_name): auth_token = AuthToken() auth_token.account_name = account_name domain = util.get_domain(account_name) if domain == None: raise AuthException('Invalid auth token account') if domain in self.domains: domain_key...
Authenticates using username and domain key.
train
https://github.com/ilgarm/pyzimbra/blob/c397bc7497554d260ec6fd1a80405aed872a70cc/pyzimbra/soap_auth.py#L125-L180
[ "def get_domain(email):\n \"\"\"\n Returns domain part of the email or None if invalid email format.\n @param email: email\n @return: str\n \"\"\"\n match = re.search('^[^@]*?@([^@]+?)$', email)\n\n if match == None:\n return None\n\n return match.group(1)\n" ]
class SoapAuthenticator(Authenticator): """ Soap authenticator. """ # --------------------------------------------------------------- properties # -------------------------------------------------------------------- bound def __init__(self): Authenticator.__init__(self) self.log...
ilgarm/pyzimbra
pyzimbra/base.py
ZimbraClientException.print_trace
python
def print_trace(self): traceback.print_exc() for tb in self.tracebacks: print tb, print ''
Prints stack trace for current exceptions chain.
train
https://github.com/ilgarm/pyzimbra/blob/c397bc7497554d260ec6fd1a80405aed872a70cc/pyzimbra/base.py#L82-L89
null
class ZimbraClientException(Exception): """ Zimbra client exception. """ # --------------------------------------------------------------- properties message = property(lambda self: self._message, lambda self, v: setattr(self, '_message', v)) tracebacks = property(lambda ...
ilgarm/pyzimbra
pyzimbra/z/client.py
ZimbraClient.authenticate
python
def authenticate(self, account_name, password): self.auth_token = self.authenticator.authenticate(self.transport, account_name, password)
Authenticates zimbra account. @param account_name: account email address @param password: account password @raise AuthException: if authentication fails @raise SoapException: if soap communication fails
train
https://github.com/ilgarm/pyzimbra/blob/c397bc7497554d260ec6fd1a80405aed872a70cc/pyzimbra/z/client.py#L40-L50
[ "def authenticate(self, transport, account_name, password=None):\n \"\"\"\n Authenticates account using soap method.\n \"\"\"\n Authenticator.authenticate(self, transport, account_name, password)\n\n if password == None:\n return self.pre_auth(transport, account_name)\n else:\n retur...
class ZimbraClient(ZimbraSoapClient): """ Zimbra non-privileged client. """ # ------------------------------------------------------------------ unbound def change_password(self, current_password, new_password): """ Changes account password. @param current_password: curren...
ilgarm/pyzimbra
pyzimbra/z/client.py
ZimbraClient.change_password
python
def change_password(self, current_password, new_password): attrs = {sconstant.A_BY: sconstant.V_NAME} account = SOAPpy.Types.stringType(data=self.auth_token.account_name, attrs=attrs) params = {sconstant.E_ACCOUNT: account, sconstant.E...
Changes account password. @param current_password: current password @param new_password: new password
train
https://github.com/ilgarm/pyzimbra/blob/c397bc7497554d260ec6fd1a80405aed872a70cc/pyzimbra/z/client.py#L53-L69
[ "def invoke(self, ns, request_name, params={}, simplify=False):\n \"\"\"\n Invokes zimbra method using established authentication session.\n @param req: zimbra request\n @parm params: request params\n @param simplify: True to return python object, False to return xml struct\n @return: zimbra respo...
class ZimbraClient(ZimbraSoapClient): """ Zimbra non-privileged client. """ # ------------------------------------------------------------------ unbound def authenticate(self, account_name, password): """ Authenticates zimbra account. @param account_name: account email addres...
ilgarm/pyzimbra
pyzimbra/z/client.py
ZimbraClient.get_account_info
python
def get_account_info(self): attrs = {sconstant.A_BY: sconstant.V_NAME} account = SOAPpy.Types.stringType(data=self.auth_token.account_name, attrs=attrs) params = {sconstant.E_ACCOUNT: account} res = self.invoke(zconstant.NS_ZIMBRA_ACC_URL, ...
Gets account info. @return: AccountInfo
train
https://github.com/ilgarm/pyzimbra/blob/c397bc7497554d260ec6fd1a80405aed872a70cc/pyzimbra/z/client.py#L72-L90
[ "def invoke(self, ns, request_name, params={}, simplify=False):\n \"\"\"\n Invokes zimbra method using established authentication session.\n @param req: zimbra request\n @parm params: request params\n @param simplify: True to return python object, False to return xml struct\n @return: zimbra respo...
class ZimbraClient(ZimbraSoapClient): """ Zimbra non-privileged client. """ # ------------------------------------------------------------------ unbound def authenticate(self, account_name, password): """ Authenticates zimbra account. @param account_name: account email addres...
ilgarm/pyzimbra
pyzimbra/z/client.py
ZimbraClient.get_info
python
def get_info(self, params={}): res = self.invoke(zconstant.NS_ZIMBRA_ACC_URL, sconstant.GetInfoRequest, params) return res
Gets mailbox info. @param params: params to retrieve @return: AccountInfo
train
https://github.com/ilgarm/pyzimbra/blob/c397bc7497554d260ec6fd1a80405aed872a70cc/pyzimbra/z/client.py#L93-L103
[ "def invoke(self, ns, request_name, params={}, simplify=False):\n \"\"\"\n Invokes zimbra method using established authentication session.\n @param req: zimbra request\n @parm params: request params\n @param simplify: True to return python object, False to return xml struct\n @return: zimbra respo...
class ZimbraClient(ZimbraSoapClient): """ Zimbra non-privileged client. """ # ------------------------------------------------------------------ unbound def authenticate(self, account_name, password): """ Authenticates zimbra account. @param account_name: account email addres...
ilgarm/pyzimbra
pyzimbra/soap_transport.py
SoapTransport.invoke
python
def invoke(self, ns, request_name, params, auth_token, simplify=False): ZimbraClientTransport.invoke(self, ns, request_name, params, auth_token, ...
Invokes zimbra soap request.
train
https://github.com/ilgarm/pyzimbra/blob/c397bc7497554d260ec6fd1a80405aed872a70cc/pyzimbra/soap_transport.py#L52-L89
[ "def invoke(self, ns, request_name, params, auth_token, simplify):\n \"\"\"\n Invokes zimbra request.\n @param ns: namespace of the request method\n @param request_name: name of the request method\n @param params: parameters to pass to method call\n @param auth_token: authentication token to use f...
class SoapTransport(ZimbraClientTransport): """ Soap transport. """ # --------------------------------------------------------------- properties http_transport = SoapHttpTransport() # -------------------------------------------------------------------- bound def __init__(self): Zim...
omaraboumrad/mastool
mastool/extension.py
Mastool.build_message
python
def build_message(self, checker): solution = ' (%s)' % checker.solution if self.with_solutions else '' return '{} {}{}'.format(checker.code, checker.msg, solution)
Builds the checker's error message to report
train
https://github.com/omaraboumrad/mastool/blob/0ec566de6717d03c6ec61affe5d1e9ff8d7e6ebd/mastool/extension.py#L32-L37
null
class Mastool(object): """Flake8 Extension""" name = 'mastool' version = __version__ def __init__(self, tree, filename): self.tree = tree self.filename = filename @classmethod def add_options(cls, parser): """Provides the --with-solutions option""" parser.add_o...
omaraboumrad/mastool
mastool/extension.py
Mastool.run
python
def run(self): paths = [x for x in practices.__dict__.values() if hasattr(x, 'code')] for node in ast.walk(self.tree): try: lineno, col_offset = node.lineno, node.col_offset except AttributeError: # Not all nodes have coordinates,...
Primary entry point to the plugin, runs once per file.
train
https://github.com/omaraboumrad/mastool/blob/0ec566de6717d03c6ec61affe5d1e9ff8d7e6ebd/mastool/extension.py#L39-L54
[ "def build_message(self, checker):\n \"\"\"Builds the checker's error message to report\"\"\"\n solution = ' (%s)' % checker.solution if self.with_solutions else ''\n return '{} {}{}'.format(checker.code,\n checker.msg,\n solution)\n" ]
class Mastool(object): """Flake8 Extension""" name = 'mastool' version = __version__ def __init__(self, tree, filename): self.tree = tree self.filename = filename @classmethod def add_options(cls, parser): """Provides the --with-solutions option""" parser.add_o...
omaraboumrad/mastool
mastool/helpers.py
is_boolean
python
def is_boolean(node): return any([ isinstance(node, ast.Name) and node.id in ('True', 'False'), hasattr(ast, 'NameConstant') # Support for Python 3 NameConstant and isinstance(node, getattr(ast, 'NameConstant')) # screw you pylint! and str(node.value) in ('True', 'False') ...
Checks if node is True or False
train
https://github.com/omaraboumrad/mastool/blob/0ec566de6717d03c6ec61affe5d1e9ff8d7e6ebd/mastool/helpers.py#L15-L23
null
""" helpers to support practices """ import ast def has_else(node): """Checks if node has else""" return ( isinstance(node, ast.If) and len(node.orelse) > 0 ) def call_name_is(siter, name): """Checks the function call name""" return ( isinstance(siter, ast.Call) ...
omaraboumrad/mastool
mastool/helpers.py
call_name_is
python
def call_name_is(siter, name): return ( isinstance(siter, ast.Call) and hasattr(siter.func, 'attr') and siter.func.attr == name )
Checks the function call name
train
https://github.com/omaraboumrad/mastool/blob/0ec566de6717d03c6ec61affe5d1e9ff8d7e6ebd/mastool/helpers.py#L26-L32
null
""" helpers to support practices """ import ast def has_else(node): """Checks if node has else""" return ( isinstance(node, ast.If) and len(node.orelse) > 0 ) def is_boolean(node): """Checks if node is True or False""" return any([ isinstance(node, ast.Name) and n...
omaraboumrad/mastool
mastool/helpers.py
target_names
python
def target_names(targets): names = [] for entry in targets: if isinstance(entry, ast.Name): names.append(entry.id) elif isinstance(entry, ast.Tuple): for element in entry.elts: if isinstance(element, ast.Name): names.append(element.id) ...
Retrieves the target names
train
https://github.com/omaraboumrad/mastool/blob/0ec566de6717d03c6ec61affe5d1e9ff8d7e6ebd/mastool/helpers.py#L35-L46
null
""" helpers to support practices """ import ast def has_else(node): """Checks if node has else""" return ( isinstance(node, ast.If) and len(node.orelse) > 0 ) def is_boolean(node): """Checks if node is True or False""" return any([ isinstance(node, ast.Name) and n...
omaraboumrad/mastool
mastool/helpers.py
labeled
python
def labeled(**kwargs): def for_practice(practice): """assigns label to practice""" practice.code = kwargs.pop('code') practice.msg = kwargs.pop('msg') practice.solution = kwargs.pop('solution') return practice return for_practice
decorator to give practices labels
train
https://github.com/omaraboumrad/mastool/blob/0ec566de6717d03c6ec61affe5d1e9ff8d7e6ebd/mastool/helpers.py#L54-L62
null
""" helpers to support practices """ import ast def has_else(node): """Checks if node has else""" return ( isinstance(node, ast.If) and len(node.orelse) > 0 ) def is_boolean(node): """Checks if node is True or False""" return any([ isinstance(node, ast.Name) and n...
omaraboumrad/mastool
mastool/practices.py
find_for_x_in_y_keys
python
def find_for_x_in_y_keys(node): return ( isinstance(node, ast.For) and h.call_name_is(node.iter, 'keys') )
Finds looping against dictionary keys
train
https://github.com/omaraboumrad/mastool/blob/0ec566de6717d03c6ec61affe5d1e9ff8d7e6ebd/mastool/practices.py#L13-L18
[ "def call_name_is(siter, name):\n \"\"\"Checks the function call name\"\"\"\n return (\n isinstance(siter, ast.Call)\n and hasattr(siter.func, 'attr')\n and siter.func.attr == name\n )\n" ]
""" Practices and Checks listing """ import ast import sys from mastool import helpers as h @h.labeled(code='M001', msg='looping against dictionary keys', solution="use 'for key in dictionary' instead.") @h.labeled(code='M002', msg='simplifiable if condition', solution=...
omaraboumrad/mastool
mastool/practices.py
find_if_x_retbool_else_retbool
python
def find_if_x_retbool_else_retbool(node): return ( isinstance(node, ast.If) and isinstance(node.body[0], ast.Return) and h.is_boolean(node.body[0].value) and h.has_else(node) and isinstance(node.orelse[0], ast.Return) and h.is_boolean(node.orelse[0].value) )
Finds simplifiable if condition
train
https://github.com/omaraboumrad/mastool/blob/0ec566de6717d03c6ec61affe5d1e9ff8d7e6ebd/mastool/practices.py#L25-L34
null
""" Practices and Checks listing """ import ast import sys from mastool import helpers as h @h.labeled(code='M001', msg='looping against dictionary keys', solution="use 'for key in dictionary' instead.") def find_for_x_in_y_keys(node): """Finds looping against dictionary keys""" return ...
omaraboumrad/mastool
mastool/practices.py
find_path_join_using_plus
python
def find_path_join_using_plus(node): return ( isinstance(node, ast.BinOp) and isinstance(node.op, ast.Add) and isinstance(node.left, ast.BinOp) and isinstance(node.left.op, ast.Add) and isinstance(node.left.right, ast.Str) and node.left.right.s in ['/', "\\"] )
Finds joining path with plus
train
https://github.com/omaraboumrad/mastool/blob/0ec566de6717d03c6ec61affe5d1e9ff8d7e6ebd/mastool/practices.py#L40-L49
null
""" Practices and Checks listing """ import ast import sys from mastool import helpers as h @h.labeled(code='M001', msg='looping against dictionary keys', solution="use 'for key in dictionary' instead.") def find_for_x_in_y_keys(node): """Finds looping against dictionary keys""" return ...
omaraboumrad/mastool
mastool/practices.py
find_assign_to_builtin
python
def find_assign_to_builtin(node): # The list of forbidden builtins is constant and not determined at # runtime anyomre. The reason behind this change is that certain # modules (like `gettext` for instance) would mess with the # builtins module making this practice yield false positives. if sys.vers...
Finds assigning to built-ins
train
https://github.com/omaraboumrad/mastool/blob/0ec566de6717d03c6ec61affe5d1e9ff8d7e6ebd/mastool/practices.py#L55-L98
[ "def target_names(targets):\n \"\"\"Retrieves the target names\"\"\"\n names = []\n for entry in targets:\n if isinstance(entry, ast.Name):\n names.append(entry.id)\n elif isinstance(entry, ast.Tuple):\n for element in entry.elts:\n if isinstance(element, ...
""" Practices and Checks listing """ import ast import sys from mastool import helpers as h @h.labeled(code='M001', msg='looping against dictionary keys', solution="use 'for key in dictionary' instead.") def find_for_x_in_y_keys(node): """Finds looping against dictionary keys""" return ...
omaraboumrad/mastool
mastool/practices.py
find_silent_exception
python
def find_silent_exception(node): return ( isinstance(node, ast.ExceptHandler) and node.type is None and len(node.body) == 1 and isinstance(node.body[0], ast.Pass) )
Finds silent generic exceptions
train
https://github.com/omaraboumrad/mastool/blob/0ec566de6717d03c6ec61affe5d1e9ff8d7e6ebd/mastool/practices.py#L116-L123
null
""" Practices and Checks listing """ import ast import sys from mastool import helpers as h @h.labeled(code='M001', msg='looping against dictionary keys', solution="use 'for key in dictionary' instead.") def find_for_x_in_y_keys(node): """Finds looping against dictionary keys""" return ...
omaraboumrad/mastool
mastool/practices.py
find_import_star
python
def find_import_star(node): return ( isinstance(node, ast.ImportFrom) and '*' in h.importfrom_names(node.names) )
Finds import stars
train
https://github.com/omaraboumrad/mastool/blob/0ec566de6717d03c6ec61affe5d1e9ff8d7e6ebd/mastool/practices.py#L129-L134
[ "def importfrom_names(names):\n \"\"\"Retrieves the importfrom names\"\"\"\n return [n.name for n in names]\n" ]
""" Practices and Checks listing """ import ast import sys from mastool import helpers as h @h.labeled(code='M001', msg='looping against dictionary keys', solution="use 'for key in dictionary' instead.") def find_for_x_in_y_keys(node): """Finds looping against dictionary keys""" return ...
omaraboumrad/mastool
mastool/practices.py
find_equals_true_or_false
python
def find_equals_true_or_false(node): return ( isinstance(node, ast.Compare) and len(node.ops) == 1 and isinstance(node.ops[0], ast.Eq) and any(h.is_boolean(n) for n in node.comparators) )
Finds equals true or false
train
https://github.com/omaraboumrad/mastool/blob/0ec566de6717d03c6ec61affe5d1e9ff8d7e6ebd/mastool/practices.py#L140-L147
null
""" Practices and Checks listing """ import ast import sys from mastool import helpers as h @h.labeled(code='M001', msg='looping against dictionary keys', solution="use 'for key in dictionary' instead.") def find_for_x_in_y_keys(node): """Finds looping against dictionary keys""" return ...
omaraboumrad/mastool
mastool/practices.py
find_poor_default_arg
python
def find_poor_default_arg(node): poor_defaults = [ ast.Call, ast.Dict, ast.DictComp, ast.GeneratorExp, ast.List, ast.ListComp, ast.Set, ast.SetComp, ] # pylint: disable=unidiomatic-typecheck return ( isinstance(node, ast.FunctionDe...
Finds poor default args
train
https://github.com/omaraboumrad/mastool/blob/0ec566de6717d03c6ec61affe5d1e9ff8d7e6ebd/mastool/practices.py#L154-L171
null
""" Practices and Checks listing """ import ast import sys from mastool import helpers as h @h.labeled(code='M001', msg='looping against dictionary keys', solution="use 'for key in dictionary' instead.") def find_for_x_in_y_keys(node): """Finds looping against dictionary keys""" return ...
omaraboumrad/mastool
mastool/practices.py
find_if_expression_as_statement
python
def find_if_expression_as_statement(node): return ( isinstance(node, ast.Expr) and isinstance(node.value, ast.IfExp) )
Finds an "if" expression as a statement
train
https://github.com/omaraboumrad/mastool/blob/0ec566de6717d03c6ec61affe5d1e9ff8d7e6ebd/mastool/practices.py#L178-L183
null
""" Practices and Checks listing """ import ast import sys from mastool import helpers as h @h.labeled(code='M001', msg='looping against dictionary keys', solution="use 'for key in dictionary' instead.") def find_for_x_in_y_keys(node): """Finds looping against dictionary keys""" return ...
omaraboumrad/mastool
mastool/practices.py
find_comprehension_as_statement
python
def find_comprehension_as_statement(node): return ( isinstance(node, ast.Expr) and isinstance(node.value, (ast.ListComp, ast.DictComp, ast.SetComp)) )
Finds a comprehension as a statement
train
https://github.com/omaraboumrad/mastool/blob/0ec566de6717d03c6ec61affe5d1e9ff8d7e6ebd/mastool/practices.py#L189-L196
null
""" Practices and Checks listing """ import ast import sys from mastool import helpers as h @h.labeled(code='M001', msg='looping against dictionary keys', solution="use 'for key in dictionary' instead.") def find_for_x_in_y_keys(node): """Finds looping against dictionary keys""" return ...
omaraboumrad/mastool
mastool/practices.py
find_generator_as_statement
python
def find_generator_as_statement(node): return ( isinstance(node, ast.Expr) and isinstance(node.value, ast.GeneratorExp) )
Finds a generator as a statement
train
https://github.com/omaraboumrad/mastool/blob/0ec566de6717d03c6ec61affe5d1e9ff8d7e6ebd/mastool/practices.py#L202-L207
null
""" Practices and Checks listing """ import ast import sys from mastool import helpers as h @h.labeled(code='M001', msg='looping against dictionary keys', solution="use 'for key in dictionary' instead.") def find_for_x_in_y_keys(node): """Finds looping against dictionary keys""" return ...
OTL/jps
jps/launcher.py
launch_modules_with_names
python
def launch_modules_with_names(modules_with_names, module_args={}, kill_before_launch=True): '''launch module.main functions in another process''' processes = [] if kill_before_launch: for module_name, name in modules_with_names: kill_module(name) for module_name, name in modules_with...
launch module.main functions in another process
train
https://github.com/OTL/jps/blob/2c5a438d59611fffca6853072c822ef22665ed87/jps/launcher.py#L32-L49
[ "def get_launched_module_pid_file(module_name):\n return '{}/{}_jps_launch.pid'.format(tempfile.gettempdir(), module_name)\n", "def kill_module(module_name):\n pid_file_path = get_launched_module_pid_file(module_name)\n if os.path.exists(pid_file_path):\n with open(pid_file_path, 'r') as f:\n ...
from multiprocessing import Process import getpass import importlib import os import signal import tempfile def get_launched_module_pid_file(module_name): return '{}/{}_jps_launch.pid'.format(tempfile.gettempdir(), module_name) def kill_module(module_name): pid_file_path = get_launched_module_pid_file(modul...
OTL/jps
jps/publisher.py
Publisher.publish
python
def publish(self, payload): '''Publish payload to the topic .. note:: If you publishes just after creating Publisher instance, it will causes lost of message. You have to add sleep if you just want to publish once. >>> pub = jps.Publisher('topic') >>> time.sleep(0.1) ...
Publish payload to the topic .. note:: If you publishes just after creating Publisher instance, it will causes lost of message. You have to add sleep if you just want to publish once. >>> pub = jps.Publisher('topic') >>> time.sleep(0.1) >>> pub.publish('{data}') ...
train
https://github.com/OTL/jps/blob/2c5a438d59611fffca6853072c822ef22665ed87/jps/publisher.py#L47-L66
null
class Publisher(object): '''Publishes data for a topic. Example: >>> pub = jps.Publisher('special_topic') >>> pub.publish('{"name": "hoge"}') :param topic_name: Topic name :param host: host of subscriber/forwarder :param pub_port: port of subscriber/forwarder :param serializer: this ...
OTL/jps
jps/utils.py
JsonMultiplePublisher.publish
python
def publish(self, json_msg): ''' json_msg = '{"topic1": 1.0, "topic2": {"x": 0.1}}' ''' pyobj = json.loads(json_msg) for topic, value in pyobj.items(): msg = '{topic} {data}'.format(topic=topic, data=json.dumps(value)) self._pub.publish(msg)
json_msg = '{"topic1": 1.0, "topic2": {"x": 0.1}}'
train
https://github.com/OTL/jps/blob/2c5a438d59611fffca6853072c822ef22665ed87/jps/utils.py#L24-L31
[ "def publish(self, payload):\n '''Publish payload to the topic\n\n .. note:: If you publishes just after creating Publisher instance, it will causes\n lost of message. You have to add sleep if you just want to publish once.\n\n >>> pub = jps.Publisher('topic')\n >>> time.sleep(0.1)\n >...
class JsonMultiplePublisher(object): '''publish multiple topics by one json message Example: >>> p = JsonMultiplePublisher() >>> p.publish('{"topic1": 1.0, "topic2": {"x": 0.1}}') ''' def __init__(self): self._pub = Publisher('*')
OTL/jps
jps/tools.py
pub
python
def pub(topic_name, json_msg, repeat_rate=None, host=jps.env.get_master_host(), pub_port=jps.DEFAULT_PUB_PORT): '''publishes the data to the topic :param topic_name: name of the topic :param json_msg: data to be published :param repeat_rate: if None, publishes once. if not None, it is used as [Hz]. ...
publishes the data to the topic :param topic_name: name of the topic :param json_msg: data to be published :param repeat_rate: if None, publishes once. if not None, it is used as [Hz].
train
https://github.com/OTL/jps/blob/2c5a438d59611fffca6853072c822ef22665ed87/jps/tools.py#L11-L28
[ "def publish(self, payload):\n '''Publish payload to the topic\n\n .. note:: If you publishes just after creating Publisher instance, it will causes\n lost of message. You have to add sleep if you just want to publish once.\n\n >>> pub = jps.Publisher('topic')\n >>> time.sleep(0.1)\n >...
import argparse import datetime import jps import json import os import signal import sys import time def echo(topic_name, num_print=None, out=sys.stdout, host=jps.env.get_master_host(), sub_port=jps.DEFAULT_SUB_PORT): '''print the data for the given topic forever ''' class PrintWithCount(object): ...
OTL/jps
jps/tools.py
echo
python
def echo(topic_name, num_print=None, out=sys.stdout, host=jps.env.get_master_host(), sub_port=jps.DEFAULT_SUB_PORT): '''print the data for the given topic forever ''' class PrintWithCount(object): def __init__(self, out): self._printed = 0 self._out = out def print_...
print the data for the given topic forever
train
https://github.com/OTL/jps/blob/2c5a438d59611fffca6853072c822ef22665ed87/jps/tools.py#L31-L55
[ "def spin_once(self, polling_sec=0.010):\n '''Read the queued data and call the callback for them.\n You have to handle KeyboardInterrupt (\\C-c) manually.\n\n Example:\n\n >>> def callback(msg):\n ... print msg\n >>> sub = jps.Subscriber('topic_name', callback)\n >>> try:\n ... while Tr...
import argparse import datetime import jps import json import os import signal import sys import time def pub(topic_name, json_msg, repeat_rate=None, host=jps.env.get_master_host(), pub_port=jps.DEFAULT_PUB_PORT): '''publishes the data to the topic :param topic_name: name of the topic :param json_msg: da...
OTL/jps
jps/tools.py
show_list
python
def show_list(timeout_in_sec, out=sys.stdout, host=jps.env.get_master_host(), sub_port=jps.DEFAULT_SUB_PORT): '''get the name list of the topics, and print it ''' class TopicNameStore(object): def __init__(self): self._topic_names = set() def callback(self, msg, topic): ...
get the name list of the topics, and print it
train
https://github.com/OTL/jps/blob/2c5a438d59611fffca6853072c822ef22665ed87/jps/tools.py#L58-L81
[ "def spin_once(self, polling_sec=0.010):\n '''Read the queued data and call the callback for them.\n You have to handle KeyboardInterrupt (\\C-c) manually.\n\n Example:\n\n >>> def callback(msg):\n ... print msg\n >>> sub = jps.Subscriber('topic_name', callback)\n >>> try:\n ... while Tr...
import argparse import datetime import jps import json import os import signal import sys import time def pub(topic_name, json_msg, repeat_rate=None, host=jps.env.get_master_host(), pub_port=jps.DEFAULT_PUB_PORT): '''publishes the data to the topic :param topic_name: name of the topic :param json_msg: da...
OTL/jps
jps/tools.py
record
python
def record(file_path, topic_names=[], host=jps.env.get_master_host(), sub_port=jps.DEFAULT_SUB_PORT): '''record the topic data to the file ''' class TopicRecorder(object): def __init__(self, file_path, topic_names): self._topic_names = topic_names self._file_path = file_path...
record the topic data to the file
train
https://github.com/OTL/jps/blob/2c5a438d59611fffca6853072c822ef22665ed87/jps/tools.py#L84-L127
[ "def spin(self, use_thread=False):\n '''call callback for all data forever (until \\C-c)\n\n :param use_thread: use thread for spin (do not block)\n '''\n if use_thread:\n if self._thread is not None:\n raise Error('spin called twice')\n self._thread = threading.Thread(target=se...
import argparse import datetime import jps import json import os import signal import sys import time def pub(topic_name, json_msg, repeat_rate=None, host=jps.env.get_master_host(), pub_port=jps.DEFAULT_PUB_PORT): '''publishes the data to the topic :param topic_name: name of the topic :param json_msg: da...
OTL/jps
jps/tools.py
play
python
def play(file_path, host=jps.env.get_master_host(), pub_port=jps.DEFAULT_PUB_PORT): '''replay the recorded data by record() ''' pub = jps.Publisher('*', host=host, pub_port=pub_port) time.sleep(0.2) last_time = None print('start publishing file {}'.format(file_path)) with open(file_path, 'r'...
replay the recorded data by record()
train
https://github.com/OTL/jps/blob/2c5a438d59611fffca6853072c822ef22665ed87/jps/tools.py#L130-L149
null
import argparse import datetime import jps import json import os import signal import sys import time def pub(topic_name, json_msg, repeat_rate=None, host=jps.env.get_master_host(), pub_port=jps.DEFAULT_PUB_PORT): '''publishes the data to the topic :param topic_name: name of the topic :param json_msg: da...
OTL/jps
jps/tools.py
topic_command
python
def topic_command(): '''command line tool for jps ''' parser = argparse.ArgumentParser(description='json pub/sub tool') pub_common_parser = jps.ArgumentParser(subscriber=False, add_help=False) sub_common_parser = jps.ArgumentParser(publisher=False, add_help=False) command_parsers = parser.add_su...
command line tool for jps
train
https://github.com/OTL/jps/blob/2c5a438d59611fffca6853072c822ef22665ed87/jps/tools.py#L152-L208
[ "def record(file_path, topic_names=[], host=jps.env.get_master_host(), sub_port=jps.DEFAULT_SUB_PORT):\n '''record the topic data to the file\n '''\n class TopicRecorder(object):\n\n def __init__(self, file_path, topic_names):\n self._topic_names = topic_names\n self._file_path...
import argparse import datetime import jps import json import os import signal import sys import time def pub(topic_name, json_msg, repeat_rate=None, host=jps.env.get_master_host(), pub_port=jps.DEFAULT_PUB_PORT): '''publishes the data to the topic :param topic_name: name of the topic :param json_msg: da...
OTL/jps
jps/queue.py
main
python
def main(req_port=None, res_port=None, use_security=False): '''main of queue :param req_port: port for clients :param res_port: port for servers ''' if req_port is None: req_port = env.get_req_port() if res_port is None: res_port = env.get_res_port() auth = None try: ...
main of queue :param req_port: port for clients :param res_port: port for servers
train
https://github.com/OTL/jps/blob/2c5a438d59611fffca6853072c822ef22665ed87/jps/queue.py#L18-L51
[ "def create_certificates(keys_dir='certificates'):\n if not os.path.exists(keys_dir):\n os.mkdir(keys_dir)\n server_public_file, server_secret_file = zmq.auth.create_certificates(\n keys_dir, \"server\")\n client_public_file, client_secret_file = zmq.auth.create_certificates(\n keys_di...
import os import zmq from .args import ArgumentParser from . import env from .security import Authenticator from .security import create_certificates def command(): parser = ArgumentParser(description='jps queue', service=True, publisher=False, subscriber=False) args = parser.par...
OTL/jps
jps/forwarder.py
main
python
def main(pub_port=None, sub_port=None): '''main of forwarder :param sub_port: port for subscribers :param pub_port: port for publishers ''' try: if sub_port is None: sub_port = get_sub_port() if pub_port is None: pub_port = get_pub_port() context = zm...
main of forwarder :param sub_port: port for subscribers :param pub_port: port for publishers
train
https://github.com/OTL/jps/blob/2c5a438d59611fffca6853072c822ef22665ed87/jps/forwarder.py#L13-L37
[ "def get_pub_port():\n return os.environ.get('JPS_MASTER_PUB_PORT', DEFAULT_PUB_PORT)\n", "def get_sub_port():\n return os.environ.get('JPS_MASTER_SUB_PORT', DEFAULT_SUB_PORT)\n" ]
import zmq from .args import ArgumentParser from .env import get_pub_port from .env import get_sub_port def command(): parser = ArgumentParser(description='jps forwarder') args = parser.parse_args() main(args.publisher_port, args.subscriber_port) if __name__ == "__main__": main()
OTL/jps
jps/service.py
ServiceServer.spin
python
def spin(self, use_thread=False): '''call callback for all data forever (until \C-c) :param use_thread: use thread for spin (do not block) ''' if use_thread: if self._thread is not None: raise 'spin called twice' self._thread = threading.Thread(ta...
call callback for all data forever (until \C-c) :param use_thread: use thread for spin (do not block)
train
https://github.com/OTL/jps/blob/2c5a438d59611fffca6853072c822ef22665ed87/jps/service.py#L40-L52
[ "def _spin_internal(self):\n while True:\n self.spin_once()\n" ]
class ServiceServer(object): ''' Example: >>> def callback(req): ... return 'req = {req}'.format(req=req) ... >>> service = jps.ServiceServer(callback) >>> service.spin() ''' def __init__(self, callback, host=None, res_port=None, use_security=False): if host is None: ...
OTL/jps
jps/security.py
Authenticator.instance
python
def instance(cls, public_keys_dir): '''Please avoid create multi instance''' if public_keys_dir in cls._authenticators: return cls._authenticators[public_keys_dir] new_instance = cls(public_keys_dir) cls._authenticators[public_keys_dir] = new_instance return new_insta...
Please avoid create multi instance
train
https://github.com/OTL/jps/blob/2c5a438d59611fffca6853072c822ef22665ed87/jps/security.py#L18-L24
null
class Authenticator(object): _authenticators = {} @classmethod def __init__(self, public_keys_dir): self._auth = ThreadAuthenticator(zmq.Context.instance()) self._auth.start() self._auth.allow('*') self._auth.configure_curve(domain='*', location=public_keys_dir) def s...
OTL/jps
jps/security.py
Authenticator.set_server_key
python
def set_server_key(self, zmq_socket, server_secret_key_path): '''must call before bind''' load_and_set_key(zmq_socket, server_secret_key_path) zmq_socket.curve_server = True
must call before bind
train
https://github.com/OTL/jps/blob/2c5a438d59611fffca6853072c822ef22665ed87/jps/security.py#L32-L35
[ "def load_and_set_key(zmq_socket, key_path):\n public, secret = zmq.auth.load_certificate(key_path)\n zmq_socket.curve_secretkey = secret\n zmq_socket.curve_publickey = public\n" ]
class Authenticator(object): _authenticators = {} @classmethod def instance(cls, public_keys_dir): '''Please avoid create multi instance''' if public_keys_dir in cls._authenticators: return cls._authenticators[public_keys_dir] new_instance = cls(public_keys_dir) ...
OTL/jps
jps/security.py
Authenticator.set_client_key
python
def set_client_key(self, zmq_socket, client_secret_key_path, server_public_key_path): '''must call before bind''' load_and_set_key(zmq_socket, client_secret_key_path) server_public, _ = zmq.auth.load_certificate(server_public_key_path) zmq_socket.curve_serverkey = server_public
must call before bind
train
https://github.com/OTL/jps/blob/2c5a438d59611fffca6853072c822ef22665ed87/jps/security.py#L37-L41
[ "def load_and_set_key(zmq_socket, key_path):\n public, secret = zmq.auth.load_certificate(key_path)\n zmq_socket.curve_secretkey = secret\n zmq_socket.curve_publickey = public\n" ]
class Authenticator(object): _authenticators = {} @classmethod def instance(cls, public_keys_dir): '''Please avoid create multi instance''' if public_keys_dir in cls._authenticators: return cls._authenticators[public_keys_dir] new_instance = cls(public_keys_dir) ...
OTL/jps
jps/subscriber.py
Subscriber.spin_once
python
def spin_once(self, polling_sec=0.010): '''Read the queued data and call the callback for them. You have to handle KeyboardInterrupt (\C-c) manually. Example: >>> def callback(msg): ... print msg >>> sub = jps.Subscriber('topic_name', callback) >>> try: ...
Read the queued data and call the callback for them. You have to handle KeyboardInterrupt (\C-c) manually. Example: >>> def callback(msg): ... print msg >>> sub = jps.Subscriber('topic_name', callback) >>> try: ... while True: ... sub.spin_once()...
train
https://github.com/OTL/jps/blob/2c5a438d59611fffca6853072c822ef22665ed87/jps/subscriber.py#L102-L126
null
class Subscriber(object): '''Subscribe the topic and call the callback function Example: >>> def callback(msg): ... print msg ... >>> sub = jps.Subscriber('topic_name', callback) >>> sub.spin() or you can use python generator style >>> import jps >>> for msg in jps.Subscri...
OTL/jps
jps/subscriber.py
Subscriber.next
python
def next(self): '''receive next data (block until next data)''' try: raw_msg = self._socket.recv() except KeyboardInterrupt: raise StopIteration() msg, topic_name = self._strip_topic_name_if_not_wildcard(raw_msg) if msg is None: return self.nex...
receive next data (block until next data)
train
https://github.com/OTL/jps/blob/2c5a438d59611fffca6853072c822ef22665ed87/jps/subscriber.py#L152-L164
[ "def _strip_topic_name_if_not_wildcard(self, raw_msg):\n topic, _, msg = raw_msg.partition(' ')\n if self._topic != self._topic_without_star:\n return (msg, topic)\n elif topic == self._topic:\n return (msg, topic)\n return (None, topic)\n", "def deserialize(self, msg):\n if self._des...
class Subscriber(object): '''Subscribe the topic and call the callback function Example: >>> def callback(msg): ... print msg ... >>> sub = jps.Subscriber('topic_name', callback) >>> sub.spin() or you can use python generator style >>> import jps >>> for msg in jps.Subscri...
basilfx/flask-daapserver
daapserver/bonjour.py
Bonjour.publish
python
def publish(self, daap_server, preferred_database=None): if daap_server in self.daap_servers: self.unpublish(daap_server) # Zeroconf can advertise the information for one database only. Since # the protocol supports multiple database, let the user decide which # database to...
Publish a given `DAAPServer` instance. The given instances should be fully configured, including the provider. By default Zeroconf only advertises the first database, but the DAAP protocol has support for multiple databases. Therefore, the parameter `preferred_database` can be set to ch...
train
https://github.com/basilfx/flask-daapserver/blob/ca595fcbc5b657cba826eccd3be5cebba0a1db0e/daapserver/bonjour.py#L21-L101
[ "def generate_persistent_id():\n \"\"\"\n Generate a persistent ID. This ID is used in the DAAP protocol to uniquely\n identify objects when they are created.\n\n :return: A 64-bit random integer\n :rtype: int\n \"\"\"\n\n return ctypes.c_long(uuid.uuid1().int >> 64).value\n", "def unpublish(...
class Bonjour(object): """ DAAPServer Bonjour/Zeroconf handler. """ def __init__(self): """ Construct a new Bonjour/Zeroconf server. This server takes `DAAPServer` instances and advertises them. """ self.zeroconf = zeroconf.Zeroconf(zeroconf.InterfaceChoice.All)...
basilfx/flask-daapserver
daapserver/bonjour.py
Bonjour.unpublish
python
def unpublish(self, daap_server): if daap_server not in self.daap_servers: return self.zeroconf.unregister_service(self.daap_servers[daap_server]) del self.daap_servers[daap_server]
Unpublish a given server. If the server was not published, this method will not do anything. :param DAAPServer daap_server: DAAP Server instance to publish.
train
https://github.com/basilfx/flask-daapserver/blob/ca595fcbc5b657cba826eccd3be5cebba0a1db0e/daapserver/bonjour.py#L103-L117
null
class Bonjour(object): """ DAAPServer Bonjour/Zeroconf handler. """ def __init__(self): """ Construct a new Bonjour/Zeroconf server. This server takes `DAAPServer` instances and advertises them. """ self.zeroconf = zeroconf.Zeroconf(zeroconf.InterfaceChoice.All)...
basilfx/flask-daapserver
daapserver/__init__.py
DaapServer.serve_forever
python
def serve_forever(self): # Verify that the provider has a server. if self.provider.server is None: raise ValueError( "Cannot start server because the provider has no server to " "publish.") # Verify that the provider has a database to advertise. ...
Run the DAAP server. Start by advertising the server via Bonjour. Then serve requests until CTRL + C is received.
train
https://github.com/basilfx/flask-daapserver/blob/ca595fcbc5b657cba826eccd3be5cebba0a1db0e/daapserver/__init__.py#L37-L70
null
class DaapServer(object): """ DAAP Server instance. Combine all components from this module in a ready to use class. This class uses a gevent-based event loop. """ def __init__(self, provider, password=None, ip="0.0.0.0", port=3689, cache=True, cache_timeout=3600, bonjour=True, deb...
basilfx/flask-daapserver
daapserver/utils.py
diff
python
def diff(new, old): if old is not None: is_update = True removed = set(new.removed(old)) updated = set(new.updated(old)) else: is_update = False updated = new removed = set() return updated, removed, is_update
Compute the difference in items of two revisioned collections. If only `new' is specified, it is assumed it is not an update. If both are set, the removed items are returned first. Otherwise, the updated and edited ones are returned. :param set new: Set of new objects :param set old: Set of old obj...
train
https://github.com/basilfx/flask-daapserver/blob/ca595fcbc5b657cba826eccd3be5cebba0a1db0e/daapserver/utils.py#L6-L30
null
import sys import uuid import ctypes def generate_persistent_id(): """ Generate a persistent ID. This ID is used in the DAAP protocol to uniquely identify objects when they are created. :return: A 64-bit random integer :rtype: int """ return ctypes.c_long(uuid.uuid1().int >> 64).value ...
basilfx/flask-daapserver
daapserver/utils.py
parse_byte_range
python
def parse_byte_range(byte_range, min_byte=0, max_byte=sys.maxint): if not byte_range: return min_byte, max_byte begin = byte_range[0] or min_byte end = byte_range[1] or max_byte if end < begin: raise ValueError("End before begin") if begin < min_byte: raise ValueError("Be...
Parse and validate a byte range. A byte range is a tuple of (begin, end) indices. `begin' should be smaller than `end', and both should fall within the `min_byte' and `max_byte'. In case of a violation, a `ValueError` is raised.
train
https://github.com/basilfx/flask-daapserver/blob/ca595fcbc5b657cba826eccd3be5cebba0a1db0e/daapserver/utils.py#L45-L69
null
import sys import uuid import ctypes def diff(new, old): """ Compute the difference in items of two revisioned collections. If only `new' is specified, it is assumed it is not an update. If both are set, the removed items are returned first. Otherwise, the updated and edited ones are returned. ...
basilfx/flask-daapserver
daapserver/utils.py
to_tree
python
def to_tree(instance, *children): # Yield representation of self yield unicode(instance) # Iterate trough each instance child collection for i, child in enumerate(children): lines = 0 yield "|" yield "+---" + unicode(child) if i != len(children) - 1: a = "...
Generate tree structure of an instance, and its children. This method yields its results, instead of returning them.
train
https://github.com/basilfx/flask-daapserver/blob/ca595fcbc5b657cba826eccd3be5cebba0a1db0e/daapserver/utils.py#L72-L114
null
import sys import uuid import ctypes def diff(new, old): """ Compute the difference in items of two revisioned collections. If only `new' is specified, it is assumed it is not an update. If both are set, the removed items are returned first. Otherwise, the updated and edited ones are returned. ...
basilfx/flask-daapserver
daapserver/utils.py
invoke_hooks
python
def invoke_hooks(hooks, name, *args, **kwargs): callbacks = hooks.get(name, []) for callback in callbacks: callback(*args, **kwargs)
Invoke one or more hooks that have been registered under `name'. Additional arguments and keyword arguments can be provided. There is no exception catching, so if a hook fails, it will disrupt the chain and/or rest of program.
train
https://github.com/basilfx/flask-daapserver/blob/ca595fcbc5b657cba826eccd3be5cebba0a1db0e/daapserver/utils.py#L117-L129
null
import sys import uuid import ctypes def diff(new, old): """ Compute the difference in items of two revisioned collections. If only `new' is specified, it is assumed it is not an update. If both are set, the removed items are returned first. Otherwise, the updated and edited ones are returned. ...
basilfx/flask-daapserver
daapserver/provider.py
Provider.create_session
python
def create_session(self, user_agent, remote_address, client_version): self.session_counter += 1 self.sessions[self.session_counter] = session = self.session_class() # Set session properties session.user_agent = user_agent session.remote_address = remote_address session....
Create a new session. :param str user_agent: Client user agent :param str remote_addr: Remote address of client :param str client_version: Remote client version :return: The new session id :rtype: int
train
https://github.com/basilfx/flask-daapserver/blob/ca595fcbc5b657cba826eccd3be5cebba0a1db0e/daapserver/provider.py#L96-L118
[ "def invoke_hooks(hooks, name, *args, **kwargs):\n \"\"\"\n Invoke one or more hooks that have been registered under `name'. Additional\n arguments and keyword arguments can be provided.\n\n There is no exception catching, so if a hook fails, it will disrupt the\n chain and/or rest of program.\n \...
class Provider(object): """ Base provider implementation. A provider is responsible for serving the data to the client. This class should be subclassed. """ # Class type to use for sessions session_class = Session # Whether to artwork is supported supports_artwork = False # Whethe...
basilfx/flask-daapserver
daapserver/provider.py
Provider.destroy_session
python
def destroy_session(self, session_id): try: del self.sessions[session_id] except KeyError: pass # Invoke hooks invoke_hooks(self.hooks, "session_destroyed", session_id)
Destroy an (existing) session.
train
https://github.com/basilfx/flask-daapserver/blob/ca595fcbc5b657cba826eccd3be5cebba0a1db0e/daapserver/provider.py#L120-L131
[ "def invoke_hooks(hooks, name, *args, **kwargs):\n \"\"\"\n Invoke one or more hooks that have been registered under `name'. Additional\n arguments and keyword arguments can be provided.\n\n There is no exception catching, so if a hook fails, it will disrupt the\n chain and/or rest of program.\n \...
class Provider(object): """ Base provider implementation. A provider is responsible for serving the data to the client. This class should be subclassed. """ # Class type to use for sessions session_class = Session # Whether to artwork is supported supports_artwork = False # Whethe...
basilfx/flask-daapserver
daapserver/provider.py
Provider.get_next_revision
python
def get_next_revision(self, session_id, revision, delta): session = self.sessions[session_id] session.state = State.connected if delta == revision: # Increment revision. Never decrement. session.revision = max(session.revision, revision) # Wait for next rev...
Determine the next revision number for a given session id, revision and delta. In case the client is up-to-date, this method will block until the next revision is available. :param int session_id: Session identifier :param int revision: Client revision number :param int...
train
https://github.com/basilfx/flask-daapserver/blob/ca595fcbc5b657cba826eccd3be5cebba0a1db0e/daapserver/provider.py#L133-L158
null
class Provider(object): """ Base provider implementation. A provider is responsible for serving the data to the client. This class should be subclassed. """ # Class type to use for sessions session_class = Session # Whether to artwork is supported supports_artwork = False # Whethe...
basilfx/flask-daapserver
daapserver/provider.py
Provider.update
python
def update(self): with self.lock: # Increment revision and commit it. self.revision += 1 self.server.commit(self.revision + 1) # Unblock all waiting clients. self.next_revision_available.set() self.next_revision_available.clear() ...
Update this provider. Should be invoked when the server gets updated. This method will notify all clients that wait for `self.next_revision_available`.
train
https://github.com/basilfx/flask-daapserver/blob/ca595fcbc5b657cba826eccd3be5cebba0a1db0e/daapserver/provider.py#L160-L187
[ "def invoke_hooks(hooks, name, *args, **kwargs):\n \"\"\"\n Invoke one or more hooks that have been registered under `name'. Additional\n arguments and keyword arguments can be provided.\n\n There is no exception catching, so if a hook fails, it will disrupt the\n chain and/or rest of program.\n \...
class Provider(object): """ Base provider implementation. A provider is responsible for serving the data to the client. This class should be subclassed. """ # Class type to use for sessions session_class = Session # Whether to artwork is supported supports_artwork = False # Whethe...
basilfx/flask-daapserver
daapserver/provider.py
LocalFileProvider.get_item_data
python
def get_item_data(self, session, item, byte_range=None): # Parse byte range if byte_range is not None: begin, end = parse_byte_range(byte_range, max_byte=item.file_size) else: begin, end = 0, item.file_size # Open the file fp = open(item.file_name, "rb+"...
Return a file pointer to the item file. Assumes `item.file_name` points to the file on disk.
train
https://github.com/basilfx/flask-daapserver/blob/ca595fcbc5b657cba826eccd3be5cebba0a1db0e/daapserver/provider.py#L356-L382
[ "def parse_byte_range(byte_range, min_byte=0, max_byte=sys.maxint):\n \"\"\"\n Parse and validate a byte range. A byte range is a tuple of (begin, end)\n indices. `begin' should be smaller than `end', and both should fall within\n the `min_byte' and `max_byte'.\n\n In case of a violation, a `ValueErr...
class LocalFileProvider(Provider): """ Tiny implementation of a local file provider. Streams items and data from disk. """ supports_artwork = True def get_artwork_data(self, session, item): """ Return a file pointer to the artwork file. Assumes `item.album_art` points ...
basilfx/flask-daapserver
utils/benchmark_store.py
parse_arguments
python
def parse_arguments(): parser = argparse.ArgumentParser() # Add options parser.add_argument( "-n", "--number", action="store", default=1000000, type=int, help="number of items") parser.add_argument( "-p", "--pause", action="store_true", help="pause after execution") # Pars...
Parse commandline arguments.
train
https://github.com/basilfx/flask-daapserver/blob/ca595fcbc5b657cba826eccd3be5cebba0a1db0e/utils/benchmark_store.py#L9-L24
null
from six.moves import xrange from daapserver.revision import RevisionStore import argparse import sys def main(): """ Run a benchmark for N items. If N is not specified, take 1,000,000 for N. """ # Parse arguments and configure application instance. arguments, parser = parse_arguments() #...
basilfx/flask-daapserver
utils/benchmark_store.py
main
python
def main(): # Parse arguments and configure application instance. arguments, parser = parse_arguments() # Start iterating store = RevisionStore() sys.stdout.write("Iterating over %d items.\n" % arguments.number) for i in xrange(arguments.number): key = chr(65 + (i % 26)) value...
Run a benchmark for N items. If N is not specified, take 1,000,000 for N.
train
https://github.com/basilfx/flask-daapserver/blob/ca595fcbc5b657cba826eccd3be5cebba0a1db0e/utils/benchmark_store.py#L27-L48
[ "def parse_arguments():\n \"\"\"\n Parse commandline arguments.\n \"\"\"\n\n parser = argparse.ArgumentParser()\n\n # Add options\n parser.add_argument(\n \"-n\", \"--number\", action=\"store\", default=1000000, type=int,\n help=\"number of items\")\n parser.add_argument(\n ...
from six.moves import xrange from daapserver.revision import RevisionStore import argparse import sys def parse_arguments(): """ Parse commandline arguments. """ parser = argparse.ArgumentParser() # Add options parser.add_argument( "-n", "--number", action="store", default=1000000,...
basilfx/flask-daapserver
utils/transformer.py
install_new_pipeline
python
def install_new_pipeline(): def new_create_pipeline(context, *args, **kwargs): result = old_create_pipeline(context, *args, **kwargs) result.insert(1, DAAPObjectTransformer(context)) return result old_create_pipeline = Pipeline.create_pipeline Pipeline.create_pipeline = new_create...
Install above transformer into the existing pipeline creator.
train
https://github.com/basilfx/flask-daapserver/blob/ca595fcbc5b657cba826eccd3be5cebba0a1db0e/utils/transformer.py#L39-L51
null
from Cython.Compiler import Pipeline, Visitor, ExprNodes, StringEncoding import imp import os # Load the DAAP data. Cannot use normal import because setup.py will install # dependencies after this file is imported. daap_data = imp.load_source("daap_data", os.path.join( os.path.dirname(__file__), "../daapserver/da...