partition
stringclasses
3 values
func_name
stringlengths
1
134
docstring
stringlengths
1
46.9k
path
stringlengths
4
223
original_string
stringlengths
75
104k
code
stringlengths
75
104k
docstring_tokens
listlengths
1
1.97k
repo
stringlengths
7
55
language
stringclasses
1 value
url
stringlengths
87
315
code_tokens
listlengths
19
28.4k
sha
stringlengths
40
40
train
DocsWriter.write_head
Writes the head part for the generated document, with the given title and CSS
telethon_generator/docswriter.py
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=...
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=...
[ "Writes", "the", "head", "part", "for", "the", "generated", "document", "with", "the", "given", "title", "and", "CSS" ]
LonamiWebs/Telethon
python
https://github.com/LonamiWebs/Telethon/blob/1ead9757d366b58c1e0567cddb0196e20f1a445f/telethon_generator/docswriter.py#L42-L68
[ "def", "write_head", "(", "self", ",", "title", ",", "css_path", ",", "default_css", ")", ":", "self", ".", "title", "=", "title", "self", ".", "write", "(", "'''<!DOCTYPE html>\n<html>\n<head>\n <meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">\n ...
1ead9757d366b58c1e0567cddb0196e20f1a445f
train
DocsWriter.set_menu_separator
Sets the menu separator. Must be called before adding entries to the menu
telethon_generator/docswriter.py
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
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
[ "Sets", "the", "menu", "separator", ".", "Must", "be", "called", "before", "adding", "entries", "to", "the", "menu" ]
LonamiWebs/Telethon
python
https://github.com/LonamiWebs/Telethon/blob/1ead9757d366b58c1e0567cddb0196e20f1a445f/telethon_generator/docswriter.py#L70-L78
[ "def", "set_menu_separator", "(", "self", ",", "img", ")", ":", "if", "img", ":", "self", ".", "menu_separator_tag", "=", "'<img src=\"{}\" alt=\"/\" />'", ".", "format", "(", "self", ".", "_rel", "(", "img", ")", ")", "else", ":", "self", ".", "menu_separ...
1ead9757d366b58c1e0567cddb0196e20f1a445f
train
DocsWriter.add_menu
Adds a menu entry, will create it if it doesn't exist yet
telethon_generator/docswriter.py
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...
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...
[ "Adds", "a", "menu", "entry", "will", "create", "it", "if", "it", "doesn", "t", "exist", "yet" ]
LonamiWebs/Telethon
python
https://github.com/LonamiWebs/Telethon/blob/1ead9757d366b58c1e0567cddb0196e20f1a445f/telethon_generator/docswriter.py#L80-L99
[ "def", "add_menu", "(", "self", ",", "name", ",", "link", "=", "None", ")", ":", "if", "self", ".", "menu_began", ":", "if", "self", ".", "menu_separator_tag", ":", "self", ".", "write", "(", "self", ".", "menu_separator_tag", ")", "else", ":", "# Firs...
1ead9757d366b58c1e0567cddb0196e20f1a445f
train
DocsWriter.write_title
Writes a title header in the document body, with an optional depth level
telethon_generator/docswriter.py
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('...
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", "a", "title", "header", "in", "the", "document", "body", "with", "an", "optional", "depth", "level" ]
LonamiWebs/Telethon
python
https://github.com/LonamiWebs/Telethon/blob/1ead9757d366b58c1e0567cddb0196e20f1a445f/telethon_generator/docswriter.py#L107-L116
[ "def", "write_title", "(", "self", ",", "title", ",", "level", "=", "1", ",", "id", "=", "None", ")", ":", "if", "id", ":", "self", ".", "write", "(", "'<h{lv} id=\"{id}\">{title}</h{lv}>'", ",", "title", "=", "title", ",", "lv", "=", "level", ",", "...
1ead9757d366b58c1e0567cddb0196e20f1a445f
train
DocsWriter.write_code
Writes the code for the given 'tlobject' properly formatted with hyperlinks
telethon_generator/docswriter.py
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...
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...
[ "Writes", "the", "code", "for", "the", "given", "tlobject", "properly", "formatted", "with", "hyperlinks" ]
LonamiWebs/Telethon
python
https://github.com/LonamiWebs/Telethon/blob/1ead9757d366b58c1e0567cddb0196e20f1a445f/telethon_generator/docswriter.py#L118-L197
[ "def", "write_code", "(", "self", ",", "tlobject", ")", ":", "self", ".", "write", "(", "'<pre>---{}---\\n'", ",", "'functions'", "if", "tlobject", ".", "is_function", "else", "'types'", ")", "# Write the function or type and its ID", "if", "tlobject", ".", "names...
1ead9757d366b58c1e0567cddb0196e20f1a445f
train
DocsWriter.begin_table
Begins a table with the given 'column_count', required to automatically create the right amount of columns when adding items to the rows
telethon_generator/docswriter.py
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>')
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>')
[ "Begins", "a", "table", "with", "the", "given", "column_count", "required", "to", "automatically", "create", "the", "right", "amount", "of", "columns", "when", "adding", "items", "to", "the", "rows" ]
LonamiWebs/Telethon
python
https://github.com/LonamiWebs/Telethon/blob/1ead9757d366b58c1e0567cddb0196e20f1a445f/telethon_generator/docswriter.py#L199-L204
[ "def", "begin_table", "(", "self", ",", "column_count", ")", ":", "self", ".", "table_columns", "=", "column_count", "self", ".", "table_columns_left", "=", "0", "self", ".", "write", "(", "'<table>'", ")" ]
1ead9757d366b58c1e0567cddb0196e20f1a445f
train
DocsWriter.add_row
This will create a new row, or add text to the next column of the previously created, incomplete row, closing it if complete
telethon_generator/docswriter.py
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>') ...
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>') ...
[ "This", "will", "create", "a", "new", "row", "or", "add", "text", "to", "the", "next", "column", "of", "the", "previously", "created", "incomplete", "row", "closing", "it", "if", "complete" ]
LonamiWebs/Telethon
python
https://github.com/LonamiWebs/Telethon/blob/1ead9757d366b58c1e0567cddb0196e20f1a445f/telethon_generator/docswriter.py#L206-L236
[ "def", "add_row", "(", "self", ",", "text", ",", "link", "=", "None", ",", "bold", "=", "False", ",", "align", "=", "None", ")", ":", "if", "not", "self", ".", "table_columns_left", ":", "# Starting a new row", "self", ".", "write", "(", "'<tr>'", ")",...
1ead9757d366b58c1e0567cddb0196e20f1a445f
train
DocsWriter.write_copy_button
Writes a button with 'text' which can be used to copy 'text_to_copy' to clipboard when it's clicked.
telethon_generator/docswriter.py
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...
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...
[ "Writes", "a", "button", "with", "text", "which", "can", "be", "used", "to", "copy", "text_to_copy", "to", "clipboard", "when", "it", "s", "clicked", "." ]
LonamiWebs/Telethon
python
https://github.com/LonamiWebs/Telethon/blob/1ead9757d366b58c1e0567cddb0196e20f1a445f/telethon_generator/docswriter.py#L249-L254
[ "def", "write_copy_button", "(", "self", ",", "text", ",", "text_to_copy", ")", ":", "self", ".", "write_copy_script", "=", "True", "self", ".", "write", "(", "'<button onclick=\"cp(\\'{}\\');\">{}</button>'", ".", "format", "(", "text_to_copy", ",", "text", ")", ...
1ead9757d366b58c1e0567cddb0196e20f1a445f
train
DocsWriter.end_body
Ends the whole document. This should be called the last
telethon_generator/docswriter.py
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...
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...
[ "Ends", "the", "whole", "document", ".", "This", "should", "be", "called", "the", "last" ]
LonamiWebs/Telethon
python
https://github.com/LonamiWebs/Telethon/blob/1ead9757d366b58c1e0567cddb0196e20f1a445f/telethon_generator/docswriter.py#L263-L278
[ "def", "end_body", "(", "self", ")", ":", "if", "self", ".", "write_copy_script", ":", "self", ".", "write", "(", "'<textarea id=\"c\" class=\"invisible\"></textarea>'", "'<script>'", "'function cp(t){'", "'var c=document.getElementById(\"c\");'", "'c.value=t;'", "'c.select()...
1ead9757d366b58c1e0567cddb0196e20f1a445f
train
DocsWriter.write
Wrapper around handle.write
telethon_generator/docswriter.py
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)
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)
[ "Wrapper", "around", "handle", ".", "write" ]
LonamiWebs/Telethon
python
https://github.com/LonamiWebs/Telethon/blob/1ead9757d366b58c1e0567cddb0196e20f1a445f/telethon_generator/docswriter.py#L281-L286
[ "def", "write", "(", "self", ",", "s", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "args", "or", "kwargs", ":", "self", ".", "handle", ".", "write", "(", "s", ".", "format", "(", "*", "args", ",", "*", "*", "kwargs", ")", ")", ...
1ead9757d366b58c1e0567cddb0196e20f1a445f
train
ChatMethods.iter_participants
Iterator over the participants belonging to the specified chat. Args: entity (`entity`): The entity from which to retrieve the participants list. limit (`int`): Limits amount of participants fetched. search (`str`, optional): ...
telethon/client/chats.py
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...
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", "participants", "belonging", "to", "the", "specified", "chat", "." ]
LonamiWebs/Telethon
python
https://github.com/LonamiWebs/Telethon/blob/1ead9757d366b58c1e0567cddb0196e20f1a445f/telethon/client/chats.py#L277-L331
[ "def", "iter_participants", "(", "self", ",", "entity", ",", "limit", "=", "None", ",", "*", ",", "search", "=", "''", ",", "filter", "=", "None", ",", "aggressive", "=", "False", ")", ":", "return", "_ParticipantsIter", "(", "self", ",", "limit", ",",...
1ead9757d366b58c1e0567cddb0196e20f1a445f
train
ChatMethods.iter_admin_log
Iterator over the admin log for the specified channel. Note that you must be an administrator of it to use this method. If none of the filters are present (i.e. they all are ``None``), *all* event types will be returned. If at least one of them is ``True``, only those that are true wil...
telethon/client/chats.py
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...
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...
[ "Iterator", "over", "the", "admin", "log", "for", "the", "specified", "channel", "." ]
LonamiWebs/Telethon
python
https://github.com/LonamiWebs/Telethon/blob/1ead9757d366b58c1e0567cddb0196e20f1a445f/telethon/client/chats.py#L340-L454
[ "def", "iter_admin_log", "(", "self", ",", "entity", ",", "limit", "=", "None", ",", "*", ",", "max_id", "=", "0", ",", "min_id", "=", "0", ",", "search", "=", "None", ",", "admins", "=", "None", ",", "join", "=", "None", ",", "leave", "=", "None...
1ead9757d366b58c1e0567cddb0196e20f1a445f
train
ChatMethods.action
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 async with client.action(chat, 'typing'): await asyncio.sleep(2) ...
telethon/client/chats.py
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 ...
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 ...
[ "Returns", "a", "context", "-", "manager", "object", "to", "represent", "a", "chat", "action", "." ]
LonamiWebs/Telethon
python
https://github.com/LonamiWebs/Telethon/blob/1ead9757d366b58c1e0567cddb0196e20f1a445f/telethon/client/chats.py#L462-L544
[ "def", "action", "(", "self", ",", "entity", ",", "action", ",", "*", ",", "delay", "=", "4", ",", "auto_cancel", "=", "True", ")", ":", "if", "isinstance", "(", "action", ",", "str", ")", ":", "try", ":", "action", "=", "_ChatAction", ".", "_str_m...
1ead9757d366b58c1e0567cddb0196e20f1a445f
train
CdnDecrypter.prepare_decrypter
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 call. :return: (CdnDecrypter, first chunk file data)
telethon/crypto/cdndecrypter.py
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...
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...
[ "Prepares", "a", "new", "CDN", "decrypter", "." ]
LonamiWebs/Telethon
python
https://github.com/LonamiWebs/Telethon/blob/1ead9757d366b58c1e0567cddb0196e20f1a445f/telethon/crypto/cdndecrypter.py#L33-L74
[ "async", "def", "prepare_decrypter", "(", "client", ",", "cdn_client", ",", "cdn_redirect", ")", ":", "cdn_aes", "=", "AESModeCTR", "(", "key", "=", "cdn_redirect", ".", "encryption_key", ",", "# 12 first bytes of the IV..4 bytes of the offset (0, big endian)", "iv", "=...
1ead9757d366b58c1e0567cddb0196e20f1a445f
train
CdnDecrypter.get_file
Calls GetCdnFileRequest and decrypts its bytes. Also ensures that the file hasn't been tampered. :return: the CdnFile result.
telethon/crypto/cdndecrypter.py
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...
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...
[ "Calls", "GetCdnFileRequest", "and", "decrypts", "its", "bytes", ".", "Also", "ensures", "that", "the", "file", "hasn", "t", "been", "tampered", "." ]
LonamiWebs/Telethon
python
https://github.com/LonamiWebs/Telethon/blob/1ead9757d366b58c1e0567cddb0196e20f1a445f/telethon/crypto/cdndecrypter.py#L76-L93
[ "def", "get_file", "(", "self", ")", ":", "if", "self", ".", "cdn_file_hashes", ":", "cdn_hash", "=", "self", ".", "cdn_file_hashes", ".", "pop", "(", "0", ")", "cdn_file", "=", "self", ".", "client", "(", "GetCdnFileRequest", "(", "self", ".", "file_tok...
1ead9757d366b58c1e0567cddb0196e20f1a445f
train
parse
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]).
telethon/extensions/html.py
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...
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...
[ "Parses", "the", "given", "HTML", "message", "and", "returns", "its", "stripped", "representation", "plus", "a", "list", "of", "the", "MessageEntity", "s", "that", "were", "found", "." ]
LonamiWebs/Telethon
python
https://github.com/LonamiWebs/Telethon/blob/1ead9757d366b58c1e0567cddb0196e20f1a445f/telethon/extensions/html.py#L117-L131
[ "def", "parse", "(", "html", ")", ":", "if", "not", "html", ":", "return", "html", ",", "[", "]", "parser", "=", "HTMLToTelegramParser", "(", ")", "parser", ".", "feed", "(", "_add_surrogate", "(", "html", ")", ")", "text", "=", "helpers", ".", "stri...
1ead9757d366b58c1e0567cddb0196e20f1a445f
train
unparse
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 combination of both inputs.
telethon/extensions/html.py
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...
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...
[ "Performs", "the", "reverse", "operation", "to", ".", "parse", "()", "effectively", "returning", "HTML", "given", "a", "normal", "text", "and", "its", "MessageEntity", "s", "." ]
LonamiWebs/Telethon
python
https://github.com/LonamiWebs/Telethon/blob/1ead9757d366b58c1e0567cddb0196e20f1a445f/telethon/extensions/html.py#L134-L190
[ "def", "unparse", "(", "text", ",", "entities", ")", ":", "if", "not", "text", "or", "not", "entities", ":", "return", "text", "text", "=", "_add_surrogate", "(", "text", ")", "html", "=", "[", "]", "last_offset", "=", "0", "for", "entity", "in", "en...
1ead9757d366b58c1e0567cddb0196e20f1a445f
train
MessageButton.data
The ``bytes`` data for :tl:`KeyboardButtonCallback` objects.
telethon/tl/custom/messagebutton.py
def data(self): """The ``bytes`` data for :tl:`KeyboardButtonCallback` objects.""" if isinstance(self.button, types.KeyboardButtonCallback): return self.button.data
def data(self): """The ``bytes`` data for :tl:`KeyboardButtonCallback` objects.""" if isinstance(self.button, types.KeyboardButtonCallback): return self.button.data
[ "The", "bytes", "data", "for", ":", "tl", ":", "KeyboardButtonCallback", "objects", "." ]
LonamiWebs/Telethon
python
https://github.com/LonamiWebs/Telethon/blob/1ead9757d366b58c1e0567cddb0196e20f1a445f/telethon/tl/custom/messagebutton.py#L45-L48
[ "def", "data", "(", "self", ")", ":", "if", "isinstance", "(", "self", ".", "button", ",", "types", ".", "KeyboardButtonCallback", ")", ":", "return", "self", ".", "button", ".", "data" ]
1ead9757d366b58c1e0567cddb0196e20f1a445f
train
MessageButton.inline_query
The query ``str`` for :tl:`KeyboardButtonSwitchInline` objects.
telethon/tl/custom/messagebutton.py
def inline_query(self): """The query ``str`` for :tl:`KeyboardButtonSwitchInline` objects.""" if isinstance(self.button, types.KeyboardButtonSwitchInline): return self.button.query
def inline_query(self): """The query ``str`` for :tl:`KeyboardButtonSwitchInline` objects.""" if isinstance(self.button, types.KeyboardButtonSwitchInline): return self.button.query
[ "The", "query", "str", "for", ":", "tl", ":", "KeyboardButtonSwitchInline", "objects", "." ]
LonamiWebs/Telethon
python
https://github.com/LonamiWebs/Telethon/blob/1ead9757d366b58c1e0567cddb0196e20f1a445f/telethon/tl/custom/messagebutton.py#L51-L54
[ "def", "inline_query", "(", "self", ")", ":", "if", "isinstance", "(", "self", ".", "button", ",", "types", ".", "KeyboardButtonSwitchInline", ")", ":", "return", "self", ".", "button", ".", "query" ]
1ead9757d366b58c1e0567cddb0196e20f1a445f
train
MessageButton.url
The url ``str`` for :tl:`KeyboardButtonUrl` objects.
telethon/tl/custom/messagebutton.py
def url(self): """The url ``str`` for :tl:`KeyboardButtonUrl` objects.""" if isinstance(self.button, types.KeyboardButtonUrl): return self.button.url
def url(self): """The url ``str`` for :tl:`KeyboardButtonUrl` objects.""" if isinstance(self.button, types.KeyboardButtonUrl): return self.button.url
[ "The", "url", "str", "for", ":", "tl", ":", "KeyboardButtonUrl", "objects", "." ]
LonamiWebs/Telethon
python
https://github.com/LonamiWebs/Telethon/blob/1ead9757d366b58c1e0567cddb0196e20f1a445f/telethon/tl/custom/messagebutton.py#L57-L60
[ "def", "url", "(", "self", ")", ":", "if", "isinstance", "(", "self", ".", "button", ",", "types", ".", "KeyboardButtonUrl", ")", ":", "return", "self", ".", "button", ".", "url" ]
1ead9757d366b58c1e0567cddb0196e20f1a445f
train
MessageButton.click
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, it will be "clicked" and the :tl:`BotC...
telethon/tl/custom/messagebutton.py
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, ...
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, ...
[ "Emulates", "the", "behaviour", "of", "clicking", "this", "button", "." ]
LonamiWebs/Telethon
python
https://github.com/LonamiWebs/Telethon/blob/1ead9757d366b58c1e0567cddb0196e20f1a445f/telethon/tl/custom/messagebutton.py#L62-L103
[ "async", "def", "click", "(", "self", ")", ":", "if", "isinstance", "(", "self", ".", "button", ",", "types", ".", "KeyboardButton", ")", ":", "return", "await", "self", ".", "_client", ".", "send_message", "(", "self", ".", "_chat", ",", "self", ".", ...
1ead9757d366b58c1e0567cddb0196e20f1a445f
train
_into_id_set
Helper util to turn the input chat or chats into a set of IDs.
telethon/events/common.py
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: ...
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: ...
[ "Helper", "util", "to", "turn", "the", "input", "chat", "or", "chats", "into", "a", "set", "of", "IDs", "." ]
LonamiWebs/Telethon
python
https://github.com/LonamiWebs/Telethon/blob/1ead9757d366b58c1e0567cddb0196e20f1a445f/telethon/events/common.py#L11-L39
[ "async", "def", "_into_id_set", "(", "client", ",", "chats", ")", ":", "if", "chats", "is", "None", ":", "return", "None", "if", "not", "utils", ".", "is_list_like", "(", "chats", ")", ":", "chats", "=", "(", "chats", ",", ")", "result", "=", "set", ...
1ead9757d366b58c1e0567cddb0196e20f1a445f
train
name_inner_event
Decorator to rename cls.Event 'Event' as 'cls.Event
telethon/events/common.py
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
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
[ "Decorator", "to", "rename", "cls", ".", "Event", "Event", "as", "cls", ".", "Event" ]
LonamiWebs/Telethon
python
https://github.com/LonamiWebs/Telethon/blob/1ead9757d366b58c1e0567cddb0196e20f1a445f/telethon/events/common.py#L242-L248
[ "def", "name_inner_event", "(", "cls", ")", ":", "if", "hasattr", "(", "cls", ",", "'Event'", ")", ":", "cls", ".", "Event", ".", "_event_name", "=", "'{}.Event'", ".", "format", "(", "cls", ".", "__name__", ")", "else", ":", "warnings", ".", "warn", ...
1ead9757d366b58c1e0567cddb0196e20f1a445f
train
EventBuilder.resolve
Helper method to allow event builders to be resolved before usage
telethon/events/common.py
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...
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...
[ "Helper", "method", "to", "allow", "event", "builders", "to", "be", "resolved", "before", "usage" ]
LonamiWebs/Telethon
python
https://github.com/LonamiWebs/Telethon/blob/1ead9757d366b58c1e0567cddb0196e20f1a445f/telethon/events/common.py#L83-L94
[ "async", "def", "resolve", "(", "self", ",", "client", ")", ":", "if", "self", ".", "resolved", ":", "return", "if", "not", "self", ".", "_resolve_lock", ":", "self", ".", "_resolve_lock", "=", "asyncio", ".", "Lock", "(", "loop", "=", "client", ".", ...
1ead9757d366b58c1e0567cddb0196e20f1a445f
train
EventBuilder.filter
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.
telethon/events/common.py
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...
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...
[ "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", "." ]
LonamiWebs/Telethon
python
https://github.com/LonamiWebs/Telethon/blob/1ead9757d366b58c1e0567cddb0196e20f1a445f/telethon/events/common.py#L101-L120
[ "def", "filter", "(", "self", ",", "event", ")", ":", "if", "not", "self", ".", "resolved", ":", "return", "None", "if", "self", ".", "chats", "is", "not", "None", ":", "# Note: the `event.chat_id` property checks if it's `None` for us", "inside", "=", "event", ...
1ead9757d366b58c1e0567cddb0196e20f1a445f
train
EventCommon._get_entity_pair
Returns ``(entity, input_entity)`` for the given entity ID.
telethon/events/common.py
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 =...
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 =...
[ "Returns", "(", "entity", "input_entity", ")", "for", "the", "given", "entity", "ID", "." ]
LonamiWebs/Telethon
python
https://github.com/LonamiWebs/Telethon/blob/1ead9757d366b58c1e0567cddb0196e20f1a445f/telethon/events/common.py#L152-L165
[ "def", "_get_entity_pair", "(", "self", ",", "entity_id", ")", ":", "entity", "=", "self", ".", "_entities", ".", "get", "(", "entity_id", ")", "try", ":", "input_entity", "=", "utils", ".", "get_input_peer", "(", "entity", ")", "except", "TypeError", ":",...
1ead9757d366b58c1e0567cddb0196e20f1a445f
train
EventCommon._load_entities
Must load all the entities it needs from cache, and return ``False`` if it could not find all of them.
telethon/events/common.py
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...
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...
[ "Must", "load", "all", "the", "entities", "it", "needs", "from", "cache", "and", "return", "False", "if", "it", "could", "not", "find", "all", "of", "them", "." ]
LonamiWebs/Telethon
python
https://github.com/LonamiWebs/Telethon/blob/1ead9757d366b58c1e0567cddb0196e20f1a445f/telethon/events/common.py#L167-L176
[ "def", "_load_entities", "(", "self", ")", ":", "if", "not", "self", ".", "_chat_peer", ":", "return", "True", "# Nothing to load (e.g. MessageDeleted)", "self", ".", "_chat", ",", "self", ".", "_input_chat", "=", "self", ".", "_get_entity_pair", "(", "self", ...
1ead9757d366b58c1e0567cddb0196e20f1a445f
train
EventCommon._get_difference
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.
telethon/events/common.py
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...
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...
[ "Get", "the", "difference", "for", "this", "channel_id", "if", "any", "then", "load", "entities", "." ]
LonamiWebs/Telethon
python
https://github.com/LonamiWebs/Telethon/blob/1ead9757d366b58c1e0567cddb0196e20f1a445f/telethon/events/common.py#L178-L221
[ "async", "def", "_get_difference", "(", "self", ",", "channel_id", ",", "pts_date", ")", ":", "# Fetch since the last known pts/date before this update arrived,", "# in order to fetch this update at full, including its entities.", "self", ".", "client", ".", "_log", "[", "__nam...
1ead9757d366b58c1e0567cddb0196e20f1a445f
train
ChatGetter.get_chat
Returns `chat`, but will make an API call to find the chat unless it's already cached.
telethon/tl/custom/chatgetter.py
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...
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...
[ "Returns", "chat", "but", "will", "make", "an", "API", "call", "to", "find", "the", "chat", "unless", "it", "s", "already", "cached", "." ]
LonamiWebs/Telethon
python
https://github.com/LonamiWebs/Telethon/blob/1ead9757d366b58c1e0567cddb0196e20f1a445f/telethon/tl/custom/chatgetter.py#L27-L40
[ "async", "def", "get_chat", "(", "self", ")", ":", "# See `get_sender` for information about 'min'.", "if", "(", "self", ".", "_chat", "is", "None", "or", "getattr", "(", "self", ".", "_chat", ",", "'min'", ",", "None", ")", ")", "and", "await", "self", "....
1ead9757d366b58c1e0567cddb0196e20f1a445f
train
ChatGetter.input_chat
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't have enough information availabl...
telethon/tl/custom/chatgetter.py
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'...
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'...
[ "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",...
LonamiWebs/Telethon
python
https://github.com/LonamiWebs/Telethon/blob/1ead9757d366b58c1e0567cddb0196e20f1a445f/telethon/tl/custom/chatgetter.py#L43-L58
[ "def", "input_chat", "(", "self", ")", ":", "if", "self", ".", "_input_chat", "is", "None", "and", "self", ".", "_chat_peer", ":", "try", ":", "self", ".", "_input_chat", "=", "self", ".", "_client", ".", "_entity_cache", "[", "self", ".", "_chat_peer", ...
1ead9757d366b58c1e0567cddb0196e20f1a445f
train
ChatGetter.get_input_chat
Returns `input_chat`, but will make an API call to find the input chat unless it's already cached.
telethon/tl/custom/chatgetter.py
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...
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...
[ "Returns", "input_chat", "but", "will", "make", "an", "API", "call", "to", "find", "the", "input", "chat", "unless", "it", "s", "already", "cached", "." ]
LonamiWebs/Telethon
python
https://github.com/LonamiWebs/Telethon/blob/1ead9757d366b58c1e0567cddb0196e20f1a445f/telethon/tl/custom/chatgetter.py#L60-L77
[ "async", "def", "get_input_chat", "(", "self", ")", ":", "if", "self", ".", "input_chat", "is", "None", "and", "self", ".", "chat_id", ":", "try", ":", "# The chat may be recent, look in dialogs", "target", "=", "self", ".", "chat_id", "async", "for", "d", "...
1ead9757d366b58c1e0567cddb0196e20f1a445f
train
ChatGetter.is_group
True if the message was sent on a group or megagroup.
telethon/tl/custom/chatgetter.py
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...
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...
[ "True", "if", "the", "message", "was", "sent", "on", "a", "group", "or", "megagroup", "." ]
LonamiWebs/Telethon
python
https://github.com/LonamiWebs/Telethon/blob/1ead9757d366b58c1e0567cddb0196e20f1a445f/telethon/tl/custom/chatgetter.py#L97-L105
[ "def", "is_group", "(", "self", ")", ":", "if", "self", ".", "_broadcast", "is", "None", "and", "self", ".", "chat", ":", "self", ".", "_broadcast", "=", "getattr", "(", "self", ".", "chat", ",", "'broadcast'", ",", "None", ")", "return", "(", "isins...
1ead9757d366b58c1e0567cddb0196e20f1a445f
train
generate_random_long
Generates a random long integer (8 bytes), which is optionally signed
telethon/helpers.py
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')
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')
[ "Generates", "a", "random", "long", "integer", "(", "8", "bytes", ")", "which", "is", "optionally", "signed" ]
LonamiWebs/Telethon
python
https://github.com/LonamiWebs/Telethon/blob/1ead9757d366b58c1e0567cddb0196e20f1a445f/telethon/helpers.py#L11-L13
[ "def", "generate_random_long", "(", "signed", "=", "True", ")", ":", "return", "int", ".", "from_bytes", "(", "os", ".", "urandom", "(", "8", ")", ",", "signed", "=", "signed", ",", "byteorder", "=", "'little'", ")" ]
1ead9757d366b58c1e0567cddb0196e20f1a445f
train
ensure_parent_dir_exists
Ensures that the parent directory exists
telethon/helpers.py
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)
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)
[ "Ensures", "that", "the", "parent", "directory", "exists" ]
LonamiWebs/Telethon
python
https://github.com/LonamiWebs/Telethon/blob/1ead9757d366b58c1e0567cddb0196e20f1a445f/telethon/helpers.py#L16-L20
[ "def", "ensure_parent_dir_exists", "(", "file_path", ")", ":", "parent", "=", "os", ".", "path", ".", "dirname", "(", "file_path", ")", "if", "parent", ":", "os", ".", "makedirs", "(", "parent", ",", "exist_ok", "=", "True", ")" ]
1ead9757d366b58c1e0567cddb0196e20f1a445f
train
strip_text
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.
telethon/helpers.py
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...
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...
[ "Strips", "whitespace", "from", "the", "given", "text", "modifying", "the", "provided", "entities", "." ]
LonamiWebs/Telethon
python
https://github.com/LonamiWebs/Telethon/blob/1ead9757d366b58c1e0567cddb0196e20f1a445f/telethon/helpers.py#L36-L73
[ "def", "strip_text", "(", "text", ",", "entities", ")", ":", "if", "not", "entities", ":", "return", "text", ".", "strip", "(", ")", "while", "text", "and", "text", "[", "-", "1", "]", ".", "isspace", "(", ")", ":", "e", "=", "entities", "[", "-"...
1ead9757d366b58c1e0567cddb0196e20f1a445f
train
_cancel
Helper to cancel one or more tasks gracefully, logging exceptions.
telethon/helpers.py
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 ...
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 ...
[ "Helper", "to", "cancel", "one", "or", "more", "tasks", "gracefully", "logging", "exceptions", "." ]
LonamiWebs/Telethon
python
https://github.com/LonamiWebs/Telethon/blob/1ead9757d366b58c1e0567cddb0196e20f1a445f/telethon/helpers.py#L89-L103
[ "async", "def", "_cancel", "(", "log", ",", "*", "*", "tasks", ")", ":", "for", "name", ",", "task", "in", "tasks", ".", "items", "(", ")", ":", "if", "not", "task", ":", "continue", "task", ".", "cancel", "(", ")", "try", ":", "await", "task", ...
1ead9757d366b58c1e0567cddb0196e20f1a445f
train
_sync_enter
Helps to cut boilerplate on async context managers that offer synchronous variants.
telethon/helpers.py
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...
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...
[ "Helps", "to", "cut", "boilerplate", "on", "async", "context", "managers", "that", "offer", "synchronous", "variants", "." ]
LonamiWebs/Telethon
python
https://github.com/LonamiWebs/Telethon/blob/1ead9757d366b58c1e0567cddb0196e20f1a445f/telethon/helpers.py#L106-L122
[ "def", "_sync_enter", "(", "self", ")", ":", "if", "hasattr", "(", "self", ",", "'loop'", ")", ":", "loop", "=", "self", ".", "loop", "else", ":", "loop", "=", "self", ".", "_client", ".", "loop", "if", "loop", ".", "is_running", "(", ")", ":", "...
1ead9757d366b58c1e0567cddb0196e20f1a445f
train
generate_key_data_from_nonce
Generates the key data corresponding to the given nonce
telethon/helpers.py
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...
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...
[ "Generates", "the", "key", "data", "corresponding", "to", "the", "given", "nonce" ]
LonamiWebs/Telethon
python
https://github.com/LonamiWebs/Telethon/blob/1ead9757d366b58c1e0567cddb0196e20f1a445f/telethon/helpers.py#L139-L149
[ "def", "generate_key_data_from_nonce", "(", "server_nonce", ",", "new_nonce", ")", ":", "server_nonce", "=", "server_nonce", ".", "to_bytes", "(", "16", ",", "'little'", ",", "signed", "=", "True", ")", "new_nonce", "=", "new_nonce", ".", "to_bytes", "(", "32"...
1ead9757d366b58c1e0567cddb0196e20f1a445f
train
SourceBuilder.write
Writes a string into the source code, applying indentation if required
telethon_generator/sourcebuilder.py
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...
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", "applying", "indentation", "if", "required" ]
LonamiWebs/Telethon
python
https://github.com/LonamiWebs/Telethon/blob/1ead9757d366b58c1e0567cddb0196e20f1a445f/telethon_generator/sourcebuilder.py#L19-L32
[ "def", "write", "(", "self", ",", "string", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "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 prob...
1ead9757d366b58c1e0567cddb0196e20f1a445f
train
SourceBuilder.writeln
Writes a string into the source code _and_ appends a new line, applying indentation if required
telethon_generator/sourcebuilder.py
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...
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...
[ "Writes", "a", "string", "into", "the", "source", "code", "_and_", "appends", "a", "new", "line", "applying", "indentation", "if", "required" ]
LonamiWebs/Telethon
python
https://github.com/LonamiWebs/Telethon/blob/1ead9757d366b58c1e0567cddb0196e20f1a445f/telethon_generator/sourcebuilder.py#L34-L46
[ "def", "writeln", "(", "self", ",", "string", "=", "''", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "self", ".", "write", "(", "string", "+", "'\\n'", ",", "*", "args", ",", "*", "*", "kwargs", ")", "self", ".", "on_new_line", "=", "T...
1ead9757d366b58c1e0567cddb0196e20f1a445f
train
SourceBuilder.end_block
Ends an indentation block, leaving an empty line afterwards
telethon_generator/sourcebuilder.py
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
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
[ "Ends", "an", "indentation", "block", "leaving", "an", "empty", "line", "afterwards" ]
LonamiWebs/Telethon
python
https://github.com/LonamiWebs/Telethon/blob/1ead9757d366b58c1e0567cddb0196e20f1a445f/telethon_generator/sourcebuilder.py#L48-L55
[ "def", "end_block", "(", "self", ")", ":", "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_...
1ead9757d366b58c1e0567cddb0196e20f1a445f
train
_write_source_code
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 and documentation strings.
telethon_generator/generators/tlobject.py
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...
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", "source", "code", "corresponding", "to", "the", "given", "TLObject", "by", "making", "use", "of", "the", "builder", "SourceBuilder", "." ]
LonamiWebs/Telethon
python
https://github.com/LonamiWebs/Telethon/blob/1ead9757d366b58c1e0567cddb0196e20f1a445f/telethon_generator/generators/tlobject.py#L168-L182
[ "def", "_write_source_code", "(", "tlobject", ",", "kind", ",", "builder", ",", "type_constructors", ")", ":", "_write_class_init", "(", "tlobject", ",", "kind", ",", "type_constructors", ",", "builder", ")", "_write_resolve", "(", "tlobject", ",", "builder", ")...
1ead9757d366b58c1e0567cddb0196e20f1a445f
train
_write_arg_to_bytes
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...
telethon_generator/generators/tlobject.py
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...
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", ".", "__bytes__", "()", "code", "for", "the", "given", "argument", ":", "param", "builder", ":", "The", "source", "code", "builder", ":", "param", "arg", ":", "The", "argument", "to", "write", ":", "param", "args", ":", "All", "the", "...
LonamiWebs/Telethon
python
https://github.com/LonamiWebs/Telethon/blob/1ead9757d366b58c1e0567cddb0196e20f1a445f/telethon_generator/generators/tlobject.py#L410-L527
[ "def", "_write_arg_to_bytes", "(", "builder", ",", "arg", ",", "args", ",", "name", "=", "None", ")", ":", "if", "arg", ".", "generic_definition", ":", "return", "# Do nothing, this only specifies a later type", "if", "name", "is", "None", ":", "name", "=", "'...
1ead9757d366b58c1e0567cddb0196e20f1a445f
train
_write_arg_read_code
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. This is required to determine the flags value :para...
telethon_generator/generators/tlobject.py
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. ...
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. ...
[ "Writes", "the", "read", "code", "for", "the", "given", "argument", "setting", "the", "arg", ".", "name", "variable", "to", "its", "read", "value", "." ]
LonamiWebs/Telethon
python
https://github.com/LonamiWebs/Telethon/blob/1ead9757d366b58c1e0567cddb0196e20f1a445f/telethon_generator/generators/tlobject.py#L530-L646
[ "def", "_write_arg_read_code", "(", "builder", ",", "arg", ",", "args", ",", "name", ")", ":", "if", "arg", ".", "generic_definition", ":", "return", "# Do nothing, this only specifies a later type", "# The argument may be a flag, only write that flag was given!", "was_flag",...
1ead9757d366b58c1e0567cddb0196e20f1a445f
train
rpc_message_to_error
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.
telethon/errors/__init__.py
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...
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...
[ "Converts", "a", "Telegram", "s", "RPC", "Error", "to", "a", "Python", "error", "." ]
LonamiWebs/Telethon
python
https://github.com/LonamiWebs/Telethon/blob/1ead9757d366b58c1e0567cddb0196e20f1a445f/telethon/errors/__init__.py#L18-L47
[ "def", "rpc_message_to_error", "(", "rpc_error", ",", "request", ")", ":", "# Try to get the error by direct look-up, otherwise regex", "cls", "=", "rpc_errors_dict", ".", "get", "(", "rpc_error", ".", "error_message", ",", "None", ")", "if", "cls", ":", "return", "...
1ead9757d366b58c1e0567cddb0196e20f1a445f
train
Button._is_inline
Returns ``True`` if the button belongs to an inline keyboard.
telethon/tl/custom/button.py
def _is_inline(button): """ Returns ``True`` if the button belongs to an inline keyboard. """ return isinstance(button, ( types.KeyboardButtonCallback, types.KeyboardButtonSwitchInline, types.KeyboardButtonUrl ))
def _is_inline(button): """ Returns ``True`` if the button belongs to an inline keyboard. """ return isinstance(button, ( types.KeyboardButtonCallback, types.KeyboardButtonSwitchInline, types.KeyboardButtonUrl ))
[ "Returns", "True", "if", "the", "button", "belongs", "to", "an", "inline", "keyboard", "." ]
LonamiWebs/Telethon
python
https://github.com/LonamiWebs/Telethon/blob/1ead9757d366b58c1e0567cddb0196e20f1a445f/telethon/tl/custom/button.py#L44-L52
[ "def", "_is_inline", "(", "button", ")", ":", "return", "isinstance", "(", "button", ",", "(", "types", ".", "KeyboardButtonCallback", ",", "types", ".", "KeyboardButtonSwitchInline", ",", "types", ".", "KeyboardButtonUrl", ")", ")" ]
1ead9757d366b58c1e0567cddb0196e20f1a445f
train
Button.inline
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 passed as data, ``ValueError`` is raised.
telethon/tl/custom/button.py
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...
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", "inline", "button", "." ]
LonamiWebs/Telethon
python
https://github.com/LonamiWebs/Telethon/blob/1ead9757d366b58c1e0567cddb0196e20f1a445f/telethon/tl/custom/button.py#L55-L73
[ "def", "inline", "(", "text", ",", "data", "=", "None", ")", ":", "if", "not", "data", ":", "data", "=", "text", ".", "encode", "(", "'utf-8'", ")", "elif", "not", "isinstance", "(", "data", ",", "(", "bytes", ",", "bytearray", ",", "memoryview", "...
1ead9757d366b58c1e0567cddb0196e20f1a445f
train
Button.switch_inline
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 currently opened chat. Otherwise, the user will have to select a di...
telethon/tl/custom/button.py
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...
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", "to", "switch", "to", "inline", "query", "." ]
LonamiWebs/Telethon
python
https://github.com/LonamiWebs/Telethon/blob/1ead9757d366b58c1e0567cddb0196e20f1a445f/telethon/tl/custom/button.py#L76-L87
[ "def", "switch_inline", "(", "text", ",", "query", "=", "''", ",", "same_peer", "=", "False", ")", ":", "return", "types", ".", "KeyboardButtonSwitchInline", "(", "text", ",", "query", ",", "same_peer", ")" ]
1ead9757d366b58c1e0567cddb0196e20f1a445f
train
Button.text
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. single_use (`bool`): If present, the entire keyboard will be...
telethon/tl/custom/button.py
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....
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", "with", "the", "given", "text", "." ]
LonamiWebs/Telethon
python
https://github.com/LonamiWebs/Telethon/blob/1ead9757d366b58c1e0567cddb0196e20f1a445f/telethon/tl/custom/button.py#L99-L119
[ "def", "text", "(", "cls", ",", "text", ",", "*", ",", "resize", "=", "None", ",", "single_use", "=", "None", ",", "selective", "=", "None", ")", ":", "return", "cls", "(", "types", ".", "KeyboardButton", "(", "text", ")", ",", "resize", "=", "resi...
1ead9757d366b58c1e0567cddb0196e20f1a445f
train
Button.request_location
Creates a new button that will request the user's location upon being clicked. ``resize``, ``single_use`` and ``selective`` are documented in `text`.
telethon/tl/custom/button.py
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...
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", "location", "upon", "being", "clicked", "." ]
LonamiWebs/Telethon
python
https://github.com/LonamiWebs/Telethon/blob/1ead9757d366b58c1e0567cddb0196e20f1a445f/telethon/tl/custom/button.py#L122-L131
[ "def", "request_location", "(", "cls", ",", "text", ",", "*", ",", "resize", "=", "None", ",", "single_use", "=", "None", ",", "selective", "=", "None", ")", ":", "return", "cls", "(", "types", ".", "KeyboardButtonRequestGeoLocation", "(", "text", ")", "...
1ead9757d366b58c1e0567cddb0196e20f1a445f
train
Button.request_phone
Creates a new button that will request the user's phone number upon being clicked. ``resize``, ``single_use`` and ``selective`` are documented in `text`.
telethon/tl/custom/button.py
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...
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...
[ "Creates", "a", "new", "button", "that", "will", "request", "the", "user", "s", "phone", "number", "upon", "being", "clicked", "." ]
LonamiWebs/Telethon
python
https://github.com/LonamiWebs/Telethon/blob/1ead9757d366b58c1e0567cddb0196e20f1a445f/telethon/tl/custom/button.py#L134-L143
[ "def", "request_phone", "(", "cls", ",", "text", ",", "*", ",", "resize", "=", "None", ",", "single_use", "=", "None", ",", "selective", "=", "None", ")", ":", "return", "cls", "(", "types", ".", "KeyboardButtonRequestPhone", "(", "text", ")", ",", "re...
1ead9757d366b58c1e0567cddb0196e20f1a445f
train
sprint
Safe Print (handle UnicodeEncodeErrors on some terminals)
telethon_examples/interactive_telegram_client.py
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,...
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,...
[ "Safe", "Print", "(", "handle", "UnicodeEncodeErrors", "on", "some", "terminals", ")" ]
LonamiWebs/Telethon
python
https://github.com/LonamiWebs/Telethon/blob/1ead9757d366b58c1e0567cddb0196e20f1a445f/telethon_examples/interactive_telegram_client.py#L16-L23
[ "def", "sprint", "(", "string", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "try", ":", "print", "(", "string", ",", "*", "args", ",", "*", "*", "kwargs", ")", "except", "UnicodeEncodeError", ":", "string", "=", "string", ".", "encode", "(...
1ead9757d366b58c1e0567cddb0196e20f1a445f
train
print_title
Helper function to print titles to the console more nicely
telethon_examples/interactive_telegram_client.py
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)))
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)))
[ "Helper", "function", "to", "print", "titles", "to", "the", "console", "more", "nicely" ]
LonamiWebs/Telethon
python
https://github.com/LonamiWebs/Telethon/blob/1ead9757d366b58c1e0567cddb0196e20f1a445f/telethon_examples/interactive_telegram_client.py#L26-L31
[ "def", "print_title", "(", "title", ")", ":", "sprint", "(", "'\\n'", ")", "sprint", "(", "'=={}=='", ".", "format", "(", "'='", "*", "len", "(", "title", ")", ")", ")", "sprint", "(", "'= {} ='", ".", "format", "(", "title", ")", ")", "sprint", "(...
1ead9757d366b58c1e0567cddb0196e20f1a445f
train
async_input
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.
telethon_examples/interactive_telegram_client.py
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, ...
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, ...
[ "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", ...
LonamiWebs/Telethon
python
https://github.com/LonamiWebs/Telethon/blob/1ead9757d366b58c1e0567cddb0196e20f1a445f/telethon_examples/interactive_telegram_client.py#L46-L53
[ "async", "def", "async_input", "(", "prompt", ")", ":", "print", "(", "prompt", ",", "end", "=", "''", ",", "flush", "=", "True", ")", "return", "(", "await", "loop", ".", "run_in_executor", "(", "None", ",", "sys", ".", "stdin", ".", "readline", ")"...
1ead9757d366b58c1e0567cddb0196e20f1a445f
train
InteractiveTelegramClient.run
Main loop of the TelegramClient, will wait for user action
telethon_examples/interactive_telegram_client.py
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...
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...
[ "Main", "loop", "of", "the", "TelegramClient", "will", "wait", "for", "user", "action" ]
LonamiWebs/Telethon
python
https://github.com/LonamiWebs/Telethon/blob/1ead9757d366b58c1e0567cddb0196e20f1a445f/telethon_examples/interactive_telegram_client.py#L152-L310
[ "async", "def", "run", "(", "self", ")", ":", "# 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_handler", ",", ...
1ead9757d366b58c1e0567cddb0196e20f1a445f
train
InteractiveTelegramClient.send_photo
Sends the file located at path to the desired entity as a photo
telethon_examples/interactive_telegram_client.py
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!')
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", "photo" ]
LonamiWebs/Telethon
python
https://github.com/LonamiWebs/Telethon/blob/1ead9757d366b58c1e0567cddb0196e20f1a445f/telethon_examples/interactive_telegram_client.py#L312-L318
[ "async", "def", "send_photo", "(", "self", ",", "path", ",", "entity", ")", ":", "await", "self", ".", "send_file", "(", "entity", ",", "path", ",", "progress_callback", "=", "self", ".", "upload_progress_callback", ")", "print", "(", "'Photo sent!'", ")" ]
1ead9757d366b58c1e0567cddb0196e20f1a445f
train
InteractiveTelegramClient.send_document
Sends the file located at path to the desired entity as a document
telethon_examples/interactive_telegram_client.py
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!')
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!')
[ "Sends", "the", "file", "located", "at", "path", "to", "the", "desired", "entity", "as", "a", "document" ]
LonamiWebs/Telethon
python
https://github.com/LonamiWebs/Telethon/blob/1ead9757d366b58c1e0567cddb0196e20f1a445f/telethon_examples/interactive_telegram_client.py#L320-L327
[ "async", "def", "send_document", "(", "self", ",", "path", ",", "entity", ")", ":", "await", "self", ".", "send_file", "(", "entity", ",", "path", ",", "force_document", "=", "True", ",", "progress_callback", "=", "self", ".", "upload_progress_callback", ")"...
1ead9757d366b58c1e0567cddb0196e20f1a445f
train
InteractiveTelegramClient.download_media_by_id
Given a message ID, finds the media this message contained and downloads it.
telethon_examples/interactive_telegram_client.py
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...
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...
[ "Given", "a", "message", "ID", "finds", "the", "media", "this", "message", "contained", "and", "downloads", "it", "." ]
LonamiWebs/Telethon
python
https://github.com/LonamiWebs/Telethon/blob/1ead9757d366b58c1e0567cddb0196e20f1a445f/telethon_examples/interactive_telegram_client.py#L329-L347
[ "async", "def", "download_media_by_id", "(", "self", ",", "media_id", ")", ":", "try", ":", "msg", "=", "self", ".", "found_media", "[", "int", "(", "media_id", ")", "]", "except", "(", "ValueError", ",", "KeyError", ")", ":", "# ValueError when parsing, Key...
1ead9757d366b58c1e0567cddb0196e20f1a445f
train
InteractiveTelegramClient.message_handler
Callback method for received events.NewMessage
telethon_examples/interactive_telegram_client.py
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...
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...
[ "Callback", "method", "for", "received", "events", ".", "NewMessage" ]
LonamiWebs/Telethon
python
https://github.com/LonamiWebs/Telethon/blob/1ead9757d366b58c1e0567cddb0196e20f1a445f/telethon_examples/interactive_telegram_client.py#L368-L397
[ "async", "def", "message_handler", "(", "self", ",", "event", ")", ":", "# 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 *really* want it", "# you...
1ead9757d366b58c1e0567cddb0196e20f1a445f
train
_get_file_name
``ClassName -> class_name.html``.
telethon_generator/generators/docs.py
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...
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...
[ "ClassName", "-", ">", "class_name", ".", "html", "." ]
LonamiWebs/Telethon
python
https://github.com/LonamiWebs/Telethon/blob/1ead9757d366b58c1e0567cddb0196e20f1a445f/telethon_generator/generators/docs.py#L19-L25
[ "def", "_get_file_name", "(", "tlobject", ")", ":", "name", "=", "tlobject", ".", "name", "if", "isinstance", "(", "tlobject", ",", "TLObject", ")", "else", "tlobject", "# Courtesy of http://stackoverflow.com/a/1176023/4759433", "s1", "=", "re", ".", "sub", "(", ...
1ead9757d366b58c1e0567cddb0196e20f1a445f
train
get_import_code
``TLObject -> from ... import ...``.
telethon_generator/generators/docs.py
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)
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)
[ "TLObject", "-", ">", "from", "...", "import", "...", "." ]
LonamiWebs/Telethon
python
https://github.com/LonamiWebs/Telethon/blob/1ead9757d366b58c1e0567cddb0196e20f1a445f/telethon_generator/generators/docs.py#L28-L33
[ "def", "get_import_code", "(", "tlobject", ")", ":", "kind", "=", "'functions'", "if", "tlobject", ".", "is_function", "else", "'types'", "ns", "=", "'.'", "+", "tlobject", ".", "namespace", "if", "tlobject", ".", "namespace", "else", "''", "return", "'from ...
1ead9757d366b58c1e0567cddb0196e20f1a445f
train
_get_path_for
Creates and returns the path for the given TLObject at root.
telethon_generator/generators/docs.py
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)
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)
[ "Creates", "and", "returns", "the", "path", "for", "the", "given", "TLObject", "at", "root", "." ]
LonamiWebs/Telethon
python
https://github.com/LonamiWebs/Telethon/blob/1ead9757d366b58c1e0567cddb0196e20f1a445f/telethon_generator/generators/docs.py#L36-L42
[ "def", "_get_path_for", "(", "root", ",", "tlobject", ")", ":", "out_dir", "=", "root", "/", "(", "'methods'", "if", "tlobject", ".", "is_function", "else", "'constructors'", ")", "if", "tlobject", ".", "namespace", ":", "out_dir", "/=", "tlobject", ".", "...
1ead9757d366b58c1e0567cddb0196e20f1a445f
train
_get_path_for_type
Similar to `_get_path_for` but for only type names.
telethon_generator/generators/docs.py
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: ...
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: ...
[ "Similar", "to", "_get_path_for", "but", "for", "only", "type", "names", "." ]
LonamiWebs/Telethon
python
https://github.com/LonamiWebs/Telethon/blob/1ead9757d366b58c1e0567cddb0196e20f1a445f/telethon_generator/generators/docs.py#L45-L53
[ "def", "_get_path_for_type", "(", "type_", ")", ":", "if", "type_", ".", "lower", "(", ")", "in", "CORE_TYPES", ":", "return", "Path", "(", "'index.html#%s'", "%", "type_", ".", "lower", "(", ")", ")", "elif", "'.'", "in", "type_", ":", "namespace", ",...
1ead9757d366b58c1e0567cddb0196e20f1a445f
train
_find_title
Finds the <title> for the given HTML file, or (Unknown).
telethon_generator/generators/docs.py
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(...
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(...
[ "Finds", "the", "<title", ">", "for", "the", "given", "HTML", "file", "or", "(", "Unknown", ")", "." ]
LonamiWebs/Telethon
python
https://github.com/LonamiWebs/Telethon/blob/1ead9757d366b58c1e0567cddb0196e20f1a445f/telethon_generator/generators/docs.py#L56-L65
[ "def", "_find_title", "(", "html_file", ")", ":", "# 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>')", ...
1ead9757d366b58c1e0567cddb0196e20f1a445f
train
_build_menu
Builds the menu used for the current ``DocumentWriter``.
telethon_generator/generators/docs.py
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...
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...
[ "Builds", "the", "menu", "used", "for", "the", "current", "DocumentWriter", "." ]
LonamiWebs/Telethon
python
https://github.com/LonamiWebs/Telethon/blob/1ead9757d366b58c1e0567cddb0196e20f1a445f/telethon_generator/generators/docs.py#L68-L85
[ "def", "_build_menu", "(", "docs", ")", ":", "paths", "=", "[", "]", "current", "=", "docs", ".", "filename", "while", "current", "!=", "docs", ".", "root", ":", "current", "=", "current", ".", "parent", "paths", ".", "append", "(", "current", ")", "...
1ead9757d366b58c1e0567cddb0196e20f1a445f
train
_generate_index
Generates the index file for the specified folder
telethon_generator/generators/docs.py
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...
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", "the", "index", "file", "for", "the", "specified", "folder" ]
LonamiWebs/Telethon
python
https://github.com/LonamiWebs/Telethon/blob/1ead9757d366b58c1e0567cddb0196e20f1a445f/telethon_generator/generators/docs.py#L88-L155
[ "def", "_generate_index", "(", "root", ",", "folder", ",", "paths", ",", "bots_index", "=", "False", ",", "bots_index_paths", "=", "(", ")", ")", ":", "# Determine the namespaces listed here (as sub folders)", "# and the files (.html files) that we should link to", "namespa...
1ead9757d366b58c1e0567cddb0196e20f1a445f
train
_get_description
Generates a proper description for the given argument.
telethon_generator/generators/docs.py
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...
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...
[ "Generates", "a", "proper", "description", "for", "the", "given", "argument", "." ]
LonamiWebs/Telethon
python
https://github.com/LonamiWebs/Telethon/blob/1ead9757d366b58c1e0567cddb0196e20f1a445f/telethon_generator/generators/docs.py#L158-L196
[ "def", "_get_description", "(", "arg", ")", ":", "desc", "=", "[", "]", "otherwise", "=", "False", "if", "arg", ".", "can_be_inferred", ":", "desc", ".", "append", "(", "'If left unspecified, it will be inferred automatically.'", ")", "otherwise", "=", "True", "...
1ead9757d366b58c1e0567cddb0196e20f1a445f
train
_copy_replace
Copies the src file into dst applying the replacements dict
telethon_generator/generators/docs.py
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)]), ...
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)]), ...
[ "Copies", "the", "src", "file", "into", "dst", "applying", "the", "replacements", "dict" ]
LonamiWebs/Telethon
python
https://github.com/LonamiWebs/Telethon/blob/1ead9757d366b58c1e0567cddb0196e20f1a445f/telethon_generator/generators/docs.py#L199-L206
[ "def", "_copy_replace", "(", "src", ",", "dst", ",", "replacements", ")", ":", "with", "src", ".", "open", "(", ")", "as", "infile", ",", "dst", ".", "open", "(", "'w'", ")", "as", "outfile", ":", "outfile", ".", "write", "(", "re", ".", "sub", "...
1ead9757d366b58c1e0567cddb0196e20f1a445f
train
_write_html_pages
Generates the documentation HTML files from from ``scheme.tl`` to ``/methods`` and ``/constructors``, etc.
telethon_generator/generators/docs.py
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...
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...
[ "Generates", "the", "documentation", "HTML", "files", "from", "from", "scheme", ".", "tl", "to", "/", "methods", "and", "/", "constructors", "etc", "." ]
LonamiWebs/Telethon
python
https://github.com/LonamiWebs/Telethon/blob/1ead9757d366b58c1e0567cddb0196e20f1a445f/telethon_generator/generators/docs.py#L209-L591
[ "def", "_write_html_pages", "(", "root", ",", "tlobjects", ",", "methods", ",", "layer", ",", "input_res", ")", ":", "# Save 'Type: [Constructors]' for use in both:", "# * Seeing the return type or constructors belonging to the same type.", "# * Generating the types documentation, sh...
1ead9757d366b58c1e0567cddb0196e20f1a445f
train
_create_structure
Pre-create the required directory structure in `output_dir` for the input objects.
telethon_generator/generators/docs.py
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...
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...
[ "Pre", "-", "create", "the", "required", "directory", "structure", "in", "output_dir", "for", "the", "input", "objects", "." ]
LonamiWebs/Telethon
python
https://github.com/LonamiWebs/Telethon/blob/1ead9757d366b58c1e0567cddb0196e20f1a445f/telethon_generator/generators/docs.py#L603-L631
[ "def", "_create_structure", "(", "tlobjects", ",", "output_dir", ")", ":", "types_ns", "=", "set", "(", ")", "method_ns", "=", "set", "(", ")", "for", "obj", "in", "tlobjects", ":", "if", "obj", ".", "namespace", ":", "if", "obj", ".", "is_function", "...
1ead9757d366b58c1e0567cddb0196e20f1a445f
train
PatroniSequentialThreadingHandler.create_connection
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...
patroni/dcs/zookeeper.py
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...
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...
[ "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",...
zalando/patroni
python
https://github.com/zalando/patroni/blob/f6d29081c90af52064b981cdd877a07338d86038/patroni/dcs/zookeeper.py#L29-L47
[ "def", "create_connection", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "args", "=", "list", "(", "args", ")", "if", "len", "(", "args", ")", "==", "0", ":", "# kazoo 2.6.0 slightly changed the way how it calls create_connection method", ...
f6d29081c90af52064b981cdd877a07338d86038
train
PatroniSequentialThreadingHandler.select
Python3 raises `ValueError` if socket is closed, because fd == -1
patroni/dcs/zookeeper.py
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))
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))
[ "Python3", "raises", "ValueError", "if", "socket", "is", "closed", "because", "fd", "==", "-", "1" ]
zalando/patroni
python
https://github.com/zalando/patroni/blob/f6d29081c90af52064b981cdd877a07338d86038/patroni/dcs/zookeeper.py#L49-L54
[ "def", "select", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "try", ":", "return", "super", "(", "PatroniSequentialThreadingHandler", ",", "self", ")", ".", "select", "(", "*", "args", ",", "*", "*", "kwargs", ")", "except", "Va...
f6d29081c90af52064b981cdd877a07338d86038
train
ZooKeeper._kazoo_connect
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) t...
patroni/dcs/zookeeper.py
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...
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...
[ "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",...
zalando/patroni
python
https://github.com/zalando/patroni/blob/f6d29081c90af52064b981cdd877a07338d86038/patroni/dcs/zookeeper.py#L79-L92
[ "def", "_kazoo_connect", "(", "self", ",", "host", ",", "port", ")", ":", "ret", "=", "self", ".", "_orig_kazoo_connect", "(", "host", ",", "port", ")", "return", "max", "(", "self", ".", "loop_wait", "-", "2", ",", "2", ")", "*", "1000", ",", "ret...
f6d29081c90af52064b981cdd877a07338d86038
train
ZooKeeper.set_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).
patroni/dcs/zookeeper.py
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: ...
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: ...
[ "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", ...
zalando/patroni
python
https://github.com/zalando/patroni/blob/f6d29081c90af52064b981cdd877a07338d86038/patroni/dcs/zookeeper.py#L120-L127
[ "def", "set_ttl", "(", "self", ",", "ttl", ")", ":", "if", "self", ".", "_client", ".", "_session_timeout", "!=", "ttl", ":", "self", ".", "_client", ".", "_session_timeout", "=", "ttl", "self", ".", "_client", ".", "restart", "(", ")", "return", "True...
f6d29081c90af52064b981cdd877a07338d86038
train
service_name_from_scope_name
Translate scope name to service name which can be used in dns. 230 = 253 - len('replica.') - len('.service.consul')
patroni/dcs/consul.py
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 ...
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 ...
[ "Translate", "scope", "name", "to", "service", "name", "which", "can", "be", "used", "in", "dns", "." ]
zalando/patroni
python
https://github.com/zalando/patroni/blob/f6d29081c90af52064b981cdd877a07338d86038/patroni/dcs/consul.py#L163-L174
[ "def", "service_name_from_scope_name", "(", "scope_name", ")", ":", "def", "replace_char", "(", "match", ")", ":", "c", "=", "match", ".", "group", "(", "0", ")", "return", "'-'", "if", "c", "in", "'. _'", "else", "\"u{:04d}\"", ".", "format", "(", "ord"...
f6d29081c90af52064b981cdd877a07338d86038
train
Consul._do_refresh_session
:returns: `!True` if it had to create new session
patroni/dcs/consul.py
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) ...
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) ...
[ ":", "returns", ":", "!True", "if", "it", "had", "to", "create", "new", "session" ]
zalando/patroni
python
https://github.com/zalando/patroni/blob/f6d29081c90af52064b981cdd877a07338d86038/patroni/dcs/consul.py#L268-L290
[ "def", "_do_refresh_session", "(", "self", ")", ":", "if", "self", ".", "_session", "and", "self", ".", "_last_session_refresh", "+", "self", ".", "_loop_wait", ">", "time", ".", "time", "(", ")", ":", "return", "False", "if", "self", ".", "_session", ":...
f6d29081c90af52064b981cdd877a07338d86038
train
PostmasterProcess._read_postmaster_pidfile
Reads and parses postmaster.pid from the data directory :returns dictionary of values if successful, empty dictionary otherwise
patroni/postmaster.py
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...
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...
[ "Reads", "and", "parses", "postmaster", ".", "pid", "from", "the", "data", "directory" ]
zalando/patroni
python
https://github.com/zalando/patroni/blob/f6d29081c90af52064b981cdd877a07338d86038/patroni/postmaster.py#L40-L50
[ "def", "_read_postmaster_pidfile", "(", "data_dir", ")", ":", "pid_line_names", "=", "[", "'pid'", ",", "'data_dir'", ",", "'start_time'", ",", "'port'", ",", "'socket_dir'", ",", "'listen_addr'", ",", "'shmem_key'", "]", "try", ":", "with", "open", "(", "os",...
f6d29081c90af52064b981cdd877a07338d86038
train
PostmasterProcess.signal_stop
Signal postmaster process to stop :returns None if signaled, True if process is already gone, False if error
patroni/postmaster.py
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)) ...
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)) ...
[ "Signal", "postmaster", "process", "to", "stop" ]
zalando/patroni
python
https://github.com/zalando/patroni/blob/f6d29081c90af52064b981cdd877a07338d86038/patroni/postmaster.py#L97-L113
[ "def", "signal_stop", "(", "self", ",", "mode", ")", ":", "if", "self", ".", "is_single_user", ":", "logger", ".", "warning", "(", "\"Cannot stop server; single-user server is running (PID: {0})\"", ".", "format", "(", "self", ".", "pid", ")", ")", "return", "Fa...
f6d29081c90af52064b981cdd877a07338d86038
train
repr_size
>>> repr_size(1000) '1000 Bytes' >>> repr_size(8257332324597) '7.5 TiB'
patroni/scripts/wale_restore.py
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),...
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),...
[ ">>>", "repr_size", "(", "1000", ")", "1000", "Bytes", ">>>", "repr_size", "(", "8257332324597", ")", "7", ".", "5", "TiB" ]
zalando/patroni
python
https://github.com/zalando/patroni/blob/f6d29081c90af52064b981cdd877a07338d86038/patroni/scripts/wale_restore.py#L63-L76
[ "def", "repr_size", "(", "n_bytes", ")", ":", "if", "n_bytes", "<", "1024", ":", "return", "'{0} Bytes'", ".", "format", "(", "n_bytes", ")", "i", "=", "-", "1", "while", "n_bytes", ">", "1023", ":", "n_bytes", "/=", "1024.0", "i", "+=", "1", "return...
f6d29081c90af52064b981cdd877a07338d86038
train
size_as_bytes
>>> size_as_bytes(7.5, 'T') 8246337208320
patroni/scripts/wale_restore.py
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))
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))
[ ">>>", "size_as_bytes", "(", "7", ".", "5", "T", ")", "8246337208320" ]
zalando/patroni
python
https://github.com/zalando/patroni/blob/f6d29081c90af52064b981cdd877a07338d86038/patroni/scripts/wale_restore.py#L79-L90
[ "def", "size_as_bytes", "(", "size_", ",", "prefix", ")", ":", "prefix", "=", "prefix", ".", "upper", "(", ")", "assert", "prefix", "in", "si_prefixes", "exponent", "=", "si_prefixes", ".", "index", "(", "prefix", ")", "+", "1", "return", "int", "(", "...
f6d29081c90af52064b981cdd877a07338d86038
train
WALERestore.run
Creates a new replica using WAL-E Returns ------- ExitCode 0 = Success 1 = Error, try again 2 = Error, don't try again
patroni/scripts/wale_restore.py
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...
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...
[ "Creates", "a", "new", "replica", "using", "WAL", "-", "E" ]
zalando/patroni
python
https://github.com/zalando/patroni/blob/f6d29081c90af52064b981cdd877a07338d86038/patroni/scripts/wale_restore.py#L131-L158
[ "def", "run", "(", "self", ")", ":", "if", "self", ".", "init_error", ":", "logger", ".", "error", "(", "'init error: %r did not exist at initialization time'", ",", "self", ".", "wal_e", ".", "env_dir", ")", "return", "ExitCode", ".", "FAIL", "try", ":", "s...
f6d29081c90af52064b981cdd877a07338d86038
train
WALERestore.should_use_s3_to_create_replica
determine whether it makes sense to use S3 and not pg_basebackup
patroni/scripts/wale_restore.py
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'] ...
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'] ...
[ "determine", "whether", "it", "makes", "sense", "to", "use", "S3", "and", "not", "pg_basebackup" ]
zalando/patroni
python
https://github.com/zalando/patroni/blob/f6d29081c90af52064b981cdd877a07338d86038/patroni/scripts/wale_restore.py#L160-L295
[ "def", "should_use_s3_to_create_replica", "(", "self", ")", ":", "threshold_megabytes", "=", "self", ".", "wal_e", ".", "threshold_mb", "threshold_percent", "=", "self", ".", "wal_e", ".", "threshold_pct", "try", ":", "cmd", "=", "self", ".", "wal_e", ".", "cm...
f6d29081c90af52064b981cdd877a07338d86038
train
watching
>>> len(list(watching(True, 1, 0))) 1 >>> len(list(watching(True, 1, 1))) 2 >>> len(list(watching(True, None, 0))) 1
patroni/ctl.py
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...
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...
[ ">>>", "len", "(", "list", "(", "watching", "(", "True", "1", "0", ")))", "1", ">>>", "len", "(", "list", "(", "watching", "(", "True", "1", "1", ")))", "2", ">>>", "len", "(", "list", "(", "watching", "(", "True", "None", "0", ")))", "1" ]
zalando/patroni
python
https://github.com/zalando/patroni/blob/f6d29081c90af52064b981cdd877a07338d86038/patroni/ctl.py#L189-L214
[ "def", "watching", "(", "w", ",", "watch", ",", "max_count", "=", "None", ",", "clear", "=", "True", ")", ":", "if", "w", "and", "not", "watch", ":", "watch", "=", "2", "if", "watch", "and", "clear", ":", "click", ".", "clear", "(", ")", "yield",...
f6d29081c90af52064b981cdd877a07338d86038
train
_do_failover_or_switchover
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 keep the client up to date.
patroni/ctl.py
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...
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...
[ "We", "want", "to", "trigger", "a", "failover", "or", "switchover", "for", "the", "specified", "cluster", "name", "." ]
zalando/patroni
python
https://github.com/zalando/patroni/blob/f6d29081c90af52064b981cdd877a07338d86038/patroni/ctl.py#L585-L680
[ "def", "_do_failover_or_switchover", "(", "obj", ",", "action", ",", "cluster_name", ",", "master", ",", "candidate", ",", "force", ",", "scheduled", "=", "None", ")", ":", "dcs", "=", "get_dcs", "(", "obj", ",", "cluster_name", ")", "cluster", "=", "dcs",...
f6d29081c90af52064b981cdd877a07338d86038
train
touch_member
Rip-off of the ha.touch_member without inter-class dependencies
patroni/ctl.py
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...
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...
[ "Rip", "-", "off", "of", "the", "ha", ".", "touch_member", "without", "inter", "-", "class", "dependencies" ]
zalando/patroni
python
https://github.com/zalando/patroni/blob/f6d29081c90af52064b981cdd877a07338d86038/patroni/ctl.py#L827-L846
[ "def", "touch_member", "(", "config", ",", "dcs", ")", ":", "p", "=", "Postgresql", "(", "config", "[", "'postgresql'", "]", ")", "p", ".", "set_state", "(", "'running'", ")", "p", ".", "set_role", "(", "'master'", ")", "def", "restapi_connection_string", ...
f6d29081c90af52064b981cdd877a07338d86038
train
set_defaults
fill-in some basic configuration parameters if config file is not set
patroni/ctl.py
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'...
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'...
[ "fill", "-", "in", "some", "basic", "configuration", "parameters", "if", "config", "file", "is", "not", "set" ]
zalando/patroni
python
https://github.com/zalando/patroni/blob/f6d29081c90af52064b981cdd877a07338d86038/patroni/ctl.py#L849-L855
[ "def", "set_defaults", "(", "config", ",", "cluster_name", ")", ":", "config", "[", "'postgresql'", "]", ".", "setdefault", "(", "'name'", ",", "cluster_name", ")", "config", "[", "'postgresql'", "]", ".", "setdefault", "(", "'scope'", ",", "cluster_name", "...
f6d29081c90af52064b981cdd877a07338d86038
train
temporary_file
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. :returns path of the created file.
patroni/ctl.py
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. ...
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. ...
[ "Creates", "a", "temporary", "file", "with", "specified", "contents", "that", "persists", "for", "the", "context", "." ]
zalando/patroni
python
https://github.com/zalando/patroni/blob/f6d29081c90af52064b981cdd877a07338d86038/patroni/ctl.py#L970-L985
[ "def", "temporary_file", "(", "contents", ",", "suffix", "=", "''", ",", "prefix", "=", "'tmp'", ")", ":", "tmp", "=", "tempfile", ".", "NamedTemporaryFile", "(", "suffix", "=", "suffix", ",", "prefix", "=", "prefix", ",", "delete", "=", "False", ")", ...
f6d29081c90af52064b981cdd877a07338d86038
train
show_diff
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.
patroni/ctl.py
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...
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...
[ "Shows", "a", "diff", "between", "two", "strings", "." ]
zalando/patroni
python
https://github.com/zalando/patroni/blob/f6d29081c90af52064b981cdd877a07338d86038/patroni/ctl.py#L988-L1012
[ "def", "show_diff", "(", "before_editing", ",", "after_editing", ")", ":", "def", "listify", "(", "string", ")", ":", "return", "[", "l", "+", "'\\n'", "for", "l", "in", "string", ".", "rstrip", "(", "'\\n'", ")", ".", "split", "(", "'\\n'", ")", "]"...
f6d29081c90af52064b981cdd877a07338d86038
train
format_config_for_editing
Formats configuration as YAML for human consumption. :param data: configuration as nested dictionaries :returns unicode YAML of the configuration
patroni/ctl.py
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)
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)
[ "Formats", "configuration", "as", "YAML", "for", "human", "consumption", "." ]
zalando/patroni
python
https://github.com/zalando/patroni/blob/f6d29081c90af52064b981cdd877a07338d86038/patroni/ctl.py#L1015-L1020
[ "def", "format_config_for_editing", "(", "data", ")", ":", "return", "yaml", ".", "safe_dump", "(", "data", ",", "default_flow_style", "=", "False", ",", "encoding", "=", "None", ",", "allow_unicode", "=", "True", ")" ]
f6d29081c90af52064b981cdd877a07338d86038
train
apply_config_changes
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 PostgreSQL GUCs containing dots. Values are interpreted as ...
patroni/ctl.py
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...
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", "config", "changes", "specified", "as", "a", "list", "of", "key", "-", "value", "pairs", "." ]
zalando/patroni
python
https://github.com/zalando/patroni/blob/f6d29081c90af52064b981cdd877a07338d86038/patroni/ctl.py#L1023-L1061
[ "def", "apply_config_changes", "(", "before_editing", ",", "data", ",", "kvpairs", ")", ":", "changed_data", "=", "copy", ".", "deepcopy", "(", "data", ")", "def", "set_path_value", "(", "config", ",", "path", ",", "value", ",", "prefix", "=", "(", ")", ...
f6d29081c90af52064b981cdd877a07338d86038
train
apply_yaml_file
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
patroni/ctl.py
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 =...
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 =...
[ "Applies", "changes", "from", "a", "YAML", "file", "to", "configuration" ]
zalando/patroni
python
https://github.com/zalando/patroni/blob/f6d29081c90af52064b981cdd877a07338d86038/patroni/ctl.py#L1064-L1081
[ "def", "apply_yaml_file", "(", "data", ",", "filename", ")", ":", "changed_data", "=", "copy", ".", "deepcopy", "(", "data", ")", "if", "filename", "==", "'-'", ":", "new_options", "=", "yaml", ".", "safe_load", "(", "sys", ".", "stdin", ")", "else", "...
f6d29081c90af52064b981cdd877a07338d86038
train
invoke_editor
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
patroni/ctl.py
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...
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...
[ "Starts", "editor", "command", "to", "edit", "configuration", "in", "human", "readable", "format" ]
zalando/patroni
python
https://github.com/zalando/patroni/blob/f6d29081c90af52064b981cdd877a07338d86038/patroni/ctl.py#L1084-L1104
[ "def", "invoke_editor", "(", "before_editing", ",", "cluster_name", ")", ":", "editor_cmd", "=", "os", ".", "environ", ".", "get", "(", "'EDITOR'", ")", "if", "not", "editor_cmd", ":", "raise", "PatroniCtlException", "(", "'EDITOR environment variable is not set'", ...
f6d29081c90af52064b981cdd877a07338d86038
train
AWSConnection._tag_ebs
set tags, carrying the cluster name, instance role and instance id for the EBS storage
patroni/scripts/aws.py
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...
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...
[ "set", "tags", "carrying", "the", "cluster", "name", "instance", "role", "and", "instance", "id", "for", "the", "EBS", "storage" ]
zalando/patroni
python
https://github.com/zalando/patroni/blob/f6d29081c90af52064b981cdd877a07338d86038/patroni/scripts/aws.py#L43-L47
[ "def", "_tag_ebs", "(", "self", ",", "conn", ",", "role", ")", ":", "tags", "=", "{", "'Name'", ":", "'spilo_'", "+", "self", ".", "cluster_name", ",", "'Role'", ":", "role", ",", "'Instance'", ":", "self", ".", "instance_id", "}", "volumes", "=", "c...
f6d29081c90af52064b981cdd877a07338d86038
train
AWSConnection._tag_ec2
tag the current EC2 instance with a cluster role
patroni/scripts/aws.py
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)
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)
[ "tag", "the", "current", "EC2", "instance", "with", "a", "cluster", "role" ]
zalando/patroni
python
https://github.com/zalando/patroni/blob/f6d29081c90af52064b981cdd877a07338d86038/patroni/scripts/aws.py#L49-L52
[ "def", "_tag_ec2", "(", "self", ",", "conn", ",", "role", ")", ":", "tags", "=", "{", "'Role'", ":", "role", "}", "conn", ".", "create_tags", "(", "[", "self", ".", "instance_id", "]", ",", "tags", ")" ]
f6d29081c90af52064b981cdd877a07338d86038
train
_MemberStatus.failover_limitation
Returns reason why this node can't promote or None if everything is ok.
patroni/ha.py
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...
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...
[ "Returns", "reason", "why", "this", "node", "can", "t", "promote", "or", "None", "if", "everything", "is", "ok", "." ]
zalando/patroni
python
https://github.com/zalando/patroni/blob/f6d29081c90af52064b981cdd877a07338d86038/patroni/ha.py#L46-L54
[ "def", "failover_limitation", "(", "self", ")", ":", "if", "not", "self", ".", "reachable", ":", "return", "'not reachable'", "if", "self", ".", "tags", ".", "get", "(", "'nofailover'", ",", "False", ")", ":", "return", "'not allowed to promote'", "if", "sel...
f6d29081c90af52064b981cdd877a07338d86038
train
Ha.get_effective_tags
Return configuration tags merged with dynamically applied tags.
patroni/ha.py
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']...
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']...
[ "Return", "configuration", "tags", "merged", "with", "dynamically", "applied", "tags", "." ]
zalando/patroni
python
https://github.com/zalando/patroni/blob/f6d29081c90af52064b981cdd877a07338d86038/patroni/ha.py#L163-L169
[ "def", "get_effective_tags", "(", "self", ")", ":", "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", ">", ...
f6d29081c90af52064b981cdd877a07338d86038
train
Ha.bootstrap_standby_leader
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.
patroni/ha.py
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() ...
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() ...
[ "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", ...
zalando/patroni
python
https://github.com/zalando/patroni/blob/f6d29081c90af52064b981cdd877a07338d86038/patroni/ha.py#L258-L270
[ "def", "bootstrap_standby_leader", "(", "self", ")", ":", "clone_source", "=", "self", ".", "get_remote_master", "(", ")", "msg", "=", "'clone from remote master {0}'", ".", "format", "(", "clone_source", ".", "conn_url", ")", "result", "=", "self", ".", "clone"...
f6d29081c90af52064b981cdd877a07338d86038
train
Ha.process_sync_replication
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, then that node must have synchronous_standby s...
patroni/ha.py
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, ...
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, ...
[ "Process", "synchronous", "standby", "beahvior", "." ]
zalando/patroni
python
https://github.com/zalando/patroni/blob/f6d29081c90af52064b981cdd877a07338d86038/patroni/ha.py#L400-L446
[ "def", "process_sync_replication", "(", "self", ")", ":", "if", "self", ".", "is_synchronous_mode", "(", ")", ":", "current", "=", "self", ".", "cluster", ".", "sync", ".", "leader", "and", "self", ".", "cluster", ".", "sync", ".", "sync_standby", "picked"...
f6d29081c90af52064b981cdd877a07338d86038
train
Ha.while_not_sync_standby
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 or if the leader changes or goes away we are also f...
patroni/ha.py
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 ...
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 ...
[ "Runs", "specified", "action", "while", "trying", "to", "make", "sure", "that", "the", "node", "is", "not", "assigned", "synchronous", "standby", "status", "." ]
zalando/patroni
python
https://github.com/zalando/patroni/blob/f6d29081c90af52064b981cdd877a07338d86038/patroni/ha.py#L452-L487
[ "def", "while_not_sync_standby", "(", "self", ",", "func", ")", ":", "if", "not", "self", ".", "is_synchronous_mode", "(", ")", "or", "self", ".", "patroni", ".", "nosync", ":", "return", "func", "(", ")", "with", "self", ".", "_member_state_lock", ":", ...
f6d29081c90af52064b981cdd877a07338d86038
train
Ha.fetch_node_status
This function perform http get request on member.api_url and fetches its status :returns: `_MemberStatus` object
patroni/ha.py
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',...
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',...
[ "This", "function", "perform", "http", "get", "request", "on", "member", ".", "api_url", "and", "fetches", "its", "status", ":", "returns", ":", "_MemberStatus", "object" ]
zalando/patroni
python
https://github.com/zalando/patroni/blob/f6d29081c90af52064b981cdd877a07338d86038/patroni/ha.py#L547-L558
[ "def", "fetch_node_status", "(", "member", ")", ":", "try", ":", "response", "=", "requests", ".", "get", "(", "member", ".", "api_url", ",", "timeout", "=", "2", ",", "verify", "=", "False", ")", "logger", ".", "info", "(", "'Got response from %s %s: %s'"...
f6d29081c90af52064b981cdd877a07338d86038