repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
lsst-sqre/documenteer
documenteer/stackdocs/build.py
remove_existing_links
def remove_existing_links(root_dir): """Delete any symlinks present at the root of a directory. Parameters ---------- root_dir : `str` Directory that might contain symlinks. Notes ----- This function is used to remove any symlinks created by `link_directories`. Running ``remove_existing_links`` at the beginning of a build ensures that builds are isolated. For example, if a package is un-setup it won't re-appear in the documentation because its symlink still exists. """ logger = logging.getLogger(__name__) for name in os.listdir(root_dir): full_name = os.path.join(root_dir, name) if os.path.islink(full_name): logger.debug('Deleting existing symlink {0}'.format(full_name)) os.remove(full_name)
python
def remove_existing_links(root_dir): """Delete any symlinks present at the root of a directory. Parameters ---------- root_dir : `str` Directory that might contain symlinks. Notes ----- This function is used to remove any symlinks created by `link_directories`. Running ``remove_existing_links`` at the beginning of a build ensures that builds are isolated. For example, if a package is un-setup it won't re-appear in the documentation because its symlink still exists. """ logger = logging.getLogger(__name__) for name in os.listdir(root_dir): full_name = os.path.join(root_dir, name) if os.path.islink(full_name): logger.debug('Deleting existing symlink {0}'.format(full_name)) os.remove(full_name)
[ "def", "remove_existing_links", "(", "root_dir", ")", ":", "logger", "=", "logging", ".", "getLogger", "(", "__name__", ")", "for", "name", "in", "os", ".", "listdir", "(", "root_dir", ")", ":", "full_name", "=", "os", ".", "path", ".", "join", "(", "root_dir", ",", "name", ")", "if", "os", ".", "path", ".", "islink", "(", "full_name", ")", ":", "logger", ".", "debug", "(", "'Deleting existing symlink {0}'", ".", "format", "(", "full_name", ")", ")", "os", ".", "remove", "(", "full_name", ")" ]
Delete any symlinks present at the root of a directory. Parameters ---------- root_dir : `str` Directory that might contain symlinks. Notes ----- This function is used to remove any symlinks created by `link_directories`. Running ``remove_existing_links`` at the beginning of a build ensures that builds are isolated. For example, if a package is un-setup it won't re-appear in the documentation because its symlink still exists.
[ "Delete", "any", "symlinks", "present", "at", "the", "root", "of", "a", "directory", "." ]
75f02901a80042b28d074df1cc1dca32eb8e38c8
https://github.com/lsst-sqre/documenteer/blob/75f02901a80042b28d074df1cc1dca32eb8e38c8/documenteer/stackdocs/build.py#L434-L455
train
ehansis/ozelot
ozelot/orm/base.py
render_diagram
def render_diagram(out_base): """Render a data model diagram Included in the diagram are all classes from the model registry. For your project, write a small script that imports all models that you would like to have included and then calls this function. .. note:: This function requires the 'dot' executable from the GraphViz package to be installed and its location configured in your `project_config.py` variable :attr:`DOT_EXECUTABLE`. Args: out_base (str): output base path (file endings will be appended) """ import codecs import subprocess import sadisplay # generate class descriptions desc = sadisplay.describe(list(model_registry.values()), show_methods=False, show_properties=True, show_indexes=True, ) # write description in DOT format with codecs.open(out_base + '.dot', 'w', encoding='utf-8') as f: f.write(sadisplay.dot(desc)) # check existence of DOT_EXECUTABLE variable and file if not hasattr(config, 'DOT_EXECUTABLE'): raise RuntimeError("Please configure the 'DOT_EXECUTABLE' variable in your 'project_config.py'") if not os.path.exists(config.DOT_EXECUTABLE): raise IOError("Could not find file pointed to by 'DOT_EXECUTABLE': " + str(config.DOT_EXECUTABLE)) # render to image using DOT # noinspection PyUnresolvedReferences subprocess.check_call([ config.DOT_EXECUTABLE, '-T', 'png', '-o', out_base + '.png', out_base + '.dot' ])
python
def render_diagram(out_base): """Render a data model diagram Included in the diagram are all classes from the model registry. For your project, write a small script that imports all models that you would like to have included and then calls this function. .. note:: This function requires the 'dot' executable from the GraphViz package to be installed and its location configured in your `project_config.py` variable :attr:`DOT_EXECUTABLE`. Args: out_base (str): output base path (file endings will be appended) """ import codecs import subprocess import sadisplay # generate class descriptions desc = sadisplay.describe(list(model_registry.values()), show_methods=False, show_properties=True, show_indexes=True, ) # write description in DOT format with codecs.open(out_base + '.dot', 'w', encoding='utf-8') as f: f.write(sadisplay.dot(desc)) # check existence of DOT_EXECUTABLE variable and file if not hasattr(config, 'DOT_EXECUTABLE'): raise RuntimeError("Please configure the 'DOT_EXECUTABLE' variable in your 'project_config.py'") if not os.path.exists(config.DOT_EXECUTABLE): raise IOError("Could not find file pointed to by 'DOT_EXECUTABLE': " + str(config.DOT_EXECUTABLE)) # render to image using DOT # noinspection PyUnresolvedReferences subprocess.check_call([ config.DOT_EXECUTABLE, '-T', 'png', '-o', out_base + '.png', out_base + '.dot' ])
[ "def", "render_diagram", "(", "out_base", ")", ":", "import", "codecs", "import", "subprocess", "import", "sadisplay", "# generate class descriptions", "desc", "=", "sadisplay", ".", "describe", "(", "list", "(", "model_registry", ".", "values", "(", ")", ")", ",", "show_methods", "=", "False", ",", "show_properties", "=", "True", ",", "show_indexes", "=", "True", ",", ")", "# write description in DOT format", "with", "codecs", ".", "open", "(", "out_base", "+", "'.dot'", ",", "'w'", ",", "encoding", "=", "'utf-8'", ")", "as", "f", ":", "f", ".", "write", "(", "sadisplay", ".", "dot", "(", "desc", ")", ")", "# check existence of DOT_EXECUTABLE variable and file", "if", "not", "hasattr", "(", "config", ",", "'DOT_EXECUTABLE'", ")", ":", "raise", "RuntimeError", "(", "\"Please configure the 'DOT_EXECUTABLE' variable in your 'project_config.py'\"", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "config", ".", "DOT_EXECUTABLE", ")", ":", "raise", "IOError", "(", "\"Could not find file pointed to by 'DOT_EXECUTABLE': \"", "+", "str", "(", "config", ".", "DOT_EXECUTABLE", ")", ")", "# render to image using DOT", "# noinspection PyUnresolvedReferences", "subprocess", ".", "check_call", "(", "[", "config", ".", "DOT_EXECUTABLE", ",", "'-T'", ",", "'png'", ",", "'-o'", ",", "out_base", "+", "'.png'", ",", "out_base", "+", "'.dot'", "]", ")" ]
Render a data model diagram Included in the diagram are all classes from the model registry. For your project, write a small script that imports all models that you would like to have included and then calls this function. .. note:: This function requires the 'dot' executable from the GraphViz package to be installed and its location configured in your `project_config.py` variable :attr:`DOT_EXECUTABLE`. Args: out_base (str): output base path (file endings will be appended)
[ "Render", "a", "data", "model", "diagram" ]
948675e02eb6fca940450f5cb814f53e97159e5b
https://github.com/ehansis/ozelot/blob/948675e02eb6fca940450f5cb814f53e97159e5b/ozelot/orm/base.py#L187-L228
train
ehansis/ozelot
ozelot/orm/base.py
ExtendedBase.get_max_id
def get_max_id(cls, session): """Get the current max value of the ``id`` column. When creating and storing ORM objects in bulk, :mod:`sqlalchemy` does not automatically generate an incrementing primary key ``id``. To do this manually, one needs to know the current max ``id``. For ORM object classes that are derived from other ORM object classes, the max ``id`` of the lowest base class is returned. This is designed to be used with inheritance by joining, in which derived and base class objects have identical ``id`` values. Args: session: database session to operate in """ # sqlalchemy allows only one level of inheritance, so just check this class and all its bases id_base = None for c in [cls] + list(cls.__bases__): for base_class in c.__bases__: if base_class.__name__ == 'Base': if id_base is None: # we found our base class for determining the ID id_base = c else: raise RuntimeError("Multiple base object classes for class " + cls.__name__) # this should never happen if id_base is None: raise RuntimeError("Error searching for base class of " + cls.__name__) # get its max ID max_id = session.query(func.max(id_base.id)).scalar() # if no object is present, None is returned if max_id is None: max_id = 0 return max_id
python
def get_max_id(cls, session): """Get the current max value of the ``id`` column. When creating and storing ORM objects in bulk, :mod:`sqlalchemy` does not automatically generate an incrementing primary key ``id``. To do this manually, one needs to know the current max ``id``. For ORM object classes that are derived from other ORM object classes, the max ``id`` of the lowest base class is returned. This is designed to be used with inheritance by joining, in which derived and base class objects have identical ``id`` values. Args: session: database session to operate in """ # sqlalchemy allows only one level of inheritance, so just check this class and all its bases id_base = None for c in [cls] + list(cls.__bases__): for base_class in c.__bases__: if base_class.__name__ == 'Base': if id_base is None: # we found our base class for determining the ID id_base = c else: raise RuntimeError("Multiple base object classes for class " + cls.__name__) # this should never happen if id_base is None: raise RuntimeError("Error searching for base class of " + cls.__name__) # get its max ID max_id = session.query(func.max(id_base.id)).scalar() # if no object is present, None is returned if max_id is None: max_id = 0 return max_id
[ "def", "get_max_id", "(", "cls", ",", "session", ")", ":", "# sqlalchemy allows only one level of inheritance, so just check this class and all its bases", "id_base", "=", "None", "for", "c", "in", "[", "cls", "]", "+", "list", "(", "cls", ".", "__bases__", ")", ":", "for", "base_class", "in", "c", ".", "__bases__", ":", "if", "base_class", ".", "__name__", "==", "'Base'", ":", "if", "id_base", "is", "None", ":", "# we found our base class for determining the ID", "id_base", "=", "c", "else", ":", "raise", "RuntimeError", "(", "\"Multiple base object classes for class \"", "+", "cls", ".", "__name__", ")", "# this should never happen", "if", "id_base", "is", "None", ":", "raise", "RuntimeError", "(", "\"Error searching for base class of \"", "+", "cls", ".", "__name__", ")", "# get its max ID", "max_id", "=", "session", ".", "query", "(", "func", ".", "max", "(", "id_base", ".", "id", ")", ")", ".", "scalar", "(", ")", "# if no object is present, None is returned", "if", "max_id", "is", "None", ":", "max_id", "=", "0", "return", "max_id" ]
Get the current max value of the ``id`` column. When creating and storing ORM objects in bulk, :mod:`sqlalchemy` does not automatically generate an incrementing primary key ``id``. To do this manually, one needs to know the current max ``id``. For ORM object classes that are derived from other ORM object classes, the max ``id`` of the lowest base class is returned. This is designed to be used with inheritance by joining, in which derived and base class objects have identical ``id`` values. Args: session: database session to operate in
[ "Get", "the", "current", "max", "value", "of", "the", "id", "column", "." ]
948675e02eb6fca940450f5cb814f53e97159e5b
https://github.com/ehansis/ozelot/blob/948675e02eb6fca940450f5cb814f53e97159e5b/ozelot/orm/base.py#L112-L146
train
ehansis/ozelot
ozelot/orm/base.py
ExtendedBase.truncate_to_field_length
def truncate_to_field_length(self, field, value): """Truncate the value of a string field to the field's max length. Use this in a validator to check/truncate values before inserting them into the database. Copy the below example code after ``@validates`` to your model class and replace ``field1`` and ``field2`` with your field name(s). :Example: from sqlalchemy.orm import validates # ... omitting other imports ... class MyModel(base.Base): field1 = Column(String(128)) field2 = Column(String(64)) @validates('field1', 'field2') def truncate(self, field, value): return self.truncate_to_field_length(field, value) Args: field (str): field name to validate value (str/unicode): value to validate Returns: str/unicode: value truncated to field max length """ max_len = getattr(self.__class__, field).prop.columns[0].type.length if value and len(value) > max_len: return value[:max_len] else: return value
python
def truncate_to_field_length(self, field, value): """Truncate the value of a string field to the field's max length. Use this in a validator to check/truncate values before inserting them into the database. Copy the below example code after ``@validates`` to your model class and replace ``field1`` and ``field2`` with your field name(s). :Example: from sqlalchemy.orm import validates # ... omitting other imports ... class MyModel(base.Base): field1 = Column(String(128)) field2 = Column(String(64)) @validates('field1', 'field2') def truncate(self, field, value): return self.truncate_to_field_length(field, value) Args: field (str): field name to validate value (str/unicode): value to validate Returns: str/unicode: value truncated to field max length """ max_len = getattr(self.__class__, field).prop.columns[0].type.length if value and len(value) > max_len: return value[:max_len] else: return value
[ "def", "truncate_to_field_length", "(", "self", ",", "field", ",", "value", ")", ":", "max_len", "=", "getattr", "(", "self", ".", "__class__", ",", "field", ")", ".", "prop", ".", "columns", "[", "0", "]", ".", "type", ".", "length", "if", "value", "and", "len", "(", "value", ")", ">", "max_len", ":", "return", "value", "[", ":", "max_len", "]", "else", ":", "return", "value" ]
Truncate the value of a string field to the field's max length. Use this in a validator to check/truncate values before inserting them into the database. Copy the below example code after ``@validates`` to your model class and replace ``field1`` and ``field2`` with your field name(s). :Example: from sqlalchemy.orm import validates # ... omitting other imports ... class MyModel(base.Base): field1 = Column(String(128)) field2 = Column(String(64)) @validates('field1', 'field2') def truncate(self, field, value): return self.truncate_to_field_length(field, value) Args: field (str): field name to validate value (str/unicode): value to validate Returns: str/unicode: value truncated to field max length
[ "Truncate", "the", "value", "of", "a", "string", "field", "to", "the", "field", "s", "max", "length", "." ]
948675e02eb6fca940450f5cb814f53e97159e5b
https://github.com/ehansis/ozelot/blob/948675e02eb6fca940450f5cb814f53e97159e5b/ozelot/orm/base.py#L148-L181
train
untwisted/untwisted
untwisted/tkinter.py
extern
def extern(obj, timeout=200): """ Tell Tkinter to process untnwisted event loop. It registers just once the update handle. """ global installed # Register it just once. if not installed: install_hook(obj, timeout) installed = True
python
def extern(obj, timeout=200): """ Tell Tkinter to process untnwisted event loop. It registers just once the update handle. """ global installed # Register it just once. if not installed: install_hook(obj, timeout) installed = True
[ "def", "extern", "(", "obj", ",", "timeout", "=", "200", ")", ":", "global", "installed", "# Register it just once.", "if", "not", "installed", ":", "install_hook", "(", "obj", ",", "timeout", ")", "installed", "=", "True" ]
Tell Tkinter to process untnwisted event loop. It registers just once the update handle.
[ "Tell", "Tkinter", "to", "process", "untnwisted", "event", "loop", ".", "It", "registers", "just", "once", "the", "update", "handle", "." ]
8a8d9c8a8d0f3452d5de67cd760297bb5759f637
https://github.com/untwisted/untwisted/blob/8a8d9c8a8d0f3452d5de67cd760297bb5759f637/untwisted/tkinter.py#L15-L25
train
untwisted/untwisted
untwisted/tkinter.py
intern
def intern(obj, timeout): """ Tell untwisted to process an extern event loop. """ core.gear.timeout = timeout core.gear.pool.append(obj)
python
def intern(obj, timeout): """ Tell untwisted to process an extern event loop. """ core.gear.timeout = timeout core.gear.pool.append(obj)
[ "def", "intern", "(", "obj", ",", "timeout", ")", ":", "core", ".", "gear", ".", "timeout", "=", "timeout", "core", ".", "gear", ".", "pool", ".", "append", "(", "obj", ")" ]
Tell untwisted to process an extern event loop.
[ "Tell", "untwisted", "to", "process", "an", "extern", "event", "loop", "." ]
8a8d9c8a8d0f3452d5de67cd760297bb5759f637
https://github.com/untwisted/untwisted/blob/8a8d9c8a8d0f3452d5de67cd760297bb5759f637/untwisted/tkinter.py#L27-L34
train
lsst-sqre/documenteer
documenteer/sphinxext/jira.py
_make_ticket_node
def _make_ticket_node(ticket_id, config, options=None): """Construct a reference node for a JIRA ticket.""" options = options or {} ref = config.jira_uri_template.format(ticket=ticket_id) link = nodes.reference(text=ticket_id, refuri=ref, **options) return link
python
def _make_ticket_node(ticket_id, config, options=None): """Construct a reference node for a JIRA ticket.""" options = options or {} ref = config.jira_uri_template.format(ticket=ticket_id) link = nodes.reference(text=ticket_id, refuri=ref, **options) return link
[ "def", "_make_ticket_node", "(", "ticket_id", ",", "config", ",", "options", "=", "None", ")", ":", "options", "=", "options", "or", "{", "}", "ref", "=", "config", ".", "jira_uri_template", ".", "format", "(", "ticket", "=", "ticket_id", ")", "link", "=", "nodes", ".", "reference", "(", "text", "=", "ticket_id", ",", "refuri", "=", "ref", ",", "*", "*", "options", ")", "return", "link" ]
Construct a reference node for a JIRA ticket.
[ "Construct", "a", "reference", "node", "for", "a", "JIRA", "ticket", "." ]
75f02901a80042b28d074df1cc1dca32eb8e38c8
https://github.com/lsst-sqre/documenteer/blob/75f02901a80042b28d074df1cc1dca32eb8e38c8/documenteer/sphinxext/jira.py#L16-L21
train
lsst-sqre/documenteer
documenteer/sphinxext/jira.py
_oxford_comma_separator
def _oxford_comma_separator(i, length): """Make a separator for a prose-like list with `,` between items except for `, and` after the second to last item. """ if length == 1: return None elif length < 3 and i == 0: return ' and ' elif i < length - 2: return ', ' elif i == length - 2: return ', and ' else: return None
python
def _oxford_comma_separator(i, length): """Make a separator for a prose-like list with `,` between items except for `, and` after the second to last item. """ if length == 1: return None elif length < 3 and i == 0: return ' and ' elif i < length - 2: return ', ' elif i == length - 2: return ', and ' else: return None
[ "def", "_oxford_comma_separator", "(", "i", ",", "length", ")", ":", "if", "length", "==", "1", ":", "return", "None", "elif", "length", "<", "3", "and", "i", "==", "0", ":", "return", "' and '", "elif", "i", "<", "length", "-", "2", ":", "return", "', '", "elif", "i", "==", "length", "-", "2", ":", "return", "', and '", "else", ":", "return", "None" ]
Make a separator for a prose-like list with `,` between items except for `, and` after the second to last item.
[ "Make", "a", "separator", "for", "a", "prose", "-", "like", "list", "with", "between", "items", "except", "for", "and", "after", "the", "second", "to", "last", "item", "." ]
75f02901a80042b28d074df1cc1dca32eb8e38c8
https://github.com/lsst-sqre/documenteer/blob/75f02901a80042b28d074df1cc1dca32eb8e38c8/documenteer/sphinxext/jira.py#L37-L50
train
lsst-sqre/documenteer
documenteer/sphinxext/jira.py
jira_role
def jira_role(name, rawtext, text, lineno, inliner, options=None, content=None, oxford_comma=True): """Sphinx role for referencing a JIRA ticket. Examples:: :jira:`DM-6181` -> DM-6181 :jira:`DM-6181,DM-6181` -> DM-6180 and DM-6181 :jira:`DM-6181,DM-6181,DM-6182` -> DM-6180, DM-6181, and DM-6182 """ options = options or {} content = content or [] config = inliner.document.settings.env.app.config ticket_ids = [each.strip() for each in utils.unescape(text).split(',')] n_tickets = len(ticket_ids) if oxford_comma: sep_factory = _oxford_comma_separator else: sep_factory = _comma_separator node_list = [] for i, ticket_id in enumerate(ticket_ids): node = _make_ticket_node(ticket_id, config, options=options) node_list.append(node) sep_text = sep_factory(i, n_tickets) if sep_text is not None: sep = nodes.raw(text=sep_text, format='html') node_list.append(sep) return node_list, []
python
def jira_role(name, rawtext, text, lineno, inliner, options=None, content=None, oxford_comma=True): """Sphinx role for referencing a JIRA ticket. Examples:: :jira:`DM-6181` -> DM-6181 :jira:`DM-6181,DM-6181` -> DM-6180 and DM-6181 :jira:`DM-6181,DM-6181,DM-6182` -> DM-6180, DM-6181, and DM-6182 """ options = options or {} content = content or [] config = inliner.document.settings.env.app.config ticket_ids = [each.strip() for each in utils.unescape(text).split(',')] n_tickets = len(ticket_ids) if oxford_comma: sep_factory = _oxford_comma_separator else: sep_factory = _comma_separator node_list = [] for i, ticket_id in enumerate(ticket_ids): node = _make_ticket_node(ticket_id, config, options=options) node_list.append(node) sep_text = sep_factory(i, n_tickets) if sep_text is not None: sep = nodes.raw(text=sep_text, format='html') node_list.append(sep) return node_list, []
[ "def", "jira_role", "(", "name", ",", "rawtext", ",", "text", ",", "lineno", ",", "inliner", ",", "options", "=", "None", ",", "content", "=", "None", ",", "oxford_comma", "=", "True", ")", ":", "options", "=", "options", "or", "{", "}", "content", "=", "content", "or", "[", "]", "config", "=", "inliner", ".", "document", ".", "settings", ".", "env", ".", "app", ".", "config", "ticket_ids", "=", "[", "each", ".", "strip", "(", ")", "for", "each", "in", "utils", ".", "unescape", "(", "text", ")", ".", "split", "(", "','", ")", "]", "n_tickets", "=", "len", "(", "ticket_ids", ")", "if", "oxford_comma", ":", "sep_factory", "=", "_oxford_comma_separator", "else", ":", "sep_factory", "=", "_comma_separator", "node_list", "=", "[", "]", "for", "i", ",", "ticket_id", "in", "enumerate", "(", "ticket_ids", ")", ":", "node", "=", "_make_ticket_node", "(", "ticket_id", ",", "config", ",", "options", "=", "options", ")", "node_list", ".", "append", "(", "node", ")", "sep_text", "=", "sep_factory", "(", "i", ",", "n_tickets", ")", "if", "sep_text", "is", "not", "None", ":", "sep", "=", "nodes", ".", "raw", "(", "text", "=", "sep_text", ",", "format", "=", "'html'", ")", "node_list", ".", "append", "(", "sep", ")", "return", "node_list", ",", "[", "]" ]
Sphinx role for referencing a JIRA ticket. Examples:: :jira:`DM-6181` -> DM-6181 :jira:`DM-6181,DM-6181` -> DM-6180 and DM-6181 :jira:`DM-6181,DM-6181,DM-6182` -> DM-6180, DM-6181, and DM-6182
[ "Sphinx", "role", "for", "referencing", "a", "JIRA", "ticket", "." ]
75f02901a80042b28d074df1cc1dca32eb8e38c8
https://github.com/lsst-sqre/documenteer/blob/75f02901a80042b28d074df1cc1dca32eb8e38c8/documenteer/sphinxext/jira.py#L53-L83
train
lsst-sqre/documenteer
documenteer/sphinxext/jira.py
jira_bracket_role
def jira_bracket_role(name, rawtext, text, lineno, inliner, options=None, content=None, open_symbol='[', close_symbol=']'): """Sphinx role for referencing a JIRA ticket with ticket numbers enclosed in braces. Useful for changelogs. Examples:: :jirab:`DM-6181` -> [DM-6181] :jirab:`DM-6181,DM-6181` -> [DM-6180, DM-6181] :jirab:`DM-6181,DM-6181,DM-6182` -> [DM-6180, DM-6181, DM-6182] """ node_list, _ = jira_role(name, rawtext, text, lineno, inliner, options=options, content=None, oxford_comma=False) node_list = nodes.raw(text=open_symbol, format='html') \ + node_list + nodes.raw(text=close_symbol, format='html') return node_list, []
python
def jira_bracket_role(name, rawtext, text, lineno, inliner, options=None, content=None, open_symbol='[', close_symbol=']'): """Sphinx role for referencing a JIRA ticket with ticket numbers enclosed in braces. Useful for changelogs. Examples:: :jirab:`DM-6181` -> [DM-6181] :jirab:`DM-6181,DM-6181` -> [DM-6180, DM-6181] :jirab:`DM-6181,DM-6181,DM-6182` -> [DM-6180, DM-6181, DM-6182] """ node_list, _ = jira_role(name, rawtext, text, lineno, inliner, options=options, content=None, oxford_comma=False) node_list = nodes.raw(text=open_symbol, format='html') \ + node_list + nodes.raw(text=close_symbol, format='html') return node_list, []
[ "def", "jira_bracket_role", "(", "name", ",", "rawtext", ",", "text", ",", "lineno", ",", "inliner", ",", "options", "=", "None", ",", "content", "=", "None", ",", "open_symbol", "=", "'['", ",", "close_symbol", "=", "']'", ")", ":", "node_list", ",", "_", "=", "jira_role", "(", "name", ",", "rawtext", ",", "text", ",", "lineno", ",", "inliner", ",", "options", "=", "options", ",", "content", "=", "None", ",", "oxford_comma", "=", "False", ")", "node_list", "=", "nodes", ".", "raw", "(", "text", "=", "open_symbol", ",", "format", "=", "'html'", ")", "+", "node_list", "+", "nodes", ".", "raw", "(", "text", "=", "close_symbol", ",", "format", "=", "'html'", ")", "return", "node_list", ",", "[", "]" ]
Sphinx role for referencing a JIRA ticket with ticket numbers enclosed in braces. Useful for changelogs. Examples:: :jirab:`DM-6181` -> [DM-6181] :jirab:`DM-6181,DM-6181` -> [DM-6180, DM-6181] :jirab:`DM-6181,DM-6181,DM-6182` -> [DM-6180, DM-6181, DM-6182]
[ "Sphinx", "role", "for", "referencing", "a", "JIRA", "ticket", "with", "ticket", "numbers", "enclosed", "in", "braces", ".", "Useful", "for", "changelogs", "." ]
75f02901a80042b28d074df1cc1dca32eb8e38c8
https://github.com/lsst-sqre/documenteer/blob/75f02901a80042b28d074df1cc1dca32eb8e38c8/documenteer/sphinxext/jira.py#L86-L102
train
lsst-sqre/documenteer
documenteer/sphinxext/jira.py
jira_parens_role
def jira_parens_role(name, rawtext, text, lineno, inliner, options=None, content=None): """Sphinx role for referencing a JIRA ticket with ticket numbers enclosed in parentheses. Useful for changelogs. Examples:: :jirap:`DM-6181` -> (DM-6181) :jirap:`DM-6181,DM-6181` -> (DM-6180, DM-6181) :jirap:`DM-6181,DM-6181,DM-6182` -> (DM-6180, DM-6181, DM-6182) """ return jira_bracket_role(name, rawtext, text, lineno, inliner, options=None, content=None, open_symbol='(', close_symbol=')')
python
def jira_parens_role(name, rawtext, text, lineno, inliner, options=None, content=None): """Sphinx role for referencing a JIRA ticket with ticket numbers enclosed in parentheses. Useful for changelogs. Examples:: :jirap:`DM-6181` -> (DM-6181) :jirap:`DM-6181,DM-6181` -> (DM-6180, DM-6181) :jirap:`DM-6181,DM-6181,DM-6182` -> (DM-6180, DM-6181, DM-6182) """ return jira_bracket_role(name, rawtext, text, lineno, inliner, options=None, content=None, open_symbol='(', close_symbol=')')
[ "def", "jira_parens_role", "(", "name", ",", "rawtext", ",", "text", ",", "lineno", ",", "inliner", ",", "options", "=", "None", ",", "content", "=", "None", ")", ":", "return", "jira_bracket_role", "(", "name", ",", "rawtext", ",", "text", ",", "lineno", ",", "inliner", ",", "options", "=", "None", ",", "content", "=", "None", ",", "open_symbol", "=", "'('", ",", "close_symbol", "=", "')'", ")" ]
Sphinx role for referencing a JIRA ticket with ticket numbers enclosed in parentheses. Useful for changelogs. Examples:: :jirap:`DM-6181` -> (DM-6181) :jirap:`DM-6181,DM-6181` -> (DM-6180, DM-6181) :jirap:`DM-6181,DM-6181,DM-6182` -> (DM-6180, DM-6181, DM-6182)
[ "Sphinx", "role", "for", "referencing", "a", "JIRA", "ticket", "with", "ticket", "numbers", "enclosed", "in", "parentheses", ".", "Useful", "for", "changelogs", "." ]
75f02901a80042b28d074df1cc1dca32eb8e38c8
https://github.com/lsst-sqre/documenteer/blob/75f02901a80042b28d074df1cc1dca32eb8e38c8/documenteer/sphinxext/jira.py#L105-L118
train
ffcalculator/fantasydata-python
fantasy_data/FantasyData.py
FantasyDataBase._method_call
def _method_call(self, method, category, **kwargs): """ Call API method. Generate request. Parse response. Process errors `method` str API method url for request. Contains parameters `params` dict parameters for method url """ session = requests.Session() try: response = session.get("http://" + self._api_address) except requests.exceptions.ConnectionError: raise FantasyDataError('Error: Cannot connect to the FantasyData API') method = method.format(format=self._response_format, **kwargs) request_url = "/v3/{game_type}/{category}/{format}/{method}?{get_params}".format( game_type=self.game_type, category=category, format=self._response_format, method=method, get_params=self._get_params) response = session.get(self._api_schema + self._api_address + request_url, headers=self._headers) result = response.json() if isinstance(result, dict) and response.status_code: if response.status_code == 401: raise FantasyDataError('Error: Invalid API key') elif response.status_code == 200: # for NBA everything is ok here. pass else: raise FantasyDataError('Error: Failed to get response') return result
python
def _method_call(self, method, category, **kwargs): """ Call API method. Generate request. Parse response. Process errors `method` str API method url for request. Contains parameters `params` dict parameters for method url """ session = requests.Session() try: response = session.get("http://" + self._api_address) except requests.exceptions.ConnectionError: raise FantasyDataError('Error: Cannot connect to the FantasyData API') method = method.format(format=self._response_format, **kwargs) request_url = "/v3/{game_type}/{category}/{format}/{method}?{get_params}".format( game_type=self.game_type, category=category, format=self._response_format, method=method, get_params=self._get_params) response = session.get(self._api_schema + self._api_address + request_url, headers=self._headers) result = response.json() if isinstance(result, dict) and response.status_code: if response.status_code == 401: raise FantasyDataError('Error: Invalid API key') elif response.status_code == 200: # for NBA everything is ok here. pass else: raise FantasyDataError('Error: Failed to get response') return result
[ "def", "_method_call", "(", "self", ",", "method", ",", "category", ",", "*", "*", "kwargs", ")", ":", "session", "=", "requests", ".", "Session", "(", ")", "try", ":", "response", "=", "session", ".", "get", "(", "\"http://\"", "+", "self", ".", "_api_address", ")", "except", "requests", ".", "exceptions", ".", "ConnectionError", ":", "raise", "FantasyDataError", "(", "'Error: Cannot connect to the FantasyData API'", ")", "method", "=", "method", ".", "format", "(", "format", "=", "self", ".", "_response_format", ",", "*", "*", "kwargs", ")", "request_url", "=", "\"/v3/{game_type}/{category}/{format}/{method}?{get_params}\"", ".", "format", "(", "game_type", "=", "self", ".", "game_type", ",", "category", "=", "category", ",", "format", "=", "self", ".", "_response_format", ",", "method", "=", "method", ",", "get_params", "=", "self", ".", "_get_params", ")", "response", "=", "session", ".", "get", "(", "self", ".", "_api_schema", "+", "self", ".", "_api_address", "+", "request_url", ",", "headers", "=", "self", ".", "_headers", ")", "result", "=", "response", ".", "json", "(", ")", "if", "isinstance", "(", "result", ",", "dict", ")", "and", "response", ".", "status_code", ":", "if", "response", ".", "status_code", "==", "401", ":", "raise", "FantasyDataError", "(", "'Error: Invalid API key'", ")", "elif", "response", ".", "status_code", "==", "200", ":", "# for NBA everything is ok here.", "pass", "else", ":", "raise", "FantasyDataError", "(", "'Error: Failed to get response'", ")", "return", "result" ]
Call API method. Generate request. Parse response. Process errors `method` str API method url for request. Contains parameters `params` dict parameters for method url
[ "Call", "API", "method", ".", "Generate", "request", ".", "Parse", "response", ".", "Process", "errors", "method", "str", "API", "method", "url", "for", "request", ".", "Contains", "parameters", "params", "dict", "parameters", "for", "method", "url" ]
af90cac1e80d8356cffaa80621ee513201f6c661
https://github.com/ffcalculator/fantasydata-python/blob/af90cac1e80d8356cffaa80621ee513201f6c661/fantasy_data/FantasyData.py#L38-L70
train
ffcalculator/fantasydata-python
fantasy_data/FantasyData.py
FantasyData.get_projected_player_game_stats_by_player
def get_projected_player_game_stats_by_player(self, season, week, player_id): """ Projected Player Game Stats by Player """ result = self._method_call("PlayerGameProjectionStatsByPlayerID/{season}/{week}/{player_id}", "projections", season=season, week=week, player_id=player_id) return result
python
def get_projected_player_game_stats_by_player(self, season, week, player_id): """ Projected Player Game Stats by Player """ result = self._method_call("PlayerGameProjectionStatsByPlayerID/{season}/{week}/{player_id}", "projections", season=season, week=week, player_id=player_id) return result
[ "def", "get_projected_player_game_stats_by_player", "(", "self", ",", "season", ",", "week", ",", "player_id", ")", ":", "result", "=", "self", ".", "_method_call", "(", "\"PlayerGameProjectionStatsByPlayerID/{season}/{week}/{player_id}\"", ",", "\"projections\"", ",", "season", "=", "season", ",", "week", "=", "week", ",", "player_id", "=", "player_id", ")", "return", "result" ]
Projected Player Game Stats by Player
[ "Projected", "Player", "Game", "Stats", "by", "Player" ]
af90cac1e80d8356cffaa80621ee513201f6c661
https://github.com/ffcalculator/fantasydata-python/blob/af90cac1e80d8356cffaa80621ee513201f6c661/fantasy_data/FantasyData.py#L161-L166
train
ffcalculator/fantasydata-python
fantasy_data/FantasyData.py
FantasyData.get_projected_player_game_stats_by_team
def get_projected_player_game_stats_by_team(self, season, week, team_id): """ Projected Player Game Stats by Team """ result = self._method_call("PlayerGameProjectionStatsByTeam/{season}/{week}/{team_id}", "projections", season=season, week=week, team_id=team_id) return result
python
def get_projected_player_game_stats_by_team(self, season, week, team_id): """ Projected Player Game Stats by Team """ result = self._method_call("PlayerGameProjectionStatsByTeam/{season}/{week}/{team_id}", "projections", season=season, week=week, team_id=team_id) return result
[ "def", "get_projected_player_game_stats_by_team", "(", "self", ",", "season", ",", "week", ",", "team_id", ")", ":", "result", "=", "self", ".", "_method_call", "(", "\"PlayerGameProjectionStatsByTeam/{season}/{week}/{team_id}\"", ",", "\"projections\"", ",", "season", "=", "season", ",", "week", "=", "week", ",", "team_id", "=", "team_id", ")", "return", "result" ]
Projected Player Game Stats by Team
[ "Projected", "Player", "Game", "Stats", "by", "Team" ]
af90cac1e80d8356cffaa80621ee513201f6c661
https://github.com/ffcalculator/fantasydata-python/blob/af90cac1e80d8356cffaa80621ee513201f6c661/fantasy_data/FantasyData.py#L168-L173
train
ffcalculator/fantasydata-python
fantasy_data/FantasyData.py
FantasyData.get_projected_player_game_stats_by_week
def get_projected_player_game_stats_by_week(self, season, week): """ Projected Player Game Stats by Week """ result = self._method_call("PlayerGameProjectionStatsByWeek/{season}/{week}", "projections", season=season, week=week) return result
python
def get_projected_player_game_stats_by_week(self, season, week): """ Projected Player Game Stats by Week """ result = self._method_call("PlayerGameProjectionStatsByWeek/{season}/{week}", "projections", season=season, week=week) return result
[ "def", "get_projected_player_game_stats_by_week", "(", "self", ",", "season", ",", "week", ")", ":", "result", "=", "self", ".", "_method_call", "(", "\"PlayerGameProjectionStatsByWeek/{season}/{week}\"", ",", "\"projections\"", ",", "season", "=", "season", ",", "week", "=", "week", ")", "return", "result" ]
Projected Player Game Stats by Week
[ "Projected", "Player", "Game", "Stats", "by", "Week" ]
af90cac1e80d8356cffaa80621ee513201f6c661
https://github.com/ffcalculator/fantasydata-python/blob/af90cac1e80d8356cffaa80621ee513201f6c661/fantasy_data/FantasyData.py#L175-L180
train
ffcalculator/fantasydata-python
fantasy_data/FantasyData.py
FantasyData.get_projected_fantasy_defense_game_stats_by_week
def get_projected_fantasy_defense_game_stats_by_week(self, season, week): """ Projected Fantasy Defense Game Stats by Week """ result = self._method_call("FantasyDefenseProjectionsByGame/{season}/{week}", "projections", season=season, week=week) return result
python
def get_projected_fantasy_defense_game_stats_by_week(self, season, week): """ Projected Fantasy Defense Game Stats by Week """ result = self._method_call("FantasyDefenseProjectionsByGame/{season}/{week}", "projections", season=season, week=week) return result
[ "def", "get_projected_fantasy_defense_game_stats_by_week", "(", "self", ",", "season", ",", "week", ")", ":", "result", "=", "self", ".", "_method_call", "(", "\"FantasyDefenseProjectionsByGame/{season}/{week}\"", ",", "\"projections\"", ",", "season", "=", "season", ",", "week", "=", "week", ")", "return", "result" ]
Projected Fantasy Defense Game Stats by Week
[ "Projected", "Fantasy", "Defense", "Game", "Stats", "by", "Week" ]
af90cac1e80d8356cffaa80621ee513201f6c661
https://github.com/ffcalculator/fantasydata-python/blob/af90cac1e80d8356cffaa80621ee513201f6c661/fantasy_data/FantasyData.py#L182-L187
train
ffcalculator/fantasydata-python
fantasy_data/FantasyData.py
FantasyData.get_injuries
def get_injuries(self, season, week): """ Injuries by week """ result = self._method_call("Injuries/{season}/{week}", "stats", season=season, week=week) return result
python
def get_injuries(self, season, week): """ Injuries by week """ result = self._method_call("Injuries/{season}/{week}", "stats", season=season, week=week) return result
[ "def", "get_injuries", "(", "self", ",", "season", ",", "week", ")", ":", "result", "=", "self", ".", "_method_call", "(", "\"Injuries/{season}/{week}\"", ",", "\"stats\"", ",", "season", "=", "season", ",", "week", "=", "week", ")", "return", "result" ]
Injuries by week
[ "Injuries", "by", "week" ]
af90cac1e80d8356cffaa80621ee513201f6c661
https://github.com/ffcalculator/fantasydata-python/blob/af90cac1e80d8356cffaa80621ee513201f6c661/fantasy_data/FantasyData.py#L232-L237
train
ffcalculator/fantasydata-python
fantasy_data/FantasyData.py
FantasyData.get_injuries_by_team
def get_injuries_by_team(self, season, week, team_id): """ Injuries by week and team """ result = self._method_call("Injuries/{season}/{week}/{team_id}", "stats", season=season, week=week, team_id=team_id) return result
python
def get_injuries_by_team(self, season, week, team_id): """ Injuries by week and team """ result = self._method_call("Injuries/{season}/{week}/{team_id}", "stats", season=season, week=week, team_id=team_id) return result
[ "def", "get_injuries_by_team", "(", "self", ",", "season", ",", "week", ",", "team_id", ")", ":", "result", "=", "self", ".", "_method_call", "(", "\"Injuries/{season}/{week}/{team_id}\"", ",", "\"stats\"", ",", "season", "=", "season", ",", "week", "=", "week", ",", "team_id", "=", "team_id", ")", "return", "result" ]
Injuries by week and team
[ "Injuries", "by", "week", "and", "team" ]
af90cac1e80d8356cffaa80621ee513201f6c661
https://github.com/ffcalculator/fantasydata-python/blob/af90cac1e80d8356cffaa80621ee513201f6c661/fantasy_data/FantasyData.py#L239-L244
train
ffcalculator/fantasydata-python
fantasy_data/FantasyData.py
FantasyData.get_box_score_by_team
def get_box_score_by_team(self, season, week, team_id): """ Box score by week and team """ result = self._method_call("BoxScoreV3/{season}/{week}/{team_id}", "stats", season=season, week=week, team_id=team_id) return result
python
def get_box_score_by_team(self, season, week, team_id): """ Box score by week and team """ result = self._method_call("BoxScoreV3/{season}/{week}/{team_id}", "stats", season=season, week=week, team_id=team_id) return result
[ "def", "get_box_score_by_team", "(", "self", ",", "season", ",", "week", ",", "team_id", ")", ":", "result", "=", "self", ".", "_method_call", "(", "\"BoxScoreV3/{season}/{week}/{team_id}\"", ",", "\"stats\"", ",", "season", "=", "season", ",", "week", "=", "week", ",", "team_id", "=", "team_id", ")", "return", "result" ]
Box score by week and team
[ "Box", "score", "by", "week", "and", "team" ]
af90cac1e80d8356cffaa80621ee513201f6c661
https://github.com/ffcalculator/fantasydata-python/blob/af90cac1e80d8356cffaa80621ee513201f6c661/fantasy_data/FantasyData.py#L246-L251
train
DheerendraRathor/django-auth-ldap-ng
django_auth_ldap/backend.py
_LDAPUser.authenticate
def authenticate(self, password): """ Authenticates against the LDAP directory and returns the corresponding User object if successful. Returns None on failure. """ user = None try: self._authenticate_user_dn(password) self._check_requirements() self._get_or_create_user() user = self._user except self.AuthenticationFailed as e: logger.debug(u"Authentication failed for %s: %s" % (self._username, e)) except ldap.LDAPError as e: results = ldap_error.send(self.backend.__class__, context='authenticate', exception=e) if len(results) == 0: logger.warning(u"Caught LDAPError while authenticating %s: %s", self._username, pprint.pformat(e)) except Exception: logger.exception(u"Caught Exception while authenticating %s", self._username) raise return user
python
def authenticate(self, password): """ Authenticates against the LDAP directory and returns the corresponding User object if successful. Returns None on failure. """ user = None try: self._authenticate_user_dn(password) self._check_requirements() self._get_or_create_user() user = self._user except self.AuthenticationFailed as e: logger.debug(u"Authentication failed for %s: %s" % (self._username, e)) except ldap.LDAPError as e: results = ldap_error.send(self.backend.__class__, context='authenticate', exception=e) if len(results) == 0: logger.warning(u"Caught LDAPError while authenticating %s: %s", self._username, pprint.pformat(e)) except Exception: logger.exception(u"Caught Exception while authenticating %s", self._username) raise return user
[ "def", "authenticate", "(", "self", ",", "password", ")", ":", "user", "=", "None", "try", ":", "self", ".", "_authenticate_user_dn", "(", "password", ")", "self", ".", "_check_requirements", "(", ")", "self", ".", "_get_or_create_user", "(", ")", "user", "=", "self", ".", "_user", "except", "self", ".", "AuthenticationFailed", "as", "e", ":", "logger", ".", "debug", "(", "u\"Authentication failed for %s: %s\"", "%", "(", "self", ".", "_username", ",", "e", ")", ")", "except", "ldap", ".", "LDAPError", "as", "e", ":", "results", "=", "ldap_error", ".", "send", "(", "self", ".", "backend", ".", "__class__", ",", "context", "=", "'authenticate'", ",", "exception", "=", "e", ")", "if", "len", "(", "results", ")", "==", "0", ":", "logger", ".", "warning", "(", "u\"Caught LDAPError while authenticating %s: %s\"", ",", "self", ".", "_username", ",", "pprint", ".", "pformat", "(", "e", ")", ")", "except", "Exception", ":", "logger", ".", "exception", "(", "u\"Caught Exception while authenticating %s\"", ",", "self", ".", "_username", ")", "raise", "return", "user" ]
Authenticates against the LDAP directory and returns the corresponding User object if successful. Returns None on failure.
[ "Authenticates", "against", "the", "LDAP", "directory", "and", "returns", "the", "corresponding", "User", "object", "if", "successful", ".", "Returns", "None", "on", "failure", "." ]
4d2458bd90c4539353c5bfd5ea793c1e59780ee8
https://github.com/DheerendraRathor/django-auth-ldap-ng/blob/4d2458bd90c4539353c5bfd5ea793c1e59780ee8/django_auth_ldap/backend.py#L325-L351
train
DheerendraRathor/django-auth-ldap-ng
django_auth_ldap/backend.py
_LDAPUser.get_group_permissions
def get_group_permissions(self): """ If allowed by the configuration, this returns the set of permissions defined by the user's LDAP group memberships. """ if self._group_permissions is None: self._group_permissions = set() if self.settings.FIND_GROUP_PERMS: try: self._load_group_permissions() except ldap.LDAPError as e: results = ldap_error.send(self.backend.__class__, context='get_group_permissions', exception=e) if len(results) == 0: logger.warning("Caught LDAPError loading group permissions: %s", pprint.pformat(e)) return self._group_permissions
python
def get_group_permissions(self): """ If allowed by the configuration, this returns the set of permissions defined by the user's LDAP group memberships. """ if self._group_permissions is None: self._group_permissions = set() if self.settings.FIND_GROUP_PERMS: try: self._load_group_permissions() except ldap.LDAPError as e: results = ldap_error.send(self.backend.__class__, context='get_group_permissions', exception=e) if len(results) == 0: logger.warning("Caught LDAPError loading group permissions: %s", pprint.pformat(e)) return self._group_permissions
[ "def", "get_group_permissions", "(", "self", ")", ":", "if", "self", ".", "_group_permissions", "is", "None", ":", "self", ".", "_group_permissions", "=", "set", "(", ")", "if", "self", ".", "settings", ".", "FIND_GROUP_PERMS", ":", "try", ":", "self", ".", "_load_group_permissions", "(", ")", "except", "ldap", ".", "LDAPError", "as", "e", ":", "results", "=", "ldap_error", ".", "send", "(", "self", ".", "backend", ".", "__class__", ",", "context", "=", "'get_group_permissions'", ",", "exception", "=", "e", ")", "if", "len", "(", "results", ")", "==", "0", ":", "logger", ".", "warning", "(", "\"Caught LDAPError loading group permissions: %s\"", ",", "pprint", ".", "pformat", "(", "e", ")", ")", "return", "self", ".", "_group_permissions" ]
If allowed by the configuration, this returns the set of permissions defined by the user's LDAP group memberships.
[ "If", "allowed", "by", "the", "configuration", "this", "returns", "the", "set", "of", "permissions", "defined", "by", "the", "user", "s", "LDAP", "group", "memberships", "." ]
4d2458bd90c4539353c5bfd5ea793c1e59780ee8
https://github.com/DheerendraRathor/django-auth-ldap-ng/blob/4d2458bd90c4539353c5bfd5ea793c1e59780ee8/django_auth_ldap/backend.py#L353-L372
train
DheerendraRathor/django-auth-ldap-ng
django_auth_ldap/backend.py
_LDAPUser._populate_user
def _populate_user(self): """ Populates our User object with information from the LDAP directory. """ self._populate_user_from_attributes() self._populate_user_from_group_memberships() self._populate_user_from_dn_regex() self._populate_user_from_dn_regex_negation()
python
def _populate_user(self): """ Populates our User object with information from the LDAP directory. """ self._populate_user_from_attributes() self._populate_user_from_group_memberships() self._populate_user_from_dn_regex() self._populate_user_from_dn_regex_negation()
[ "def", "_populate_user", "(", "self", ")", ":", "self", ".", "_populate_user_from_attributes", "(", ")", "self", ".", "_populate_user_from_group_memberships", "(", ")", "self", ".", "_populate_user_from_dn_regex", "(", ")", "self", ".", "_populate_user_from_dn_regex_negation", "(", ")" ]
Populates our User object with information from the LDAP directory.
[ "Populates", "our", "User", "object", "with", "information", "from", "the", "LDAP", "directory", "." ]
4d2458bd90c4539353c5bfd5ea793c1e59780ee8
https://github.com/DheerendraRathor/django-auth-ldap-ng/blob/4d2458bd90c4539353c5bfd5ea793c1e59780ee8/django_auth_ldap/backend.py#L584-L591
train
DheerendraRathor/django-auth-ldap-ng
django_auth_ldap/backend.py
_LDAPUser._populate_and_save_user_profile
def _populate_and_save_user_profile(self): """ Populates a User profile object with fields from the LDAP directory. """ try: app_label, class_name = django.conf.settings.AUTH_PROFILE_MODULE.split('.') profile_model = apps.get_model(app_label, class_name) profile, created = profile_model.objects.get_or_create(user=self._user) save_profile = False logger.debug("Populating Django user profile for %s", get_user_username(self._user)) save_profile = self._populate_profile_from_attributes(profile) or save_profile save_profile = self._populate_profile_flags_from_dn_regex(profile) or save_profile save_profile = self._populate_profile_from_group_memberships(profile) or save_profile signal_responses = populate_user_profile.send(self.backend.__class__, profile=profile, ldap_user=self) if len(signal_responses) > 0: save_profile = True if save_profile: profile.save() except ObjectDoesNotExist: logger.debug("Django user %s does not have a profile to populate", get_user_username(self._user)) except LookupError: logger.debug('User Profile model defined in settings.AUTH_PROFILE_MODULE is invalid')
python
def _populate_and_save_user_profile(self): """ Populates a User profile object with fields from the LDAP directory. """ try: app_label, class_name = django.conf.settings.AUTH_PROFILE_MODULE.split('.') profile_model = apps.get_model(app_label, class_name) profile, created = profile_model.objects.get_or_create(user=self._user) save_profile = False logger.debug("Populating Django user profile for %s", get_user_username(self._user)) save_profile = self._populate_profile_from_attributes(profile) or save_profile save_profile = self._populate_profile_flags_from_dn_regex(profile) or save_profile save_profile = self._populate_profile_from_group_memberships(profile) or save_profile signal_responses = populate_user_profile.send(self.backend.__class__, profile=profile, ldap_user=self) if len(signal_responses) > 0: save_profile = True if save_profile: profile.save() except ObjectDoesNotExist: logger.debug("Django user %s does not have a profile to populate", get_user_username(self._user)) except LookupError: logger.debug('User Profile model defined in settings.AUTH_PROFILE_MODULE is invalid')
[ "def", "_populate_and_save_user_profile", "(", "self", ")", ":", "try", ":", "app_label", ",", "class_name", "=", "django", ".", "conf", ".", "settings", ".", "AUTH_PROFILE_MODULE", ".", "split", "(", "'.'", ")", "profile_model", "=", "apps", ".", "get_model", "(", "app_label", ",", "class_name", ")", "profile", ",", "created", "=", "profile_model", ".", "objects", ".", "get_or_create", "(", "user", "=", "self", ".", "_user", ")", "save_profile", "=", "False", "logger", ".", "debug", "(", "\"Populating Django user profile for %s\"", ",", "get_user_username", "(", "self", ".", "_user", ")", ")", "save_profile", "=", "self", ".", "_populate_profile_from_attributes", "(", "profile", ")", "or", "save_profile", "save_profile", "=", "self", ".", "_populate_profile_flags_from_dn_regex", "(", "profile", ")", "or", "save_profile", "save_profile", "=", "self", ".", "_populate_profile_from_group_memberships", "(", "profile", ")", "or", "save_profile", "signal_responses", "=", "populate_user_profile", ".", "send", "(", "self", ".", "backend", ".", "__class__", ",", "profile", "=", "profile", ",", "ldap_user", "=", "self", ")", "if", "len", "(", "signal_responses", ")", ">", "0", ":", "save_profile", "=", "True", "if", "save_profile", ":", "profile", ".", "save", "(", ")", "except", "ObjectDoesNotExist", ":", "logger", ".", "debug", "(", "\"Django user %s does not have a profile to populate\"", ",", "get_user_username", "(", "self", ".", "_user", ")", ")", "except", "LookupError", ":", "logger", ".", "debug", "(", "'User Profile model defined in settings.AUTH_PROFILE_MODULE is invalid'", ")" ]
Populates a User profile object with fields from the LDAP directory.
[ "Populates", "a", "User", "profile", "object", "with", "fields", "from", "the", "LDAP", "directory", "." ]
4d2458bd90c4539353c5bfd5ea793c1e59780ee8
https://github.com/DheerendraRathor/django-auth-ldap-ng/blob/4d2458bd90c4539353c5bfd5ea793c1e59780ee8/django_auth_ldap/backend.py#L633-L658
train
DheerendraRathor/django-auth-ldap-ng
django_auth_ldap/backend.py
_LDAPUser._populate_profile_from_attributes
def _populate_profile_from_attributes(self, profile): """ Populate the given profile object from AUTH_LDAP_PROFILE_ATTR_MAP. Returns True if the profile was modified. """ save_profile = False for field, attr in self.settings.PROFILE_ATTR_MAP.items(): try: # user_attrs is a hash of lists of attribute values setattr(profile, field, self.attrs[attr][0]) save_profile = True except Exception: logger.warning("%s does not have a value for the attribute %s", self.dn, attr) return save_profile
python
def _populate_profile_from_attributes(self, profile): """ Populate the given profile object from AUTH_LDAP_PROFILE_ATTR_MAP. Returns True if the profile was modified. """ save_profile = False for field, attr in self.settings.PROFILE_ATTR_MAP.items(): try: # user_attrs is a hash of lists of attribute values setattr(profile, field, self.attrs[attr][0]) save_profile = True except Exception: logger.warning("%s does not have a value for the attribute %s", self.dn, attr) return save_profile
[ "def", "_populate_profile_from_attributes", "(", "self", ",", "profile", ")", ":", "save_profile", "=", "False", "for", "field", ",", "attr", "in", "self", ".", "settings", ".", "PROFILE_ATTR_MAP", ".", "items", "(", ")", ":", "try", ":", "# user_attrs is a hash of lists of attribute values", "setattr", "(", "profile", ",", "field", ",", "self", ".", "attrs", "[", "attr", "]", "[", "0", "]", ")", "save_profile", "=", "True", "except", "Exception", ":", "logger", ".", "warning", "(", "\"%s does not have a value for the attribute %s\"", ",", "self", ".", "dn", ",", "attr", ")", "return", "save_profile" ]
Populate the given profile object from AUTH_LDAP_PROFILE_ATTR_MAP. Returns True if the profile was modified.
[ "Populate", "the", "given", "profile", "object", "from", "AUTH_LDAP_PROFILE_ATTR_MAP", ".", "Returns", "True", "if", "the", "profile", "was", "modified", "." ]
4d2458bd90c4539353c5bfd5ea793c1e59780ee8
https://github.com/DheerendraRathor/django-auth-ldap-ng/blob/4d2458bd90c4539353c5bfd5ea793c1e59780ee8/django_auth_ldap/backend.py#L660-L675
train
DheerendraRathor/django-auth-ldap-ng
django_auth_ldap/backend.py
_LDAPUser._populate_profile_from_group_memberships
def _populate_profile_from_group_memberships(self, profile): """ Populate the given profile object from AUTH_LDAP_PROFILE_FLAGS_BY_GROUP. Returns True if the profile was modified. """ save_profile = False for field, group_dns in self.settings.PROFILE_FLAGS_BY_GROUP.items(): if isinstance(group_dns, six.string_types): group_dns = [group_dns] value = any(self._get_groups().is_member_of(dn) for dn in group_dns) setattr(profile, field, value) save_profile = True return save_profile
python
def _populate_profile_from_group_memberships(self, profile): """ Populate the given profile object from AUTH_LDAP_PROFILE_FLAGS_BY_GROUP. Returns True if the profile was modified. """ save_profile = False for field, group_dns in self.settings.PROFILE_FLAGS_BY_GROUP.items(): if isinstance(group_dns, six.string_types): group_dns = [group_dns] value = any(self._get_groups().is_member_of(dn) for dn in group_dns) setattr(profile, field, value) save_profile = True return save_profile
[ "def", "_populate_profile_from_group_memberships", "(", "self", ",", "profile", ")", ":", "save_profile", "=", "False", "for", "field", ",", "group_dns", "in", "self", ".", "settings", ".", "PROFILE_FLAGS_BY_GROUP", ".", "items", "(", ")", ":", "if", "isinstance", "(", "group_dns", ",", "six", ".", "string_types", ")", ":", "group_dns", "=", "[", "group_dns", "]", "value", "=", "any", "(", "self", ".", "_get_groups", "(", ")", ".", "is_member_of", "(", "dn", ")", "for", "dn", "in", "group_dns", ")", "setattr", "(", "profile", ",", "field", ",", "value", ")", "save_profile", "=", "True", "return", "save_profile" ]
Populate the given profile object from AUTH_LDAP_PROFILE_FLAGS_BY_GROUP. Returns True if the profile was modified.
[ "Populate", "the", "given", "profile", "object", "from", "AUTH_LDAP_PROFILE_FLAGS_BY_GROUP", ".", "Returns", "True", "if", "the", "profile", "was", "modified", "." ]
4d2458bd90c4539353c5bfd5ea793c1e59780ee8
https://github.com/DheerendraRathor/django-auth-ldap-ng/blob/4d2458bd90c4539353c5bfd5ea793c1e59780ee8/django_auth_ldap/backend.py#L692-L706
train
DheerendraRathor/django-auth-ldap-ng
django_auth_ldap/backend.py
_LDAPUser._load_group_permissions
def _load_group_permissions(self): """ Populates self._group_permissions based on LDAP group membership and Django group permissions. """ group_names = self._get_groups().get_group_names() perms = Permission.objects.filter(group__name__in=group_names) perms = perms.values_list('content_type__app_label', 'codename') perms = perms.order_by() self._group_permissions = set(["%s.%s" % (ct, name) for ct, name in perms])
python
def _load_group_permissions(self): """ Populates self._group_permissions based on LDAP group membership and Django group permissions. """ group_names = self._get_groups().get_group_names() perms = Permission.objects.filter(group__name__in=group_names) perms = perms.values_list('content_type__app_label', 'codename') perms = perms.order_by() self._group_permissions = set(["%s.%s" % (ct, name) for ct, name in perms])
[ "def", "_load_group_permissions", "(", "self", ")", ":", "group_names", "=", "self", ".", "_get_groups", "(", ")", ".", "get_group_names", "(", ")", "perms", "=", "Permission", ".", "objects", ".", "filter", "(", "group__name__in", "=", "group_names", ")", "perms", "=", "perms", ".", "values_list", "(", "'content_type__app_label'", ",", "'codename'", ")", "perms", "=", "perms", ".", "order_by", "(", ")", "self", ".", "_group_permissions", "=", "set", "(", "[", "\"%s.%s\"", "%", "(", "ct", ",", "name", ")", "for", "ct", ",", "name", "in", "perms", "]", ")" ]
Populates self._group_permissions based on LDAP group membership and Django group permissions.
[ "Populates", "self", ".", "_group_permissions", "based", "on", "LDAP", "group", "membership", "and", "Django", "group", "permissions", "." ]
4d2458bd90c4539353c5bfd5ea793c1e59780ee8
https://github.com/DheerendraRathor/django-auth-ldap-ng/blob/4d2458bd90c4539353c5bfd5ea793c1e59780ee8/django_auth_ldap/backend.py#L729-L740
train
gmdzy2010/dingtalk_sdk_gmdzy2010
dingtalk_sdk_gmdzy2010/message_request.py
WorkNoticeRequest.get_task_id
def get_task_id(self): """Method to get all department members.""" task_id = self.json_response.get("task_id", None) self.logger.info("%s\t%s" % (self.request_method, self.request_url)) return task_id
python
def get_task_id(self): """Method to get all department members.""" task_id = self.json_response.get("task_id", None) self.logger.info("%s\t%s" % (self.request_method, self.request_url)) return task_id
[ "def", "get_task_id", "(", "self", ")", ":", "task_id", "=", "self", ".", "json_response", ".", "get", "(", "\"task_id\"", ",", "None", ")", "self", ".", "logger", ".", "info", "(", "\"%s\\t%s\"", "%", "(", "self", ".", "request_method", ",", "self", ".", "request_url", ")", ")", "return", "task_id" ]
Method to get all department members.
[ "Method", "to", "get", "all", "department", "members", "." ]
b06cb1f78f89be9554dcb6101af8bc72718a9ecd
https://github.com/gmdzy2010/dingtalk_sdk_gmdzy2010/blob/b06cb1f78f89be9554dcb6101af8bc72718a9ecd/dingtalk_sdk_gmdzy2010/message_request.py#L24-L28
train
gmdzy2010/dingtalk_sdk_gmdzy2010
dingtalk_sdk_gmdzy2010/message_request.py
SendGroupChatRequest.get_message_id
def get_message_id(self): """Method to get messageId of group created.""" message_id = self.json_response.get("messageId", None) self.logger.info("%s\t%s" % (self.request_method, self.request_url)) return message_id
python
def get_message_id(self): """Method to get messageId of group created.""" message_id = self.json_response.get("messageId", None) self.logger.info("%s\t%s" % (self.request_method, self.request_url)) return message_id
[ "def", "get_message_id", "(", "self", ")", ":", "message_id", "=", "self", ".", "json_response", ".", "get", "(", "\"messageId\"", ",", "None", ")", "self", ".", "logger", ".", "info", "(", "\"%s\\t%s\"", "%", "(", "self", ".", "request_method", ",", "self", ".", "request_url", ")", ")", "return", "message_id" ]
Method to get messageId of group created.
[ "Method", "to", "get", "messageId", "of", "group", "created", "." ]
b06cb1f78f89be9554dcb6101af8bc72718a9ecd
https://github.com/gmdzy2010/dingtalk_sdk_gmdzy2010/blob/b06cb1f78f89be9554dcb6101af8bc72718a9ecd/dingtalk_sdk_gmdzy2010/message_request.py#L168-L172
train
brutus/wdiffhtml
tasks/__init__.py
change_dir
def change_dir(directory): """ Wraps a function to run in a given directory. """ def cd_decorator(func): @wraps(func) def wrapper(*args, **kwargs): org_path = os.getcwd() os.chdir(directory) func(*args, **kwargs) os.chdir(org_path) return wrapper return cd_decorator
python
def change_dir(directory): """ Wraps a function to run in a given directory. """ def cd_decorator(func): @wraps(func) def wrapper(*args, **kwargs): org_path = os.getcwd() os.chdir(directory) func(*args, **kwargs) os.chdir(org_path) return wrapper return cd_decorator
[ "def", "change_dir", "(", "directory", ")", ":", "def", "cd_decorator", "(", "func", ")", ":", "@", "wraps", "(", "func", ")", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "org_path", "=", "os", ".", "getcwd", "(", ")", "os", ".", "chdir", "(", "directory", ")", "func", "(", "*", "args", ",", "*", "*", "kwargs", ")", "os", ".", "chdir", "(", "org_path", ")", "return", "wrapper", "return", "cd_decorator" ]
Wraps a function to run in a given directory.
[ "Wraps", "a", "function", "to", "run", "in", "a", "given", "directory", "." ]
e97b524a7945f7a626e33ec141343120c524d9fa
https://github.com/brutus/wdiffhtml/blob/e97b524a7945f7a626e33ec141343120c524d9fa/tasks/__init__.py#L27-L40
train
brutus/wdiffhtml
tasks/__init__.py
build_css
def build_css(minimize=True): """ Builds CSS from SASS. """ print('Build CSS') args = {} args['style'] = 'compressed' if minimize else 'nested' cmd = CMD_SASS.format(**args) run(cmd)
python
def build_css(minimize=True): """ Builds CSS from SASS. """ print('Build CSS') args = {} args['style'] = 'compressed' if minimize else 'nested' cmd = CMD_SASS.format(**args) run(cmd)
[ "def", "build_css", "(", "minimize", "=", "True", ")", ":", "print", "(", "'Build CSS'", ")", "args", "=", "{", "}", "args", "[", "'style'", "]", "=", "'compressed'", "if", "minimize", "else", "'nested'", "cmd", "=", "CMD_SASS", ".", "format", "(", "*", "*", "args", ")", "run", "(", "cmd", ")" ]
Builds CSS from SASS.
[ "Builds", "CSS", "from", "SASS", "." ]
e97b524a7945f7a626e33ec141343120c524d9fa
https://github.com/brutus/wdiffhtml/blob/e97b524a7945f7a626e33ec141343120c524d9fa/tasks/__init__.py#L45-L54
train
mojaie/chorus
chorus/util/debug.py
profile
def profile(func): """ Decorator Execute cProfile """ def _f(*args, **kwargs): print("\n<<<---") pr = cProfile.Profile() pr.enable() res = func(*args, **kwargs) p = pstats.Stats(pr) p.strip_dirs().sort_stats('cumtime').print_stats(20) print("\n--->>>") return res return _f
python
def profile(func): """ Decorator Execute cProfile """ def _f(*args, **kwargs): print("\n<<<---") pr = cProfile.Profile() pr.enable() res = func(*args, **kwargs) p = pstats.Stats(pr) p.strip_dirs().sort_stats('cumtime').print_stats(20) print("\n--->>>") return res return _f
[ "def", "profile", "(", "func", ")", ":", "def", "_f", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "print", "(", "\"\\n<<<---\"", ")", "pr", "=", "cProfile", ".", "Profile", "(", ")", "pr", ".", "enable", "(", ")", "res", "=", "func", "(", "*", "args", ",", "*", "*", "kwargs", ")", "p", "=", "pstats", ".", "Stats", "(", "pr", ")", "p", ".", "strip_dirs", "(", ")", ".", "sort_stats", "(", "'cumtime'", ")", ".", "print_stats", "(", "20", ")", "print", "(", "\"\\n--->>>\"", ")", "return", "res", "return", "_f" ]
Decorator Execute cProfile
[ "Decorator", "Execute", "cProfile" ]
fc7fe23a0272554c67671645ab07830b315eeb1b
https://github.com/mojaie/chorus/blob/fc7fe23a0272554c67671645ab07830b315eeb1b/chorus/util/debug.py#L17-L30
train
mojaie/chorus
chorus/util/debug.py
total_size
def total_size(obj, verbose=False): """ Returns approximate memory size""" seen = set() def sizeof(o): if id(o) in seen: return 0 seen.add(id(o)) s = sys.getsizeof(o, default=0) if verbose: print(s, type(o), repr(o)) if isinstance(o, (tuple, list, set, frozenset, deque)): s += sum(map(sizeof, iter(o))) elif isinstance(o, dict): s += sum(map(sizeof, chain.from_iterable(o.items()))) elif "__dict__" in dir(o): s += sum(map(sizeof, chain.from_iterable(o.__dict__.items()))) return s return sizeof(obj)
python
def total_size(obj, verbose=False): """ Returns approximate memory size""" seen = set() def sizeof(o): if id(o) in seen: return 0 seen.add(id(o)) s = sys.getsizeof(o, default=0) if verbose: print(s, type(o), repr(o)) if isinstance(o, (tuple, list, set, frozenset, deque)): s += sum(map(sizeof, iter(o))) elif isinstance(o, dict): s += sum(map(sizeof, chain.from_iterable(o.items()))) elif "__dict__" in dir(o): s += sum(map(sizeof, chain.from_iterable(o.__dict__.items()))) return s return sizeof(obj)
[ "def", "total_size", "(", "obj", ",", "verbose", "=", "False", ")", ":", "seen", "=", "set", "(", ")", "def", "sizeof", "(", "o", ")", ":", "if", "id", "(", "o", ")", "in", "seen", ":", "return", "0", "seen", ".", "add", "(", "id", "(", "o", ")", ")", "s", "=", "sys", ".", "getsizeof", "(", "o", ",", "default", "=", "0", ")", "if", "verbose", ":", "print", "(", "s", ",", "type", "(", "o", ")", ",", "repr", "(", "o", ")", ")", "if", "isinstance", "(", "o", ",", "(", "tuple", ",", "list", ",", "set", ",", "frozenset", ",", "deque", ")", ")", ":", "s", "+=", "sum", "(", "map", "(", "sizeof", ",", "iter", "(", "o", ")", ")", ")", "elif", "isinstance", "(", "o", ",", "dict", ")", ":", "s", "+=", "sum", "(", "map", "(", "sizeof", ",", "chain", ".", "from_iterable", "(", "o", ".", "items", "(", ")", ")", ")", ")", "elif", "\"__dict__\"", "in", "dir", "(", "o", ")", ":", "s", "+=", "sum", "(", "map", "(", "sizeof", ",", "chain", ".", "from_iterable", "(", "o", ".", "__dict__", ".", "items", "(", ")", ")", ")", ")", "return", "s", "return", "sizeof", "(", "obj", ")" ]
Returns approximate memory size
[ "Returns", "approximate", "memory", "size" ]
fc7fe23a0272554c67671645ab07830b315eeb1b
https://github.com/mojaie/chorus/blob/fc7fe23a0272554c67671645ab07830b315eeb1b/chorus/util/debug.py#L33-L52
train
mojaie/chorus
chorus/util/debug.py
mute
def mute(func): """ Decorator Make stdout silent """ def _f(*args, **kwargs): sys.stdout = open(os.devnull, 'w') res = func(*args, **kwargs) sys.stdout.close() sys.stdout = sys.__stdout__ return res return _f
python
def mute(func): """ Decorator Make stdout silent """ def _f(*args, **kwargs): sys.stdout = open(os.devnull, 'w') res = func(*args, **kwargs) sys.stdout.close() sys.stdout = sys.__stdout__ return res return _f
[ "def", "mute", "(", "func", ")", ":", "def", "_f", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "sys", ".", "stdout", "=", "open", "(", "os", ".", "devnull", ",", "'w'", ")", "res", "=", "func", "(", "*", "args", ",", "*", "*", "kwargs", ")", "sys", ".", "stdout", ".", "close", "(", ")", "sys", ".", "stdout", "=", "sys", ".", "__stdout__", "return", "res", "return", "_f" ]
Decorator Make stdout silent
[ "Decorator", "Make", "stdout", "silent" ]
fc7fe23a0272554c67671645ab07830b315eeb1b
https://github.com/mojaie/chorus/blob/fc7fe23a0272554c67671645ab07830b315eeb1b/chorus/util/debug.py#L97-L107
train
lsst-sqre/documenteer
documenteer/sphinxconfig/stackconf.py
_insert_html_configs
def _insert_html_configs(c, *, project_name, short_project_name): """Insert HTML theme configurations. """ # Use the lsst-sphinx-bootstrap-theme c['templates_path'] = [ '_templates', lsst_sphinx_bootstrap_theme.get_html_templates_path()] c['html_theme'] = 'lsst_sphinx_bootstrap_theme' c['html_theme_path'] = [lsst_sphinx_bootstrap_theme.get_html_theme_path()] # Theme options are theme-specific and customize the look and feel of a # theme further. For a list of options available for each theme, see the # documentation. c['html_theme_options'] = {'logotext': short_project_name} # The name for this set of Sphinx documents. If None, it defaults to # "<project> v<release> documentation". c['html_title'] = project_name # A shorter title for the navigation bar. Default is the same as # html_title. c['html_short_title'] = short_project_name # The name of an image file (relative to this directory) to place at the # top of the sidebar. c['html_logo'] = None # The name of an image file (within the static path) to use as favicon of # the docs. This file should be a Windows icon file (.ico) being 16x16 or # 32x32 pixels large. c['html_favicon'] = None # Add any paths that contain custom static files (such as style sheets) # here, relative to this directory. They are copied after the builtin # static files, so a file named "default.css" will overwrite the builtin # "default.css". if os.path.isdir('_static'): c['html_static_path'] = ['_static'] else: # If a project does not have a _static/ directory, don't list it # so that there isn't a warning. c['html_static_path'] = [] # Add any extra paths that contain custom files (such as robots.txt or # .htaccess) here, relative to this directory. These files are copied # directly to the root of the documentation. # html_extra_path = [] # If not '', a 'Last updated on:' timestamp is inserted at every page # bottom, using the given strftime format. c['html_last_updated_fmt'] = '%b %d, %Y' # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. c['html_use_smartypants'] = True # If false, no module index is generated. c['html_domain_indices'] = False # If false, no index is generated. c['html_use_index'] = False # If true, the index is split into individual pages for each letter. c['html_split_index'] = False # If true, links to the reST sources are added to the pages. c['html_show_sourcelink'] = True # If true, "Created using Sphinx" is shown in the HTML footer. Default is # True. c['html_show_sphinx'] = True # If true, "(C) Copyright ..." is shown in the HTML footer. Default is # True. c['html_show_copyright'] = True # If true, an OpenSearch description file will be output, and all pages # will contain a <link> tag referring to it. The value of this option must # be the base URL from which the finished HTML is served. # html_use_opensearch = '' # This is the file name suffix for HTML files (e.g. ".xhtml"). c['html_file_suffix'] = '.html' # Language to be used for generating the HTML full-text search index. c['html_search_language'] = 'en' # A dictionary with options for the search language support, empty by # default. Now only 'ja' uses this config value # html_search_options = {'type': 'default'} # The name of a javascript file (relative to the configuration directory) # that implements a search results scorer. If empty, the default will be # used. # html_search_scorer = 'scorer.js' return c
python
def _insert_html_configs(c, *, project_name, short_project_name): """Insert HTML theme configurations. """ # Use the lsst-sphinx-bootstrap-theme c['templates_path'] = [ '_templates', lsst_sphinx_bootstrap_theme.get_html_templates_path()] c['html_theme'] = 'lsst_sphinx_bootstrap_theme' c['html_theme_path'] = [lsst_sphinx_bootstrap_theme.get_html_theme_path()] # Theme options are theme-specific and customize the look and feel of a # theme further. For a list of options available for each theme, see the # documentation. c['html_theme_options'] = {'logotext': short_project_name} # The name for this set of Sphinx documents. If None, it defaults to # "<project> v<release> documentation". c['html_title'] = project_name # A shorter title for the navigation bar. Default is the same as # html_title. c['html_short_title'] = short_project_name # The name of an image file (relative to this directory) to place at the # top of the sidebar. c['html_logo'] = None # The name of an image file (within the static path) to use as favicon of # the docs. This file should be a Windows icon file (.ico) being 16x16 or # 32x32 pixels large. c['html_favicon'] = None # Add any paths that contain custom static files (such as style sheets) # here, relative to this directory. They are copied after the builtin # static files, so a file named "default.css" will overwrite the builtin # "default.css". if os.path.isdir('_static'): c['html_static_path'] = ['_static'] else: # If a project does not have a _static/ directory, don't list it # so that there isn't a warning. c['html_static_path'] = [] # Add any extra paths that contain custom files (such as robots.txt or # .htaccess) here, relative to this directory. These files are copied # directly to the root of the documentation. # html_extra_path = [] # If not '', a 'Last updated on:' timestamp is inserted at every page # bottom, using the given strftime format. c['html_last_updated_fmt'] = '%b %d, %Y' # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. c['html_use_smartypants'] = True # If false, no module index is generated. c['html_domain_indices'] = False # If false, no index is generated. c['html_use_index'] = False # If true, the index is split into individual pages for each letter. c['html_split_index'] = False # If true, links to the reST sources are added to the pages. c['html_show_sourcelink'] = True # If true, "Created using Sphinx" is shown in the HTML footer. Default is # True. c['html_show_sphinx'] = True # If true, "(C) Copyright ..." is shown in the HTML footer. Default is # True. c['html_show_copyright'] = True # If true, an OpenSearch description file will be output, and all pages # will contain a <link> tag referring to it. The value of this option must # be the base URL from which the finished HTML is served. # html_use_opensearch = '' # This is the file name suffix for HTML files (e.g. ".xhtml"). c['html_file_suffix'] = '.html' # Language to be used for generating the HTML full-text search index. c['html_search_language'] = 'en' # A dictionary with options for the search language support, empty by # default. Now only 'ja' uses this config value # html_search_options = {'type': 'default'} # The name of a javascript file (relative to the configuration directory) # that implements a search results scorer. If empty, the default will be # used. # html_search_scorer = 'scorer.js' return c
[ "def", "_insert_html_configs", "(", "c", ",", "*", ",", "project_name", ",", "short_project_name", ")", ":", "# Use the lsst-sphinx-bootstrap-theme", "c", "[", "'templates_path'", "]", "=", "[", "'_templates'", ",", "lsst_sphinx_bootstrap_theme", ".", "get_html_templates_path", "(", ")", "]", "c", "[", "'html_theme'", "]", "=", "'lsst_sphinx_bootstrap_theme'", "c", "[", "'html_theme_path'", "]", "=", "[", "lsst_sphinx_bootstrap_theme", ".", "get_html_theme_path", "(", ")", "]", "# Theme options are theme-specific and customize the look and feel of a", "# theme further. For a list of options available for each theme, see the", "# documentation.", "c", "[", "'html_theme_options'", "]", "=", "{", "'logotext'", ":", "short_project_name", "}", "# The name for this set of Sphinx documents. If None, it defaults to", "# \"<project> v<release> documentation\".", "c", "[", "'html_title'", "]", "=", "project_name", "# A shorter title for the navigation bar. Default is the same as", "# html_title.", "c", "[", "'html_short_title'", "]", "=", "short_project_name", "# The name of an image file (relative to this directory) to place at the", "# top of the sidebar.", "c", "[", "'html_logo'", "]", "=", "None", "# The name of an image file (within the static path) to use as favicon of", "# the docs. This file should be a Windows icon file (.ico) being 16x16 or", "# 32x32 pixels large.", "c", "[", "'html_favicon'", "]", "=", "None", "# Add any paths that contain custom static files (such as style sheets)", "# here, relative to this directory. They are copied after the builtin", "# static files, so a file named \"default.css\" will overwrite the builtin", "# \"default.css\".", "if", "os", ".", "path", ".", "isdir", "(", "'_static'", ")", ":", "c", "[", "'html_static_path'", "]", "=", "[", "'_static'", "]", "else", ":", "# If a project does not have a _static/ directory, don't list it", "# so that there isn't a warning.", "c", "[", "'html_static_path'", "]", "=", "[", "]", "# Add any extra paths that contain custom files (such as robots.txt or", "# .htaccess) here, relative to this directory. These files are copied", "# directly to the root of the documentation.", "# html_extra_path = []", "# If not '', a 'Last updated on:' timestamp is inserted at every page", "# bottom, using the given strftime format.", "c", "[", "'html_last_updated_fmt'", "]", "=", "'%b %d, %Y'", "# If true, SmartyPants will be used to convert quotes and dashes to", "# typographically correct entities.", "c", "[", "'html_use_smartypants'", "]", "=", "True", "# If false, no module index is generated.", "c", "[", "'html_domain_indices'", "]", "=", "False", "# If false, no index is generated.", "c", "[", "'html_use_index'", "]", "=", "False", "# If true, the index is split into individual pages for each letter.", "c", "[", "'html_split_index'", "]", "=", "False", "# If true, links to the reST sources are added to the pages.", "c", "[", "'html_show_sourcelink'", "]", "=", "True", "# If true, \"Created using Sphinx\" is shown in the HTML footer. Default is", "# True.", "c", "[", "'html_show_sphinx'", "]", "=", "True", "# If true, \"(C) Copyright ...\" is shown in the HTML footer. Default is", "# True.", "c", "[", "'html_show_copyright'", "]", "=", "True", "# If true, an OpenSearch description file will be output, and all pages", "# will contain a <link> tag referring to it. The value of this option must", "# be the base URL from which the finished HTML is served.", "# html_use_opensearch = ''", "# This is the file name suffix for HTML files (e.g. \".xhtml\").", "c", "[", "'html_file_suffix'", "]", "=", "'.html'", "# Language to be used for generating the HTML full-text search index.", "c", "[", "'html_search_language'", "]", "=", "'en'", "# A dictionary with options for the search language support, empty by", "# default. Now only 'ja' uses this config value", "# html_search_options = {'type': 'default'}", "# The name of a javascript file (relative to the configuration directory)", "# that implements a search results scorer. If empty, the default will be", "# used.", "# html_search_scorer = 'scorer.js'", "return", "c" ]
Insert HTML theme configurations.
[ "Insert", "HTML", "theme", "configurations", "." ]
75f02901a80042b28d074df1cc1dca32eb8e38c8
https://github.com/lsst-sqre/documenteer/blob/75f02901a80042b28d074df1cc1dca32eb8e38c8/documenteer/sphinxconfig/stackconf.py#L71-L167
train
lsst-sqre/documenteer
documenteer/sphinxconfig/stackconf.py
_insert_common_sphinx_configs
def _insert_common_sphinx_configs(c, *, project_name): """Add common core Sphinx configurations to the state. """ c['project'] = project_name # The suffix(es) of source filenames. # You can specify multiple suffix as a list of string: c['source_suffix'] = '.rst' # The encoding of source files. c['source_encoding'] = 'utf-8-sig' # The master toctree document. c['master_doc'] = 'index' # Configure figure numbering c['numfig'] = True c['numfig_format'] = {'figure': 'Figure %s', 'table': 'Table %s', 'code-block': 'Listing %s'} # The reST default role (used for this markup: `text`) c['default_role'] = 'obj' # This is added to the end of RST files - a good place to put substitutions # to be used globally. c['rst_epilog'] = """ .. _Astropy: http://astropy.org """ # A list of warning types to suppress arbitrary warning messages. We mean # to override directives in # astropy_helpers.sphinx.ext.autodoc_enhancements, thus need to ignore # those warning. This can be removed once the patch gets released in # upstream Sphinx (https://github.com/sphinx-doc/sphinx/pull/1843). # Suppress the warnings requires Sphinx v1.4.2 c['suppress_warnings'] = ['app.add_directive', ] return c
python
def _insert_common_sphinx_configs(c, *, project_name): """Add common core Sphinx configurations to the state. """ c['project'] = project_name # The suffix(es) of source filenames. # You can specify multiple suffix as a list of string: c['source_suffix'] = '.rst' # The encoding of source files. c['source_encoding'] = 'utf-8-sig' # The master toctree document. c['master_doc'] = 'index' # Configure figure numbering c['numfig'] = True c['numfig_format'] = {'figure': 'Figure %s', 'table': 'Table %s', 'code-block': 'Listing %s'} # The reST default role (used for this markup: `text`) c['default_role'] = 'obj' # This is added to the end of RST files - a good place to put substitutions # to be used globally. c['rst_epilog'] = """ .. _Astropy: http://astropy.org """ # A list of warning types to suppress arbitrary warning messages. We mean # to override directives in # astropy_helpers.sphinx.ext.autodoc_enhancements, thus need to ignore # those warning. This can be removed once the patch gets released in # upstream Sphinx (https://github.com/sphinx-doc/sphinx/pull/1843). # Suppress the warnings requires Sphinx v1.4.2 c['suppress_warnings'] = ['app.add_directive', ] return c
[ "def", "_insert_common_sphinx_configs", "(", "c", ",", "*", ",", "project_name", ")", ":", "c", "[", "'project'", "]", "=", "project_name", "# The suffix(es) of source filenames.", "# You can specify multiple suffix as a list of string:", "c", "[", "'source_suffix'", "]", "=", "'.rst'", "# The encoding of source files.", "c", "[", "'source_encoding'", "]", "=", "'utf-8-sig'", "# The master toctree document.", "c", "[", "'master_doc'", "]", "=", "'index'", "# Configure figure numbering", "c", "[", "'numfig'", "]", "=", "True", "c", "[", "'numfig_format'", "]", "=", "{", "'figure'", ":", "'Figure %s'", ",", "'table'", ":", "'Table %s'", ",", "'code-block'", ":", "'Listing %s'", "}", "# The reST default role (used for this markup: `text`)", "c", "[", "'default_role'", "]", "=", "'obj'", "# This is added to the end of RST files - a good place to put substitutions", "# to be used globally.", "c", "[", "'rst_epilog'", "]", "=", "\"\"\"\n.. _Astropy: http://astropy.org\n \"\"\"", "# A list of warning types to suppress arbitrary warning messages. We mean", "# to override directives in", "# astropy_helpers.sphinx.ext.autodoc_enhancements, thus need to ignore", "# those warning. This can be removed once the patch gets released in", "# upstream Sphinx (https://github.com/sphinx-doc/sphinx/pull/1843).", "# Suppress the warnings requires Sphinx v1.4.2", "c", "[", "'suppress_warnings'", "]", "=", "[", "'app.add_directive'", ",", "]", "return", "c" ]
Add common core Sphinx configurations to the state.
[ "Add", "common", "core", "Sphinx", "configurations", "to", "the", "state", "." ]
75f02901a80042b28d074df1cc1dca32eb8e38c8
https://github.com/lsst-sqre/documenteer/blob/75f02901a80042b28d074df1cc1dca32eb8e38c8/documenteer/sphinxconfig/stackconf.py#L170-L208
train
lsst-sqre/documenteer
documenteer/sphinxconfig/stackconf.py
_insert_breathe_configs
def _insert_breathe_configs(c, *, project_name, doxygen_xml_dirname): """Add breathe extension configurations to the state. """ if doxygen_xml_dirname is not None: c['breathe_projects'] = {project_name: doxygen_xml_dirname} c['breathe_default_project'] = project_name return c
python
def _insert_breathe_configs(c, *, project_name, doxygen_xml_dirname): """Add breathe extension configurations to the state. """ if doxygen_xml_dirname is not None: c['breathe_projects'] = {project_name: doxygen_xml_dirname} c['breathe_default_project'] = project_name return c
[ "def", "_insert_breathe_configs", "(", "c", ",", "*", ",", "project_name", ",", "doxygen_xml_dirname", ")", ":", "if", "doxygen_xml_dirname", "is", "not", "None", ":", "c", "[", "'breathe_projects'", "]", "=", "{", "project_name", ":", "doxygen_xml_dirname", "}", "c", "[", "'breathe_default_project'", "]", "=", "project_name", "return", "c" ]
Add breathe extension configurations to the state.
[ "Add", "breathe", "extension", "configurations", "to", "the", "state", "." ]
75f02901a80042b28d074df1cc1dca32eb8e38c8
https://github.com/lsst-sqre/documenteer/blob/75f02901a80042b28d074df1cc1dca32eb8e38c8/documenteer/sphinxconfig/stackconf.py#L211-L217
train
lsst-sqre/documenteer
documenteer/sphinxconfig/stackconf.py
_insert_automodapi_configs
def _insert_automodapi_configs(c): """Add configurations related to automodapi, autodoc, and numpydoc to the state. """ # Don't show summaries of the members in each class along with the # class' docstring c['numpydoc_show_class_members'] = False c['autosummary_generate'] = True c['automodapi_toctreedirnm'] = 'py-api' c['automodsumm_inherited_members'] = True # Docstrings for classes and methods are inherited from parents. c['autodoc_inherit_docstrings'] = True # Class documentation should only contain the class docstring and # ignore the __init__ docstring, account to LSST coding standards. # c['autoclass_content'] = "both" c['autoclass_content'] = "class" # Default flags for automodapi directives. Special members are dunder # methods. # NOTE: We want to used `inherited-members`, but it seems to be causing # documentation duplication in the automodapi listings. We're leaving # this out for now. See https://jira.lsstcorp.org/browse/DM-14782 for # additional notes. # NOTE: Without inherited members set, special-members doesn't need seem # to have an effect (even for special members where the docstrings are # directly written in the class, not inherited. # c['autodoc_default_flags'] = ['inherited-members'] c['autodoc_default_flags'] = ['show-inheritance', 'special-members'] return c
python
def _insert_automodapi_configs(c): """Add configurations related to automodapi, autodoc, and numpydoc to the state. """ # Don't show summaries of the members in each class along with the # class' docstring c['numpydoc_show_class_members'] = False c['autosummary_generate'] = True c['automodapi_toctreedirnm'] = 'py-api' c['automodsumm_inherited_members'] = True # Docstrings for classes and methods are inherited from parents. c['autodoc_inherit_docstrings'] = True # Class documentation should only contain the class docstring and # ignore the __init__ docstring, account to LSST coding standards. # c['autoclass_content'] = "both" c['autoclass_content'] = "class" # Default flags for automodapi directives. Special members are dunder # methods. # NOTE: We want to used `inherited-members`, but it seems to be causing # documentation duplication in the automodapi listings. We're leaving # this out for now. See https://jira.lsstcorp.org/browse/DM-14782 for # additional notes. # NOTE: Without inherited members set, special-members doesn't need seem # to have an effect (even for special members where the docstrings are # directly written in the class, not inherited. # c['autodoc_default_flags'] = ['inherited-members'] c['autodoc_default_flags'] = ['show-inheritance', 'special-members'] return c
[ "def", "_insert_automodapi_configs", "(", "c", ")", ":", "# Don't show summaries of the members in each class along with the", "# class' docstring", "c", "[", "'numpydoc_show_class_members'", "]", "=", "False", "c", "[", "'autosummary_generate'", "]", "=", "True", "c", "[", "'automodapi_toctreedirnm'", "]", "=", "'py-api'", "c", "[", "'automodsumm_inherited_members'", "]", "=", "True", "# Docstrings for classes and methods are inherited from parents.", "c", "[", "'autodoc_inherit_docstrings'", "]", "=", "True", "# Class documentation should only contain the class docstring and", "# ignore the __init__ docstring, account to LSST coding standards.", "# c['autoclass_content'] = \"both\"", "c", "[", "'autoclass_content'", "]", "=", "\"class\"", "# Default flags for automodapi directives. Special members are dunder", "# methods.", "# NOTE: We want to used `inherited-members`, but it seems to be causing", "# documentation duplication in the automodapi listings. We're leaving", "# this out for now. See https://jira.lsstcorp.org/browse/DM-14782 for", "# additional notes.", "# NOTE: Without inherited members set, special-members doesn't need seem", "# to have an effect (even for special members where the docstrings are", "# directly written in the class, not inherited.", "# c['autodoc_default_flags'] = ['inherited-members']", "c", "[", "'autodoc_default_flags'", "]", "=", "[", "'show-inheritance'", ",", "'special-members'", "]", "return", "c" ]
Add configurations related to automodapi, autodoc, and numpydoc to the state.
[ "Add", "configurations", "related", "to", "automodapi", "autodoc", "and", "numpydoc", "to", "the", "state", "." ]
75f02901a80042b28d074df1cc1dca32eb8e38c8
https://github.com/lsst-sqre/documenteer/blob/75f02901a80042b28d074df1cc1dca32eb8e38c8/documenteer/sphinxconfig/stackconf.py#L220-L254
train
lsst-sqre/documenteer
documenteer/sphinxconfig/stackconf.py
_insert_matplotlib_configs
def _insert_matplotlib_configs(c): """Add configurations related to matplotlib's plot directive to the state. """ if 'extensions' not in c: c['extensions'] = [] try: import matplotlib.sphinxext.plot_directive c['extensions'] += [matplotlib.sphinxext.plot_directive.__name__] except (ImportError, AttributeError): # AttributeError is checked here in case matplotlib is installed but # Sphinx isn't. Note that this module is imported by the config file # generator, even if we're not building the docs. warnings.warn( "matplotlib's plot_directive could not be imported. " "Inline plots will not be included in the output.") return c
python
def _insert_matplotlib_configs(c): """Add configurations related to matplotlib's plot directive to the state. """ if 'extensions' not in c: c['extensions'] = [] try: import matplotlib.sphinxext.plot_directive c['extensions'] += [matplotlib.sphinxext.plot_directive.__name__] except (ImportError, AttributeError): # AttributeError is checked here in case matplotlib is installed but # Sphinx isn't. Note that this module is imported by the config file # generator, even if we're not building the docs. warnings.warn( "matplotlib's plot_directive could not be imported. " "Inline plots will not be included in the output.") return c
[ "def", "_insert_matplotlib_configs", "(", "c", ")", ":", "if", "'extensions'", "not", "in", "c", ":", "c", "[", "'extensions'", "]", "=", "[", "]", "try", ":", "import", "matplotlib", ".", "sphinxext", ".", "plot_directive", "c", "[", "'extensions'", "]", "+=", "[", "matplotlib", ".", "sphinxext", ".", "plot_directive", ".", "__name__", "]", "except", "(", "ImportError", ",", "AttributeError", ")", ":", "# AttributeError is checked here in case matplotlib is installed but", "# Sphinx isn't. Note that this module is imported by the config file", "# generator, even if we're not building the docs.", "warnings", ".", "warn", "(", "\"matplotlib's plot_directive could not be imported. \"", "\"Inline plots will not be included in the output.\"", ")", "return", "c" ]
Add configurations related to matplotlib's plot directive to the state.
[ "Add", "configurations", "related", "to", "matplotlib", "s", "plot", "directive", "to", "the", "state", "." ]
75f02901a80042b28d074df1cc1dca32eb8e38c8
https://github.com/lsst-sqre/documenteer/blob/75f02901a80042b28d074df1cc1dca32eb8e38c8/documenteer/sphinxconfig/stackconf.py#L257-L274
train
lsst-sqre/documenteer
documenteer/sphinxconfig/stackconf.py
_insert_single_package_eups_version
def _insert_single_package_eups_version(c, eups_version): """Insert version information into the configuration namespace. Parameters ---------- eups_version The EUPS version string (as opposed to tag). This comes from the ``__version__`` attribute of individual modules and is only set for single package documentation builds that use the `build_package_configs` configuration entrypoint. Notes ----- The variables are: ``release_eups_tag`` Always ``current``. ``version``, ``release`` Equal to ``eups_version``. ``release_git_ref`` Always ``master``. ``scipipe_conda_ref`` Always ``master``. ``newinstall_ref`` Always ``master``. ``pipelines_demo_ref`` Always ``master``. """ c['release_eups_tag'] = 'current' c['release_git_ref'] = 'master' c['version'] = eups_version c['release'] = eups_version c['scipipe_conda_ref'] = 'master' c['pipelines_demo_ref'] = 'master' c['newinstall_ref'] = 'master' return c
python
def _insert_single_package_eups_version(c, eups_version): """Insert version information into the configuration namespace. Parameters ---------- eups_version The EUPS version string (as opposed to tag). This comes from the ``__version__`` attribute of individual modules and is only set for single package documentation builds that use the `build_package_configs` configuration entrypoint. Notes ----- The variables are: ``release_eups_tag`` Always ``current``. ``version``, ``release`` Equal to ``eups_version``. ``release_git_ref`` Always ``master``. ``scipipe_conda_ref`` Always ``master``. ``newinstall_ref`` Always ``master``. ``pipelines_demo_ref`` Always ``master``. """ c['release_eups_tag'] = 'current' c['release_git_ref'] = 'master' c['version'] = eups_version c['release'] = eups_version c['scipipe_conda_ref'] = 'master' c['pipelines_demo_ref'] = 'master' c['newinstall_ref'] = 'master' return c
[ "def", "_insert_single_package_eups_version", "(", "c", ",", "eups_version", ")", ":", "c", "[", "'release_eups_tag'", "]", "=", "'current'", "c", "[", "'release_git_ref'", "]", "=", "'master'", "c", "[", "'version'", "]", "=", "eups_version", "c", "[", "'release'", "]", "=", "eups_version", "c", "[", "'scipipe_conda_ref'", "]", "=", "'master'", "c", "[", "'pipelines_demo_ref'", "]", "=", "'master'", "c", "[", "'newinstall_ref'", "]", "=", "'master'", "return", "c" ]
Insert version information into the configuration namespace. Parameters ---------- eups_version The EUPS version string (as opposed to tag). This comes from the ``__version__`` attribute of individual modules and is only set for single package documentation builds that use the `build_package_configs` configuration entrypoint. Notes ----- The variables are: ``release_eups_tag`` Always ``current``. ``version``, ``release`` Equal to ``eups_version``. ``release_git_ref`` Always ``master``. ``scipipe_conda_ref`` Always ``master``. ``newinstall_ref`` Always ``master``. ``pipelines_demo_ref`` Always ``master``.
[ "Insert", "version", "information", "into", "the", "configuration", "namespace", "." ]
75f02901a80042b28d074df1cc1dca32eb8e38c8
https://github.com/lsst-sqre/documenteer/blob/75f02901a80042b28d074df1cc1dca32eb8e38c8/documenteer/sphinxconfig/stackconf.py#L298-L333
train
lsst-sqre/documenteer
documenteer/sphinxconfig/stackconf.py
_insert_eups_version
def _insert_eups_version(c): """Insert information about the current EUPS tag into the configuration namespace. The variables are: ``release_eups_tag`` The EUPS tag (obtained from the ``EUPS_TAG`` environment variable, falling back to ``d_latest`` if not available). ``version``, ``release`` Same as ``release_eups_tag``. ``release_git_ref`` The git ref (branch or tag) corresponding ot the EUPS tag. ``scipipe_conda_ref`` Git ref for the https://github.com/lsst/scipipe_conda_env repo. ``newinstall_ref`` Git ref for the https://github.com/lsst/lsst repo. ``pipelines_demo_ref`` Git ref for the https://github.com/lsst/lsst_dm_stack_demo repo. """ # Attempt to get the eups tag from the build environment eups_tag = os.getenv('EUPS_TAG') if eups_tag is None: eups_tag = 'd_latest' # Try to guess the git ref that corresponds to this tag if eups_tag in ('d_latest', 'w_latest', 'current'): git_ref = 'master' elif eups_tag.startswith('d_'): # Daily EUPS tags are not tagged on git git_ref = 'master' elif eups_tag.startswith('v'): # Major version or release candidate tag git_ref = eups_tag.lstrip('v').replace('_', '.') elif eups_tag.startswith('w_'): # Regular weekly tag git_ref = eups_tag.replace('_', '.') else: # Ideally shouldn't get to this point git_ref = 'master' # Now set variables for the Jinja context c['release_eups_tag'] = eups_tag c['release_git_ref'] = git_ref c['version'] = eups_tag c['release'] = eups_tag c['scipipe_conda_ref'] = git_ref c['pipelines_demo_ref'] = git_ref c['newinstall_ref'] = git_ref return c
python
def _insert_eups_version(c): """Insert information about the current EUPS tag into the configuration namespace. The variables are: ``release_eups_tag`` The EUPS tag (obtained from the ``EUPS_TAG`` environment variable, falling back to ``d_latest`` if not available). ``version``, ``release`` Same as ``release_eups_tag``. ``release_git_ref`` The git ref (branch or tag) corresponding ot the EUPS tag. ``scipipe_conda_ref`` Git ref for the https://github.com/lsst/scipipe_conda_env repo. ``newinstall_ref`` Git ref for the https://github.com/lsst/lsst repo. ``pipelines_demo_ref`` Git ref for the https://github.com/lsst/lsst_dm_stack_demo repo. """ # Attempt to get the eups tag from the build environment eups_tag = os.getenv('EUPS_TAG') if eups_tag is None: eups_tag = 'd_latest' # Try to guess the git ref that corresponds to this tag if eups_tag in ('d_latest', 'w_latest', 'current'): git_ref = 'master' elif eups_tag.startswith('d_'): # Daily EUPS tags are not tagged on git git_ref = 'master' elif eups_tag.startswith('v'): # Major version or release candidate tag git_ref = eups_tag.lstrip('v').replace('_', '.') elif eups_tag.startswith('w_'): # Regular weekly tag git_ref = eups_tag.replace('_', '.') else: # Ideally shouldn't get to this point git_ref = 'master' # Now set variables for the Jinja context c['release_eups_tag'] = eups_tag c['release_git_ref'] = git_ref c['version'] = eups_tag c['release'] = eups_tag c['scipipe_conda_ref'] = git_ref c['pipelines_demo_ref'] = git_ref c['newinstall_ref'] = git_ref return c
[ "def", "_insert_eups_version", "(", "c", ")", ":", "# Attempt to get the eups tag from the build environment", "eups_tag", "=", "os", ".", "getenv", "(", "'EUPS_TAG'", ")", "if", "eups_tag", "is", "None", ":", "eups_tag", "=", "'d_latest'", "# Try to guess the git ref that corresponds to this tag", "if", "eups_tag", "in", "(", "'d_latest'", ",", "'w_latest'", ",", "'current'", ")", ":", "git_ref", "=", "'master'", "elif", "eups_tag", ".", "startswith", "(", "'d_'", ")", ":", "# Daily EUPS tags are not tagged on git", "git_ref", "=", "'master'", "elif", "eups_tag", ".", "startswith", "(", "'v'", ")", ":", "# Major version or release candidate tag", "git_ref", "=", "eups_tag", ".", "lstrip", "(", "'v'", ")", ".", "replace", "(", "'_'", ",", "'.'", ")", "elif", "eups_tag", ".", "startswith", "(", "'w_'", ")", ":", "# Regular weekly tag", "git_ref", "=", "eups_tag", ".", "replace", "(", "'_'", ",", "'.'", ")", "else", ":", "# Ideally shouldn't get to this point", "git_ref", "=", "'master'", "# Now set variables for the Jinja context", "c", "[", "'release_eups_tag'", "]", "=", "eups_tag", "c", "[", "'release_git_ref'", "]", "=", "git_ref", "c", "[", "'version'", "]", "=", "eups_tag", "c", "[", "'release'", "]", "=", "eups_tag", "c", "[", "'scipipe_conda_ref'", "]", "=", "git_ref", "c", "[", "'pipelines_demo_ref'", "]", "=", "git_ref", "c", "[", "'newinstall_ref'", "]", "=", "git_ref", "return", "c" ]
Insert information about the current EUPS tag into the configuration namespace. The variables are: ``release_eups_tag`` The EUPS tag (obtained from the ``EUPS_TAG`` environment variable, falling back to ``d_latest`` if not available). ``version``, ``release`` Same as ``release_eups_tag``. ``release_git_ref`` The git ref (branch or tag) corresponding ot the EUPS tag. ``scipipe_conda_ref`` Git ref for the https://github.com/lsst/scipipe_conda_env repo. ``newinstall_ref`` Git ref for the https://github.com/lsst/lsst repo. ``pipelines_demo_ref`` Git ref for the https://github.com/lsst/lsst_dm_stack_demo repo.
[ "Insert", "information", "about", "the", "current", "EUPS", "tag", "into", "the", "configuration", "namespace", "." ]
75f02901a80042b28d074df1cc1dca32eb8e38c8
https://github.com/lsst-sqre/documenteer/blob/75f02901a80042b28d074df1cc1dca32eb8e38c8/documenteer/sphinxconfig/stackconf.py#L336-L386
train
lsst-sqre/documenteer
documenteer/sphinxconfig/stackconf.py
build_pipelines_lsst_io_configs
def build_pipelines_lsst_io_configs(*, project_name, copyright=None): """Build a `dict` of Sphinx configurations that populate the ``conf.py`` of the main pipelines_lsst_io Sphinx project for LSST Science Pipelines documentation. The ``conf.py`` file can ingest these configurations via:: from documenteer.sphinxconfig.stackconf import \ build_pipelines_lsst_io_configs _g = globals() _g.update(build_pipelines_lsst_io_configs( project_name='LSST Science Pipelines') You can subsequently customize the Sphinx configuration by directly assigning global variables, as usual in a Sphinx ``config.py``, e.g.:: copyright = '2016 Association of Universities for ' 'Research in Astronomy, Inc.' Parameters ---------- project_name : `str` Name of the project copyright : `str`, optional Copyright statement. Do not include the 'Copyright (c)' string; it'll be added automatically. Returns ------- c : dict Dictionary of configurations that should be added to the ``conf.py`` global namespace via:: _g = global() _g.update(c) """ # Work around Sphinx bug related to large and highly-nested source files sys.setrecursionlimit(2000) c = {} c = _insert_common_sphinx_configs( c, project_name=project_name) # HTML theme c = _insert_html_configs( c, project_name=project_name, short_project_name=project_name) # Sphinx extension modules c = _insert_extensions(c) # Intersphinx configuration c = _insert_intersphinx_mapping(c) # Breathe extension configuration # FIXME configure this for multiple sites # Automodapi and numpydoc configurations c = _insert_automodapi_configs(c) # Matplotlib configurations c = _insert_matplotlib_configs(c) # Graphviz configurations c = _insert_graphviz_configs(c) # Add versioning information c = _insert_eups_version(c) # Always use "now" as the date for the main site's docs because we can't # look at the Git history of each stack package. date = datetime.datetime.now() c['today'] = date.strftime('%Y-%m-%d') # Use this copyright for now. Ultimately we want to gather COPYRIGHT files # and build an integrated copyright that way. c['copyright'] = '2015-{year} LSST contributors'.format( year=date.year) # Hide todo directives in the "published" documentation on the main site. c['todo_include_todos'] = False # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. c['exclude_patterns'] = [ 'README.rst', # Build products '_build', # Source for release notes (contents are included in built pages) 'releases/note-source/*.rst', 'releases/tickets-source/*.rst', # EUPS configuration directory 'ups', # Recommended directory for pip installing doc eng Python packages '.pyvenv', # GitHub templates '.github', # This 'home' directory is created by the docubase image for the # sqre/infra/documenteer ci.lsst.codes Jenkins job. Ideally this # shouldn't be in the directory at all, but we certainly need to # ignore it while its here. 'home', ] # Insert rst_epilog configuration c = _insert_rst_epilog(c) # Set up the context for the sphinx-jinja extension c = _insert_jinja_configuration(c) return c
python
def build_pipelines_lsst_io_configs(*, project_name, copyright=None): """Build a `dict` of Sphinx configurations that populate the ``conf.py`` of the main pipelines_lsst_io Sphinx project for LSST Science Pipelines documentation. The ``conf.py`` file can ingest these configurations via:: from documenteer.sphinxconfig.stackconf import \ build_pipelines_lsst_io_configs _g = globals() _g.update(build_pipelines_lsst_io_configs( project_name='LSST Science Pipelines') You can subsequently customize the Sphinx configuration by directly assigning global variables, as usual in a Sphinx ``config.py``, e.g.:: copyright = '2016 Association of Universities for ' 'Research in Astronomy, Inc.' Parameters ---------- project_name : `str` Name of the project copyright : `str`, optional Copyright statement. Do not include the 'Copyright (c)' string; it'll be added automatically. Returns ------- c : dict Dictionary of configurations that should be added to the ``conf.py`` global namespace via:: _g = global() _g.update(c) """ # Work around Sphinx bug related to large and highly-nested source files sys.setrecursionlimit(2000) c = {} c = _insert_common_sphinx_configs( c, project_name=project_name) # HTML theme c = _insert_html_configs( c, project_name=project_name, short_project_name=project_name) # Sphinx extension modules c = _insert_extensions(c) # Intersphinx configuration c = _insert_intersphinx_mapping(c) # Breathe extension configuration # FIXME configure this for multiple sites # Automodapi and numpydoc configurations c = _insert_automodapi_configs(c) # Matplotlib configurations c = _insert_matplotlib_configs(c) # Graphviz configurations c = _insert_graphviz_configs(c) # Add versioning information c = _insert_eups_version(c) # Always use "now" as the date for the main site's docs because we can't # look at the Git history of each stack package. date = datetime.datetime.now() c['today'] = date.strftime('%Y-%m-%d') # Use this copyright for now. Ultimately we want to gather COPYRIGHT files # and build an integrated copyright that way. c['copyright'] = '2015-{year} LSST contributors'.format( year=date.year) # Hide todo directives in the "published" documentation on the main site. c['todo_include_todos'] = False # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. c['exclude_patterns'] = [ 'README.rst', # Build products '_build', # Source for release notes (contents are included in built pages) 'releases/note-source/*.rst', 'releases/tickets-source/*.rst', # EUPS configuration directory 'ups', # Recommended directory for pip installing doc eng Python packages '.pyvenv', # GitHub templates '.github', # This 'home' directory is created by the docubase image for the # sqre/infra/documenteer ci.lsst.codes Jenkins job. Ideally this # shouldn't be in the directory at all, but we certainly need to # ignore it while its here. 'home', ] # Insert rst_epilog configuration c = _insert_rst_epilog(c) # Set up the context for the sphinx-jinja extension c = _insert_jinja_configuration(c) return c
[ "def", "build_pipelines_lsst_io_configs", "(", "*", ",", "project_name", ",", "copyright", "=", "None", ")", ":", "# Work around Sphinx bug related to large and highly-nested source files", "sys", ".", "setrecursionlimit", "(", "2000", ")", "c", "=", "{", "}", "c", "=", "_insert_common_sphinx_configs", "(", "c", ",", "project_name", "=", "project_name", ")", "# HTML theme", "c", "=", "_insert_html_configs", "(", "c", ",", "project_name", "=", "project_name", ",", "short_project_name", "=", "project_name", ")", "# Sphinx extension modules", "c", "=", "_insert_extensions", "(", "c", ")", "# Intersphinx configuration", "c", "=", "_insert_intersphinx_mapping", "(", "c", ")", "# Breathe extension configuration", "# FIXME configure this for multiple sites", "# Automodapi and numpydoc configurations", "c", "=", "_insert_automodapi_configs", "(", "c", ")", "# Matplotlib configurations", "c", "=", "_insert_matplotlib_configs", "(", "c", ")", "# Graphviz configurations", "c", "=", "_insert_graphviz_configs", "(", "c", ")", "# Add versioning information", "c", "=", "_insert_eups_version", "(", "c", ")", "# Always use \"now\" as the date for the main site's docs because we can't", "# look at the Git history of each stack package.", "date", "=", "datetime", ".", "datetime", ".", "now", "(", ")", "c", "[", "'today'", "]", "=", "date", ".", "strftime", "(", "'%Y-%m-%d'", ")", "# Use this copyright for now. Ultimately we want to gather COPYRIGHT files", "# and build an integrated copyright that way.", "c", "[", "'copyright'", "]", "=", "'2015-{year} LSST contributors'", ".", "format", "(", "year", "=", "date", ".", "year", ")", "# Hide todo directives in the \"published\" documentation on the main site.", "c", "[", "'todo_include_todos'", "]", "=", "False", "# List of patterns, relative to source directory, that match files and", "# directories to ignore when looking for source files.", "c", "[", "'exclude_patterns'", "]", "=", "[", "'README.rst'", ",", "# Build products", "'_build'", ",", "# Source for release notes (contents are included in built pages)", "'releases/note-source/*.rst'", ",", "'releases/tickets-source/*.rst'", ",", "# EUPS configuration directory", "'ups'", ",", "# Recommended directory for pip installing doc eng Python packages", "'.pyvenv'", ",", "# GitHub templates", "'.github'", ",", "# This 'home' directory is created by the docubase image for the", "# sqre/infra/documenteer ci.lsst.codes Jenkins job. Ideally this", "# shouldn't be in the directory at all, but we certainly need to", "# ignore it while its here.", "'home'", ",", "]", "# Insert rst_epilog configuration", "c", "=", "_insert_rst_epilog", "(", "c", ")", "# Set up the context for the sphinx-jinja extension", "c", "=", "_insert_jinja_configuration", "(", "c", ")", "return", "c" ]
Build a `dict` of Sphinx configurations that populate the ``conf.py`` of the main pipelines_lsst_io Sphinx project for LSST Science Pipelines documentation. The ``conf.py`` file can ingest these configurations via:: from documenteer.sphinxconfig.stackconf import \ build_pipelines_lsst_io_configs _g = globals() _g.update(build_pipelines_lsst_io_configs( project_name='LSST Science Pipelines') You can subsequently customize the Sphinx configuration by directly assigning global variables, as usual in a Sphinx ``config.py``, e.g.:: copyright = '2016 Association of Universities for ' 'Research in Astronomy, Inc.' Parameters ---------- project_name : `str` Name of the project copyright : `str`, optional Copyright statement. Do not include the 'Copyright (c)' string; it'll be added automatically. Returns ------- c : dict Dictionary of configurations that should be added to the ``conf.py`` global namespace via:: _g = global() _g.update(c)
[ "Build", "a", "dict", "of", "Sphinx", "configurations", "that", "populate", "the", "conf", ".", "py", "of", "the", "main", "pipelines_lsst_io", "Sphinx", "project", "for", "LSST", "Science", "Pipelines", "documentation", "." ]
75f02901a80042b28d074df1cc1dca32eb8e38c8
https://github.com/lsst-sqre/documenteer/blob/75f02901a80042b28d074df1cc1dca32eb8e38c8/documenteer/sphinxconfig/stackconf.py#L533-L647
train
klen/muffin-redis
muffin_redis.py
Plugin.setup
def setup(self, app): """Setup the plugin.""" super().setup(app) self.cfg.port = int(self.cfg.port) self.cfg.db = int(self.cfg.db) self.cfg.poolsize = int(self.cfg.poolsize)
python
def setup(self, app): """Setup the plugin.""" super().setup(app) self.cfg.port = int(self.cfg.port) self.cfg.db = int(self.cfg.db) self.cfg.poolsize = int(self.cfg.poolsize)
[ "def", "setup", "(", "self", ",", "app", ")", ":", "super", "(", ")", ".", "setup", "(", "app", ")", "self", ".", "cfg", ".", "port", "=", "int", "(", "self", ".", "cfg", ".", "port", ")", "self", ".", "cfg", ".", "db", "=", "int", "(", "self", ".", "cfg", ".", "db", ")", "self", ".", "cfg", ".", "poolsize", "=", "int", "(", "self", ".", "cfg", ".", "poolsize", ")" ]
Setup the plugin.
[ "Setup", "the", "plugin", "." ]
b0cb8c1ba1511d501c2084def156710e75aaf781
https://github.com/klen/muffin-redis/blob/b0cb8c1ba1511d501c2084def156710e75aaf781/muffin_redis.py#L49-L54
train
klen/muffin-redis
muffin_redis.py
Plugin.startup
async def startup(self, app): """Connect to Redis.""" if self.cfg.fake: if not FakeConnection: raise PluginException('Install fakeredis for fake connections.') self.conn = await FakeConnection.create() if self.cfg.pubsub: self.pubsub_conn = self.conn else: try: if self.cfg.poolsize <= 1: self.conn = await asyncio.wait_for( asyncio_redis.Connection.create( host=self.cfg.host, port=self.cfg.port, password=self.cfg.password, db=self.cfg.db, ), self.cfg.timeout) else: self.conn = await asyncio.wait_for(asyncio_redis.Pool.create( host=self.cfg.host, port=self.cfg.port, password=self.cfg.password, db=self.cfg.db, poolsize=self.cfg.poolsize, ), self.cfg.timeout) if self.cfg.pubsub: self.pubsub_conn = await asyncio.wait_for( asyncio_redis.Connection.create( host=self.cfg.host, port=self.cfg.port, password=self.cfg.password, db=self.cfg.db, ), self.cfg.timeout ) except asyncio.TimeoutError: raise PluginException('Muffin-redis connection timeout.') if self.cfg.pubsub: self.pubsub_subscription = await self.pubsub_conn.start_subscribe() self.pubsub_reader = ensure_future(self._pubsub_reader_proc(), loop=self.app.loop)
python
async def startup(self, app): """Connect to Redis.""" if self.cfg.fake: if not FakeConnection: raise PluginException('Install fakeredis for fake connections.') self.conn = await FakeConnection.create() if self.cfg.pubsub: self.pubsub_conn = self.conn else: try: if self.cfg.poolsize <= 1: self.conn = await asyncio.wait_for( asyncio_redis.Connection.create( host=self.cfg.host, port=self.cfg.port, password=self.cfg.password, db=self.cfg.db, ), self.cfg.timeout) else: self.conn = await asyncio.wait_for(asyncio_redis.Pool.create( host=self.cfg.host, port=self.cfg.port, password=self.cfg.password, db=self.cfg.db, poolsize=self.cfg.poolsize, ), self.cfg.timeout) if self.cfg.pubsub: self.pubsub_conn = await asyncio.wait_for( asyncio_redis.Connection.create( host=self.cfg.host, port=self.cfg.port, password=self.cfg.password, db=self.cfg.db, ), self.cfg.timeout ) except asyncio.TimeoutError: raise PluginException('Muffin-redis connection timeout.') if self.cfg.pubsub: self.pubsub_subscription = await self.pubsub_conn.start_subscribe() self.pubsub_reader = ensure_future(self._pubsub_reader_proc(), loop=self.app.loop)
[ "async", "def", "startup", "(", "self", ",", "app", ")", ":", "if", "self", ".", "cfg", ".", "fake", ":", "if", "not", "FakeConnection", ":", "raise", "PluginException", "(", "'Install fakeredis for fake connections.'", ")", "self", ".", "conn", "=", "await", "FakeConnection", ".", "create", "(", ")", "if", "self", ".", "cfg", ".", "pubsub", ":", "self", ".", "pubsub_conn", "=", "self", ".", "conn", "else", ":", "try", ":", "if", "self", ".", "cfg", ".", "poolsize", "<=", "1", ":", "self", ".", "conn", "=", "await", "asyncio", ".", "wait_for", "(", "asyncio_redis", ".", "Connection", ".", "create", "(", "host", "=", "self", ".", "cfg", ".", "host", ",", "port", "=", "self", ".", "cfg", ".", "port", ",", "password", "=", "self", ".", "cfg", ".", "password", ",", "db", "=", "self", ".", "cfg", ".", "db", ",", ")", ",", "self", ".", "cfg", ".", "timeout", ")", "else", ":", "self", ".", "conn", "=", "await", "asyncio", ".", "wait_for", "(", "asyncio_redis", ".", "Pool", ".", "create", "(", "host", "=", "self", ".", "cfg", ".", "host", ",", "port", "=", "self", ".", "cfg", ".", "port", ",", "password", "=", "self", ".", "cfg", ".", "password", ",", "db", "=", "self", ".", "cfg", ".", "db", ",", "poolsize", "=", "self", ".", "cfg", ".", "poolsize", ",", ")", ",", "self", ".", "cfg", ".", "timeout", ")", "if", "self", ".", "cfg", ".", "pubsub", ":", "self", ".", "pubsub_conn", "=", "await", "asyncio", ".", "wait_for", "(", "asyncio_redis", ".", "Connection", ".", "create", "(", "host", "=", "self", ".", "cfg", ".", "host", ",", "port", "=", "self", ".", "cfg", ".", "port", ",", "password", "=", "self", ".", "cfg", ".", "password", ",", "db", "=", "self", ".", "cfg", ".", "db", ",", ")", ",", "self", ".", "cfg", ".", "timeout", ")", "except", "asyncio", ".", "TimeoutError", ":", "raise", "PluginException", "(", "'Muffin-redis connection timeout.'", ")", "if", "self", ".", "cfg", ".", "pubsub", ":", "self", ".", "pubsub_subscription", "=", "await", "self", ".", "pubsub_conn", ".", "start_subscribe", "(", ")", "self", ".", "pubsub_reader", "=", "ensure_future", "(", "self", ".", "_pubsub_reader_proc", "(", ")", ",", "loop", "=", "self", ".", "app", ".", "loop", ")" ]
Connect to Redis.
[ "Connect", "to", "Redis", "." ]
b0cb8c1ba1511d501c2084def156710e75aaf781
https://github.com/klen/muffin-redis/blob/b0cb8c1ba1511d501c2084def156710e75aaf781/muffin_redis.py#L56-L92
train
klen/muffin-redis
muffin_redis.py
Plugin.cleanup
async def cleanup(self, app): """Close self connections.""" self.conn.close() if self.pubsub_conn: self.pubsub_reader.cancel() self.pubsub_conn.close() # give connections a chance to actually terminate # TODO: use better method once it will be added, # see https://github.com/jonathanslenders/asyncio-redis/issues/56 await asyncio.sleep(0)
python
async def cleanup(self, app): """Close self connections.""" self.conn.close() if self.pubsub_conn: self.pubsub_reader.cancel() self.pubsub_conn.close() # give connections a chance to actually terminate # TODO: use better method once it will be added, # see https://github.com/jonathanslenders/asyncio-redis/issues/56 await asyncio.sleep(0)
[ "async", "def", "cleanup", "(", "self", ",", "app", ")", ":", "self", ".", "conn", ".", "close", "(", ")", "if", "self", ".", "pubsub_conn", ":", "self", ".", "pubsub_reader", ".", "cancel", "(", ")", "self", ".", "pubsub_conn", ".", "close", "(", ")", "# give connections a chance to actually terminate", "# TODO: use better method once it will be added,", "# see https://github.com/jonathanslenders/asyncio-redis/issues/56", "await", "asyncio", ".", "sleep", "(", "0", ")" ]
Close self connections.
[ "Close", "self", "connections", "." ]
b0cb8c1ba1511d501c2084def156710e75aaf781
https://github.com/klen/muffin-redis/blob/b0cb8c1ba1511d501c2084def156710e75aaf781/muffin_redis.py#L94-L103
train
klen/muffin-redis
muffin_redis.py
Plugin.set
def set(self, key, value, *args, **kwargs): """Store the given value into Redis. :returns: a coroutine """ if self.cfg.jsonpickle: value = jsonpickle.encode(value) return self.conn.set(key, value, *args, **kwargs)
python
def set(self, key, value, *args, **kwargs): """Store the given value into Redis. :returns: a coroutine """ if self.cfg.jsonpickle: value = jsonpickle.encode(value) return self.conn.set(key, value, *args, **kwargs)
[ "def", "set", "(", "self", ",", "key", ",", "value", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "self", ".", "cfg", ".", "jsonpickle", ":", "value", "=", "jsonpickle", ".", "encode", "(", "value", ")", "return", "self", ".", "conn", ".", "set", "(", "key", ",", "value", ",", "*", "args", ",", "*", "*", "kwargs", ")" ]
Store the given value into Redis. :returns: a coroutine
[ "Store", "the", "given", "value", "into", "Redis", "." ]
b0cb8c1ba1511d501c2084def156710e75aaf781
https://github.com/klen/muffin-redis/blob/b0cb8c1ba1511d501c2084def156710e75aaf781/muffin_redis.py#L105-L112
train
klen/muffin-redis
muffin_redis.py
Plugin.get
async def get(self, key): """Decode the value.""" value = await self.conn.get(key) if self.cfg.jsonpickle: if isinstance(value, bytes): return jsonpickle.decode(value.decode('utf-8')) if isinstance(value, str): return jsonpickle.decode(value) return value
python
async def get(self, key): """Decode the value.""" value = await self.conn.get(key) if self.cfg.jsonpickle: if isinstance(value, bytes): return jsonpickle.decode(value.decode('utf-8')) if isinstance(value, str): return jsonpickle.decode(value) return value
[ "async", "def", "get", "(", "self", ",", "key", ")", ":", "value", "=", "await", "self", ".", "conn", ".", "get", "(", "key", ")", "if", "self", ".", "cfg", ".", "jsonpickle", ":", "if", "isinstance", "(", "value", ",", "bytes", ")", ":", "return", "jsonpickle", ".", "decode", "(", "value", ".", "decode", "(", "'utf-8'", ")", ")", "if", "isinstance", "(", "value", ",", "str", ")", ":", "return", "jsonpickle", ".", "decode", "(", "value", ")", "return", "value" ]
Decode the value.
[ "Decode", "the", "value", "." ]
b0cb8c1ba1511d501c2084def156710e75aaf781
https://github.com/klen/muffin-redis/blob/b0cb8c1ba1511d501c2084def156710e75aaf781/muffin_redis.py#L114-L124
train
klen/muffin-redis
muffin_redis.py
Plugin.publish
def publish(self, channel, message): """Publish message to channel. :returns: a coroutine """ if self.cfg.jsonpickle: message = jsonpickle.encode(message) return self.conn.publish(channel, message)
python
def publish(self, channel, message): """Publish message to channel. :returns: a coroutine """ if self.cfg.jsonpickle: message = jsonpickle.encode(message) return self.conn.publish(channel, message)
[ "def", "publish", "(", "self", ",", "channel", ",", "message", ")", ":", "if", "self", ".", "cfg", ".", "jsonpickle", ":", "message", "=", "jsonpickle", ".", "encode", "(", "message", ")", "return", "self", ".", "conn", ".", "publish", "(", "channel", ",", "message", ")" ]
Publish message to channel. :returns: a coroutine
[ "Publish", "message", "to", "channel", "." ]
b0cb8c1ba1511d501c2084def156710e75aaf781
https://github.com/klen/muffin-redis/blob/b0cb8c1ba1511d501c2084def156710e75aaf781/muffin_redis.py#L126-L133
train
klen/muffin-redis
muffin_redis.py
Plugin.start_subscribe
def start_subscribe(self): """Create a new Subscription context manager.""" if not self.conn: raise ValueError('Not connected') elif not self.pubsub_conn: raise ValueError('PubSub not enabled') # creates a new context manager return Subscription(self)
python
def start_subscribe(self): """Create a new Subscription context manager.""" if not self.conn: raise ValueError('Not connected') elif not self.pubsub_conn: raise ValueError('PubSub not enabled') # creates a new context manager return Subscription(self)
[ "def", "start_subscribe", "(", "self", ")", ":", "if", "not", "self", ".", "conn", ":", "raise", "ValueError", "(", "'Not connected'", ")", "elif", "not", "self", ".", "pubsub_conn", ":", "raise", "ValueError", "(", "'PubSub not enabled'", ")", "# creates a new context manager", "return", "Subscription", "(", "self", ")" ]
Create a new Subscription context manager.
[ "Create", "a", "new", "Subscription", "context", "manager", "." ]
b0cb8c1ba1511d501c2084def156710e75aaf781
https://github.com/klen/muffin-redis/blob/b0cb8c1ba1511d501c2084def156710e75aaf781/muffin_redis.py#L135-L143
train
klen/muffin-redis
muffin_redis.py
Subscription._subscribe
async def _subscribe(self, channels, is_mask): """Subscribe to given channel.""" news = [] for channel in channels: key = channel, is_mask self._channels.append(key) if key in self._plugin._subscriptions: self._plugin._subscriptions[key].append(self._queue) else: self._plugin._subscriptions[key] = [self._queue] news.append(channel) if news: await getattr(self._sub, 'psubscribe' if is_mask else 'subscribe')(news)
python
async def _subscribe(self, channels, is_mask): """Subscribe to given channel.""" news = [] for channel in channels: key = channel, is_mask self._channels.append(key) if key in self._plugin._subscriptions: self._plugin._subscriptions[key].append(self._queue) else: self._plugin._subscriptions[key] = [self._queue] news.append(channel) if news: await getattr(self._sub, 'psubscribe' if is_mask else 'subscribe')(news)
[ "async", "def", "_subscribe", "(", "self", ",", "channels", ",", "is_mask", ")", ":", "news", "=", "[", "]", "for", "channel", "in", "channels", ":", "key", "=", "channel", ",", "is_mask", "self", ".", "_channels", ".", "append", "(", "key", ")", "if", "key", "in", "self", ".", "_plugin", ".", "_subscriptions", ":", "self", ".", "_plugin", ".", "_subscriptions", "[", "key", "]", ".", "append", "(", "self", ".", "_queue", ")", "else", ":", "self", ".", "_plugin", ".", "_subscriptions", "[", "key", "]", "=", "[", "self", ".", "_queue", "]", "news", ".", "append", "(", "channel", ")", "if", "news", ":", "await", "getattr", "(", "self", ".", "_sub", ",", "'psubscribe'", "if", "is_mask", "else", "'subscribe'", ")", "(", "news", ")" ]
Subscribe to given channel.
[ "Subscribe", "to", "given", "channel", "." ]
b0cb8c1ba1511d501c2084def156710e75aaf781
https://github.com/klen/muffin-redis/blob/b0cb8c1ba1511d501c2084def156710e75aaf781/muffin_redis.py#L229-L241
train
klen/muffin-redis
muffin_redis.py
Subscription._unsubscribe
async def _unsubscribe(self, channels, is_mask): """Unsubscribe from given channel.""" vanished = [] if channels: for channel in channels: key = channel, is_mask self._channels.remove(key) self._plugin._subscriptions[key].remove(self._queue) if not self._plugin._subscriptions[key]: # we were last sub? vanished.append(channel) del self._plugin._subscriptions[key] else: while self._channels: channel, is_mask = key = self._channels.pop() self._plugin._subscriptions[key].remove(self._queue) if not self._plugin._subscriptions[key]: vanished.append(channel) del self._plugin._subscriptions[key] if vanished: await getattr(self._sub, 'punsubscribe' if is_mask else 'unsubscribe')(vanished)
python
async def _unsubscribe(self, channels, is_mask): """Unsubscribe from given channel.""" vanished = [] if channels: for channel in channels: key = channel, is_mask self._channels.remove(key) self._plugin._subscriptions[key].remove(self._queue) if not self._plugin._subscriptions[key]: # we were last sub? vanished.append(channel) del self._plugin._subscriptions[key] else: while self._channels: channel, is_mask = key = self._channels.pop() self._plugin._subscriptions[key].remove(self._queue) if not self._plugin._subscriptions[key]: vanished.append(channel) del self._plugin._subscriptions[key] if vanished: await getattr(self._sub, 'punsubscribe' if is_mask else 'unsubscribe')(vanished)
[ "async", "def", "_unsubscribe", "(", "self", ",", "channels", ",", "is_mask", ")", ":", "vanished", "=", "[", "]", "if", "channels", ":", "for", "channel", "in", "channels", ":", "key", "=", "channel", ",", "is_mask", "self", ".", "_channels", ".", "remove", "(", "key", ")", "self", ".", "_plugin", ".", "_subscriptions", "[", "key", "]", ".", "remove", "(", "self", ".", "_queue", ")", "if", "not", "self", ".", "_plugin", ".", "_subscriptions", "[", "key", "]", ":", "# we were last sub?", "vanished", ".", "append", "(", "channel", ")", "del", "self", ".", "_plugin", ".", "_subscriptions", "[", "key", "]", "else", ":", "while", "self", ".", "_channels", ":", "channel", ",", "is_mask", "=", "key", "=", "self", ".", "_channels", ".", "pop", "(", ")", "self", ".", "_plugin", ".", "_subscriptions", "[", "key", "]", ".", "remove", "(", "self", ".", "_queue", ")", "if", "not", "self", ".", "_plugin", ".", "_subscriptions", "[", "key", "]", ":", "vanished", ".", "append", "(", "channel", ")", "del", "self", ".", "_plugin", ".", "_subscriptions", "[", "key", "]", "if", "vanished", ":", "await", "getattr", "(", "self", ".", "_sub", ",", "'punsubscribe'", "if", "is_mask", "else", "'unsubscribe'", ")", "(", "vanished", ")" ]
Unsubscribe from given channel.
[ "Unsubscribe", "from", "given", "channel", "." ]
b0cb8c1ba1511d501c2084def156710e75aaf781
https://github.com/klen/muffin-redis/blob/b0cb8c1ba1511d501c2084def156710e75aaf781/muffin_redis.py#L243-L262
train
sfstpala/pcr
pcr/aes.py
AES.xor
def xor(a, b): """Bitwise xor on equal length bytearrays.""" return bytearray(i ^ j for i, j in zip(a, b))
python
def xor(a, b): """Bitwise xor on equal length bytearrays.""" return bytearray(i ^ j for i, j in zip(a, b))
[ "def", "xor", "(", "a", ",", "b", ")", ":", "return", "bytearray", "(", "i", "^", "j", "for", "i", ",", "j", "in", "zip", "(", "a", ",", "b", ")", ")" ]
Bitwise xor on equal length bytearrays.
[ "Bitwise", "xor", "on", "equal", "length", "bytearrays", "." ]
313ec17585565a0b9740f7b3f47d7a93bf37a7fc
https://github.com/sfstpala/pcr/blob/313ec17585565a0b9740f7b3f47d7a93bf37a7fc/pcr/aes.py#L110-L112
train
fkarb/xltable
xltable/expression.py
Expression.value
def value(self): """Set a calculated value for this Expression. Used when writing formulas using XlsxWriter to give cells an initial value when the sheet is loaded without being calculated. """ try: if isinstance(self.__value, Expression): return self.__value.value return self.__value except AttributeError: return 0
python
def value(self): """Set a calculated value for this Expression. Used when writing formulas using XlsxWriter to give cells an initial value when the sheet is loaded without being calculated. """ try: if isinstance(self.__value, Expression): return self.__value.value return self.__value except AttributeError: return 0
[ "def", "value", "(", "self", ")", ":", "try", ":", "if", "isinstance", "(", "self", ".", "__value", ",", "Expression", ")", ":", "return", "self", ".", "__value", ".", "value", "return", "self", ".", "__value", "except", "AttributeError", ":", "return", "0" ]
Set a calculated value for this Expression. Used when writing formulas using XlsxWriter to give cells an initial value when the sheet is loaded without being calculated.
[ "Set", "a", "calculated", "value", "for", "this", "Expression", ".", "Used", "when", "writing", "formulas", "using", "XlsxWriter", "to", "give", "cells", "an", "initial", "value", "when", "the", "sheet", "is", "loaded", "without", "being", "calculated", "." ]
7a592642d27ad5ee90d2aa8c26338abaa9d84bea
https://github.com/fkarb/xltable/blob/7a592642d27ad5ee90d2aa8c26338abaa9d84bea/xltable/expression.py#L59-L69
train
fkarb/xltable
xltable/expression.py
Expression.has_value
def has_value(self): """return True if value has been set""" try: if isinstance(self.__value, Expression): return self.__value.has_value return True except AttributeError: return False
python
def has_value(self): """return True if value has been set""" try: if isinstance(self.__value, Expression): return self.__value.has_value return True except AttributeError: return False
[ "def", "has_value", "(", "self", ")", ":", "try", ":", "if", "isinstance", "(", "self", ".", "__value", ",", "Expression", ")", ":", "return", "self", ".", "__value", ".", "has_value", "return", "True", "except", "AttributeError", ":", "return", "False" ]
return True if value has been set
[ "return", "True", "if", "value", "has", "been", "set" ]
7a592642d27ad5ee90d2aa8c26338abaa9d84bea
https://github.com/fkarb/xltable/blob/7a592642d27ad5ee90d2aa8c26338abaa9d84bea/xltable/expression.py#L72-L79
train
zsimic/runez
src/runez/file.py
copy
def copy(source, destination, ignore=None, adapter=None, fatal=True, logger=LOG.debug): """Copy source -> destination Args: source (str | None): Source file or folder destination (str | None): Destination file or folder ignore (callable | list | str | None): Names to be ignored adapter (callable | None): Optional function to call on 'source' before copy fatal (bool | None): Abort execution on failure if True logger (callable | None): Logger to use Returns: (int): 1 if effectively done, 0 if no-op, -1 on failure """ return _file_op(source, destination, _copy, adapter, fatal, logger, ignore=ignore)
python
def copy(source, destination, ignore=None, adapter=None, fatal=True, logger=LOG.debug): """Copy source -> destination Args: source (str | None): Source file or folder destination (str | None): Destination file or folder ignore (callable | list | str | None): Names to be ignored adapter (callable | None): Optional function to call on 'source' before copy fatal (bool | None): Abort execution on failure if True logger (callable | None): Logger to use Returns: (int): 1 if effectively done, 0 if no-op, -1 on failure """ return _file_op(source, destination, _copy, adapter, fatal, logger, ignore=ignore)
[ "def", "copy", "(", "source", ",", "destination", ",", "ignore", "=", "None", ",", "adapter", "=", "None", ",", "fatal", "=", "True", ",", "logger", "=", "LOG", ".", "debug", ")", ":", "return", "_file_op", "(", "source", ",", "destination", ",", "_copy", ",", "adapter", ",", "fatal", ",", "logger", ",", "ignore", "=", "ignore", ")" ]
Copy source -> destination Args: source (str | None): Source file or folder destination (str | None): Destination file or folder ignore (callable | list | str | None): Names to be ignored adapter (callable | None): Optional function to call on 'source' before copy fatal (bool | None): Abort execution on failure if True logger (callable | None): Logger to use Returns: (int): 1 if effectively done, 0 if no-op, -1 on failure
[ "Copy", "source", "-", ">", "destination" ]
14363b719a1aae1528859a501a22d075ce0abfcc
https://github.com/zsimic/runez/blob/14363b719a1aae1528859a501a22d075ce0abfcc/src/runez/file.py#L15-L29
train
zsimic/runez
src/runez/file.py
move
def move(source, destination, adapter=None, fatal=True, logger=LOG.debug): """ Move source -> destination :param str|None source: Source file or folder :param str|None destination: Destination file or folder :param callable adapter: Optional function to call on 'source' before copy :param bool|None fatal: Abort execution on failure if True :param callable|None logger: Logger to use :return int: 1 if effectively done, 0 if no-op, -1 on failure """ return _file_op(source, destination, _move, adapter, fatal, logger)
python
def move(source, destination, adapter=None, fatal=True, logger=LOG.debug): """ Move source -> destination :param str|None source: Source file or folder :param str|None destination: Destination file or folder :param callable adapter: Optional function to call on 'source' before copy :param bool|None fatal: Abort execution on failure if True :param callable|None logger: Logger to use :return int: 1 if effectively done, 0 if no-op, -1 on failure """ return _file_op(source, destination, _move, adapter, fatal, logger)
[ "def", "move", "(", "source", ",", "destination", ",", "adapter", "=", "None", ",", "fatal", "=", "True", ",", "logger", "=", "LOG", ".", "debug", ")", ":", "return", "_file_op", "(", "source", ",", "destination", ",", "_move", ",", "adapter", ",", "fatal", ",", "logger", ")" ]
Move source -> destination :param str|None source: Source file or folder :param str|None destination: Destination file or folder :param callable adapter: Optional function to call on 'source' before copy :param bool|None fatal: Abort execution on failure if True :param callable|None logger: Logger to use :return int: 1 if effectively done, 0 if no-op, -1 on failure
[ "Move", "source", "-", ">", "destination" ]
14363b719a1aae1528859a501a22d075ce0abfcc
https://github.com/zsimic/runez/blob/14363b719a1aae1528859a501a22d075ce0abfcc/src/runez/file.py#L144-L155
train
zsimic/runez
src/runez/file.py
symlink
def symlink(source, destination, adapter=None, must_exist=True, fatal=True, logger=LOG.debug): """ Symlink source <- destination :param str|None source: Source file or folder :param str|None destination: Destination file or folder :param callable adapter: Optional function to call on 'source' before copy :param bool must_exist: If True, verify that source does indeed exist :param bool|None fatal: Abort execution on failure if True :param callable|None logger: Logger to use :return int: 1 if effectively done, 0 if no-op, -1 on failure """ return _file_op(source, destination, _symlink, adapter, fatal, logger, must_exist=must_exist)
python
def symlink(source, destination, adapter=None, must_exist=True, fatal=True, logger=LOG.debug): """ Symlink source <- destination :param str|None source: Source file or folder :param str|None destination: Destination file or folder :param callable adapter: Optional function to call on 'source' before copy :param bool must_exist: If True, verify that source does indeed exist :param bool|None fatal: Abort execution on failure if True :param callable|None logger: Logger to use :return int: 1 if effectively done, 0 if no-op, -1 on failure """ return _file_op(source, destination, _symlink, adapter, fatal, logger, must_exist=must_exist)
[ "def", "symlink", "(", "source", ",", "destination", ",", "adapter", "=", "None", ",", "must_exist", "=", "True", ",", "fatal", "=", "True", ",", "logger", "=", "LOG", ".", "debug", ")", ":", "return", "_file_op", "(", "source", ",", "destination", ",", "_symlink", ",", "adapter", ",", "fatal", ",", "logger", ",", "must_exist", "=", "must_exist", ")" ]
Symlink source <- destination :param str|None source: Source file or folder :param str|None destination: Destination file or folder :param callable adapter: Optional function to call on 'source' before copy :param bool must_exist: If True, verify that source does indeed exist :param bool|None fatal: Abort execution on failure if True :param callable|None logger: Logger to use :return int: 1 if effectively done, 0 if no-op, -1 on failure
[ "Symlink", "source", "<", "-", "destination" ]
14363b719a1aae1528859a501a22d075ce0abfcc
https://github.com/zsimic/runez/blob/14363b719a1aae1528859a501a22d075ce0abfcc/src/runez/file.py#L158-L170
train
jslang/responsys
responsys/types.py
InteractType.soap_attribute
def soap_attribute(self, name, value): """ Marks an attribute as being a part of the data defined by the soap datatype""" setattr(self, name, value) self._attributes.add(name)
python
def soap_attribute(self, name, value): """ Marks an attribute as being a part of the data defined by the soap datatype""" setattr(self, name, value) self._attributes.add(name)
[ "def", "soap_attribute", "(", "self", ",", "name", ",", "value", ")", ":", "setattr", "(", "self", ",", "name", ",", "value", ")", "self", ".", "_attributes", ".", "add", "(", "name", ")" ]
Marks an attribute as being a part of the data defined by the soap datatype
[ "Marks", "an", "attribute", "as", "being", "a", "part", "of", "the", "data", "defined", "by", "the", "soap", "datatype" ]
9b355a444c0c75dff41064502c1e2b76dfd5cb93
https://github.com/jslang/responsys/blob/9b355a444c0c75dff41064502c1e2b76dfd5cb93/responsys/types.py#L32-L35
train
jslang/responsys
responsys/types.py
InteractType.get_soap_object
def get_soap_object(self, client): """ Create and return a soap service type defined for this instance """ def to_soap_attribute(attr): words = attr.split('_') words = words[:1] + [word.capitalize() for word in words[1:]] return ''.join(words) soap_object = client.factory.create(self.soap_name) for attr in self._attributes: value = getattr(self, attr) setattr(soap_object, to_soap_attribute(attr), value) return soap_object
python
def get_soap_object(self, client): """ Create and return a soap service type defined for this instance """ def to_soap_attribute(attr): words = attr.split('_') words = words[:1] + [word.capitalize() for word in words[1:]] return ''.join(words) soap_object = client.factory.create(self.soap_name) for attr in self._attributes: value = getattr(self, attr) setattr(soap_object, to_soap_attribute(attr), value) return soap_object
[ "def", "get_soap_object", "(", "self", ",", "client", ")", ":", "def", "to_soap_attribute", "(", "attr", ")", ":", "words", "=", "attr", ".", "split", "(", "'_'", ")", "words", "=", "words", "[", ":", "1", "]", "+", "[", "word", ".", "capitalize", "(", ")", "for", "word", "in", "words", "[", "1", ":", "]", "]", "return", "''", ".", "join", "(", "words", ")", "soap_object", "=", "client", ".", "factory", ".", "create", "(", "self", ".", "soap_name", ")", "for", "attr", "in", "self", ".", "_attributes", ":", "value", "=", "getattr", "(", "self", ",", "attr", ")", "setattr", "(", "soap_object", ",", "to_soap_attribute", "(", "attr", ")", ",", "value", ")", "return", "soap_object" ]
Create and return a soap service type defined for this instance
[ "Create", "and", "return", "a", "soap", "service", "type", "defined", "for", "this", "instance" ]
9b355a444c0c75dff41064502c1e2b76dfd5cb93
https://github.com/jslang/responsys/blob/9b355a444c0c75dff41064502c1e2b76dfd5cb93/responsys/types.py#L37-L49
train
jslang/responsys
responsys/types.py
RecordData.get_soap_object
def get_soap_object(self, client): """ Override default get_soap_object behavior to account for child Record types """ record_data = super().get_soap_object(client) record_data.records = [Record(r).get_soap_object(client) for r in record_data.records] return record_data
python
def get_soap_object(self, client): """ Override default get_soap_object behavior to account for child Record types """ record_data = super().get_soap_object(client) record_data.records = [Record(r).get_soap_object(client) for r in record_data.records] return record_data
[ "def", "get_soap_object", "(", "self", ",", "client", ")", ":", "record_data", "=", "super", "(", ")", ".", "get_soap_object", "(", "client", ")", "record_data", ".", "records", "=", "[", "Record", "(", "r", ")", ".", "get_soap_object", "(", "client", ")", "for", "r", "in", "record_data", ".", "records", "]", "return", "record_data" ]
Override default get_soap_object behavior to account for child Record types
[ "Override", "default", "get_soap_object", "behavior", "to", "account", "for", "child", "Record", "types" ]
9b355a444c0c75dff41064502c1e2b76dfd5cb93
https://github.com/jslang/responsys/blob/9b355a444c0c75dff41064502c1e2b76dfd5cb93/responsys/types.py#L158-L162
train
ShadowBlip/Neteria
neteria/server.py
NeteriaServer.handle_message_registered
def handle_message_registered(self, msg_data, host): """Processes messages that have been delivered by a registered client. Args: msg (string): The raw packet data delivered from the listener. This data will be unserialized and then processed based on the packet's method. host (tuple): The (address, host) tuple of the source message. Returns: A response that will be sent back to the client via the listener. """ response = None if msg_data["method"] == "EVENT": logger.debug("<%s> <euuid:%s> Event message " "received" % (msg_data["cuuid"], msg_data["euuid"])) response = self.event(msg_data["cuuid"], host, msg_data["euuid"], msg_data["event_data"], msg_data["timestamp"], msg_data["priority"]) elif msg_data["method"] == "OK EVENT": logger.debug("<%s> <euuid:%s> Event confirmation message " "received" % (msg_data["cuuid"], msg_data["euuid"])) try: del self.event_uuids[msg_data["euuid"]] except KeyError: logger.warning("<%s> <euuid:%s> Euuid does not exist in event " "buffer. Key was removed before we could process " "it." % (msg_data["cuuid"], msg_data["euuid"])) elif msg_data["method"] == "OK NOTIFY": logger.debug("<%s> <euuid:%s> Ok notify " "received" % (msg_data["cuuid"], msg_data["euuid"])) try: del self.event_uuids[msg_data["euuid"]] except KeyError: logger.warning("<%s> <euuid:%s> Euuid does not exist in event " "buffer. Key was removed before we could process " "it." % (msg_data["cuuid"], msg_data["euuid"])) return response
python
def handle_message_registered(self, msg_data, host): """Processes messages that have been delivered by a registered client. Args: msg (string): The raw packet data delivered from the listener. This data will be unserialized and then processed based on the packet's method. host (tuple): The (address, host) tuple of the source message. Returns: A response that will be sent back to the client via the listener. """ response = None if msg_data["method"] == "EVENT": logger.debug("<%s> <euuid:%s> Event message " "received" % (msg_data["cuuid"], msg_data["euuid"])) response = self.event(msg_data["cuuid"], host, msg_data["euuid"], msg_data["event_data"], msg_data["timestamp"], msg_data["priority"]) elif msg_data["method"] == "OK EVENT": logger.debug("<%s> <euuid:%s> Event confirmation message " "received" % (msg_data["cuuid"], msg_data["euuid"])) try: del self.event_uuids[msg_data["euuid"]] except KeyError: logger.warning("<%s> <euuid:%s> Euuid does not exist in event " "buffer. Key was removed before we could process " "it." % (msg_data["cuuid"], msg_data["euuid"])) elif msg_data["method"] == "OK NOTIFY": logger.debug("<%s> <euuid:%s> Ok notify " "received" % (msg_data["cuuid"], msg_data["euuid"])) try: del self.event_uuids[msg_data["euuid"]] except KeyError: logger.warning("<%s> <euuid:%s> Euuid does not exist in event " "buffer. Key was removed before we could process " "it." % (msg_data["cuuid"], msg_data["euuid"])) return response
[ "def", "handle_message_registered", "(", "self", ",", "msg_data", ",", "host", ")", ":", "response", "=", "None", "if", "msg_data", "[", "\"method\"", "]", "==", "\"EVENT\"", ":", "logger", ".", "debug", "(", "\"<%s> <euuid:%s> Event message \"", "\"received\"", "%", "(", "msg_data", "[", "\"cuuid\"", "]", ",", "msg_data", "[", "\"euuid\"", "]", ")", ")", "response", "=", "self", ".", "event", "(", "msg_data", "[", "\"cuuid\"", "]", ",", "host", ",", "msg_data", "[", "\"euuid\"", "]", ",", "msg_data", "[", "\"event_data\"", "]", ",", "msg_data", "[", "\"timestamp\"", "]", ",", "msg_data", "[", "\"priority\"", "]", ")", "elif", "msg_data", "[", "\"method\"", "]", "==", "\"OK EVENT\"", ":", "logger", ".", "debug", "(", "\"<%s> <euuid:%s> Event confirmation message \"", "\"received\"", "%", "(", "msg_data", "[", "\"cuuid\"", "]", ",", "msg_data", "[", "\"euuid\"", "]", ")", ")", "try", ":", "del", "self", ".", "event_uuids", "[", "msg_data", "[", "\"euuid\"", "]", "]", "except", "KeyError", ":", "logger", ".", "warning", "(", "\"<%s> <euuid:%s> Euuid does not exist in event \"", "\"buffer. Key was removed before we could process \"", "\"it.\"", "%", "(", "msg_data", "[", "\"cuuid\"", "]", ",", "msg_data", "[", "\"euuid\"", "]", ")", ")", "elif", "msg_data", "[", "\"method\"", "]", "==", "\"OK NOTIFY\"", ":", "logger", ".", "debug", "(", "\"<%s> <euuid:%s> Ok notify \"", "\"received\"", "%", "(", "msg_data", "[", "\"cuuid\"", "]", ",", "msg_data", "[", "\"euuid\"", "]", ")", ")", "try", ":", "del", "self", ".", "event_uuids", "[", "msg_data", "[", "\"euuid\"", "]", "]", "except", "KeyError", ":", "logger", ".", "warning", "(", "\"<%s> <euuid:%s> Euuid does not exist in event \"", "\"buffer. Key was removed before we could process \"", "\"it.\"", "%", "(", "msg_data", "[", "\"cuuid\"", "]", ",", "msg_data", "[", "\"euuid\"", "]", ")", ")", "return", "response" ]
Processes messages that have been delivered by a registered client. Args: msg (string): The raw packet data delivered from the listener. This data will be unserialized and then processed based on the packet's method. host (tuple): The (address, host) tuple of the source message. Returns: A response that will be sent back to the client via the listener.
[ "Processes", "messages", "that", "have", "been", "delivered", "by", "a", "registered", "client", "." ]
1a8c976eb2beeca0a5a272a34ac58b2c114495a4
https://github.com/ShadowBlip/Neteria/blob/1a8c976eb2beeca0a5a272a34ac58b2c114495a4/neteria/server.py#L272-L318
train
ShadowBlip/Neteria
neteria/server.py
NeteriaServer.autodiscover
def autodiscover(self, message): """This function simply returns the server version number as a response to the client. Args: message (dict): A dictionary of the autodiscover message from the client. Returns: A JSON string of the "OHAI Client" server response with the server's version number. Examples: >>> response '{"method": "OHAI Client", "version": "1.0"}' """ # Check to see if the client's version is the same as our own. if message["version"] in self.allowed_versions: logger.debug("<%s> Client version matches server " "version." % message["cuuid"]) response = serialize_data({"method": "OHAI Client", "version": self.version, "server_name": self.server_name}, self.compression, encryption=False) else: logger.warning("<%s> Client version %s does not match allowed server " "versions %s" % (message["cuuid"], message["version"], self.version)) response = serialize_data({"method": "BYE REGISTER"}, self.compression, encryption=False) return response
python
def autodiscover(self, message): """This function simply returns the server version number as a response to the client. Args: message (dict): A dictionary of the autodiscover message from the client. Returns: A JSON string of the "OHAI Client" server response with the server's version number. Examples: >>> response '{"method": "OHAI Client", "version": "1.0"}' """ # Check to see if the client's version is the same as our own. if message["version"] in self.allowed_versions: logger.debug("<%s> Client version matches server " "version." % message["cuuid"]) response = serialize_data({"method": "OHAI Client", "version": self.version, "server_name": self.server_name}, self.compression, encryption=False) else: logger.warning("<%s> Client version %s does not match allowed server " "versions %s" % (message["cuuid"], message["version"], self.version)) response = serialize_data({"method": "BYE REGISTER"}, self.compression, encryption=False) return response
[ "def", "autodiscover", "(", "self", ",", "message", ")", ":", "# Check to see if the client's version is the same as our own.", "if", "message", "[", "\"version\"", "]", "in", "self", ".", "allowed_versions", ":", "logger", ".", "debug", "(", "\"<%s> Client version matches server \"", "\"version.\"", "%", "message", "[", "\"cuuid\"", "]", ")", "response", "=", "serialize_data", "(", "{", "\"method\"", ":", "\"OHAI Client\"", ",", "\"version\"", ":", "self", ".", "version", ",", "\"server_name\"", ":", "self", ".", "server_name", "}", ",", "self", ".", "compression", ",", "encryption", "=", "False", ")", "else", ":", "logger", ".", "warning", "(", "\"<%s> Client version %s does not match allowed server \"", "\"versions %s\"", "%", "(", "message", "[", "\"cuuid\"", "]", ",", "message", "[", "\"version\"", "]", ",", "self", ".", "version", ")", ")", "response", "=", "serialize_data", "(", "{", "\"method\"", ":", "\"BYE REGISTER\"", "}", ",", "self", ".", "compression", ",", "encryption", "=", "False", ")", "return", "response" ]
This function simply returns the server version number as a response to the client. Args: message (dict): A dictionary of the autodiscover message from the client. Returns: A JSON string of the "OHAI Client" server response with the server's version number. Examples: >>> response '{"method": "OHAI Client", "version": "1.0"}'
[ "This", "function", "simply", "returns", "the", "server", "version", "number", "as", "a", "response", "to", "the", "client", "." ]
1a8c976eb2beeca0a5a272a34ac58b2c114495a4
https://github.com/ShadowBlip/Neteria/blob/1a8c976eb2beeca0a5a272a34ac58b2c114495a4/neteria/server.py#L321-L356
train
ShadowBlip/Neteria
neteria/server.py
NeteriaServer.register
def register(self, message, host): """This function will register a particular client in the server's registry dictionary. Any clients that are registered will be able to send and recieve events to and from the server. Args: message (dict): The client message from the client who wants to register. host (tuple): The (address, port) tuple of the client that is registering. Returns: A server response with an "OK REGISTER" if the registration was successful or a "BYE REGISTER" if unsuccessful. """ # Get the client generated cuuid from the register message cuuid = message["cuuid"] # Check to see if we've hit the maximum number of registrations # If we've reached the maximum limit, return a failure response to the # client. if len(self.registry) > self.registration_limit: logger.warning("<%s> Registration limit exceeded" % cuuid) response = serialize_data({"method": "BYE REGISTER"}, self.compression, encryption=False) return response # Insert a new record in the database with the client's information data = {"host": host[0], "port": host[1], "time": datetime.now()} # Prepare an OK REGISTER response to the client to let it know that it # has registered return_msg = {"method": "OK REGISTER"} # If the register request has a public key included in it, then include # it in the registry. if "encryption" in message and self.encryption: data["encryption"] = PublicKey(message["encryption"][0], message["encryption"][1]) # Add the host to the encrypted_hosts dictionary so we know to # decrypt messages from this host self.encrypted_hosts[host] = cuuid # If the client requested encryption and we have it enabled, send # our public key to the client return_msg["encryption"] = [self.encryption.n, self.encryption.e] # Add the entry to the registry if cuuid in self.registry: for key in data: self.registry[cuuid][key]=data[key] else: self.registry[cuuid] = data self.registry[cuuid]["authenticated"] = False # Serialize our response to the client response = serialize_data(return_msg, self.compression, encryption=False) # For debugging, print all the current rows in the registry logger.debug("<%s> Registry entries:" % cuuid) for (key, value) in self.registry.items(): logger.debug("<%s> %s %s" % (str(cuuid), str(key), pformat(value))) return response
python
def register(self, message, host): """This function will register a particular client in the server's registry dictionary. Any clients that are registered will be able to send and recieve events to and from the server. Args: message (dict): The client message from the client who wants to register. host (tuple): The (address, port) tuple of the client that is registering. Returns: A server response with an "OK REGISTER" if the registration was successful or a "BYE REGISTER" if unsuccessful. """ # Get the client generated cuuid from the register message cuuid = message["cuuid"] # Check to see if we've hit the maximum number of registrations # If we've reached the maximum limit, return a failure response to the # client. if len(self.registry) > self.registration_limit: logger.warning("<%s> Registration limit exceeded" % cuuid) response = serialize_data({"method": "BYE REGISTER"}, self.compression, encryption=False) return response # Insert a new record in the database with the client's information data = {"host": host[0], "port": host[1], "time": datetime.now()} # Prepare an OK REGISTER response to the client to let it know that it # has registered return_msg = {"method": "OK REGISTER"} # If the register request has a public key included in it, then include # it in the registry. if "encryption" in message and self.encryption: data["encryption"] = PublicKey(message["encryption"][0], message["encryption"][1]) # Add the host to the encrypted_hosts dictionary so we know to # decrypt messages from this host self.encrypted_hosts[host] = cuuid # If the client requested encryption and we have it enabled, send # our public key to the client return_msg["encryption"] = [self.encryption.n, self.encryption.e] # Add the entry to the registry if cuuid in self.registry: for key in data: self.registry[cuuid][key]=data[key] else: self.registry[cuuid] = data self.registry[cuuid]["authenticated"] = False # Serialize our response to the client response = serialize_data(return_msg, self.compression, encryption=False) # For debugging, print all the current rows in the registry logger.debug("<%s> Registry entries:" % cuuid) for (key, value) in self.registry.items(): logger.debug("<%s> %s %s" % (str(cuuid), str(key), pformat(value))) return response
[ "def", "register", "(", "self", ",", "message", ",", "host", ")", ":", "# Get the client generated cuuid from the register message", "cuuid", "=", "message", "[", "\"cuuid\"", "]", "# Check to see if we've hit the maximum number of registrations", "# If we've reached the maximum limit, return a failure response to the", "# client.", "if", "len", "(", "self", ".", "registry", ")", ">", "self", ".", "registration_limit", ":", "logger", ".", "warning", "(", "\"<%s> Registration limit exceeded\"", "%", "cuuid", ")", "response", "=", "serialize_data", "(", "{", "\"method\"", ":", "\"BYE REGISTER\"", "}", ",", "self", ".", "compression", ",", "encryption", "=", "False", ")", "return", "response", "# Insert a new record in the database with the client's information", "data", "=", "{", "\"host\"", ":", "host", "[", "0", "]", ",", "\"port\"", ":", "host", "[", "1", "]", ",", "\"time\"", ":", "datetime", ".", "now", "(", ")", "}", "# Prepare an OK REGISTER response to the client to let it know that it", "# has registered", "return_msg", "=", "{", "\"method\"", ":", "\"OK REGISTER\"", "}", "# If the register request has a public key included in it, then include", "# it in the registry.", "if", "\"encryption\"", "in", "message", "and", "self", ".", "encryption", ":", "data", "[", "\"encryption\"", "]", "=", "PublicKey", "(", "message", "[", "\"encryption\"", "]", "[", "0", "]", ",", "message", "[", "\"encryption\"", "]", "[", "1", "]", ")", "# Add the host to the encrypted_hosts dictionary so we know to", "# decrypt messages from this host", "self", ".", "encrypted_hosts", "[", "host", "]", "=", "cuuid", "# If the client requested encryption and we have it enabled, send", "# our public key to the client", "return_msg", "[", "\"encryption\"", "]", "=", "[", "self", ".", "encryption", ".", "n", ",", "self", ".", "encryption", ".", "e", "]", "# Add the entry to the registry", "if", "cuuid", "in", "self", ".", "registry", ":", "for", "key", "in", "data", ":", "self", ".", "registry", "[", "cuuid", "]", "[", "key", "]", "=", "data", "[", "key", "]", "else", ":", "self", ".", "registry", "[", "cuuid", "]", "=", "data", "self", ".", "registry", "[", "cuuid", "]", "[", "\"authenticated\"", "]", "=", "False", "# Serialize our response to the client", "response", "=", "serialize_data", "(", "return_msg", ",", "self", ".", "compression", ",", "encryption", "=", "False", ")", "# For debugging, print all the current rows in the registry", "logger", ".", "debug", "(", "\"<%s> Registry entries:\"", "%", "cuuid", ")", "for", "(", "key", ",", "value", ")", "in", "self", ".", "registry", ".", "items", "(", ")", ":", "logger", ".", "debug", "(", "\"<%s> %s %s\"", "%", "(", "str", "(", "cuuid", ")", ",", "str", "(", "key", ")", ",", "pformat", "(", "value", ")", ")", ")", "return", "response" ]
This function will register a particular client in the server's registry dictionary. Any clients that are registered will be able to send and recieve events to and from the server. Args: message (dict): The client message from the client who wants to register. host (tuple): The (address, port) tuple of the client that is registering. Returns: A server response with an "OK REGISTER" if the registration was successful or a "BYE REGISTER" if unsuccessful.
[ "This", "function", "will", "register", "a", "particular", "client", "in", "the", "server", "s", "registry", "dictionary", "." ]
1a8c976eb2beeca0a5a272a34ac58b2c114495a4
https://github.com/ShadowBlip/Neteria/blob/1a8c976eb2beeca0a5a272a34ac58b2c114495a4/neteria/server.py#L359-L429
train
ShadowBlip/Neteria
neteria/server.py
NeteriaServer.is_registered
def is_registered(self, cuuid, host): """This function will check to see if a given host with client uuid is currently registered. Args: cuuid (string): The client uuid that wishes to register. host (tuple): The (address, port) tuple of the client that is registering. Returns: Will return True if the client is registered and will return False if it is not. """ # Check to see if the host with the client uuid exists in the registry # table. if (cuuid in self.registry) and (self.registry[cuuid]["host"] == host): return True else: return False
python
def is_registered(self, cuuid, host): """This function will check to see if a given host with client uuid is currently registered. Args: cuuid (string): The client uuid that wishes to register. host (tuple): The (address, port) tuple of the client that is registering. Returns: Will return True if the client is registered and will return False if it is not. """ # Check to see if the host with the client uuid exists in the registry # table. if (cuuid in self.registry) and (self.registry[cuuid]["host"] == host): return True else: return False
[ "def", "is_registered", "(", "self", ",", "cuuid", ",", "host", ")", ":", "# Check to see if the host with the client uuid exists in the registry", "# table.", "if", "(", "cuuid", "in", "self", ".", "registry", ")", "and", "(", "self", ".", "registry", "[", "cuuid", "]", "[", "\"host\"", "]", "==", "host", ")", ":", "return", "True", "else", ":", "return", "False" ]
This function will check to see if a given host with client uuid is currently registered. Args: cuuid (string): The client uuid that wishes to register. host (tuple): The (address, port) tuple of the client that is registering. Returns: Will return True if the client is registered and will return False if it is not.
[ "This", "function", "will", "check", "to", "see", "if", "a", "given", "host", "with", "client", "uuid", "is", "currently", "registered", "." ]
1a8c976eb2beeca0a5a272a34ac58b2c114495a4
https://github.com/ShadowBlip/Neteria/blob/1a8c976eb2beeca0a5a272a34ac58b2c114495a4/neteria/server.py#L432-L451
train
ShadowBlip/Neteria
neteria/server.py
NeteriaServer.event
def event(self, cuuid, host, euuid, event_data, timestamp, priority): """This function will process event packets and send them to legal checks. Args: cuuid (string): The client uuid that the event came from. host (tuple): The (address, port) tuple of the client. euuid (string): The event uuid of the specific event. event_data (any): The event data that we will be sending to the middleware to be judged and executed. timestamp (string): The client provided timestamp of when the event was created. priority (string): The priority of the event. This is normally set to either "normal" or "high". If an event was sent with a high priority, then the client will not wait for a response from the server before executing the event locally. Returns: A LEGAL/ILLEGAL response to be sent to the client. """ # Set the initial response to none response = None # If the host we're sending to is using encryption, get their key to # encrypt. if host in self.encrypted_hosts: logger.debug("Encrypted!") client_key = self.registry[cuuid]["encryption"] else: logger.debug("Not encrypted :<") client_key = None # Get the port and host port = host[1] host = host[0] # First, we need to check if the request is coming from a registered # client. If it's not coming from a registered client, we tell them to # fuck off and register first. if not self.is_registered(cuuid, host): logger.warning("<%s> Sending BYE EVENT: Client not registered." % cuuid) response = serialize_data({"method": "BYE EVENT", "data": "Not registered"}, self.compression, self.encryption, client_key) return response # Check our stored event uuid's to see if we're already processing # this event. if euuid in self.event_uuids: logger.warning("<%s> Event ID is already being processed: %s" % (cuuid, euuid)) # If we're already working on this event, return none so we do not # reply to the client return response # If we're not already processing this event, store the event uuid # until we receive a confirmation from the client that it received our # judgement. self.event_uuids[euuid] = 0 logger.debug("<%s> <euuid:%s> Currently processing events: " "%s" % (cuuid, euuid, str(self.event_uuids))) logger.debug("<%s> <euuid:%s> New event being processed" % (cuuid, euuid)) logger.debug("<%s> <euuid:%s> Event Data: %s" % (cuuid, euuid, pformat(event_data))) # Send the event to the game middleware to determine if the event is # legal or not and to process the event in the Game Server if it is # legal. if self.middleware.event_legal(cuuid, euuid, event_data): logger.debug("<%s> <euuid:%s> Event LEGAL. Sending judgement " "to client." % (cuuid, euuid)) response = serialize_data({"method": "LEGAL", "euuid": euuid, "priority": priority}, self.compression, self.encryption, client_key) # Execute the event thread = threading.Thread(target=self.middleware.event_execute, args=(cuuid, euuid, event_data) ) thread.start() else: logger.debug("<%s> <euuid:%s> Event ILLEGAL. Sending judgement " "to client." % (cuuid, euuid)) response = serialize_data({"method": "ILLEGAL", "euuid": euuid, "priority": priority}, self.compression, self.encryption, client_key) # Schedule a task to run in x seconds to check to see if we've timed # out in receiving a response from the client. self.listener.call_later(self.timeout, self.retransmit, {"euuid": euuid, "response": response, "cuuid": cuuid}) return response
python
def event(self, cuuid, host, euuid, event_data, timestamp, priority): """This function will process event packets and send them to legal checks. Args: cuuid (string): The client uuid that the event came from. host (tuple): The (address, port) tuple of the client. euuid (string): The event uuid of the specific event. event_data (any): The event data that we will be sending to the middleware to be judged and executed. timestamp (string): The client provided timestamp of when the event was created. priority (string): The priority of the event. This is normally set to either "normal" or "high". If an event was sent with a high priority, then the client will not wait for a response from the server before executing the event locally. Returns: A LEGAL/ILLEGAL response to be sent to the client. """ # Set the initial response to none response = None # If the host we're sending to is using encryption, get their key to # encrypt. if host in self.encrypted_hosts: logger.debug("Encrypted!") client_key = self.registry[cuuid]["encryption"] else: logger.debug("Not encrypted :<") client_key = None # Get the port and host port = host[1] host = host[0] # First, we need to check if the request is coming from a registered # client. If it's not coming from a registered client, we tell them to # fuck off and register first. if not self.is_registered(cuuid, host): logger.warning("<%s> Sending BYE EVENT: Client not registered." % cuuid) response = serialize_data({"method": "BYE EVENT", "data": "Not registered"}, self.compression, self.encryption, client_key) return response # Check our stored event uuid's to see if we're already processing # this event. if euuid in self.event_uuids: logger.warning("<%s> Event ID is already being processed: %s" % (cuuid, euuid)) # If we're already working on this event, return none so we do not # reply to the client return response # If we're not already processing this event, store the event uuid # until we receive a confirmation from the client that it received our # judgement. self.event_uuids[euuid] = 0 logger.debug("<%s> <euuid:%s> Currently processing events: " "%s" % (cuuid, euuid, str(self.event_uuids))) logger.debug("<%s> <euuid:%s> New event being processed" % (cuuid, euuid)) logger.debug("<%s> <euuid:%s> Event Data: %s" % (cuuid, euuid, pformat(event_data))) # Send the event to the game middleware to determine if the event is # legal or not and to process the event in the Game Server if it is # legal. if self.middleware.event_legal(cuuid, euuid, event_data): logger.debug("<%s> <euuid:%s> Event LEGAL. Sending judgement " "to client." % (cuuid, euuid)) response = serialize_data({"method": "LEGAL", "euuid": euuid, "priority": priority}, self.compression, self.encryption, client_key) # Execute the event thread = threading.Thread(target=self.middleware.event_execute, args=(cuuid, euuid, event_data) ) thread.start() else: logger.debug("<%s> <euuid:%s> Event ILLEGAL. Sending judgement " "to client." % (cuuid, euuid)) response = serialize_data({"method": "ILLEGAL", "euuid": euuid, "priority": priority}, self.compression, self.encryption, client_key) # Schedule a task to run in x seconds to check to see if we've timed # out in receiving a response from the client. self.listener.call_later(self.timeout, self.retransmit, {"euuid": euuid, "response": response, "cuuid": cuuid}) return response
[ "def", "event", "(", "self", ",", "cuuid", ",", "host", ",", "euuid", ",", "event_data", ",", "timestamp", ",", "priority", ")", ":", "# Set the initial response to none", "response", "=", "None", "# If the host we're sending to is using encryption, get their key to", "# encrypt.", "if", "host", "in", "self", ".", "encrypted_hosts", ":", "logger", ".", "debug", "(", "\"Encrypted!\"", ")", "client_key", "=", "self", ".", "registry", "[", "cuuid", "]", "[", "\"encryption\"", "]", "else", ":", "logger", ".", "debug", "(", "\"Not encrypted :<\"", ")", "client_key", "=", "None", "# Get the port and host", "port", "=", "host", "[", "1", "]", "host", "=", "host", "[", "0", "]", "# First, we need to check if the request is coming from a registered", "# client. If it's not coming from a registered client, we tell them to", "# fuck off and register first.", "if", "not", "self", ".", "is_registered", "(", "cuuid", ",", "host", ")", ":", "logger", ".", "warning", "(", "\"<%s> Sending BYE EVENT: Client not registered.\"", "%", "cuuid", ")", "response", "=", "serialize_data", "(", "{", "\"method\"", ":", "\"BYE EVENT\"", ",", "\"data\"", ":", "\"Not registered\"", "}", ",", "self", ".", "compression", ",", "self", ".", "encryption", ",", "client_key", ")", "return", "response", "# Check our stored event uuid's to see if we're already processing", "# this event.", "if", "euuid", "in", "self", ".", "event_uuids", ":", "logger", ".", "warning", "(", "\"<%s> Event ID is already being processed: %s\"", "%", "(", "cuuid", ",", "euuid", ")", ")", "# If we're already working on this event, return none so we do not", "# reply to the client", "return", "response", "# If we're not already processing this event, store the event uuid", "# until we receive a confirmation from the client that it received our", "# judgement.", "self", ".", "event_uuids", "[", "euuid", "]", "=", "0", "logger", ".", "debug", "(", "\"<%s> <euuid:%s> Currently processing events: \"", "\"%s\"", "%", "(", "cuuid", ",", "euuid", ",", "str", "(", "self", ".", "event_uuids", ")", ")", ")", "logger", ".", "debug", "(", "\"<%s> <euuid:%s> New event being processed\"", "%", "(", "cuuid", ",", "euuid", ")", ")", "logger", ".", "debug", "(", "\"<%s> <euuid:%s> Event Data: %s\"", "%", "(", "cuuid", ",", "euuid", ",", "pformat", "(", "event_data", ")", ")", ")", "# Send the event to the game middleware to determine if the event is", "# legal or not and to process the event in the Game Server if it is", "# legal.", "if", "self", ".", "middleware", ".", "event_legal", "(", "cuuid", ",", "euuid", ",", "event_data", ")", ":", "logger", ".", "debug", "(", "\"<%s> <euuid:%s> Event LEGAL. Sending judgement \"", "\"to client.\"", "%", "(", "cuuid", ",", "euuid", ")", ")", "response", "=", "serialize_data", "(", "{", "\"method\"", ":", "\"LEGAL\"", ",", "\"euuid\"", ":", "euuid", ",", "\"priority\"", ":", "priority", "}", ",", "self", ".", "compression", ",", "self", ".", "encryption", ",", "client_key", ")", "# Execute the event", "thread", "=", "threading", ".", "Thread", "(", "target", "=", "self", ".", "middleware", ".", "event_execute", ",", "args", "=", "(", "cuuid", ",", "euuid", ",", "event_data", ")", ")", "thread", ".", "start", "(", ")", "else", ":", "logger", ".", "debug", "(", "\"<%s> <euuid:%s> Event ILLEGAL. Sending judgement \"", "\"to client.\"", "%", "(", "cuuid", ",", "euuid", ")", ")", "response", "=", "serialize_data", "(", "{", "\"method\"", ":", "\"ILLEGAL\"", ",", "\"euuid\"", ":", "euuid", ",", "\"priority\"", ":", "priority", "}", ",", "self", ".", "compression", ",", "self", ".", "encryption", ",", "client_key", ")", "# Schedule a task to run in x seconds to check to see if we've timed", "# out in receiving a response from the client.", "self", ".", "listener", ".", "call_later", "(", "self", ".", "timeout", ",", "self", ".", "retransmit", ",", "{", "\"euuid\"", ":", "euuid", ",", "\"response\"", ":", "response", ",", "\"cuuid\"", ":", "cuuid", "}", ")", "return", "response" ]
This function will process event packets and send them to legal checks. Args: cuuid (string): The client uuid that the event came from. host (tuple): The (address, port) tuple of the client. euuid (string): The event uuid of the specific event. event_data (any): The event data that we will be sending to the middleware to be judged and executed. timestamp (string): The client provided timestamp of when the event was created. priority (string): The priority of the event. This is normally set to either "normal" or "high". If an event was sent with a high priority, then the client will not wait for a response from the server before executing the event locally. Returns: A LEGAL/ILLEGAL response to be sent to the client.
[ "This", "function", "will", "process", "event", "packets", "and", "send", "them", "to", "legal", "checks", "." ]
1a8c976eb2beeca0a5a272a34ac58b2c114495a4
https://github.com/ShadowBlip/Neteria/blob/1a8c976eb2beeca0a5a272a34ac58b2c114495a4/neteria/server.py#L454-L555
train
ShadowBlip/Neteria
neteria/server.py
NeteriaServer.notify
def notify(self, cuuid, event_data): """This function will send a NOTIFY event to a registered client. NOTIFY messages are nearly identical to EVENT messages, except that NOTIFY messages are always sent from server -> client. EVENT messages are always sent from client -> server. In addition to this difference, NOTIFY messages are not processed by a middleware to determine if they are legal or not, since all messages from the server should be considered LEGAL. Args: cuuid (string): The client uuid to send the event data to. event_data (any): The event data that we will be sending to the client. Returns: None """ # Generate an event uuid for the notify event euuid = str(uuid.uuid1()) # If the client uses encryption, get their key to encrypt if "encryption" in self.registry[cuuid]: client_key = self.registry[cuuid]["encryption"] else: client_key = None logger.debug("<%s> <%s> Sending NOTIFY event to client with event data: " "%s" % (str(cuuid), str(euuid), pformat(event_data))) # Look up the host details based on cuuid try: ip_address = self.registry[cuuid]["host"] except KeyError: logger.warning("<%s> <%s> Host not found in registry! Transmit " "Canceled" % (str(cuuid), str(euuid))) return False try: port = self.registry[cuuid]["port"] except KeyError: logger.warning("<%s> <%s> Port not found! Transmit " "Canceled" % (str(cuuid), str(euuid))) return False # Set up the packet and address to send to packet = serialize_data({"method": "NOTIFY", "event_data": event_data, "euuid": euuid}, self.compression, self.encryption, client_key) address = (ip_address, port) # If we're not already processing this event, store the event uuid # until we receive a confirmation from the client that it received our # notification. self.event_uuids[euuid] = 0 # This is the current retry attempt logger.debug("<%s> Currently processing events: " "%s" % (cuuid, pformat(self.event_uuids))) logger.debug("<%s> New NOTIFY event being processed:" % cuuid) logger.debug("<%s> EUUID: %s" % (cuuid, euuid)) logger.debug("<%s> Event Data: %s" % (cuuid, pformat(event_data))) # Send the packet to the client self.listener.send_datagram(packet, address) # Schedule a task to run in x seconds to check to see if we've timed # out in receiving a response from the client/ self.listener.call_later(self.timeout, self.retransmit, {"euuid": euuid, "response": packet, "cuuid": cuuid})
python
def notify(self, cuuid, event_data): """This function will send a NOTIFY event to a registered client. NOTIFY messages are nearly identical to EVENT messages, except that NOTIFY messages are always sent from server -> client. EVENT messages are always sent from client -> server. In addition to this difference, NOTIFY messages are not processed by a middleware to determine if they are legal or not, since all messages from the server should be considered LEGAL. Args: cuuid (string): The client uuid to send the event data to. event_data (any): The event data that we will be sending to the client. Returns: None """ # Generate an event uuid for the notify event euuid = str(uuid.uuid1()) # If the client uses encryption, get their key to encrypt if "encryption" in self.registry[cuuid]: client_key = self.registry[cuuid]["encryption"] else: client_key = None logger.debug("<%s> <%s> Sending NOTIFY event to client with event data: " "%s" % (str(cuuid), str(euuid), pformat(event_data))) # Look up the host details based on cuuid try: ip_address = self.registry[cuuid]["host"] except KeyError: logger.warning("<%s> <%s> Host not found in registry! Transmit " "Canceled" % (str(cuuid), str(euuid))) return False try: port = self.registry[cuuid]["port"] except KeyError: logger.warning("<%s> <%s> Port not found! Transmit " "Canceled" % (str(cuuid), str(euuid))) return False # Set up the packet and address to send to packet = serialize_data({"method": "NOTIFY", "event_data": event_data, "euuid": euuid}, self.compression, self.encryption, client_key) address = (ip_address, port) # If we're not already processing this event, store the event uuid # until we receive a confirmation from the client that it received our # notification. self.event_uuids[euuid] = 0 # This is the current retry attempt logger.debug("<%s> Currently processing events: " "%s" % (cuuid, pformat(self.event_uuids))) logger.debug("<%s> New NOTIFY event being processed:" % cuuid) logger.debug("<%s> EUUID: %s" % (cuuid, euuid)) logger.debug("<%s> Event Data: %s" % (cuuid, pformat(event_data))) # Send the packet to the client self.listener.send_datagram(packet, address) # Schedule a task to run in x seconds to check to see if we've timed # out in receiving a response from the client/ self.listener.call_later(self.timeout, self.retransmit, {"euuid": euuid, "response": packet, "cuuid": cuuid})
[ "def", "notify", "(", "self", ",", "cuuid", ",", "event_data", ")", ":", "# Generate an event uuid for the notify event", "euuid", "=", "str", "(", "uuid", ".", "uuid1", "(", ")", ")", "# If the client uses encryption, get their key to encrypt", "if", "\"encryption\"", "in", "self", ".", "registry", "[", "cuuid", "]", ":", "client_key", "=", "self", ".", "registry", "[", "cuuid", "]", "[", "\"encryption\"", "]", "else", ":", "client_key", "=", "None", "logger", ".", "debug", "(", "\"<%s> <%s> Sending NOTIFY event to client with event data: \"", "\"%s\"", "%", "(", "str", "(", "cuuid", ")", ",", "str", "(", "euuid", ")", ",", "pformat", "(", "event_data", ")", ")", ")", "# Look up the host details based on cuuid", "try", ":", "ip_address", "=", "self", ".", "registry", "[", "cuuid", "]", "[", "\"host\"", "]", "except", "KeyError", ":", "logger", ".", "warning", "(", "\"<%s> <%s> Host not found in registry! Transmit \"", "\"Canceled\"", "%", "(", "str", "(", "cuuid", ")", ",", "str", "(", "euuid", ")", ")", ")", "return", "False", "try", ":", "port", "=", "self", ".", "registry", "[", "cuuid", "]", "[", "\"port\"", "]", "except", "KeyError", ":", "logger", ".", "warning", "(", "\"<%s> <%s> Port not found! Transmit \"", "\"Canceled\"", "%", "(", "str", "(", "cuuid", ")", ",", "str", "(", "euuid", ")", ")", ")", "return", "False", "# Set up the packet and address to send to", "packet", "=", "serialize_data", "(", "{", "\"method\"", ":", "\"NOTIFY\"", ",", "\"event_data\"", ":", "event_data", ",", "\"euuid\"", ":", "euuid", "}", ",", "self", ".", "compression", ",", "self", ".", "encryption", ",", "client_key", ")", "address", "=", "(", "ip_address", ",", "port", ")", "# If we're not already processing this event, store the event uuid", "# until we receive a confirmation from the client that it received our", "# notification.", "self", ".", "event_uuids", "[", "euuid", "]", "=", "0", "# This is the current retry attempt", "logger", ".", "debug", "(", "\"<%s> Currently processing events: \"", "\"%s\"", "%", "(", "cuuid", ",", "pformat", "(", "self", ".", "event_uuids", ")", ")", ")", "logger", ".", "debug", "(", "\"<%s> New NOTIFY event being processed:\"", "%", "cuuid", ")", "logger", ".", "debug", "(", "\"<%s> EUUID: %s\"", "%", "(", "cuuid", ",", "euuid", ")", ")", "logger", ".", "debug", "(", "\"<%s> Event Data: %s\"", "%", "(", "cuuid", ",", "pformat", "(", "event_data", ")", ")", ")", "# Send the packet to the client", "self", ".", "listener", ".", "send_datagram", "(", "packet", ",", "address", ")", "# Schedule a task to run in x seconds to check to see if we've timed", "# out in receiving a response from the client/", "self", ".", "listener", ".", "call_later", "(", "self", ".", "timeout", ",", "self", ".", "retransmit", ",", "{", "\"euuid\"", ":", "euuid", ",", "\"response\"", ":", "packet", ",", "\"cuuid\"", ":", "cuuid", "}", ")" ]
This function will send a NOTIFY event to a registered client. NOTIFY messages are nearly identical to EVENT messages, except that NOTIFY messages are always sent from server -> client. EVENT messages are always sent from client -> server. In addition to this difference, NOTIFY messages are not processed by a middleware to determine if they are legal or not, since all messages from the server should be considered LEGAL. Args: cuuid (string): The client uuid to send the event data to. event_data (any): The event data that we will be sending to the client. Returns: None
[ "This", "function", "will", "send", "a", "NOTIFY", "event", "to", "a", "registered", "client", "." ]
1a8c976eb2beeca0a5a272a34ac58b2c114495a4
https://github.com/ShadowBlip/Neteria/blob/1a8c976eb2beeca0a5a272a34ac58b2c114495a4/neteria/server.py#L558-L630
train
untwisted/untwisted
untwisted/wrappers.py
once
def once(dispatcher, event, handle, *args): """ Used to do a mapping like event -> handle but handle is called just once upon event. """ def shell(dispatcher, *args): try: handle(dispatcher, *args) except Exception as e: raise e finally: dispatcher.del_map(event, shell) dispatcher.add_map(event, shell, *args)
python
def once(dispatcher, event, handle, *args): """ Used to do a mapping like event -> handle but handle is called just once upon event. """ def shell(dispatcher, *args): try: handle(dispatcher, *args) except Exception as e: raise e finally: dispatcher.del_map(event, shell) dispatcher.add_map(event, shell, *args)
[ "def", "once", "(", "dispatcher", ",", "event", ",", "handle", ",", "*", "args", ")", ":", "def", "shell", "(", "dispatcher", ",", "*", "args", ")", ":", "try", ":", "handle", "(", "dispatcher", ",", "*", "args", ")", "except", "Exception", "as", "e", ":", "raise", "e", "finally", ":", "dispatcher", ".", "del_map", "(", "event", ",", "shell", ")", "dispatcher", ".", "add_map", "(", "event", ",", "shell", ",", "*", "args", ")" ]
Used to do a mapping like event -> handle but handle is called just once upon event.
[ "Used", "to", "do", "a", "mapping", "like", "event", "-", ">", "handle", "but", "handle", "is", "called", "just", "once", "upon", "event", "." ]
8a8d9c8a8d0f3452d5de67cd760297bb5759f637
https://github.com/untwisted/untwisted/blob/8a8d9c8a8d0f3452d5de67cd760297bb5759f637/untwisted/wrappers.py#L7-L20
train
untwisted/untwisted
untwisted/core.py
Gear.mainloop
def mainloop(self): """ This is the reactor mainloop. It is intented to be called when a reactor is installed. from untwisted.network import * # It processes forever. core.gear.mainloop() """ while True: # It calls repeteadly the reactor # update method. try: self.update() except Kill: # It breaks the loop # silently. # people implementing reactors from other mainloop # should implement this try: catch # suitably to their needs. break except KeyboardInterrupt: print(self.base) raise
python
def mainloop(self): """ This is the reactor mainloop. It is intented to be called when a reactor is installed. from untwisted.network import * # It processes forever. core.gear.mainloop() """ while True: # It calls repeteadly the reactor # update method. try: self.update() except Kill: # It breaks the loop # silently. # people implementing reactors from other mainloop # should implement this try: catch # suitably to their needs. break except KeyboardInterrupt: print(self.base) raise
[ "def", "mainloop", "(", "self", ")", ":", "while", "True", ":", "# It calls repeteadly the reactor", "# update method.", "try", ":", "self", ".", "update", "(", ")", "except", "Kill", ":", "# It breaks the loop", "# silently.", "# people implementing reactors from other mainloop", "# should implement this try: catch", "# suitably to their needs.", "break", "except", "KeyboardInterrupt", ":", "print", "(", "self", ".", "base", ")", "raise" ]
This is the reactor mainloop. It is intented to be called when a reactor is installed. from untwisted.network import * # It processes forever. core.gear.mainloop()
[ "This", "is", "the", "reactor", "mainloop", ".", "It", "is", "intented", "to", "be", "called", "when", "a", "reactor", "is", "installed", "." ]
8a8d9c8a8d0f3452d5de67cd760297bb5759f637
https://github.com/untwisted/untwisted/blob/8a8d9c8a8d0f3452d5de67cd760297bb5759f637/untwisted/core.py#L41-L68
train
thorgate/django-esteid
esteid/digidocservice/service.py
DigiDocService.start_session
def start_session(self, b_hold_session, sig_doc_xml=None, datafile=None): """Start a DigidocService session :return: True if session was started and session code was stored in I{session_code} """ response = self.__invoke('StartSession', { 'bHoldSession': b_hold_session, 'SigDocXML': sig_doc_xml or SkipValue, 'datafile': datafile or SkipValue, # This parameter is deprecated and exists only due to historical reasons. We need to specify it as # SkipValue to keep zeep happy 'SigningProfile': SkipValue, }) if response['Sesscode']: self.data_files = [] self.session_code = response['Sesscode'] if sig_doc_xml: self.container = PreviouslyCreatedContainer() return True # If b_hold_session is set to False, response will not contain a session # in case of errors, exceptions are raised from __invoke anyway return False
python
def start_session(self, b_hold_session, sig_doc_xml=None, datafile=None): """Start a DigidocService session :return: True if session was started and session code was stored in I{session_code} """ response = self.__invoke('StartSession', { 'bHoldSession': b_hold_session, 'SigDocXML': sig_doc_xml or SkipValue, 'datafile': datafile or SkipValue, # This parameter is deprecated and exists only due to historical reasons. We need to specify it as # SkipValue to keep zeep happy 'SigningProfile': SkipValue, }) if response['Sesscode']: self.data_files = [] self.session_code = response['Sesscode'] if sig_doc_xml: self.container = PreviouslyCreatedContainer() return True # If b_hold_session is set to False, response will not contain a session # in case of errors, exceptions are raised from __invoke anyway return False
[ "def", "start_session", "(", "self", ",", "b_hold_session", ",", "sig_doc_xml", "=", "None", ",", "datafile", "=", "None", ")", ":", "response", "=", "self", ".", "__invoke", "(", "'StartSession'", ",", "{", "'bHoldSession'", ":", "b_hold_session", ",", "'SigDocXML'", ":", "sig_doc_xml", "or", "SkipValue", ",", "'datafile'", ":", "datafile", "or", "SkipValue", ",", "# This parameter is deprecated and exists only due to historical reasons. We need to specify it as", "# SkipValue to keep zeep happy", "'SigningProfile'", ":", "SkipValue", ",", "}", ")", "if", "response", "[", "'Sesscode'", "]", ":", "self", ".", "data_files", "=", "[", "]", "self", ".", "session_code", "=", "response", "[", "'Sesscode'", "]", "if", "sig_doc_xml", ":", "self", ".", "container", "=", "PreviouslyCreatedContainer", "(", ")", "return", "True", "# If b_hold_session is set to False, response will not contain a session", "# in case of errors, exceptions are raised from __invoke anyway", "return", "False" ]
Start a DigidocService session :return: True if session was started and session code was stored in I{session_code}
[ "Start", "a", "DigidocService", "session" ]
407ae513e357fedea0e3e42198df8eb9d9ff0646
https://github.com/thorgate/django-esteid/blob/407ae513e357fedea0e3e42198df8eb9d9ff0646/esteid/digidocservice/service.py#L153-L179
train
thorgate/django-esteid
esteid/digidocservice/service.py
DigiDocService.mobile_sign
def mobile_sign(self, id_code, country, phone_nr, language=None, signing_profile='LT_TM'): """ This can be used to add a signature to existing data files WARNING: Must have at least one datafile in the session """ if not (self.container and isinstance(self.container, PreviouslyCreatedContainer)): assert self.data_files, 'To use MobileSign endpoint the application must ' \ 'add at least one data file to users session' response = self.__invoke('MobileSign', { 'SignerIDCode': id_code, 'SignersCountry': country, 'SignerPhoneNo': phone_nr, 'Language': self.parse_language(language), 'Role': SkipValue, 'City': SkipValue, 'StateOrProvince': SkipValue, 'PostalCode': SkipValue, 'CountryName': SkipValue, 'ServiceName': self.service_name, 'AdditionalDataToBeDisplayed': self.mobile_message, # Either LT or LT_TM, see: http://sk-eid.github.io/dds-documentation/api/api_docs/#mobilesign 'SigningProfile': signing_profile, 'MessagingMode': 'asynchClientServer', 'AsyncConfiguration': SkipValue, 'ReturnDocInfo': SkipValue, 'ReturnDocData': SkipValue, }) return response
python
def mobile_sign(self, id_code, country, phone_nr, language=None, signing_profile='LT_TM'): """ This can be used to add a signature to existing data files WARNING: Must have at least one datafile in the session """ if not (self.container and isinstance(self.container, PreviouslyCreatedContainer)): assert self.data_files, 'To use MobileSign endpoint the application must ' \ 'add at least one data file to users session' response = self.__invoke('MobileSign', { 'SignerIDCode': id_code, 'SignersCountry': country, 'SignerPhoneNo': phone_nr, 'Language': self.parse_language(language), 'Role': SkipValue, 'City': SkipValue, 'StateOrProvince': SkipValue, 'PostalCode': SkipValue, 'CountryName': SkipValue, 'ServiceName': self.service_name, 'AdditionalDataToBeDisplayed': self.mobile_message, # Either LT or LT_TM, see: http://sk-eid.github.io/dds-documentation/api/api_docs/#mobilesign 'SigningProfile': signing_profile, 'MessagingMode': 'asynchClientServer', 'AsyncConfiguration': SkipValue, 'ReturnDocInfo': SkipValue, 'ReturnDocData': SkipValue, }) return response
[ "def", "mobile_sign", "(", "self", ",", "id_code", ",", "country", ",", "phone_nr", ",", "language", "=", "None", ",", "signing_profile", "=", "'LT_TM'", ")", ":", "if", "not", "(", "self", ".", "container", "and", "isinstance", "(", "self", ".", "container", ",", "PreviouslyCreatedContainer", ")", ")", ":", "assert", "self", ".", "data_files", ",", "'To use MobileSign endpoint the application must '", "'add at least one data file to users session'", "response", "=", "self", ".", "__invoke", "(", "'MobileSign'", ",", "{", "'SignerIDCode'", ":", "id_code", ",", "'SignersCountry'", ":", "country", ",", "'SignerPhoneNo'", ":", "phone_nr", ",", "'Language'", ":", "self", ".", "parse_language", "(", "language", ")", ",", "'Role'", ":", "SkipValue", ",", "'City'", ":", "SkipValue", ",", "'StateOrProvince'", ":", "SkipValue", ",", "'PostalCode'", ":", "SkipValue", ",", "'CountryName'", ":", "SkipValue", ",", "'ServiceName'", ":", "self", ".", "service_name", ",", "'AdditionalDataToBeDisplayed'", ":", "self", ".", "mobile_message", ",", "# Either LT or LT_TM, see: http://sk-eid.github.io/dds-documentation/api/api_docs/#mobilesign", "'SigningProfile'", ":", "signing_profile", ",", "'MessagingMode'", ":", "'asynchClientServer'", ",", "'AsyncConfiguration'", ":", "SkipValue", ",", "'ReturnDocInfo'", ":", "SkipValue", ",", "'ReturnDocData'", ":", "SkipValue", ",", "}", ")", "return", "response" ]
This can be used to add a signature to existing data files WARNING: Must have at least one datafile in the session
[ "This", "can", "be", "used", "to", "add", "a", "signature", "to", "existing", "data", "files" ]
407ae513e357fedea0e3e42198df8eb9d9ff0646
https://github.com/thorgate/django-esteid/blob/407ae513e357fedea0e3e42198df8eb9d9ff0646/esteid/digidocservice/service.py#L299-L334
train
sfstpala/pcr
pcr/maths.py
is_prime
def is_prime(n, k=64): """ Test whether n is prime probabilisticly. This uses the Miller-Rabin primality test. If n is composite, then this test will declare it to be probably prime with a probability of at most 4**-k. To be on the safe side, a value of k=64 for integers up to 3072 bits is recommended (error probability = 2**-128). If the function is used for RSA or DSA, NIST recommends some values in FIPS PUB 186-3: <http://csrc.nist.gov/publications/fips/fips186-3/fips_186-3.pdf> Do not use this function for small numbers. """ if n == 2: return True if n < 2 or n % 2 == 0: return False for i in range(3, 2048): # performace optimisation if n % i == 0: return False s = 0 d = n - 1 while True: q, r = divmod(d, 2) if r == 1: break s += 1 d = q for i in range(k): a = random.randint(2, n - 1) if check_candidate(a, d, n, s): return False return True
python
def is_prime(n, k=64): """ Test whether n is prime probabilisticly. This uses the Miller-Rabin primality test. If n is composite, then this test will declare it to be probably prime with a probability of at most 4**-k. To be on the safe side, a value of k=64 for integers up to 3072 bits is recommended (error probability = 2**-128). If the function is used for RSA or DSA, NIST recommends some values in FIPS PUB 186-3: <http://csrc.nist.gov/publications/fips/fips186-3/fips_186-3.pdf> Do not use this function for small numbers. """ if n == 2: return True if n < 2 or n % 2 == 0: return False for i in range(3, 2048): # performace optimisation if n % i == 0: return False s = 0 d = n - 1 while True: q, r = divmod(d, 2) if r == 1: break s += 1 d = q for i in range(k): a = random.randint(2, n - 1) if check_candidate(a, d, n, s): return False return True
[ "def", "is_prime", "(", "n", ",", "k", "=", "64", ")", ":", "if", "n", "==", "2", ":", "return", "True", "if", "n", "<", "2", "or", "n", "%", "2", "==", "0", ":", "return", "False", "for", "i", "in", "range", "(", "3", ",", "2048", ")", ":", "# performace optimisation", "if", "n", "%", "i", "==", "0", ":", "return", "False", "s", "=", "0", "d", "=", "n", "-", "1", "while", "True", ":", "q", ",", "r", "=", "divmod", "(", "d", ",", "2", ")", "if", "r", "==", "1", ":", "break", "s", "+=", "1", "d", "=", "q", "for", "i", "in", "range", "(", "k", ")", ":", "a", "=", "random", ".", "randint", "(", "2", ",", "n", "-", "1", ")", "if", "check_candidate", "(", "a", ",", "d", ",", "n", ",", "s", ")", ":", "return", "False", "return", "True" ]
Test whether n is prime probabilisticly. This uses the Miller-Rabin primality test. If n is composite, then this test will declare it to be probably prime with a probability of at most 4**-k. To be on the safe side, a value of k=64 for integers up to 3072 bits is recommended (error probability = 2**-128). If the function is used for RSA or DSA, NIST recommends some values in FIPS PUB 186-3: <http://csrc.nist.gov/publications/fips/fips186-3/fips_186-3.pdf> Do not use this function for small numbers.
[ "Test", "whether", "n", "is", "prime", "probabilisticly", "." ]
313ec17585565a0b9740f7b3f47d7a93bf37a7fc
https://github.com/sfstpala/pcr/blob/313ec17585565a0b9740f7b3f47d7a93bf37a7fc/pcr/maths.py#L34-L71
train
sfstpala/pcr
pcr/maths.py
get_prime
def get_prime(bits, k=64): """ Return a random prime up to a certain length. This function uses random.SystemRandom. """ if bits % 8 != 0 or bits == 0: raise ValueError("bits must be >= 0 and divisible by 8") while True: n = int.from_bytes(os.urandom(bits // 8), "big") if is_prime(n, k): return n
python
def get_prime(bits, k=64): """ Return a random prime up to a certain length. This function uses random.SystemRandom. """ if bits % 8 != 0 or bits == 0: raise ValueError("bits must be >= 0 and divisible by 8") while True: n = int.from_bytes(os.urandom(bits // 8), "big") if is_prime(n, k): return n
[ "def", "get_prime", "(", "bits", ",", "k", "=", "64", ")", ":", "if", "bits", "%", "8", "!=", "0", "or", "bits", "==", "0", ":", "raise", "ValueError", "(", "\"bits must be >= 0 and divisible by 8\"", ")", "while", "True", ":", "n", "=", "int", ".", "from_bytes", "(", "os", ".", "urandom", "(", "bits", "//", "8", ")", ",", "\"big\"", ")", "if", "is_prime", "(", "n", ",", "k", ")", ":", "return", "n" ]
Return a random prime up to a certain length. This function uses random.SystemRandom.
[ "Return", "a", "random", "prime", "up", "to", "a", "certain", "length", "." ]
313ec17585565a0b9740f7b3f47d7a93bf37a7fc
https://github.com/sfstpala/pcr/blob/313ec17585565a0b9740f7b3f47d7a93bf37a7fc/pcr/maths.py#L74-L86
train
sfstpala/pcr
pcr/maths.py
make_rsa_keys
def make_rsa_keys(bits=2048, e=65537, k=64): """ Create RSA key pair. Returns n, e, d, where (n, e) is the public key and (n, e, d) is the private key (and k is the number of rounds used in the Miller-Rabin primality test). """ p, q = None, None while p == q: p, q = get_prime(bits // 2), get_prime(bits // 2) n = p * q phi_n = phi(n, p, q) d = mult_inv(e, phi_n) return n, e, d
python
def make_rsa_keys(bits=2048, e=65537, k=64): """ Create RSA key pair. Returns n, e, d, where (n, e) is the public key and (n, e, d) is the private key (and k is the number of rounds used in the Miller-Rabin primality test). """ p, q = None, None while p == q: p, q = get_prime(bits // 2), get_prime(bits // 2) n = p * q phi_n = phi(n, p, q) d = mult_inv(e, phi_n) return n, e, d
[ "def", "make_rsa_keys", "(", "bits", "=", "2048", ",", "e", "=", "65537", ",", "k", "=", "64", ")", ":", "p", ",", "q", "=", "None", ",", "None", "while", "p", "==", "q", ":", "p", ",", "q", "=", "get_prime", "(", "bits", "//", "2", ")", ",", "get_prime", "(", "bits", "//", "2", ")", "n", "=", "p", "*", "q", "phi_n", "=", "phi", "(", "n", ",", "p", ",", "q", ")", "d", "=", "mult_inv", "(", "e", ",", "phi_n", ")", "return", "n", ",", "e", ",", "d" ]
Create RSA key pair. Returns n, e, d, where (n, e) is the public key and (n, e, d) is the private key (and k is the number of rounds used in the Miller-Rabin primality test).
[ "Create", "RSA", "key", "pair", "." ]
313ec17585565a0b9740f7b3f47d7a93bf37a7fc
https://github.com/sfstpala/pcr/blob/313ec17585565a0b9740f7b3f47d7a93bf37a7fc/pcr/maths.py#L119-L135
train
bluekeyes/sphinx-javalink
javalink/__init__.py
setup
def setup(app): """Register the extension with Sphinx. Args: app: The Sphinx application. """ for name, (default, rebuild, _) in ref.CONFIG_VALUES.iteritems(): app.add_config_value(name, default, rebuild) app.add_directive('javaimport', ref.JavarefImportDirective) app.add_role('javaref', ref.JavarefRole(app)) app.connect('builder-inited', initialize_env) app.connect('env-purge-doc', ref.purge_imports) app.connect('env-merge-info', ref.merge_imports) app.connect('build-finished', ref.cleanup)
python
def setup(app): """Register the extension with Sphinx. Args: app: The Sphinx application. """ for name, (default, rebuild, _) in ref.CONFIG_VALUES.iteritems(): app.add_config_value(name, default, rebuild) app.add_directive('javaimport', ref.JavarefImportDirective) app.add_role('javaref', ref.JavarefRole(app)) app.connect('builder-inited', initialize_env) app.connect('env-purge-doc', ref.purge_imports) app.connect('env-merge-info', ref.merge_imports) app.connect('build-finished', ref.cleanup)
[ "def", "setup", "(", "app", ")", ":", "for", "name", ",", "(", "default", ",", "rebuild", ",", "_", ")", "in", "ref", ".", "CONFIG_VALUES", ".", "iteritems", "(", ")", ":", "app", ".", "add_config_value", "(", "name", ",", "default", ",", "rebuild", ")", "app", ".", "add_directive", "(", "'javaimport'", ",", "ref", ".", "JavarefImportDirective", ")", "app", ".", "add_role", "(", "'javaref'", ",", "ref", ".", "JavarefRole", "(", "app", ")", ")", "app", ".", "connect", "(", "'builder-inited'", ",", "initialize_env", ")", "app", ".", "connect", "(", "'env-purge-doc'", ",", "ref", ".", "purge_imports", ")", "app", ".", "connect", "(", "'env-merge-info'", ",", "ref", ".", "merge_imports", ")", "app", ".", "connect", "(", "'build-finished'", ",", "ref", ".", "cleanup", ")" ]
Register the extension with Sphinx. Args: app: The Sphinx application.
[ "Register", "the", "extension", "with", "Sphinx", "." ]
490e37506efa53e95ad88a665e347536e75b6254
https://github.com/bluekeyes/sphinx-javalink/blob/490e37506efa53e95ad88a665e347536e75b6254/javalink/__init__.py#L9-L25
train
bluekeyes/sphinx-javalink
javalink/__init__.py
validate_env
def validate_env(app): """Purge expired values from the environment. When certain configuration values change, related values in the environment must be cleared. While Sphinx can rebuild documents on configuration changes, it does not notify extensions when this happens. Instead, cache relevant values in the environment in order to detect when they change. Args: app: The Sphinx application. """ if not hasattr(app.env, 'javalink_config_cache'): app.env.javalink_config_cache = {} for conf_attr, (_, _, env_attr) in ref.CONFIG_VALUES.iteritems(): if not env_attr: continue value = getattr(app.config, conf_attr) cached = app.env.javalink_config_cache.get(conf_attr, value) app.env.javalink_config_cache[conf_attr] = value if value != cached: app.verbose('[javalink] config.%s has changed, clearing related env', conf_attr) delattr(app.env, env_attr)
python
def validate_env(app): """Purge expired values from the environment. When certain configuration values change, related values in the environment must be cleared. While Sphinx can rebuild documents on configuration changes, it does not notify extensions when this happens. Instead, cache relevant values in the environment in order to detect when they change. Args: app: The Sphinx application. """ if not hasattr(app.env, 'javalink_config_cache'): app.env.javalink_config_cache = {} for conf_attr, (_, _, env_attr) in ref.CONFIG_VALUES.iteritems(): if not env_attr: continue value = getattr(app.config, conf_attr) cached = app.env.javalink_config_cache.get(conf_attr, value) app.env.javalink_config_cache[conf_attr] = value if value != cached: app.verbose('[javalink] config.%s has changed, clearing related env', conf_attr) delattr(app.env, env_attr)
[ "def", "validate_env", "(", "app", ")", ":", "if", "not", "hasattr", "(", "app", ".", "env", ",", "'javalink_config_cache'", ")", ":", "app", ".", "env", ".", "javalink_config_cache", "=", "{", "}", "for", "conf_attr", ",", "(", "_", ",", "_", ",", "env_attr", ")", "in", "ref", ".", "CONFIG_VALUES", ".", "iteritems", "(", ")", ":", "if", "not", "env_attr", ":", "continue", "value", "=", "getattr", "(", "app", ".", "config", ",", "conf_attr", ")", "cached", "=", "app", ".", "env", ".", "javalink_config_cache", ".", "get", "(", "conf_attr", ",", "value", ")", "app", ".", "env", ".", "javalink_config_cache", "[", "conf_attr", "]", "=", "value", "if", "value", "!=", "cached", ":", "app", ".", "verbose", "(", "'[javalink] config.%s has changed, clearing related env'", ",", "conf_attr", ")", "delattr", "(", "app", ".", "env", ",", "env_attr", ")" ]
Purge expired values from the environment. When certain configuration values change, related values in the environment must be cleared. While Sphinx can rebuild documents on configuration changes, it does not notify extensions when this happens. Instead, cache relevant values in the environment in order to detect when they change. Args: app: The Sphinx application.
[ "Purge", "expired", "values", "from", "the", "environment", "." ]
490e37506efa53e95ad88a665e347536e75b6254
https://github.com/bluekeyes/sphinx-javalink/blob/490e37506efa53e95ad88a665e347536e75b6254/javalink/__init__.py#L32-L58
train
bluekeyes/sphinx-javalink
javalink/__init__.py
find_rt_jar
def find_rt_jar(javahome=None): """Find the path to the Java standard library jar. The jar is expected to exist at the path 'jre/lib/rt.jar' inside a standard Java installation directory. The directory is found using the following procedure: 1. If the javehome argument is provided, use the value as the directory. 2. If the JAVA_HOME environment variable is set, use the value as the directory. 3. Find the location of the ``java`` binary in the current PATH and compute the installation directory from this location. Args: javahome: A path to a Java installation directory (optional). """ if not javahome: if 'JAVA_HOME' in os.environ: javahome = os.environ['JAVA_HOME'] elif sys.platform == 'darwin': # The default java binary on OS X is not part of a standard Oracle # install, so building paths relative to it does not work like it # does on other platforms. javahome = _find_osx_javahome() else: javahome = _get_javahome_from_java(_find_java_binary()) rtpath = os.path.join(javahome, 'jre', 'lib', 'rt.jar') if not os.path.isfile(rtpath): msg = 'Could not find rt.jar: {} is not a file'.format(rtpath) raise ExtensionError(msg) return rtpath
python
def find_rt_jar(javahome=None): """Find the path to the Java standard library jar. The jar is expected to exist at the path 'jre/lib/rt.jar' inside a standard Java installation directory. The directory is found using the following procedure: 1. If the javehome argument is provided, use the value as the directory. 2. If the JAVA_HOME environment variable is set, use the value as the directory. 3. Find the location of the ``java`` binary in the current PATH and compute the installation directory from this location. Args: javahome: A path to a Java installation directory (optional). """ if not javahome: if 'JAVA_HOME' in os.environ: javahome = os.environ['JAVA_HOME'] elif sys.platform == 'darwin': # The default java binary on OS X is not part of a standard Oracle # install, so building paths relative to it does not work like it # does on other platforms. javahome = _find_osx_javahome() else: javahome = _get_javahome_from_java(_find_java_binary()) rtpath = os.path.join(javahome, 'jre', 'lib', 'rt.jar') if not os.path.isfile(rtpath): msg = 'Could not find rt.jar: {} is not a file'.format(rtpath) raise ExtensionError(msg) return rtpath
[ "def", "find_rt_jar", "(", "javahome", "=", "None", ")", ":", "if", "not", "javahome", ":", "if", "'JAVA_HOME'", "in", "os", ".", "environ", ":", "javahome", "=", "os", ".", "environ", "[", "'JAVA_HOME'", "]", "elif", "sys", ".", "platform", "==", "'darwin'", ":", "# The default java binary on OS X is not part of a standard Oracle", "# install, so building paths relative to it does not work like it", "# does on other platforms.", "javahome", "=", "_find_osx_javahome", "(", ")", "else", ":", "javahome", "=", "_get_javahome_from_java", "(", "_find_java_binary", "(", ")", ")", "rtpath", "=", "os", ".", "path", ".", "join", "(", "javahome", ",", "'jre'", ",", "'lib'", ",", "'rt.jar'", ")", "if", "not", "os", ".", "path", ".", "isfile", "(", "rtpath", ")", ":", "msg", "=", "'Could not find rt.jar: {} is not a file'", ".", "format", "(", "rtpath", ")", "raise", "ExtensionError", "(", "msg", ")", "return", "rtpath" ]
Find the path to the Java standard library jar. The jar is expected to exist at the path 'jre/lib/rt.jar' inside a standard Java installation directory. The directory is found using the following procedure: 1. If the javehome argument is provided, use the value as the directory. 2. If the JAVA_HOME environment variable is set, use the value as the directory. 3. Find the location of the ``java`` binary in the current PATH and compute the installation directory from this location. Args: javahome: A path to a Java installation directory (optional).
[ "Find", "the", "path", "to", "the", "Java", "standard", "library", "jar", "." ]
490e37506efa53e95ad88a665e347536e75b6254
https://github.com/bluekeyes/sphinx-javalink/blob/490e37506efa53e95ad88a665e347536e75b6254/javalink/__init__.py#L61-L95
train
blue-yonder/cee_syslog_handler
cee_syslog_handler/__init__.py
RegexFilter.filter
def filter(self, record): """ Returns True if the record shall be logged. False otherwise. https://github.com/python/cpython/blob/2.7/Lib/logging/__init__.py#L607 """ found = self._pattern.search(record.getMessage()) return not found
python
def filter(self, record): """ Returns True if the record shall be logged. False otherwise. https://github.com/python/cpython/blob/2.7/Lib/logging/__init__.py#L607 """ found = self._pattern.search(record.getMessage()) return not found
[ "def", "filter", "(", "self", ",", "record", ")", ":", "found", "=", "self", ".", "_pattern", ".", "search", "(", "record", ".", "getMessage", "(", ")", ")", "return", "not", "found" ]
Returns True if the record shall be logged. False otherwise. https://github.com/python/cpython/blob/2.7/Lib/logging/__init__.py#L607
[ "Returns", "True", "if", "the", "record", "shall", "be", "logged", ".", "False", "otherwise", "." ]
c6006b59d38d4d8dabfc1301c689c71f35e3b8b8
https://github.com/blue-yonder/cee_syslog_handler/blob/c6006b59d38d4d8dabfc1301c689c71f35e3b8b8/cee_syslog_handler/__init__.py#L266-L273
train
zsimic/runez
src/runez/convert.py
_get_value
def _get_value(obj, key): """Get a value for 'key' from 'obj', if possible""" if isinstance(obj, (list, tuple)): for item in obj: v = _find_value(key, item) if v is not None: return v return None if isinstance(obj, dict): return obj.get(key) if obj is not None: return getattr(obj, key, None)
python
def _get_value(obj, key): """Get a value for 'key' from 'obj', if possible""" if isinstance(obj, (list, tuple)): for item in obj: v = _find_value(key, item) if v is not None: return v return None if isinstance(obj, dict): return obj.get(key) if obj is not None: return getattr(obj, key, None)
[ "def", "_get_value", "(", "obj", ",", "key", ")", ":", "if", "isinstance", "(", "obj", ",", "(", "list", ",", "tuple", ")", ")", ":", "for", "item", "in", "obj", ":", "v", "=", "_find_value", "(", "key", ",", "item", ")", "if", "v", "is", "not", "None", ":", "return", "v", "return", "None", "if", "isinstance", "(", "obj", ",", "dict", ")", ":", "return", "obj", ".", "get", "(", "key", ")", "if", "obj", "is", "not", "None", ":", "return", "getattr", "(", "obj", ",", "key", ",", "None", ")" ]
Get a value for 'key' from 'obj', if possible
[ "Get", "a", "value", "for", "key", "from", "obj", "if", "possible" ]
14363b719a1aae1528859a501a22d075ce0abfcc
https://github.com/zsimic/runez/blob/14363b719a1aae1528859a501a22d075ce0abfcc/src/runez/convert.py#L262-L273
train
zsimic/runez
src/runez/convert.py
_find_value
def _find_value(key, *args): """Find a value for 'key' in any of the objects given as 'args'""" for arg in args: v = _get_value(arg, key) if v is not None: return v
python
def _find_value(key, *args): """Find a value for 'key' in any of the objects given as 'args'""" for arg in args: v = _get_value(arg, key) if v is not None: return v
[ "def", "_find_value", "(", "key", ",", "*", "args", ")", ":", "for", "arg", "in", "args", ":", "v", "=", "_get_value", "(", "arg", ",", "key", ")", "if", "v", "is", "not", "None", ":", "return", "v" ]
Find a value for 'key' in any of the objects given as 'args
[ "Find", "a", "value", "for", "key", "in", "any", "of", "the", "objects", "given", "as", "args" ]
14363b719a1aae1528859a501a22d075ce0abfcc
https://github.com/zsimic/runez/blob/14363b719a1aae1528859a501a22d075ce0abfcc/src/runez/convert.py#L276-L281
train
abantos/bolt
bolt/_btutils.py
add_search_path
def add_search_path(*path_tokens): """ Adds a new search path from where modules can be loaded. This function is provided for test applications to add locations to the search path, so any required functionality can be loaded. It helps keeping the step implementation modules simple by placing the bulk of the implementation in separate utility libraries. This function can also be used to add the application being tested to the path, so its functionality can be made available for testing. :param arglist path_tokens: Variable list of path tokens that is joined to create the full, absolute path to be added. """ full_path = os.path.join(*path_tokens) if full_path not in sys.path: sys.path.insert(0, os.path.abspath(full_path))
python
def add_search_path(*path_tokens): """ Adds a new search path from where modules can be loaded. This function is provided for test applications to add locations to the search path, so any required functionality can be loaded. It helps keeping the step implementation modules simple by placing the bulk of the implementation in separate utility libraries. This function can also be used to add the application being tested to the path, so its functionality can be made available for testing. :param arglist path_tokens: Variable list of path tokens that is joined to create the full, absolute path to be added. """ full_path = os.path.join(*path_tokens) if full_path not in sys.path: sys.path.insert(0, os.path.abspath(full_path))
[ "def", "add_search_path", "(", "*", "path_tokens", ")", ":", "full_path", "=", "os", ".", "path", ".", "join", "(", "*", "path_tokens", ")", "if", "full_path", "not", "in", "sys", ".", "path", ":", "sys", ".", "path", ".", "insert", "(", "0", ",", "os", ".", "path", ".", "abspath", "(", "full_path", ")", ")" ]
Adds a new search path from where modules can be loaded. This function is provided for test applications to add locations to the search path, so any required functionality can be loaded. It helps keeping the step implementation modules simple by placing the bulk of the implementation in separate utility libraries. This function can also be used to add the application being tested to the path, so its functionality can be made available for testing. :param arglist path_tokens: Variable list of path tokens that is joined to create the full, absolute path to be added.
[ "Adds", "a", "new", "search", "path", "from", "where", "modules", "can", "be", "loaded", ".", "This", "function", "is", "provided", "for", "test", "applications", "to", "add", "locations", "to", "the", "search", "path", "so", "any", "required", "functionality", "can", "be", "loaded", ".", "It", "helps", "keeping", "the", "step", "implementation", "modules", "simple", "by", "placing", "the", "bulk", "of", "the", "implementation", "in", "separate", "utility", "libraries", ".", "This", "function", "can", "also", "be", "used", "to", "add", "the", "application", "being", "tested", "to", "the", "path", "so", "its", "functionality", "can", "be", "made", "available", "for", "testing", "." ]
8b6a911d4a7b1a6e870748a523c9b2b91997c773
https://github.com/abantos/bolt/blob/8b6a911d4a7b1a6e870748a523c9b2b91997c773/bolt/_btutils.py#L8-L22
train
abantos/bolt
bolt/_btutils.py
load_script
def load_script(filename): """ Loads a python script as a module. This function is provided to allow applications to load a Python module by its file name. :param string filename: Name of the python file to be loaded as a module. :return: A |Python|_ module loaded from the specified file. """ path, module_name, ext = _extract_script_components(filename) add_search_path(path) return _load_module(module_name)
python
def load_script(filename): """ Loads a python script as a module. This function is provided to allow applications to load a Python module by its file name. :param string filename: Name of the python file to be loaded as a module. :return: A |Python|_ module loaded from the specified file. """ path, module_name, ext = _extract_script_components(filename) add_search_path(path) return _load_module(module_name)
[ "def", "load_script", "(", "filename", ")", ":", "path", ",", "module_name", ",", "ext", "=", "_extract_script_components", "(", "filename", ")", "add_search_path", "(", "path", ")", "return", "_load_module", "(", "module_name", ")" ]
Loads a python script as a module. This function is provided to allow applications to load a Python module by its file name. :param string filename: Name of the python file to be loaded as a module. :return: A |Python|_ module loaded from the specified file.
[ "Loads", "a", "python", "script", "as", "a", "module", "." ]
8b6a911d4a7b1a6e870748a523c9b2b91997c773
https://github.com/abantos/bolt/blob/8b6a911d4a7b1a6e870748a523c9b2b91997c773/bolt/_btutils.py#L26-L40
train
potash/drain
drain/util.py
parse_dates
def parse_dates(df, inplace=True, *args, **kwargs): """ Parse all datetime.date and datetime.datetime columns """ if not inplace: df = df.copy() for c in df.columns: i = df[c].first_valid_index() if i is not None and type(df[c].ix[i]) in (date, datetime): df[c] = pd.to_datetime(df[c], *args, **kwargs) if not inplace: return df
python
def parse_dates(df, inplace=True, *args, **kwargs): """ Parse all datetime.date and datetime.datetime columns """ if not inplace: df = df.copy() for c in df.columns: i = df[c].first_valid_index() if i is not None and type(df[c].ix[i]) in (date, datetime): df[c] = pd.to_datetime(df[c], *args, **kwargs) if not inplace: return df
[ "def", "parse_dates", "(", "df", ",", "inplace", "=", "True", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "not", "inplace", ":", "df", "=", "df", ".", "copy", "(", ")", "for", "c", "in", "df", ".", "columns", ":", "i", "=", "df", "[", "c", "]", ".", "first_valid_index", "(", ")", "if", "i", "is", "not", "None", "and", "type", "(", "df", "[", "c", "]", ".", "ix", "[", "i", "]", ")", "in", "(", "date", ",", "datetime", ")", ":", "df", "[", "c", "]", "=", "pd", ".", "to_datetime", "(", "df", "[", "c", "]", ",", "*", "args", ",", "*", "*", "kwargs", ")", "if", "not", "inplace", ":", "return", "df" ]
Parse all datetime.date and datetime.datetime columns
[ "Parse", "all", "datetime", ".", "date", "and", "datetime", ".", "datetime", "columns" ]
ddd62081cb9317beb5d21f86c8b4bb196ca3d222
https://github.com/potash/drain/blob/ddd62081cb9317beb5d21f86c8b4bb196ca3d222/drain/util.py#L45-L58
train
potash/drain
drain/util.py
to_float
def to_float(*args): """ cast numpy arrays to float32 if there's more than one, return an array """ floats = [np.array(a, dtype=np.float32) for a in args] return floats[0] if len(floats) == 1 else floats
python
def to_float(*args): """ cast numpy arrays to float32 if there's more than one, return an array """ floats = [np.array(a, dtype=np.float32) for a in args] return floats[0] if len(floats) == 1 else floats
[ "def", "to_float", "(", "*", "args", ")", ":", "floats", "=", "[", "np", ".", "array", "(", "a", ",", "dtype", "=", "np", ".", "float32", ")", "for", "a", "in", "args", "]", "return", "floats", "[", "0", "]", "if", "len", "(", "floats", ")", "==", "1", "else", "floats" ]
cast numpy arrays to float32 if there's more than one, return an array
[ "cast", "numpy", "arrays", "to", "float32", "if", "there", "s", "more", "than", "one", "return", "an", "array" ]
ddd62081cb9317beb5d21f86c8b4bb196ca3d222
https://github.com/potash/drain/blob/ddd62081cb9317beb5d21f86c8b4bb196ca3d222/drain/util.py#L83-L89
train
potash/drain
drain/util.py
get_attr
def get_attr(name): """ get a class or function by name """ i = name.rfind('.') cls = str(name[i+1:]) module = str(name[:i]) mod = __import__(module, fromlist=[cls]) return getattr(mod, cls)
python
def get_attr(name): """ get a class or function by name """ i = name.rfind('.') cls = str(name[i+1:]) module = str(name[:i]) mod = __import__(module, fromlist=[cls]) return getattr(mod, cls)
[ "def", "get_attr", "(", "name", ")", ":", "i", "=", "name", ".", "rfind", "(", "'.'", ")", "cls", "=", "str", "(", "name", "[", "i", "+", "1", ":", "]", ")", "module", "=", "str", "(", "name", "[", ":", "i", "]", ")", "mod", "=", "__import__", "(", "module", ",", "fromlist", "=", "[", "cls", "]", ")", "return", "getattr", "(", "mod", ",", "cls", ")" ]
get a class or function by name
[ "get", "a", "class", "or", "function", "by", "name" ]
ddd62081cb9317beb5d21f86c8b4bb196ca3d222
https://github.com/potash/drain/blob/ddd62081cb9317beb5d21f86c8b4bb196ca3d222/drain/util.py#L131-L140
train
potash/drain
drain/util.py
drop_constant_column_levels
def drop_constant_column_levels(df): """ drop the levels of a multi-level column dataframe which are constant operates in place """ columns = df.columns constant_levels = [i for i, level in enumerate(columns.levels) if len(level) <= 1] constant_levels.reverse() for i in constant_levels: columns = columns.droplevel(i) df.columns = columns
python
def drop_constant_column_levels(df): """ drop the levels of a multi-level column dataframe which are constant operates in place """ columns = df.columns constant_levels = [i for i, level in enumerate(columns.levels) if len(level) <= 1] constant_levels.reverse() for i in constant_levels: columns = columns.droplevel(i) df.columns = columns
[ "def", "drop_constant_column_levels", "(", "df", ")", ":", "columns", "=", "df", ".", "columns", "constant_levels", "=", "[", "i", "for", "i", ",", "level", "in", "enumerate", "(", "columns", ".", "levels", ")", "if", "len", "(", "level", ")", "<=", "1", "]", "constant_levels", ".", "reverse", "(", ")", "for", "i", "in", "constant_levels", ":", "columns", "=", "columns", ".", "droplevel", "(", "i", ")", "df", ".", "columns", "=", "columns" ]
drop the levels of a multi-level column dataframe which are constant operates in place
[ "drop", "the", "levels", "of", "a", "multi", "-", "level", "column", "dataframe", "which", "are", "constant", "operates", "in", "place" ]
ddd62081cb9317beb5d21f86c8b4bb196ca3d222
https://github.com/potash/drain/blob/ddd62081cb9317beb5d21f86c8b4bb196ca3d222/drain/util.py#L214-L225
train
potash/drain
drain/util.py
dict_diff
def dict_diff(dicts): """ Subset dictionaries to keys which map to multiple values """ diff_keys = set() for k in union(set(d.keys()) for d in dicts): values = [] for d in dicts: if k not in d: diff_keys.add(k) break else: values.append(d[k]) if nunique(values) > 1: diff_keys.add(k) break return [dict_subset(d, diff_keys) for d in dicts]
python
def dict_diff(dicts): """ Subset dictionaries to keys which map to multiple values """ diff_keys = set() for k in union(set(d.keys()) for d in dicts): values = [] for d in dicts: if k not in d: diff_keys.add(k) break else: values.append(d[k]) if nunique(values) > 1: diff_keys.add(k) break return [dict_subset(d, diff_keys) for d in dicts]
[ "def", "dict_diff", "(", "dicts", ")", ":", "diff_keys", "=", "set", "(", ")", "for", "k", "in", "union", "(", "set", "(", "d", ".", "keys", "(", ")", ")", "for", "d", "in", "dicts", ")", ":", "values", "=", "[", "]", "for", "d", "in", "dicts", ":", "if", "k", "not", "in", "d", ":", "diff_keys", ".", "add", "(", "k", ")", "break", "else", ":", "values", ".", "append", "(", "d", "[", "k", "]", ")", "if", "nunique", "(", "values", ")", ">", "1", ":", "diff_keys", ".", "add", "(", "k", ")", "break", "return", "[", "dict_subset", "(", "d", ",", "diff_keys", ")", "for", "d", "in", "dicts", "]" ]
Subset dictionaries to keys which map to multiple values
[ "Subset", "dictionaries", "to", "keys", "which", "map", "to", "multiple", "values" ]
ddd62081cb9317beb5d21f86c8b4bb196ca3d222
https://github.com/potash/drain/blob/ddd62081cb9317beb5d21f86c8b4bb196ca3d222/drain/util.py#L273-L291
train
potash/drain
drain/util.py
dict_update_union
def dict_update_union(d1, d2): """ update a set-valued dictionary when key exists, union sets """ for k in d2: if k in d1: d1[k].update(d2[k]) else: d1[k] = d2[k]
python
def dict_update_union(d1, d2): """ update a set-valued dictionary when key exists, union sets """ for k in d2: if k in d1: d1[k].update(d2[k]) else: d1[k] = d2[k]
[ "def", "dict_update_union", "(", "d1", ",", "d2", ")", ":", "for", "k", "in", "d2", ":", "if", "k", "in", "d1", ":", "d1", "[", "k", "]", ".", "update", "(", "d2", "[", "k", "]", ")", "else", ":", "d1", "[", "k", "]", "=", "d2", "[", "k", "]" ]
update a set-valued dictionary when key exists, union sets
[ "update", "a", "set", "-", "valued", "dictionary", "when", "key", "exists", "union", "sets" ]
ddd62081cb9317beb5d21f86c8b4bb196ca3d222
https://github.com/potash/drain/blob/ddd62081cb9317beb5d21f86c8b4bb196ca3d222/drain/util.py#L350-L359
train
sonic182/libsasscompiler
libsasscompiler/__init__.py
LibSassCompiler.compile_file
def compile_file(self, infile, outfile, outdated=False, force=False): """Process sass file.""" myfile = codecs.open(outfile, 'w', 'utf-8') if settings.DEBUG: myfile.write(sass.compile(filename=infile)) else: myfile.write(sass.compile(filename=infile, output_style='compressed')) return myfile.close()
python
def compile_file(self, infile, outfile, outdated=False, force=False): """Process sass file.""" myfile = codecs.open(outfile, 'w', 'utf-8') if settings.DEBUG: myfile.write(sass.compile(filename=infile)) else: myfile.write(sass.compile(filename=infile, output_style='compressed')) return myfile.close()
[ "def", "compile_file", "(", "self", ",", "infile", ",", "outfile", ",", "outdated", "=", "False", ",", "force", "=", "False", ")", ":", "myfile", "=", "codecs", ".", "open", "(", "outfile", ",", "'w'", ",", "'utf-8'", ")", "if", "settings", ".", "DEBUG", ":", "myfile", ".", "write", "(", "sass", ".", "compile", "(", "filename", "=", "infile", ")", ")", "else", ":", "myfile", ".", "write", "(", "sass", ".", "compile", "(", "filename", "=", "infile", ",", "output_style", "=", "'compressed'", ")", ")", "return", "myfile", ".", "close", "(", ")" ]
Process sass file.
[ "Process", "sass", "file", "." ]
067c2324bbed9d22966fe63d87e5b3687510bc26
https://github.com/sonic182/libsasscompiler/blob/067c2324bbed9d22966fe63d87e5b3687510bc26/libsasscompiler/__init__.py#L22-L31
train
ehansis/ozelot
ozelot/etl/targets.py
ORMTarget.from_task
def from_task(cls, task): """Create a new target representing a task and its parameters Args: task: Task instance to create target for; the task class has to inherit from :class:`ozelot.tasks.TaskBase`. Returns: ozelot.tasks.ORMTarget: a new target instance """ target = cls(name=task.get_name(), params=task.get_param_string()) return target
python
def from_task(cls, task): """Create a new target representing a task and its parameters Args: task: Task instance to create target for; the task class has to inherit from :class:`ozelot.tasks.TaskBase`. Returns: ozelot.tasks.ORMTarget: a new target instance """ target = cls(name=task.get_name(), params=task.get_param_string()) return target
[ "def", "from_task", "(", "cls", ",", "task", ")", ":", "target", "=", "cls", "(", "name", "=", "task", ".", "get_name", "(", ")", ",", "params", "=", "task", ".", "get_param_string", "(", ")", ")", "return", "target" ]
Create a new target representing a task and its parameters Args: task: Task instance to create target for; the task class has to inherit from :class:`ozelot.tasks.TaskBase`. Returns: ozelot.tasks.ORMTarget: a new target instance
[ "Create", "a", "new", "target", "representing", "a", "task", "and", "its", "parameters" ]
948675e02eb6fca940450f5cb814f53e97159e5b
https://github.com/ehansis/ozelot/blob/948675e02eb6fca940450f5cb814f53e97159e5b/ozelot/etl/targets.py#L21-L34
train
ehansis/ozelot
ozelot/etl/targets.py
ORMTarget._base_query
def _base_query(self, session): """Base query for a target. Args: session: database session to query in """ return session.query(ORMTargetMarker) \ .filter(ORMTargetMarker.name == self.name) \ .filter(ORMTargetMarker.params == self.params)
python
def _base_query(self, session): """Base query for a target. Args: session: database session to query in """ return session.query(ORMTargetMarker) \ .filter(ORMTargetMarker.name == self.name) \ .filter(ORMTargetMarker.params == self.params)
[ "def", "_base_query", "(", "self", ",", "session", ")", ":", "return", "session", ".", "query", "(", "ORMTargetMarker", ")", ".", "filter", "(", "ORMTargetMarker", ".", "name", "==", "self", ".", "name", ")", ".", "filter", "(", "ORMTargetMarker", ".", "params", "==", "self", ".", "params", ")" ]
Base query for a target. Args: session: database session to query in
[ "Base", "query", "for", "a", "target", "." ]
948675e02eb6fca940450f5cb814f53e97159e5b
https://github.com/ehansis/ozelot/blob/948675e02eb6fca940450f5cb814f53e97159e5b/ozelot/etl/targets.py#L36-L44
train
ehansis/ozelot
ozelot/etl/targets.py
ORMTarget.exists
def exists(self): """Check if a target exists This function is called by :mod:`luigi` to check if a task output exists. By default, :mod:`luigi` considers a task as complete if all it targets (outputs) exist. Returns: bool: ``True`` if target exists, ``False`` otherwise """ # get DB connection session = client.get_client().create_session() # query for target existence ret = self._base_query(session).count() > 0 session.close() return ret
python
def exists(self): """Check if a target exists This function is called by :mod:`luigi` to check if a task output exists. By default, :mod:`luigi` considers a task as complete if all it targets (outputs) exist. Returns: bool: ``True`` if target exists, ``False`` otherwise """ # get DB connection session = client.get_client().create_session() # query for target existence ret = self._base_query(session).count() > 0 session.close() return ret
[ "def", "exists", "(", "self", ")", ":", "# get DB connection", "session", "=", "client", ".", "get_client", "(", ")", ".", "create_session", "(", ")", "# query for target existence", "ret", "=", "self", ".", "_base_query", "(", "session", ")", ".", "count", "(", ")", ">", "0", "session", ".", "close", "(", ")", "return", "ret" ]
Check if a target exists This function is called by :mod:`luigi` to check if a task output exists. By default, :mod:`luigi` considers a task as complete if all it targets (outputs) exist. Returns: bool: ``True`` if target exists, ``False`` otherwise
[ "Check", "if", "a", "target", "exists" ]
948675e02eb6fca940450f5cb814f53e97159e5b
https://github.com/ehansis/ozelot/blob/948675e02eb6fca940450f5cb814f53e97159e5b/ozelot/etl/targets.py#L46-L63
train
ehansis/ozelot
ozelot/etl/targets.py
ORMTarget.create
def create(self): """Create an instance of the current target in the database If a target with the current name and params already exists, no second instance is created. """ session = client.get_client().create_session() if not self._base_query(session).count() > 0: # store a new target instance to the database marker = ORMTargetMarker(name=self.name, params=self.params) session.add(marker) session.commit() session.close()
python
def create(self): """Create an instance of the current target in the database If a target with the current name and params already exists, no second instance is created. """ session = client.get_client().create_session() if not self._base_query(session).count() > 0: # store a new target instance to the database marker = ORMTargetMarker(name=self.name, params=self.params) session.add(marker) session.commit() session.close()
[ "def", "create", "(", "self", ")", ":", "session", "=", "client", ".", "get_client", "(", ")", ".", "create_session", "(", ")", "if", "not", "self", ".", "_base_query", "(", "session", ")", ".", "count", "(", ")", ">", "0", ":", "# store a new target instance to the database", "marker", "=", "ORMTargetMarker", "(", "name", "=", "self", ".", "name", ",", "params", "=", "self", ".", "params", ")", "session", ".", "add", "(", "marker", ")", "session", ".", "commit", "(", ")", "session", ".", "close", "(", ")" ]
Create an instance of the current target in the database If a target with the current name and params already exists, no second instance is created.
[ "Create", "an", "instance", "of", "the", "current", "target", "in", "the", "database" ]
948675e02eb6fca940450f5cb814f53e97159e5b
https://github.com/ehansis/ozelot/blob/948675e02eb6fca940450f5cb814f53e97159e5b/ozelot/etl/targets.py#L65-L79
train
ehansis/ozelot
ozelot/etl/targets.py
ORMTarget.remove
def remove(self): """Remove a target Raises a ``RuntimeError`` if the target does not exist. """ session = client.get_client().create_session() if not self._base_query(session).count() > 0: session.close() raise RuntimeError("Target does not exist, name={:s}, params={:s}" "".format(self.name, self.params)) # remove the target from the database self._base_query(session).delete() session.commit() session.close()
python
def remove(self): """Remove a target Raises a ``RuntimeError`` if the target does not exist. """ session = client.get_client().create_session() if not self._base_query(session).count() > 0: session.close() raise RuntimeError("Target does not exist, name={:s}, params={:s}" "".format(self.name, self.params)) # remove the target from the database self._base_query(session).delete() session.commit() session.close()
[ "def", "remove", "(", "self", ")", ":", "session", "=", "client", ".", "get_client", "(", ")", ".", "create_session", "(", ")", "if", "not", "self", ".", "_base_query", "(", "session", ")", ".", "count", "(", ")", ">", "0", ":", "session", ".", "close", "(", ")", "raise", "RuntimeError", "(", "\"Target does not exist, name={:s}, params={:s}\"", "\"\"", ".", "format", "(", "self", ".", "name", ",", "self", ".", "params", ")", ")", "# remove the target from the database", "self", ".", "_base_query", "(", "session", ")", ".", "delete", "(", ")", "session", ".", "commit", "(", ")", "session", ".", "close", "(", ")" ]
Remove a target Raises a ``RuntimeError`` if the target does not exist.
[ "Remove", "a", "target" ]
948675e02eb6fca940450f5cb814f53e97159e5b
https://github.com/ehansis/ozelot/blob/948675e02eb6fca940450f5cb814f53e97159e5b/ozelot/etl/targets.py#L81-L97
train
dchaplinsky/translit-ua
translitua/translit.py
add_uppercase
def add_uppercase(table): """ Extend the table with uppercase options >>> print("а" in add_uppercase({"а": "a"})) True >>> print(add_uppercase({"а": "a"})["а"] == "a") True >>> print("А" in add_uppercase({"а": "a"})) True >>> print(add_uppercase({"а": "a"})["А"] == "A") True >>> print(len(add_uppercase({"а": "a"}).keys())) 2 >>> print("Аа" in add_uppercase({"аа": "aa"})) True >>> print(add_uppercase({"аа": "aa"})["Аа"] == "Aa") True """ orig = table.copy() orig.update( dict((k.capitalize(), v.capitalize()) for k, v in table.items())) return orig
python
def add_uppercase(table): """ Extend the table with uppercase options >>> print("а" in add_uppercase({"а": "a"})) True >>> print(add_uppercase({"а": "a"})["а"] == "a") True >>> print("А" in add_uppercase({"а": "a"})) True >>> print(add_uppercase({"а": "a"})["А"] == "A") True >>> print(len(add_uppercase({"а": "a"}).keys())) 2 >>> print("Аа" in add_uppercase({"аа": "aa"})) True >>> print(add_uppercase({"аа": "aa"})["Аа"] == "Aa") True """ orig = table.copy() orig.update( dict((k.capitalize(), v.capitalize()) for k, v in table.items())) return orig
[ "def", "add_uppercase", "(", "table", ")", ":", "orig", "=", "table", ".", "copy", "(", ")", "orig", ".", "update", "(", "dict", "(", "(", "k", ".", "capitalize", "(", ")", ",", "v", ".", "capitalize", "(", ")", ")", "for", "k", ",", "v", "in", "table", ".", "items", "(", ")", ")", ")", "return", "orig" ]
Extend the table with uppercase options >>> print("а" in add_uppercase({"а": "a"})) True >>> print(add_uppercase({"а": "a"})["а"] == "a") True >>> print("А" in add_uppercase({"а": "a"})) True >>> print(add_uppercase({"а": "a"})["А"] == "A") True >>> print(len(add_uppercase({"а": "a"}).keys())) 2 >>> print("Аа" in add_uppercase({"аа": "aa"})) True >>> print(add_uppercase({"аа": "aa"})["Аа"] == "Aa") True
[ "Extend", "the", "table", "with", "uppercase", "options" ]
14e634492c7ce937d77436772fa32d2de5707a9b
https://github.com/dchaplinsky/translit-ua/blob/14e634492c7ce937d77436772fa32d2de5707a9b/translitua/translit.py#L12-L35
train
dchaplinsky/translit-ua
translitua/translit.py
translit
def translit(src, table=UkrainianKMU, preserve_case=True): u""" Transliterates given unicode `src` text to transliterated variant according to a given transliteration table. Official ukrainian transliteration is used by default :param src: string to transliterate :type src: str :param table: transliteration table :type table: transliteration table object :param preserve_case: convert result to uppercase if source is uppercased (see the example below for the difference that flag makes) :type preserve_case: bool :returns: transliterated string :rtype: str >>> print(translit(u"Дмитро Згуровский")) Dmytro Zghurovskyi >>> print(translit(u"Дмитро ЗГуровский")) Dmytro ZGhurovskyi >>> print(translit(u"Дмитро згуровский")) Dmytro zghurovskyi >>> print(translit(u"Євген Петренко")) Yevhen Petrenko >>> print(translit(u"Петренко Євген")) Petrenko Yevhen >>> print(translit(u"Петренко.Євген")) Petrenko.Yevhen >>> print(translit(u"Петренко,Євген")) Petrenko,Yevhen >>> print(translit(u"Петренко/Євген")) Petrenko/Yevhen >>> print(translit(u"Євгєн")) Yevhien >>> print(translit(u"Яготин")) Yahotyn >>> print(translit(u"Ярошенко")) Yaroshenko >>> print(translit(u"Костянтин")) Kostiantyn >>> print(translit(u"Знам'янка")) Znamianka >>> print(translit(u"Знам’янка")) Znamianka >>> print(translit(u"Знам’янка")) Znamianka >>> print(translit(u"Феодосія")) Feodosiia >>> print(translit(u"Ньютон")) Niuton >>> print(translit(u"піранья")) pirania >>> print(translit(u"кур'єр")) kurier >>> print(translit(u"ЗГУРОВСЬКИЙ")) ZGHUROVSKYI >>> print(translit(u"ЗГУРОВСЬКИЙ", preserve_case=False)) ZGhUROVSKYI >>> print(translit(u"Дмитро Згуровский", UkrainianSimple)) Dmytro Zhurovskyj >>> print(translit(u"Дмитро Щуровский", UkrainianWWS)) Dmytro Ščurovskyj >>> print(translit(u"Дмитро Щуровский", UkrainianBritish)) Dmȳtro Shchurovskȳĭ >>> print(translit(u"Дмитро Щуровский", UkrainianFrench)) Dmytro Chtchourovskyy >>> print(translit(u"Дмитро Щуровский", UkrainianGerman)) Dmytro Schtschurowskyj >>> print(translit(u"Дмитро Щуровский", UkrainianGOST1971)) Dmitro Shhurovskij >>> print(translit(u"Варенье", RussianInternationalPassport)) Varen'ye >>> print(translit(u"Новьё", RussianInternationalPassport)) Nov'ye >>> print(translit(u"Варенье", RussianDriverLicense)) Varen'ye >>> print(translit(u"Подъезд", RussianDriverLicense)) Pod'yezd >>> print(translit(u"Новьё", RussianDriverLicense)) Nov'yo >>> print(translit(u"Подъёб", RussianDriverLicense)) Pod'yob >>> print(translit(u"Ель", RussianDriverLicense)) Yel' >>> print(translit(u"Ёж", RussianDriverLicense)) Yozh >>> print(translit(u"Щёки", RussianDriverLicense)) Shcheki >>> print(translit(u"Соловьи", RussianDriverLicense)) Solov'yi """ src = text_type(src) src_is_upper = src.isupper() if hasattr(table, "DELETE_PATTERN"): src = table.DELETE_PATTERN.sub(u"", src) if hasattr(table, "PATTERN1"): src = table.PATTERN1.sub(lambda x: table.SPECIAL_CASES[x.group()], src) if hasattr(table, "PATTERN2"): src = table.PATTERN2.sub(lambda x: table.FIRST_CHARACTERS[x.group()], src) res = src.translate(table.MAIN_TRANSLIT_TABLE) if src_is_upper and preserve_case: return res.upper() else: return res
python
def translit(src, table=UkrainianKMU, preserve_case=True): u""" Transliterates given unicode `src` text to transliterated variant according to a given transliteration table. Official ukrainian transliteration is used by default :param src: string to transliterate :type src: str :param table: transliteration table :type table: transliteration table object :param preserve_case: convert result to uppercase if source is uppercased (see the example below for the difference that flag makes) :type preserve_case: bool :returns: transliterated string :rtype: str >>> print(translit(u"Дмитро Згуровский")) Dmytro Zghurovskyi >>> print(translit(u"Дмитро ЗГуровский")) Dmytro ZGhurovskyi >>> print(translit(u"Дмитро згуровский")) Dmytro zghurovskyi >>> print(translit(u"Євген Петренко")) Yevhen Petrenko >>> print(translit(u"Петренко Євген")) Petrenko Yevhen >>> print(translit(u"Петренко.Євген")) Petrenko.Yevhen >>> print(translit(u"Петренко,Євген")) Petrenko,Yevhen >>> print(translit(u"Петренко/Євген")) Petrenko/Yevhen >>> print(translit(u"Євгєн")) Yevhien >>> print(translit(u"Яготин")) Yahotyn >>> print(translit(u"Ярошенко")) Yaroshenko >>> print(translit(u"Костянтин")) Kostiantyn >>> print(translit(u"Знам'янка")) Znamianka >>> print(translit(u"Знам’янка")) Znamianka >>> print(translit(u"Знам’янка")) Znamianka >>> print(translit(u"Феодосія")) Feodosiia >>> print(translit(u"Ньютон")) Niuton >>> print(translit(u"піранья")) pirania >>> print(translit(u"кур'єр")) kurier >>> print(translit(u"ЗГУРОВСЬКИЙ")) ZGHUROVSKYI >>> print(translit(u"ЗГУРОВСЬКИЙ", preserve_case=False)) ZGhUROVSKYI >>> print(translit(u"Дмитро Згуровский", UkrainianSimple)) Dmytro Zhurovskyj >>> print(translit(u"Дмитро Щуровский", UkrainianWWS)) Dmytro Ščurovskyj >>> print(translit(u"Дмитро Щуровский", UkrainianBritish)) Dmȳtro Shchurovskȳĭ >>> print(translit(u"Дмитро Щуровский", UkrainianFrench)) Dmytro Chtchourovskyy >>> print(translit(u"Дмитро Щуровский", UkrainianGerman)) Dmytro Schtschurowskyj >>> print(translit(u"Дмитро Щуровский", UkrainianGOST1971)) Dmitro Shhurovskij >>> print(translit(u"Варенье", RussianInternationalPassport)) Varen'ye >>> print(translit(u"Новьё", RussianInternationalPassport)) Nov'ye >>> print(translit(u"Варенье", RussianDriverLicense)) Varen'ye >>> print(translit(u"Подъезд", RussianDriverLicense)) Pod'yezd >>> print(translit(u"Новьё", RussianDriverLicense)) Nov'yo >>> print(translit(u"Подъёб", RussianDriverLicense)) Pod'yob >>> print(translit(u"Ель", RussianDriverLicense)) Yel' >>> print(translit(u"Ёж", RussianDriverLicense)) Yozh >>> print(translit(u"Щёки", RussianDriverLicense)) Shcheki >>> print(translit(u"Соловьи", RussianDriverLicense)) Solov'yi """ src = text_type(src) src_is_upper = src.isupper() if hasattr(table, "DELETE_PATTERN"): src = table.DELETE_PATTERN.sub(u"", src) if hasattr(table, "PATTERN1"): src = table.PATTERN1.sub(lambda x: table.SPECIAL_CASES[x.group()], src) if hasattr(table, "PATTERN2"): src = table.PATTERN2.sub(lambda x: table.FIRST_CHARACTERS[x.group()], src) res = src.translate(table.MAIN_TRANSLIT_TABLE) if src_is_upper and preserve_case: return res.upper() else: return res
[ "def", "translit", "(", "src", ",", "table", "=", "UkrainianKMU", ",", "preserve_case", "=", "True", ")", ":", "src", "=", "text_type", "(", "src", ")", "src_is_upper", "=", "src", ".", "isupper", "(", ")", "if", "hasattr", "(", "table", ",", "\"DELETE_PATTERN\"", ")", ":", "src", "=", "table", ".", "DELETE_PATTERN", ".", "sub", "(", "u\"\"", ",", "src", ")", "if", "hasattr", "(", "table", ",", "\"PATTERN1\"", ")", ":", "src", "=", "table", ".", "PATTERN1", ".", "sub", "(", "lambda", "x", ":", "table", ".", "SPECIAL_CASES", "[", "x", ".", "group", "(", ")", "]", ",", "src", ")", "if", "hasattr", "(", "table", ",", "\"PATTERN2\"", ")", ":", "src", "=", "table", ".", "PATTERN2", ".", "sub", "(", "lambda", "x", ":", "table", ".", "FIRST_CHARACTERS", "[", "x", ".", "group", "(", ")", "]", ",", "src", ")", "res", "=", "src", ".", "translate", "(", "table", ".", "MAIN_TRANSLIT_TABLE", ")", "if", "src_is_upper", "and", "preserve_case", ":", "return", "res", ".", "upper", "(", ")", "else", ":", "return", "res" ]
u""" Transliterates given unicode `src` text to transliterated variant according to a given transliteration table. Official ukrainian transliteration is used by default :param src: string to transliterate :type src: str :param table: transliteration table :type table: transliteration table object :param preserve_case: convert result to uppercase if source is uppercased (see the example below for the difference that flag makes) :type preserve_case: bool :returns: transliterated string :rtype: str >>> print(translit(u"Дмитро Згуровский")) Dmytro Zghurovskyi >>> print(translit(u"Дмитро ЗГуровский")) Dmytro ZGhurovskyi >>> print(translit(u"Дмитро згуровский")) Dmytro zghurovskyi >>> print(translit(u"Євген Петренко")) Yevhen Petrenko >>> print(translit(u"Петренко Євген")) Petrenko Yevhen >>> print(translit(u"Петренко.Євген")) Petrenko.Yevhen >>> print(translit(u"Петренко,Євген")) Petrenko,Yevhen >>> print(translit(u"Петренко/Євген")) Petrenko/Yevhen >>> print(translit(u"Євгєн")) Yevhien >>> print(translit(u"Яготин")) Yahotyn >>> print(translit(u"Ярошенко")) Yaroshenko >>> print(translit(u"Костянтин")) Kostiantyn >>> print(translit(u"Знам'янка")) Znamianka >>> print(translit(u"Знам’янка")) Znamianka >>> print(translit(u"Знам’янка")) Znamianka >>> print(translit(u"Феодосія")) Feodosiia >>> print(translit(u"Ньютон")) Niuton >>> print(translit(u"піранья")) pirania >>> print(translit(u"кур'єр")) kurier >>> print(translit(u"ЗГУРОВСЬКИЙ")) ZGHUROVSKYI >>> print(translit(u"ЗГУРОВСЬКИЙ", preserve_case=False)) ZGhUROVSKYI >>> print(translit(u"Дмитро Згуровский", UkrainianSimple)) Dmytro Zhurovskyj >>> print(translit(u"Дмитро Щуровский", UkrainianWWS)) Dmytro Ščurovskyj >>> print(translit(u"Дмитро Щуровский", UkrainianBritish)) Dmȳtro Shchurovskȳĭ >>> print(translit(u"Дмитро Щуровский", UkrainianFrench)) Dmytro Chtchourovskyy >>> print(translit(u"Дмитро Щуровский", UkrainianGerman)) Dmytro Schtschurowskyj >>> print(translit(u"Дмитро Щуровский", UkrainianGOST1971)) Dmitro Shhurovskij >>> print(translit(u"Варенье", RussianInternationalPassport)) Varen'ye >>> print(translit(u"Новьё", RussianInternationalPassport)) Nov'ye >>> print(translit(u"Варенье", RussianDriverLicense)) Varen'ye >>> print(translit(u"Подъезд", RussianDriverLicense)) Pod'yezd >>> print(translit(u"Новьё", RussianDriverLicense)) Nov'yo >>> print(translit(u"Подъёб", RussianDriverLicense)) Pod'yob >>> print(translit(u"Ель", RussianDriverLicense)) Yel' >>> print(translit(u"Ёж", RussianDriverLicense)) Yozh >>> print(translit(u"Щёки", RussianDriverLicense)) Shcheki >>> print(translit(u"Соловьи", RussianDriverLicense)) Solov'yi
[ "u", "Transliterates", "given", "unicode", "src", "text", "to", "transliterated", "variant", "according", "to", "a", "given", "transliteration", "table", ".", "Official", "ukrainian", "transliteration", "is", "used", "by", "default" ]
14e634492c7ce937d77436772fa32d2de5707a9b
https://github.com/dchaplinsky/translit-ua/blob/14e634492c7ce937d77436772fa32d2de5707a9b/translitua/translit.py#L1043-L1156
train
ehansis/ozelot
examples/leonardo/leonardo/kvstore/pipeline.py
EntityCreatorMixin.store
def store(self, df, attribute_columns): """Store entities and their attributes Args: df (pandas.DataFrame): data to store (storing appends 'id' and 'type' columns!) attribute_columns (list(str)): list of column labels that define attributes """ # ID start values depend on currently stored entities/attributes! entity_id_start = models.Entity.get_max_id(self.session) + 1 attribute_id_start = models.Attribute.get_max_id(self.session) + 1 # append ID and type columns df['id'] = range(entity_id_start, entity_id_start + len(df)) df['type'] = self.type # store entities df[['id', 'type']].to_sql(name=models.Entity.__tablename__, con=self.client.engine, if_exists='append', index=False) # store attributes for col in attribute_columns: # ID column of df is the entity ID of the attribute attr_df = df[[col, 'id']].rename(columns={'id': 'entity_id', col: 'value'}) attr_df['name'] = col # add entity ID column, need to respect already existing entities attr_df['id'] = range(attribute_id_start, attribute_id_start + len(df)) attribute_id_start += len(df) # store attr_df.to_sql(name=models.Attribute.__tablename__, con=self.client.engine, if_exists='append', index=False)
python
def store(self, df, attribute_columns): """Store entities and their attributes Args: df (pandas.DataFrame): data to store (storing appends 'id' and 'type' columns!) attribute_columns (list(str)): list of column labels that define attributes """ # ID start values depend on currently stored entities/attributes! entity_id_start = models.Entity.get_max_id(self.session) + 1 attribute_id_start = models.Attribute.get_max_id(self.session) + 1 # append ID and type columns df['id'] = range(entity_id_start, entity_id_start + len(df)) df['type'] = self.type # store entities df[['id', 'type']].to_sql(name=models.Entity.__tablename__, con=self.client.engine, if_exists='append', index=False) # store attributes for col in attribute_columns: # ID column of df is the entity ID of the attribute attr_df = df[[col, 'id']].rename(columns={'id': 'entity_id', col: 'value'}) attr_df['name'] = col # add entity ID column, need to respect already existing entities attr_df['id'] = range(attribute_id_start, attribute_id_start + len(df)) attribute_id_start += len(df) # store attr_df.to_sql(name=models.Attribute.__tablename__, con=self.client.engine, if_exists='append', index=False)
[ "def", "store", "(", "self", ",", "df", ",", "attribute_columns", ")", ":", "# ID start values depend on currently stored entities/attributes!", "entity_id_start", "=", "models", ".", "Entity", ".", "get_max_id", "(", "self", ".", "session", ")", "+", "1", "attribute_id_start", "=", "models", ".", "Attribute", ".", "get_max_id", "(", "self", ".", "session", ")", "+", "1", "# append ID and type columns", "df", "[", "'id'", "]", "=", "range", "(", "entity_id_start", ",", "entity_id_start", "+", "len", "(", "df", ")", ")", "df", "[", "'type'", "]", "=", "self", ".", "type", "# store entities", "df", "[", "[", "'id'", ",", "'type'", "]", "]", ".", "to_sql", "(", "name", "=", "models", ".", "Entity", ".", "__tablename__", ",", "con", "=", "self", ".", "client", ".", "engine", ",", "if_exists", "=", "'append'", ",", "index", "=", "False", ")", "# store attributes", "for", "col", "in", "attribute_columns", ":", "# ID column of df is the entity ID of the attribute", "attr_df", "=", "df", "[", "[", "col", ",", "'id'", "]", "]", ".", "rename", "(", "columns", "=", "{", "'id'", ":", "'entity_id'", ",", "col", ":", "'value'", "}", ")", "attr_df", "[", "'name'", "]", "=", "col", "# add entity ID column, need to respect already existing entities", "attr_df", "[", "'id'", "]", "=", "range", "(", "attribute_id_start", ",", "attribute_id_start", "+", "len", "(", "df", ")", ")", "attribute_id_start", "+=", "len", "(", "df", ")", "# store", "attr_df", ".", "to_sql", "(", "name", "=", "models", ".", "Attribute", ".", "__tablename__", ",", "con", "=", "self", ".", "client", ".", "engine", ",", "if_exists", "=", "'append'", ",", "index", "=", "False", ")" ]
Store entities and their attributes Args: df (pandas.DataFrame): data to store (storing appends 'id' and 'type' columns!) attribute_columns (list(str)): list of column labels that define attributes
[ "Store", "entities", "and", "their", "attributes" ]
948675e02eb6fca940450f5cb814f53e97159e5b
https://github.com/ehansis/ozelot/blob/948675e02eb6fca940450f5cb814f53e97159e5b/examples/leonardo/leonardo/kvstore/pipeline.py#L49-L86
train
ehansis/ozelot
examples/leonardo/leonardo/kvstore/pipeline.py
LoadPaintings.run
def run(self): """Load all paintings into the database """ df = PaintingsInputData().load() # rename columns df.rename(columns={'paintingLabel': 'name'}, inplace=True) # get artist IDs, map via artist wiki ID artists = models.Entity.query_with_attributes('artist', self.client) df['artist_id'] = df['creator_wiki_id'].map(artists.set_index('wiki_id')['id']) # define attributes to create attribute_columns = ['name', 'wiki_id', 'area', 'decade', 'artist_id'] # store entities and attributes self.store(df, attribute_columns) self.done()
python
def run(self): """Load all paintings into the database """ df = PaintingsInputData().load() # rename columns df.rename(columns={'paintingLabel': 'name'}, inplace=True) # get artist IDs, map via artist wiki ID artists = models.Entity.query_with_attributes('artist', self.client) df['artist_id'] = df['creator_wiki_id'].map(artists.set_index('wiki_id')['id']) # define attributes to create attribute_columns = ['name', 'wiki_id', 'area', 'decade', 'artist_id'] # store entities and attributes self.store(df, attribute_columns) self.done()
[ "def", "run", "(", "self", ")", ":", "df", "=", "PaintingsInputData", "(", ")", ".", "load", "(", ")", "# rename columns", "df", ".", "rename", "(", "columns", "=", "{", "'paintingLabel'", ":", "'name'", "}", ",", "inplace", "=", "True", ")", "# get artist IDs, map via artist wiki ID", "artists", "=", "models", ".", "Entity", ".", "query_with_attributes", "(", "'artist'", ",", "self", ".", "client", ")", "df", "[", "'artist_id'", "]", "=", "df", "[", "'creator_wiki_id'", "]", ".", "map", "(", "artists", ".", "set_index", "(", "'wiki_id'", ")", "[", "'id'", "]", ")", "# define attributes to create", "attribute_columns", "=", "[", "'name'", ",", "'wiki_id'", ",", "'area'", ",", "'decade'", ",", "'artist_id'", "]", "# store entities and attributes", "self", ".", "store", "(", "df", ",", "attribute_columns", ")", "self", ".", "done", "(", ")" ]
Load all paintings into the database
[ "Load", "all", "paintings", "into", "the", "database" ]
948675e02eb6fca940450f5cb814f53e97159e5b
https://github.com/ehansis/ozelot/blob/948675e02eb6fca940450f5cb814f53e97159e5b/examples/leonardo/leonardo/kvstore/pipeline.py#L149-L168
train
ShadowBlip/Neteria
neteria/core.py
serialize_data
def serialize_data(data, compression=False, encryption=False, public_key=None): """Serializes normal Python datatypes into plaintext using json. You may also choose to enable compression and encryption when serializing data to send over the network. Enabling one or both of these options will incur additional overhead. Args: data (dict): The data to convert into plain text using json. compression (boolean): True or False value on whether or not to compress the serialized data. encryption (rsa.encryption): An encryption instance used to encrypt the message if encryption is desired. public_key (str): The public key to use to encrypt if encryption is enabled. Returns: The string message serialized using json. """ message = json.dumps(data) if compression: message = zlib.compress(message) message = binascii.b2a_base64(message) if encryption and public_key: message = encryption.encrypt(message, public_key) encoded_message = str.encode(message) return encoded_message
python
def serialize_data(data, compression=False, encryption=False, public_key=None): """Serializes normal Python datatypes into plaintext using json. You may also choose to enable compression and encryption when serializing data to send over the network. Enabling one or both of these options will incur additional overhead. Args: data (dict): The data to convert into plain text using json. compression (boolean): True or False value on whether or not to compress the serialized data. encryption (rsa.encryption): An encryption instance used to encrypt the message if encryption is desired. public_key (str): The public key to use to encrypt if encryption is enabled. Returns: The string message serialized using json. """ message = json.dumps(data) if compression: message = zlib.compress(message) message = binascii.b2a_base64(message) if encryption and public_key: message = encryption.encrypt(message, public_key) encoded_message = str.encode(message) return encoded_message
[ "def", "serialize_data", "(", "data", ",", "compression", "=", "False", ",", "encryption", "=", "False", ",", "public_key", "=", "None", ")", ":", "message", "=", "json", ".", "dumps", "(", "data", ")", "if", "compression", ":", "message", "=", "zlib", ".", "compress", "(", "message", ")", "message", "=", "binascii", ".", "b2a_base64", "(", "message", ")", "if", "encryption", "and", "public_key", ":", "message", "=", "encryption", ".", "encrypt", "(", "message", ",", "public_key", ")", "encoded_message", "=", "str", ".", "encode", "(", "message", ")", "return", "encoded_message" ]
Serializes normal Python datatypes into plaintext using json. You may also choose to enable compression and encryption when serializing data to send over the network. Enabling one or both of these options will incur additional overhead. Args: data (dict): The data to convert into plain text using json. compression (boolean): True or False value on whether or not to compress the serialized data. encryption (rsa.encryption): An encryption instance used to encrypt the message if encryption is desired. public_key (str): The public key to use to encrypt if encryption is enabled. Returns: The string message serialized using json.
[ "Serializes", "normal", "Python", "datatypes", "into", "plaintext", "using", "json", "." ]
1a8c976eb2beeca0a5a272a34ac58b2c114495a4
https://github.com/ShadowBlip/Neteria/blob/1a8c976eb2beeca0a5a272a34ac58b2c114495a4/neteria/core.py#L44-L76
train
ShadowBlip/Neteria
neteria/core.py
unserialize_data
def unserialize_data(data, compression=False, encryption=False): """Unserializes the packet data and converts it from json format to normal Python datatypes. If you choose to enable encryption and/or compression when serializing data, you MUST enable the same options when unserializing data. Args: data (str): The raw, serialized packet data delivered from the transport protocol. compression (boolean): True or False value on whether or not to uncompress the serialized data. encryption (rsa.encryption): An encryption instance used to decrypt the message if encryption is desired. Returns: The message unserialized in normal Python datatypes. """ try: if encryption: data = encryption.decrypt(data) except Exception as err: logger.error("Decryption Error: " + str(err)) message = False try: if compression: data = binascii.a2b_base64(data) data = zlib.decompress(data) message = json.loads(data) except Exception as err: logger.error("Decompression Error: " + str(err)) message = False decoded_message = data.decode() if not encryption and not compression: message = json.loads(decoded_message) return message
python
def unserialize_data(data, compression=False, encryption=False): """Unserializes the packet data and converts it from json format to normal Python datatypes. If you choose to enable encryption and/or compression when serializing data, you MUST enable the same options when unserializing data. Args: data (str): The raw, serialized packet data delivered from the transport protocol. compression (boolean): True or False value on whether or not to uncompress the serialized data. encryption (rsa.encryption): An encryption instance used to decrypt the message if encryption is desired. Returns: The message unserialized in normal Python datatypes. """ try: if encryption: data = encryption.decrypt(data) except Exception as err: logger.error("Decryption Error: " + str(err)) message = False try: if compression: data = binascii.a2b_base64(data) data = zlib.decompress(data) message = json.loads(data) except Exception as err: logger.error("Decompression Error: " + str(err)) message = False decoded_message = data.decode() if not encryption and not compression: message = json.loads(decoded_message) return message
[ "def", "unserialize_data", "(", "data", ",", "compression", "=", "False", ",", "encryption", "=", "False", ")", ":", "try", ":", "if", "encryption", ":", "data", "=", "encryption", ".", "decrypt", "(", "data", ")", "except", "Exception", "as", "err", ":", "logger", ".", "error", "(", "\"Decryption Error: \"", "+", "str", "(", "err", ")", ")", "message", "=", "False", "try", ":", "if", "compression", ":", "data", "=", "binascii", ".", "a2b_base64", "(", "data", ")", "data", "=", "zlib", ".", "decompress", "(", "data", ")", "message", "=", "json", ".", "loads", "(", "data", ")", "except", "Exception", "as", "err", ":", "logger", ".", "error", "(", "\"Decompression Error: \"", "+", "str", "(", "err", ")", ")", "message", "=", "False", "decoded_message", "=", "data", ".", "decode", "(", ")", "if", "not", "encryption", "and", "not", "compression", ":", "message", "=", "json", ".", "loads", "(", "decoded_message", ")", "return", "message" ]
Unserializes the packet data and converts it from json format to normal Python datatypes. If you choose to enable encryption and/or compression when serializing data, you MUST enable the same options when unserializing data. Args: data (str): The raw, serialized packet data delivered from the transport protocol. compression (boolean): True or False value on whether or not to uncompress the serialized data. encryption (rsa.encryption): An encryption instance used to decrypt the message if encryption is desired. Returns: The message unserialized in normal Python datatypes.
[ "Unserializes", "the", "packet", "data", "and", "converts", "it", "from", "json", "format", "to", "normal", "Python", "datatypes", "." ]
1a8c976eb2beeca0a5a272a34ac58b2c114495a4
https://github.com/ShadowBlip/Neteria/blob/1a8c976eb2beeca0a5a272a34ac58b2c114495a4/neteria/core.py#L78-L119
train
ShadowBlip/Neteria
neteria/core.py
ListenerUDP.listen
def listen(self): """Starts the listen loop. If threading is enabled, then the loop will be started in its own thread. Args: None Returns: None """ self.listening = True if self.threading: from threading import Thread self.listen_thread = Thread(target=self.listen_loop) self.listen_thread.daemon = True self.listen_thread.start() self.scheduler_thread = Thread(target=self.scheduler) self.scheduler_thread.daemon = True self.scheduler_thread.start() else: self.listen_loop()
python
def listen(self): """Starts the listen loop. If threading is enabled, then the loop will be started in its own thread. Args: None Returns: None """ self.listening = True if self.threading: from threading import Thread self.listen_thread = Thread(target=self.listen_loop) self.listen_thread.daemon = True self.listen_thread.start() self.scheduler_thread = Thread(target=self.scheduler) self.scheduler_thread.daemon = True self.scheduler_thread.start() else: self.listen_loop()
[ "def", "listen", "(", "self", ")", ":", "self", ".", "listening", "=", "True", "if", "self", ".", "threading", ":", "from", "threading", "import", "Thread", "self", ".", "listen_thread", "=", "Thread", "(", "target", "=", "self", ".", "listen_loop", ")", "self", ".", "listen_thread", ".", "daemon", "=", "True", "self", ".", "listen_thread", ".", "start", "(", ")", "self", ".", "scheduler_thread", "=", "Thread", "(", "target", "=", "self", ".", "scheduler", ")", "self", ".", "scheduler_thread", ".", "daemon", "=", "True", "self", ".", "scheduler_thread", ".", "start", "(", ")", "else", ":", "self", ".", "listen_loop", "(", ")" ]
Starts the listen loop. If threading is enabled, then the loop will be started in its own thread. Args: None Returns: None
[ "Starts", "the", "listen", "loop", ".", "If", "threading", "is", "enabled", "then", "the", "loop", "will", "be", "started", "in", "its", "own", "thread", "." ]
1a8c976eb2beeca0a5a272a34ac58b2c114495a4
https://github.com/ShadowBlip/Neteria/blob/1a8c976eb2beeca0a5a272a34ac58b2c114495a4/neteria/core.py#L192-L216
train
ShadowBlip/Neteria
neteria/core.py
ListenerUDP.listen_loop
def listen_loop(self): """Starts the listen loop and executes the receieve_datagram method whenever a packet is receieved. Args: None Returns: None """ while self.listening: try: data, address = self.sock.recvfrom(self.bufsize) self.receive_datagram(data, address) if self.stats_enabled: self.stats['bytes_recieved'] += len(data) except socket.error as error: if error.errno == errno.WSAECONNRESET: logger.info("connection reset") else: raise logger.info("Shutting down the listener...")
python
def listen_loop(self): """Starts the listen loop and executes the receieve_datagram method whenever a packet is receieved. Args: None Returns: None """ while self.listening: try: data, address = self.sock.recvfrom(self.bufsize) self.receive_datagram(data, address) if self.stats_enabled: self.stats['bytes_recieved'] += len(data) except socket.error as error: if error.errno == errno.WSAECONNRESET: logger.info("connection reset") else: raise logger.info("Shutting down the listener...")
[ "def", "listen_loop", "(", "self", ")", ":", "while", "self", ".", "listening", ":", "try", ":", "data", ",", "address", "=", "self", ".", "sock", ".", "recvfrom", "(", "self", ".", "bufsize", ")", "self", ".", "receive_datagram", "(", "data", ",", "address", ")", "if", "self", ".", "stats_enabled", ":", "self", ".", "stats", "[", "'bytes_recieved'", "]", "+=", "len", "(", "data", ")", "except", "socket", ".", "error", "as", "error", ":", "if", "error", ".", "errno", "==", "errno", ".", "WSAECONNRESET", ":", "logger", ".", "info", "(", "\"connection reset\"", ")", "else", ":", "raise", "logger", ".", "info", "(", "\"Shutting down the listener...\"", ")" ]
Starts the listen loop and executes the receieve_datagram method whenever a packet is receieved. Args: None Returns: None
[ "Starts", "the", "listen", "loop", "and", "executes", "the", "receieve_datagram", "method", "whenever", "a", "packet", "is", "receieved", "." ]
1a8c976eb2beeca0a5a272a34ac58b2c114495a4
https://github.com/ShadowBlip/Neteria/blob/1a8c976eb2beeca0a5a272a34ac58b2c114495a4/neteria/core.py#L218-L242
train