INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
Writes the head part for the generated document with the given title and CSS | def write_head(self, title, css_path, default_css):
"""Writes the head part for the generated document,
with the given title and CSS
"""
self.title = title
self.write(
'''<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=... |
Sets the menu separator. Must be called before adding entries to the menu | def set_menu_separator(self, img):
"""Sets the menu separator.
Must be called before adding entries to the menu
"""
if img:
self.menu_separator_tag = '<img src="{}" alt="/" />'.format(
self._rel(img))
else:
self.menu_separator_tag = None |
Adds a menu entry will create it if it doesn t exist yet | def add_menu(self, name, link=None):
"""Adds a menu entry, will create it if it doesn't exist yet"""
if self.menu_began:
if self.menu_separator_tag:
self.write(self.menu_separator_tag)
else:
# First time, create the menu tag
self.write('<ul cla... |
Writes a title header in the document body with an optional depth level | def write_title(self, title, level=1, id=None):
"""Writes a title header in the document body,
with an optional depth level
"""
if id:
self.write('<h{lv} id="{id}">{title}</h{lv}>',
title=title, lv=level, id=id)
else:
self.write('... |
Writes the code for the given tlobject properly formatted with hyperlinks | def write_code(self, tlobject):
"""Writes the code for the given 'tlobject' properly
formatted with hyperlinks
"""
self.write('<pre>---{}---\n',
'functions' if tlobject.is_function else 'types')
# Write the function or type and its ID
if tlobject.na... |
Begins a table with the given column_count required to automatically create the right amount of columns when adding items to the rows | def begin_table(self, column_count):
"""Begins a table with the given 'column_count', required to automatically
create the right amount of columns when adding items to the rows"""
self.table_columns = column_count
self.table_columns_left = 0
self.write('<table>') |
This will create a new row or add text to the next column of the previously created incomplete row closing it if complete | def add_row(self, text, link=None, bold=False, align=None):
"""This will create a new row, or add text to the next column
of the previously created, incomplete row, closing it if complete"""
if not self.table_columns_left:
# Starting a new row
self.write('<tr>')
... |
Writes a button with text which can be used to copy text_to_copy to clipboard when it s clicked. | def write_copy_button(self, text, text_to_copy):
"""Writes a button with 'text' which can be used
to copy 'text_to_copy' to clipboard when it's clicked."""
self.write_copy_script = True
self.write('<button onclick="cp(\'{}\');">{}</button>'
.format(text_to_copy, tex... |
Ends the whole document. This should be called the last | def end_body(self):
"""Ends the whole document. This should be called the last"""
if self.write_copy_script:
self.write(
'<textarea id="c" class="invisible"></textarea>'
'<script>'
'function cp(t){'
'var c=document.getElementByI... |
Wrapper around handle. write | def write(self, s, *args, **kwargs):
"""Wrapper around handle.write"""
if args or kwargs:
self.handle.write(s.format(*args, **kwargs))
else:
self.handle.write(s) |
Iterator over the participants belonging to the specified chat. | def iter_participants(
self, entity, limit=None, *, search='',
filter=None, aggressive=False
):
"""
Iterator over the participants belonging to the specified chat.
Args:
entity (`entity`):
The entity from which to retrieve the participants... |
Iterator over the admin log for the specified channel. | def iter_admin_log(
self, entity, limit=None, *, max_id=0, min_id=0, search=None,
admins=None, join=None, leave=None, invite=None, restrict=None,
unrestrict=None, ban=None, unban=None, promote=None, demote=None,
info=None, settings=None, pinned=None, edit=None, delete=Non... |
Returns a context - manager object to represent a chat action. | def action(self, entity, action, *, delay=4, auto_cancel=True):
"""
Returns a context-manager object to represent a "chat action".
Chat actions indicate things like "user is typing", "user is
uploading a photo", etc. Normal usage is as follows:
.. code-block:: python
... |
Prepares a new CDN decrypter. | async def prepare_decrypter(client, cdn_client, cdn_redirect):
"""
Prepares a new CDN decrypter.
:param client: a TelegramClient connected to the main servers.
:param cdn_client: a new client connected to the CDN.
:param cdn_redirect: the redirect file object that caused this ca... |
Calls GetCdnFileRequest and decrypts its bytes. Also ensures that the file hasn t been tampered. | def get_file(self):
"""
Calls GetCdnFileRequest and decrypts its bytes.
Also ensures that the file hasn't been tampered.
:return: the CdnFile result.
"""
if self.cdn_file_hashes:
cdn_hash = self.cdn_file_hashes.pop(0)
cdn_file = self.client(GetCdn... |
Parses the given HTML message and returns its stripped representation plus a list of the MessageEntity s that were found. | def parse(html):
"""
Parses the given HTML message and returns its stripped representation
plus a list of the MessageEntity's that were found.
:param message: the message with HTML to be parsed.
:return: a tuple consisting of (clean message, [message entities]).
"""
if not html:
ret... |
Performs the reverse operation to. parse () effectively returning HTML given a normal text and its MessageEntity s. | def unparse(text, entities):
"""
Performs the reverse operation to .parse(), effectively returning HTML
given a normal text and its MessageEntity's.
:param text: the text to be reconverted into HTML.
:param entities: the MessageEntity's applied to the text.
:return: a HTML representation of the... |
The bytes data for: tl: KeyboardButtonCallback objects. | def data(self):
"""The ``bytes`` data for :tl:`KeyboardButtonCallback` objects."""
if isinstance(self.button, types.KeyboardButtonCallback):
return self.button.data |
The query str for: tl: KeyboardButtonSwitchInline objects. | def inline_query(self):
"""The query ``str`` for :tl:`KeyboardButtonSwitchInline` objects."""
if isinstance(self.button, types.KeyboardButtonSwitchInline):
return self.button.query |
The url str for: tl: KeyboardButtonUrl objects. | def url(self):
"""The url ``str`` for :tl:`KeyboardButtonUrl` objects."""
if isinstance(self.button, types.KeyboardButtonUrl):
return self.button.url |
Emulates the behaviour of clicking this button. | async def click(self):
"""
Emulates the behaviour of clicking this button.
If it's a normal :tl:`KeyboardButton` with text, a message will be
sent, and the sent `telethon.tl.custom.message.Message` returned.
If it's an inline :tl:`KeyboardButtonCallback` with text and data,
... |
Helper util to turn the input chat or chats into a set of IDs. | async def _into_id_set(client, chats):
"""Helper util to turn the input chat or chats into a set of IDs."""
if chats is None:
return None
if not utils.is_list_like(chats):
chats = (chats,)
result = set()
for chat in chats:
if isinstance(chat, int):
if chat < 0:
... |
Decorator to rename cls. Event Event as cls. Event | def name_inner_event(cls):
"""Decorator to rename cls.Event 'Event' as 'cls.Event'"""
if hasattr(cls, 'Event'):
cls.Event._event_name = '{}.Event'.format(cls.__name__)
else:
warnings.warn('Class {} does not have a inner Event'.format(cls))
return cls |
Helper method to allow event builders to be resolved before usage | async def resolve(self, client):
"""Helper method to allow event builders to be resolved before usage"""
if self.resolved:
return
if not self._resolve_lock:
self._resolve_lock = asyncio.Lock(loop=client.loop)
async with self._resolve_lock:
if not sel... |
If the ID of event. _chat_peer isn t in the chats set ( or it is but the set is a blacklist ) returns None otherwise the event. | def filter(self, event):
"""
If the ID of ``event._chat_peer`` isn't in the chats set (or it is
but the set is a blacklist) returns ``None``, otherwise the event.
The events must have been resolved before this can be called.
"""
if not self.resolved:
return N... |
Returns ( entity input_entity ) for the given entity ID. | def _get_entity_pair(self, entity_id):
"""
Returns ``(entity, input_entity)`` for the given entity ID.
"""
entity = self._entities.get(entity_id)
try:
input_entity = utils.get_input_peer(entity)
except TypeError:
try:
input_entity =... |
Must load all the entities it needs from cache and return False if it could not find all of them. | def _load_entities(self):
"""
Must load all the entities it needs from cache, and
return ``False`` if it could not find all of them.
"""
if not self._chat_peer:
return True # Nothing to load (e.g. MessageDeleted)
self._chat, self._input_chat = self._get_enti... |
Get the difference for this channel_id if any then load entities. | async def _get_difference(self, channel_id, pts_date):
"""
Get the difference for this `channel_id` if any, then load entities.
Calls :tl:`updates.getDifference`, which fills the entities cache
(always done by `__call__`) and lets us know about the full entities.
"""
# F... |
Returns chat but will make an API call to find the chat unless it s already cached. | async def get_chat(self):
"""
Returns `chat`, but will make an API call to find the
chat unless it's already cached.
"""
# See `get_sender` for information about 'min'.
if (self._chat is None or getattr(self._chat, 'min', None))\
and await self.get_input_c... |
This: tl: InputPeer is the input version of the chat where the message was sent. Similarly to input_sender this doesn t have things like username or similar but still useful in some cases. | def input_chat(self):
"""
This :tl:`InputPeer` is the input version of the chat where the
message was sent. Similarly to `input_sender`, this doesn't have
things like username or similar, but still useful in some cases.
Note that this might not be available if the library doesn'... |
Returns input_chat but will make an API call to find the input chat unless it s already cached. | async def get_input_chat(self):
"""
Returns `input_chat`, but will make an API call to find the
input chat unless it's already cached.
"""
if self.input_chat is None and self.chat_id:
try:
# The chat may be recent, look in dialogs
targe... |
True if the message was sent on a group or megagroup. | def is_group(self):
"""True if the message was sent on a group or megagroup."""
if self._broadcast is None and self.chat:
self._broadcast = getattr(self.chat, 'broadcast', None)
return (
isinstance(self._chat_peer, (types.PeerChat, types.PeerChannel))
and not... |
Generates a random long integer ( 8 bytes ) which is optionally signed | def generate_random_long(signed=True):
"""Generates a random long integer (8 bytes), which is optionally signed"""
return int.from_bytes(os.urandom(8), signed=signed, byteorder='little') |
Ensures that the parent directory exists | def ensure_parent_dir_exists(file_path):
"""Ensures that the parent directory exists"""
parent = os.path.dirname(file_path)
if parent:
os.makedirs(parent, exist_ok=True) |
Strips whitespace from the given text modifying the provided entities. | def strip_text(text, entities):
"""
Strips whitespace from the given text modifying the provided entities.
This assumes that there are no overlapping entities, that their length
is greater or equal to one, and that their length is not out of bounds.
"""
if not entities:
return text.stri... |
Helper to cancel one or more tasks gracefully logging exceptions. | async def _cancel(log, **tasks):
"""
Helper to cancel one or more tasks gracefully, logging exceptions.
"""
for name, task in tasks.items():
if not task:
continue
task.cancel()
try:
await task
except asyncio.CancelledError:
pass
... |
Helps to cut boilerplate on async context managers that offer synchronous variants. | def _sync_enter(self):
"""
Helps to cut boilerplate on async context
managers that offer synchronous variants.
"""
if hasattr(self, 'loop'):
loop = self.loop
else:
loop = self._client.loop
if loop.is_running():
raise RuntimeError(
'You must use "async wit... |
Generates the key data corresponding to the given nonce | def generate_key_data_from_nonce(server_nonce, new_nonce):
"""Generates the key data corresponding to the given nonce"""
server_nonce = server_nonce.to_bytes(16, 'little', signed=True)
new_nonce = new_nonce.to_bytes(32, 'little', signed=True)
hash1 = sha1(new_nonce + server_nonce).digest()
hash2 = s... |
Writes a string into the source code applying indentation if required | def write(self, string, *args, **kwargs):
"""Writes a string into the source code,
applying indentation if required
"""
if self.on_new_line:
self.on_new_line = False # We're not on a new line anymore
# If the string was not empty, indent; Else probably a new l... |
Writes a string into the source code _and_ appends a new line applying indentation if required | def writeln(self, string='', *args, **kwargs):
"""Writes a string into the source code _and_ appends a new line,
applying indentation if required
"""
self.write(string + '\n', *args, **kwargs)
self.on_new_line = True
# If we're writing a block, increment indent for th... |
Ends an indentation block leaving an empty line afterwards | def end_block(self):
"""Ends an indentation block, leaving an empty line afterwards"""
self.current_indent -= 1
# If we did not add a new line automatically yet, now it's the time!
if not self.auto_added_line:
self.writeln()
self.auto_added_line = True |
Writes the source code corresponding to the given TLObject by making use of the builder SourceBuilder. | def _write_source_code(tlobject, kind, builder, type_constructors):
"""
Writes the source code corresponding to the given TLObject
by making use of the ``builder`` `SourceBuilder`.
Additional information such as file path depth and
the ``Type: [Constructors]`` must be given for proper
importing... |
Writes the. __bytes__ () code for the given argument: param builder: The source code builder: param arg: The argument to write: param args: All the other arguments in TLObject same __bytes__. This is required to determine the flags value: param name: The name of the argument. Defaults to self. argname This argument is ... | def _write_arg_to_bytes(builder, arg, args, name=None):
"""
Writes the .__bytes__() code for the given argument
:param builder: The source code builder
:param arg: The argument to write
:param args: All the other arguments in TLObject same __bytes__.
This is required to determine th... |
Writes the read code for the given argument setting the arg. name variable to its read value. | def _write_arg_read_code(builder, arg, args, name):
"""
Writes the read code for the given argument, setting the
arg.name variable to its read value.
:param builder: The source code builder
:param arg: The argument to write
:param args: All the other arguments in TLObject same on_send.
... |
Converts a Telegram s RPC Error to a Python error. | def rpc_message_to_error(rpc_error, request):
"""
Converts a Telegram's RPC Error to a Python error.
:param rpc_error: the RpcError instance.
:param request: the request that caused this error.
:return: the RPCError as a Python exception that represents this error.
"""
# Try to get the erro... |
Returns True if the button belongs to an inline keyboard. | def _is_inline(button):
"""
Returns ``True`` if the button belongs to an inline keyboard.
"""
return isinstance(button, (
types.KeyboardButtonCallback,
types.KeyboardButtonSwitchInline,
types.KeyboardButtonUrl
)) |
Creates a new inline button. | def inline(text, data=None):
"""
Creates a new inline button.
If `data` is omitted, the given `text` will be used as `data`.
In any case `data` should be either ``bytes`` or ``str``.
Note that the given `data` must be less or equal to 64 bytes.
If more than 64 bytes are... |
Creates a new button to switch to inline query. | def switch_inline(text, query='', same_peer=False):
"""
Creates a new button to switch to inline query.
If `query` is given, it will be the default text to be used
when making the inline query.
If ``same_peer is True`` the inline query will directly be
set under the cur... |
Creates a new button with the given text. | def text(cls, text, *, resize=None, single_use=None, selective=None):
"""
Creates a new button with the given text.
Args:
resize (`bool`):
If present, the entire keyboard will be reconfigured to
be resized and be smaller if there are not many buttons.... |
Creates a new button that will request the user s location upon being clicked. | def request_location(cls, text, *,
resize=None, single_use=None, selective=None):
"""
Creates a new button that will request
the user's location upon being clicked.
``resize``, ``single_use`` and ``selective`` are documented in `text`.
"""
return... |
Creates a new button that will request the user s phone number upon being clicked. | def request_phone(cls, text, *,
resize=None, single_use=None, selective=None):
"""
Creates a new button that will request
the user's phone number upon being clicked.
``resize``, ``single_use`` and ``selective`` are documented in `text`.
"""
return c... |
Safe Print ( handle UnicodeEncodeErrors on some terminals ) | def sprint(string, *args, **kwargs):
"""Safe Print (handle UnicodeEncodeErrors on some terminals)"""
try:
print(string, *args, **kwargs)
except UnicodeEncodeError:
string = string.encode('utf-8', errors='ignore')\
.decode('ascii', errors='ignore')
print(string,... |
Helper function to print titles to the console more nicely | def print_title(title):
"""Helper function to print titles to the console more nicely"""
sprint('\n')
sprint('=={}=='.format('=' * len(title)))
sprint('= {} ='.format(title))
sprint('=={}=='.format('=' * len(title))) |
Python s input () is blocking which means the event loop we set above can t be running while we re blocking there. This method will let the loop run while we wait for input. | async def async_input(prompt):
"""
Python's ``input()`` is blocking, which means the event loop we set
above can't be running while we're blocking there. This method will
let the loop run while we wait for input.
"""
print(prompt, end='', flush=True)
return (await loop.run_in_executor(None, ... |
Main loop of the TelegramClient will wait for user action | async def run(self):
"""Main loop of the TelegramClient, will wait for user action"""
# Once everything is ready, we can add an event handler.
#
# Events are an abstraction over Telegram's "Updates" and
# are much easier to use.
self.add_event_handler(self.message_handle... |
Sends the file located at path to the desired entity as a photo | async def send_photo(self, path, entity):
"""Sends the file located at path to the desired entity as a photo"""
await self.send_file(
entity, path,
progress_callback=self.upload_progress_callback
)
print('Photo sent!') |
Sends the file located at path to the desired entity as a document | async def send_document(self, path, entity):
"""Sends the file located at path to the desired entity as a document"""
await self.send_file(
entity, path,
force_document=True,
progress_callback=self.upload_progress_callback
)
print('Document sent!') |
Given a message ID finds the media this message contained and downloads it. | async def download_media_by_id(self, media_id):
"""Given a message ID, finds the media this message contained and
downloads it.
"""
try:
msg = self.found_media[int(media_id)]
except (ValueError, KeyError):
# ValueError when parsing, KeyError when access... |
Callback method for received events. NewMessage | async def message_handler(self, event):
"""Callback method for received events.NewMessage"""
# Note that message_handler is called when a Telegram update occurs
# and an event is created. Telegram may not always send information
# about the ``.sender`` or the ``.chat``, so if you *reall... |
ClassName - > class_name. html. | def _get_file_name(tlobject):
"""``ClassName -> class_name.html``."""
name = tlobject.name if isinstance(tlobject, TLObject) else tlobject
# Courtesy of http://stackoverflow.com/a/1176023/4759433
s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', name)
result = re.sub('([a-z0-9])([A-Z])', r'\1_\2', s1).lower... |
TLObject - > from... import.... | def get_import_code(tlobject):
"""``TLObject -> from ... import ...``."""
kind = 'functions' if tlobject.is_function else 'types'
ns = '.' + tlobject.namespace if tlobject.namespace else ''
return 'from telethon.tl.{}{} import {}'\
.format(kind, ns, tlobject.class_name) |
Creates and returns the path for the given TLObject at root. | def _get_path_for(root, tlobject):
"""Creates and returns the path for the given TLObject at root."""
out_dir = root / ('methods' if tlobject.is_function else 'constructors')
if tlobject.namespace:
out_dir /= tlobject.namespace
return out_dir / _get_file_name(tlobject) |
Similar to _get_path_for but for only type names. | def _get_path_for_type(type_):
"""Similar to `_get_path_for` but for only type names."""
if type_.lower() in CORE_TYPES:
return Path('index.html#%s' % type_.lower())
elif '.' in type_:
namespace, name = type_.split('.')
return Path('types', namespace, _get_file_name(name))
else:
... |
Finds the <title > for the given HTML file or ( Unknown ). | def _find_title(html_file):
"""Finds the <title> for the given HTML file, or (Unknown)."""
# TODO Is it necessary to read files like this?
with html_file.open() as f:
for line in f:
if '<title>' in line:
# + 7 to skip len('<title>')
return line[line.index(... |
Builds the menu used for the current DocumentWriter. | def _build_menu(docs):
"""
Builds the menu used for the current ``DocumentWriter``.
"""
paths = []
current = docs.filename
while current != docs.root:
current = current.parent
paths.append(current)
for path in reversed(paths):
docs.add_menu(path.stem.title(), link=p... |
Generates the index file for the specified folder | def _generate_index(root, folder, paths,
bots_index=False, bots_index_paths=()):
"""Generates the index file for the specified folder"""
# Determine the namespaces listed here (as sub folders)
# and the files (.html files) that we should link to
namespaces = []
files = []
IND... |
Generates a proper description for the given argument. | def _get_description(arg):
"""Generates a proper description for the given argument."""
desc = []
otherwise = False
if arg.can_be_inferred:
desc.append('If left unspecified, it will be inferred automatically.')
otherwise = True
elif arg.is_flag:
desc.append('This argument def... |
Copies the src file into dst applying the replacements dict | def _copy_replace(src, dst, replacements):
"""Copies the src file into dst applying the replacements dict"""
with src.open() as infile, dst.open('w') as outfile:
outfile.write(re.sub(
'|'.join(re.escape(k) for k in replacements),
lambda m: str(replacements[m.group(0)]),
... |
Generates the documentation HTML files from from scheme. tl to/ methods and/ constructors etc. | def _write_html_pages(root, tlobjects, methods, layer, input_res):
"""
Generates the documentation HTML files from from ``scheme.tl``
to ``/methods`` and ``/constructors``, etc.
"""
# Save 'Type: [Constructors]' for use in both:
# * Seeing the return type or constructors belonging to the same ty... |
Pre - create the required directory structure in output_dir for the input objects. | def _create_structure(tlobjects, output_dir):
"""
Pre-create the required directory structure
in `output_dir` for the input objects.
"""
types_ns = set()
method_ns = set()
for obj in tlobjects:
if obj.namespace:
if obj.is_function:
method_ns.add(obj.namesp... |
This method is trying to establish connection with one of the zookeeper nodes. Somehow strategy fail earlier and retry more often works way better comparing to the original strategy try to connect with specified timeout. Since we want to try connect to zookeeper more often ( with the smaller connect_timeout ) he have t... | def create_connection(self, *args, **kwargs):
"""This method is trying to establish connection with one of the zookeeper nodes.
Somehow strategy "fail earlier and retry more often" works way better comparing to
the original strategy "try to connect with specified timeout".
Since... |
Python3 raises ValueError if socket is closed because fd == - 1 | def select(self, *args, **kwargs):
"""Python3 raises `ValueError` if socket is closed, because fd == -1"""
try:
return super(PatroniSequentialThreadingHandler, self).select(*args, **kwargs)
except ValueError as e:
raise select.error(9, str(e)) |
Kazoo is using Ping s to determine health of connection to zookeeper. If there is no response on Ping after Ping interval ( 1/ 2 from read_timeout ) it will consider current connection dead and try to connect to another node. Without this magic it was taking up to 2/ 3 from session timeout ( ttl ) to figure out that co... | def _kazoo_connect(self, host, port):
"""Kazoo is using Ping's to determine health of connection to zookeeper. If there is no
response on Ping after Ping interval (1/2 from read_timeout) it will consider current
connection dead and try to connect to another node. Without this "magic" it was taki... |
It is not possible to change ttl ( session_timeout ) in zookeeper without destroying old session and creating the new one. This method returns !True if session_timeout has been changed ( restart () has been called ). | def set_ttl(self, ttl):
"""It is not possible to change ttl (session_timeout) in zookeeper without
destroying old session and creating the new one. This method returns `!True`
if session_timeout has been changed (`restart()` has been called)."""
if self._client._session_timeout != ttl:
... |
Translate scope name to service name which can be used in dns. | def service_name_from_scope_name(scope_name):
"""Translate scope name to service name which can be used in dns.
230 = 253 - len('replica.') - len('.service.consul')
"""
def replace_char(match):
c = match.group(0)
return '-' if c in '. _' else "u{:04d}".format(ord(c))
service_name ... |
: returns: !True if it had to create new session | def _do_refresh_session(self):
""":returns: `!True` if it had to create new session"""
if self._session and self._last_session_refresh + self._loop_wait > time.time():
return False
if self._session:
try:
self._client.session.renew(self._session)
... |
Reads and parses postmaster. pid from the data directory | def _read_postmaster_pidfile(data_dir):
"""Reads and parses postmaster.pid from the data directory
:returns dictionary of values if successful, empty dictionary otherwise
"""
pid_line_names = ['pid', 'data_dir', 'start_time', 'port', 'socket_dir', 'listen_addr', 'shmem_key']
try... |
Signal postmaster process to stop | def signal_stop(self, mode):
"""Signal postmaster process to stop
:returns None if signaled, True if process is already gone, False if error
"""
if self.is_single_user:
logger.warning("Cannot stop server; single-user server is running (PID: {0})".format(self.pid))
... |
>>> repr_size ( 1000 ) 1000 Bytes >>> repr_size ( 8257332324597 ) 7. 5 TiB | def repr_size(n_bytes):
"""
>>> repr_size(1000)
'1000 Bytes'
>>> repr_size(8257332324597)
'7.5 TiB'
"""
if n_bytes < 1024:
return '{0} Bytes'.format(n_bytes)
i = -1
while n_bytes > 1023:
n_bytes /= 1024.0
i += 1
return '{0} {1}iB'.format(round(n_bytes, 1),... |
>>> size_as_bytes ( 7. 5 T ) 8246337208320 | def size_as_bytes(size_, prefix):
"""
>>> size_as_bytes(7.5, 'T')
8246337208320
"""
prefix = prefix.upper()
assert prefix in si_prefixes
exponent = si_prefixes.index(prefix) + 1
return int(size_ * (1024.0 ** exponent)) |
Creates a new replica using WAL - E | def run(self):
"""
Creates a new replica using WAL-E
Returns
-------
ExitCode
0 = Success
1 = Error, try again
2 = Error, don't try again
"""
if self.init_error:
logger.error('init error: %r did not exist at initia... |
determine whether it makes sense to use S3 and not pg_basebackup | def should_use_s3_to_create_replica(self):
""" determine whether it makes sense to use S3 and not pg_basebackup """
threshold_megabytes = self.wal_e.threshold_mb
threshold_percent = self.wal_e.threshold_pct
try:
cmd = self.wal_e.cmd + ['backup-list', '--detail', 'LATEST']
... |
>>> len ( list ( watching ( True 1 0 ))) 1 >>> len ( list ( watching ( True 1 1 ))) 2 >>> len ( list ( watching ( True None 0 ))) 1 | def watching(w, watch, max_count=None, clear=True):
"""
>>> len(list(watching(True, 1, 0)))
1
>>> len(list(watching(True, 1, 1)))
2
>>> len(list(watching(True, None, 0)))
1
"""
if w and not watch:
watch = 2
if watch and clear:
click.clear()
yield 0
if ma... |
We want to trigger a failover or switchover for the specified cluster name. | def _do_failover_or_switchover(obj, action, cluster_name, master, candidate, force, scheduled=None):
"""
We want to trigger a failover or switchover for the specified cluster name.
We verify that the cluster name, master name and candidate name are correct.
If so, we trigger an action and k... |
Rip - off of the ha. touch_member without inter - class dependencies | def touch_member(config, dcs):
''' Rip-off of the ha.touch_member without inter-class dependencies '''
p = Postgresql(config['postgresql'])
p.set_state('running')
p.set_role('master')
def restapi_connection_string(config):
protocol = 'https' if config.get('certfile') else 'http'
con... |
fill - in some basic configuration parameters if config file is not set | def set_defaults(config, cluster_name):
"""fill-in some basic configuration parameters if config file is not set """
config['postgresql'].setdefault('name', cluster_name)
config['postgresql'].setdefault('scope', cluster_name)
config['postgresql'].setdefault('listen', '127.0.0.1')
config['postgresql'... |
Creates a temporary file with specified contents that persists for the context. | def temporary_file(contents, suffix='', prefix='tmp'):
"""Creates a temporary file with specified contents that persists for the context.
:param contents: binary string that will be written to the file.
:param prefix: will be prefixed to the filename.
:param suffix: will be appended to the filename.
... |
Shows a diff between two strings. | def show_diff(before_editing, after_editing):
"""Shows a diff between two strings.
If the output is to a tty the diff will be colored. Inputs are expected to be unicode strings.
"""
def listify(string):
return [l+'\n' for l in string.rstrip('\n').split('\n')]
unified_diff = difflib.unified... |
Formats configuration as YAML for human consumption. | def format_config_for_editing(data):
"""Formats configuration as YAML for human consumption.
:param data: configuration as nested dictionaries
:returns unicode YAML of the configuration"""
return yaml.safe_dump(data, default_flow_style=False, encoding=None, allow_unicode=True) |
Applies config changes specified as a list of key - value pairs. | def apply_config_changes(before_editing, data, kvpairs):
"""Applies config changes specified as a list of key-value pairs.
Keys are interpreted as dotted paths into the configuration data structure. Except for paths beginning with
`postgresql.parameters` where rest of the path is used directly to allow for... |
Applies changes from a YAML file to configuration | def apply_yaml_file(data, filename):
"""Applies changes from a YAML file to configuration
:param data: configuration datastructure
:param filename: name of the YAML file, - is taken to mean standard input
:returns tuple of human readable and parsed datastructure after changes
"""
changed_data =... |
Starts editor command to edit configuration in human readable format | def invoke_editor(before_editing, cluster_name):
"""Starts editor command to edit configuration in human readable format
:param before_editing: human representation before editing
:returns tuple of human readable and parsed datastructure after changes
"""
editor_cmd = os.environ.get('EDITOR')
i... |
set tags carrying the cluster name instance role and instance id for the EBS storage | def _tag_ebs(self, conn, role):
""" set tags, carrying the cluster name, instance role and instance id for the EBS storage """
tags = {'Name': 'spilo_' + self.cluster_name, 'Role': role, 'Instance': self.instance_id}
volumes = conn.get_all_volumes(filters={'attachment.instance-id': self.instance... |
tag the current EC2 instance with a cluster role | def _tag_ec2(self, conn, role):
""" tag the current EC2 instance with a cluster role """
tags = {'Role': role}
conn.create_tags([self.instance_id], tags) |
Returns reason why this node can t promote or None if everything is ok. | def failover_limitation(self):
"""Returns reason why this node can't promote or None if everything is ok."""
if not self.reachable:
return 'not reachable'
if self.tags.get('nofailover', False):
return 'not allowed to promote'
if self.watchdog_failed:
r... |
Return configuration tags merged with dynamically applied tags. | def get_effective_tags(self):
"""Return configuration tags merged with dynamically applied tags."""
tags = self.patroni.tags.copy()
# _disable_sync could be modified concurrently, but we don't care as attribute get and set are atomic.
if self._disable_sync > 0:
tags['nosync']... |
If we found standby key in the configuration we need to bootstrap not a real master but a standby leader that will take base backup from a remote master and start follow it. | def bootstrap_standby_leader(self):
""" If we found 'standby' key in the configuration, we need to bootstrap
not a real master, but a 'standby leader', that will take base backup
from a remote master and start follow it.
"""
clone_source = self.get_remote_master()
... |
Process synchronous standby beahvior. | def process_sync_replication(self):
"""Process synchronous standby beahvior.
Synchronous standbys are registered in two places postgresql.conf and DCS. The order of updating them must
be right. The invariant that should be kept is that if a node is master and sync_standby is set in DCS,
... |
Runs specified action while trying to make sure that the node is not assigned synchronous standby status. | def while_not_sync_standby(self, func):
"""Runs specified action while trying to make sure that the node is not assigned synchronous standby status.
Tags us as not allowed to be a sync standby as we are going to go away, if we currently are wait for
leader to notice and pick an alternative one ... |
This function perform http get request on member. api_url and fetches its status: returns: _MemberStatus object | def fetch_node_status(member):
"""This function perform http get request on member.api_url and fetches its status
:returns: `_MemberStatus` object
"""
try:
response = requests.get(member.api_url, timeout=2, verify=False)
logger.info('Got response from %s %s: %s',... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.