repository_name
stringlengths
7
55
func_path_in_repository
stringlengths
4
223
func_name
stringlengths
1
134
whole_func_string
stringlengths
75
104k
language
stringclasses
1 value
func_code_string
stringlengths
75
104k
func_code_tokens
listlengths
19
28.4k
func_documentation_string
stringlengths
1
46.9k
func_documentation_tokens
listlengths
1
1.97k
split_name
stringclasses
1 value
func_code_url
stringlengths
87
315
cirruscluster/cirruscluster
cirruscluster/ext/ansible/utils/plugins.py
PluginLoader.find_plugin
def find_plugin(self, name): """Find a plugin named name""" suffix = ".py" if not self.class_name: suffix = "" for i in self._get_paths(): path = os.path.join(i, "%s%s" % (name, suffix)) if os.path.exists(path): return path retu...
python
def find_plugin(self, name): """Find a plugin named name""" suffix = ".py" if not self.class_name: suffix = "" for i in self._get_paths(): path = os.path.join(i, "%s%s" % (name, suffix)) if os.path.exists(path): return path retu...
[ "def", "find_plugin", "(", "self", ",", "name", ")", ":", "suffix", "=", "\".py\"", "if", "not", "self", ".", "class_name", ":", "suffix", "=", "\"\"", "for", "i", "in", "self", ".", "_get_paths", "(", ")", ":", "path", "=", "os", ".", "path", ".",...
Find a plugin named name
[ "Find", "a", "plugin", "named", "name" ]
train
https://github.com/cirruscluster/cirruscluster/blob/977409929dd81322d886425cdced10608117d5d7/cirruscluster/ext/ansible/utils/plugins.py#L87-L96
edeposit/edeposit.amqp.aleph
src/edeposit/amqp/aleph/datastructures/eperiodical_semantic_info.py
EPeriodicalSemanticInfo.from_xml
def from_xml(xml): """ Pick informations from :class:`.MARCXMLRecord` object and use it to build :class:`.SemanticInfo` structure. Args: xml (str/MARCXMLRecord): MarcXML which will be converted to SemanticInfo. In case of str, ``<record>`` tag is required. ...
python
def from_xml(xml): """ Pick informations from :class:`.MARCXMLRecord` object and use it to build :class:`.SemanticInfo` structure. Args: xml (str/MARCXMLRecord): MarcXML which will be converted to SemanticInfo. In case of str, ``<record>`` tag is required. ...
[ "def", "from_xml", "(", "xml", ")", ":", "hasAcquisitionFields", "=", "False", "acquisitionFields", "=", "[", "]", "isClosed", "=", "False", "isSummaryRecord", "=", "False", "contentOfFMT", "=", "\"\"", "parsedSummaryRecordSysNumber", "=", "\"\"", "summaryRecordSysN...
Pick informations from :class:`.MARCXMLRecord` object and use it to build :class:`.SemanticInfo` structure. Args: xml (str/MARCXMLRecord): MarcXML which will be converted to SemanticInfo. In case of str, ``<record>`` tag is required. Returns: structure: ...
[ "Pick", "informations", "from", ":", "class", ":", ".", "MARCXMLRecord", "object", "and", "use", "it", "to", "build", ":", "class", ":", ".", "SemanticInfo", "structure", "." ]
train
https://github.com/edeposit/edeposit.amqp.aleph/blob/360342c0504d5daa2344e864762cdf938d4149c7/src/edeposit/amqp/aleph/datastructures/eperiodical_semantic_info.py#L53-L131
praekelt/jmbo-calendar
jmbo_calendar/admin.py
EventAdmin.get_fieldsets
def get_fieldsets(self, *args, **kwargs): """Re-order fields""" result = super(EventAdmin, self).get_fieldsets(*args, **kwargs) result = list(result) fields = list(result[0][1]['fields']) for name in ('content', 'start', 'end', 'repeat', 'repeat_until', \ 'external_li...
python
def get_fieldsets(self, *args, **kwargs): """Re-order fields""" result = super(EventAdmin, self).get_fieldsets(*args, **kwargs) result = list(result) fields = list(result[0][1]['fields']) for name in ('content', 'start', 'end', 'repeat', 'repeat_until', \ 'external_li...
[ "def", "get_fieldsets", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "result", "=", "super", "(", "EventAdmin", ",", "self", ")", ".", "get_fieldsets", "(", "*", "args", ",", "*", "*", "kwargs", ")", "result", "=", "list", "(",...
Re-order fields
[ "Re", "-", "order", "fields" ]
train
https://github.com/praekelt/jmbo-calendar/blob/ac39f3ad4c155d6755ec5c5a51fb815268b8c18c/jmbo_calendar/admin.py#L36-L46
ludeeus/pyuptimerobot
pyuptimerobot/__init__.py
UptimeRobot.getMonitors
def getMonitors(self, apikey, monitors='none'): """Get departure info from stopid.""" data= 'api_key=' + apikey + '&format=json' if monitors != 'none': data += '&monitors=' + monitors fetchUrl = self.BASE_URL fetchUrl += 'getMonitors' try: monitors...
python
def getMonitors(self, apikey, monitors='none'): """Get departure info from stopid.""" data= 'api_key=' + apikey + '&format=json' if monitors != 'none': data += '&monitors=' + monitors fetchUrl = self.BASE_URL fetchUrl += 'getMonitors' try: monitors...
[ "def", "getMonitors", "(", "self", ",", "apikey", ",", "monitors", "=", "'none'", ")", ":", "data", "=", "'api_key='", "+", "apikey", "+", "'&format=json'", "if", "monitors", "!=", "'none'", ":", "data", "+=", "'&monitors='", "+", "monitors", "fetchUrl", "...
Get departure info from stopid.
[ "Get", "departure", "info", "from", "stopid", "." ]
train
https://github.com/ludeeus/pyuptimerobot/blob/d1bf3964823ef578f60f974356371ac7606040f4/pyuptimerobot/__init__.py#L16-L32
flo-compbio/gopca-server
gpserver/cli.py
add_reporting_args
def add_reporting_args(parser): """Add reporting arguments to an argument parser. Parameters ---------- parser: `argparse.ArgumentParser` Returns ------- `argparse.ArgumentGroup` The argument group created. """ g = parser.add_argument_group('Reporting options') g.add_a...
python
def add_reporting_args(parser): """Add reporting arguments to an argument parser. Parameters ---------- parser: `argparse.ArgumentParser` Returns ------- `argparse.ArgumentGroup` The argument group created. """ g = parser.add_argument_group('Reporting options') g.add_a...
[ "def", "add_reporting_args", "(", "parser", ")", ":", "g", "=", "parser", ".", "add_argument_group", "(", "'Reporting options'", ")", "g", ".", "add_argument", "(", "'-l'", ",", "'--log-file'", ",", "default", "=", "None", ",", "type", "=", "str_type", ",", ...
Add reporting arguments to an argument parser. Parameters ---------- parser: `argparse.ArgumentParser` Returns ------- `argparse.ArgumentGroup` The argument group created.
[ "Add", "reporting", "arguments", "to", "an", "argument", "parser", "." ]
train
https://github.com/flo-compbio/gopca-server/blob/4fe396b12c39c0f156ce3bc4538cade54c9d7ffe/gpserver/cli.py#L67-L91
vietjtnguyen/nut
nut/replay.py
BatchFile.getMessage
def getMessage(self, message): ''' Conveniently retrieves message contents from a batch file. Can throw a :class:`python:RuntimeError` if the message batch filename doesn't match this batch filename. ''' if message.filename != self._filename: raise RuntimeErro...
python
def getMessage(self, message): ''' Conveniently retrieves message contents from a batch file. Can throw a :class:`python:RuntimeError` if the message batch filename doesn't match this batch filename. ''' if message.filename != self._filename: raise RuntimeErro...
[ "def", "getMessage", "(", "self", ",", "message", ")", ":", "if", "message", ".", "filename", "!=", "self", ".", "_filename", ":", "raise", "RuntimeError", "(", "'Message filename ({:}) does not match batch filename ({:}).'", ".", "format", "(", "message", ".", "f...
Conveniently retrieves message contents from a batch file. Can throw a :class:`python:RuntimeError` if the message batch filename doesn't match this batch filename.
[ "Conveniently", "retrieves", "message", "contents", "from", "a", "batch", "file", ".", "Can", "throw", "a", ":", "class", ":", "python", ":", "RuntimeError", "if", "the", "message", "batch", "filename", "doesn", "t", "match", "this", "batch", "filename", "."...
train
https://github.com/vietjtnguyen/nut/blob/3b9c272ebc6d858c790e43d2fc507885d8029d36/nut/replay.py#L60-L74
vietjtnguyen/nut
nut/replay.py
MessageLoader.run
def run(self): ''' Overrides :meth:`python:threading.Thread.run`. ''' global _global_kill for message in self._messages: # Get the message contents from the batch file batch_file = self._getBatchFile(message) message_contents = batch_file.get...
python
def run(self): ''' Overrides :meth:`python:threading.Thread.run`. ''' global _global_kill for message in self._messages: # Get the message contents from the batch file batch_file = self._getBatchFile(message) message_contents = batch_file.get...
[ "def", "run", "(", "self", ")", ":", "global", "_global_kill", "for", "message", "in", "self", ".", "_messages", ":", "# Get the message contents from the batch file", "batch_file", "=", "self", ".", "_getBatchFile", "(", "message", ")", "message_contents", "=", "...
Overrides :meth:`python:threading.Thread.run`.
[ "Overrides", ":", "meth", ":", "python", ":", "threading", ".", "Thread", ".", "run", "." ]
train
https://github.com/vietjtnguyen/nut/blob/3b9c272ebc6d858c790e43d2fc507885d8029d36/nut/replay.py#L157-L186
shaypal5/utilitime
utilitime/datetime/datetime.py
utc_offset_by_timezone
def utc_offset_by_timezone(timezone_name): """Returns the UTC offset of the given timezone in hours. Arguments --------- timezone_name: str A string with a name of a timezone. Returns ------- int The UTC offset of the given timezone, in hours. """ return int(pytz.ti...
python
def utc_offset_by_timezone(timezone_name): """Returns the UTC offset of the given timezone in hours. Arguments --------- timezone_name: str A string with a name of a timezone. Returns ------- int The UTC offset of the given timezone, in hours. """ return int(pytz.ti...
[ "def", "utc_offset_by_timezone", "(", "timezone_name", ")", ":", "return", "int", "(", "pytz", ".", "timezone", "(", "timezone_name", ")", ".", "utcoffset", "(", "utc_time", "(", ")", ")", ".", "total_seconds", "(", ")", "/", "SECONDS_IN_HOUR", ")" ]
Returns the UTC offset of the given timezone in hours. Arguments --------- timezone_name: str A string with a name of a timezone. Returns ------- int The UTC offset of the given timezone, in hours.
[ "Returns", "the", "UTC", "offset", "of", "the", "given", "timezone", "in", "hours", "." ]
train
https://github.com/shaypal5/utilitime/blob/554ca05fa83c2dbf5d6cf9c9cfa6b03ee6cdb609/utilitime/datetime/datetime.py#L29-L43
shaypal5/utilitime
utilitime/datetime/datetime.py
localize_datetime
def localize_datetime(datetime_obj, timezone_name): """Localizes the given UTC-aligned datetime by the given timezone. Arguments --------- datetime_obj : datetime.datetime A datetime object decipting a specific point in time, aligned by UTC. timezone_name: str A string with a name o...
python
def localize_datetime(datetime_obj, timezone_name): """Localizes the given UTC-aligned datetime by the given timezone. Arguments --------- datetime_obj : datetime.datetime A datetime object decipting a specific point in time, aligned by UTC. timezone_name: str A string with a name o...
[ "def", "localize_datetime", "(", "datetime_obj", ",", "timezone_name", ")", ":", "return", "datetime_obj", ".", "replace", "(", "tzinfo", "=", "pytz", ".", "utc", ")", ".", "astimezone", "(", "pytz", ".", "timezone", "(", "timezone_name", ")", ")" ]
Localizes the given UTC-aligned datetime by the given timezone. Arguments --------- datetime_obj : datetime.datetime A datetime object decipting a specific point in time, aligned by UTC. timezone_name: str A string with a name of a timezone. Returns ------- datetime.datetim...
[ "Localizes", "the", "given", "UTC", "-", "aligned", "datetime", "by", "the", "given", "timezone", "." ]
train
https://github.com/shaypal5/utilitime/blob/554ca05fa83c2dbf5d6cf9c9cfa6b03ee6cdb609/utilitime/datetime/datetime.py#L46-L62
eallik/spinoff
spinoff/remoting/pickler.py
IncomingMessageUnpickler._load_build
def _load_build(self): """See `pickle.py` in Python's source code.""" # if the ctor. function (penultimate on the stack) is the `Ref` class... if isinstance(self.stack[-2], Ref): # Ref.__setstate__ will know it's a remote ref if the state is a tuple self.stack[-1] = (self...
python
def _load_build(self): """See `pickle.py` in Python's source code.""" # if the ctor. function (penultimate on the stack) is the `Ref` class... if isinstance(self.stack[-2], Ref): # Ref.__setstate__ will know it's a remote ref if the state is a tuple self.stack[-1] = (self...
[ "def", "_load_build", "(", "self", ")", ":", "# if the ctor. function (penultimate on the stack) is the `Ref` class...", "if", "isinstance", "(", "self", ".", "stack", "[", "-", "2", "]", ",", "Ref", ")", ":", "# Ref.__setstate__ will know it's a remote ref if the state is ...
See `pickle.py` in Python's source code.
[ "See", "pickle", ".", "py", "in", "Python", "s", "source", "code", "." ]
train
https://github.com/eallik/spinoff/blob/06b00d6b86c7422c9cb8f9a4b2915906e92b7d52/spinoff/remoting/pickler.py#L17-L34
edeposit/edeposit.amqp.storage
src/edeposit/amqp/storage/structures/db/shared.py
path_to_zip
def path_to_zip(path): """ Compress `path` to the ZIP. Args: path (str): Path to the directory. Returns: str: Path to the zipped file (in /tmp). """ if not os.path.exists(path): raise IOError("%s doesn't exists!" % path) with tempfile.NamedTemporaryFile(delete=Fals...
python
def path_to_zip(path): """ Compress `path` to the ZIP. Args: path (str): Path to the directory. Returns: str: Path to the zipped file (in /tmp). """ if not os.path.exists(path): raise IOError("%s doesn't exists!" % path) with tempfile.NamedTemporaryFile(delete=Fals...
[ "def", "path_to_zip", "(", "path", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "path", ")", ":", "raise", "IOError", "(", "\"%s doesn't exists!\"", "%", "path", ")", "with", "tempfile", ".", "NamedTemporaryFile", "(", "delete", "=", "Fa...
Compress `path` to the ZIP. Args: path (str): Path to the directory. Returns: str: Path to the zipped file (in /tmp).
[ "Compress", "path", "to", "the", "ZIP", "." ]
train
https://github.com/edeposit/edeposit.amqp.storage/blob/fb6bd326249847de04b17b64e856c878665cea92/src/edeposit/amqp/storage/structures/db/shared.py#L14-L35
edeposit/edeposit.amqp.storage
src/edeposit/amqp/storage/structures/db/shared.py
read_as_base64
def read_as_base64(fn): """ Convert given `fn` to base64 and return it. This method does the process in not-so-much memory consuming way. Args: fn (str): Path to the file which should be converted. Returns: str: File encoded as base64. """ with open(fn) as unpacked_file: ...
python
def read_as_base64(fn): """ Convert given `fn` to base64 and return it. This method does the process in not-so-much memory consuming way. Args: fn (str): Path to the file which should be converted. Returns: str: File encoded as base64. """ with open(fn) as unpacked_file: ...
[ "def", "read_as_base64", "(", "fn", ")", ":", "with", "open", "(", "fn", ")", "as", "unpacked_file", ":", "with", "tempfile", ".", "TemporaryFile", "(", ")", "as", "b64_file", ":", "base64", ".", "encode", "(", "unpacked_file", ",", "b64_file", ")", "b64...
Convert given `fn` to base64 and return it. This method does the process in not-so-much memory consuming way. Args: fn (str): Path to the file which should be converted. Returns: str: File encoded as base64.
[ "Convert", "given", "fn", "to", "base64", "and", "return", "it", ".", "This", "method", "does", "the", "process", "in", "not", "-", "so", "-", "much", "memory", "consuming", "way", "." ]
train
https://github.com/edeposit/edeposit.amqp.storage/blob/fb6bd326249847de04b17b64e856c878665cea92/src/edeposit/amqp/storage/structures/db/shared.py#L38-L55
hkff/FodtlMon
fodtlmon/tools/color.py
_pad_input
def _pad_input(incoming): """Avoid IndexError and KeyError by ignoring un-related fields. Example: '{0}{autored}' becomes '{{0}}{autored}'. Positional arguments: incoming -- the input unicode value. Returns: Padded unicode value. """ incoming_expanded = incoming.replace('{', '{{').rep...
python
def _pad_input(incoming): """Avoid IndexError and KeyError by ignoring un-related fields. Example: '{0}{autored}' becomes '{{0}}{autored}'. Positional arguments: incoming -- the input unicode value. Returns: Padded unicode value. """ incoming_expanded = incoming.replace('{', '{{').rep...
[ "def", "_pad_input", "(", "incoming", ")", ":", "incoming_expanded", "=", "incoming", ".", "replace", "(", "'{'", ",", "'{{'", ")", ".", "replace", "(", "'}'", ",", "'}}'", ")", "for", "key", "in", "_BASE_CODES", ":", "before", ",", "after", "=", "'{{%...
Avoid IndexError and KeyError by ignoring un-related fields. Example: '{0}{autored}' becomes '{{0}}{autored}'. Positional arguments: incoming -- the input unicode value. Returns: Padded unicode value.
[ "Avoid", "IndexError", "and", "KeyError", "by", "ignoring", "un", "-", "related", "fields", "." ]
train
https://github.com/hkff/FodtlMon/blob/0c9015a1a1f0a4a64d52945c86b45441d5871c56/fodtlmon/tools/color.py#L218-L234
hkff/FodtlMon
fodtlmon/tools/color.py
_parse_input
def _parse_input(incoming): """Performs the actual conversion of tags to ANSI escaped codes. Provides a version of the input without any colors for len() and other methods. Positional arguments: incoming -- the input unicode value. Returns: 2-item tuple. First item is the parsed output. Secon...
python
def _parse_input(incoming): """Performs the actual conversion of tags to ANSI escaped codes. Provides a version of the input without any colors for len() and other methods. Positional arguments: incoming -- the input unicode value. Returns: 2-item tuple. First item is the parsed output. Secon...
[ "def", "_parse_input", "(", "incoming", ")", ":", "codes", "=", "dict", "(", "(", "k", ",", "v", ")", "for", "k", ",", "v", "in", "_AutoCodes", "(", ")", ".", "items", "(", ")", "if", "'{%s}'", "%", "k", "in", "incoming", ")", "color_codes", "=",...
Performs the actual conversion of tags to ANSI escaped codes. Provides a version of the input without any colors for len() and other methods. Positional arguments: incoming -- the input unicode value. Returns: 2-item tuple. First item is the parsed output. Second item is a version of the input wi...
[ "Performs", "the", "actual", "conversion", "of", "tags", "to", "ANSI", "escaped", "codes", "." ]
train
https://github.com/hkff/FodtlMon/blob/0c9015a1a1f0a4a64d52945c86b45441d5871c56/fodtlmon/tools/color.py#L237-L267
hkff/FodtlMon
fodtlmon/tools/color.py
list_tags
def list_tags(): """Lists the available tags. Returns: Tuple of tuples. Child tuples are four items: ('opening tag', 'closing tag', main ansi value, closing ansi value). """ codes = _AutoCodes() grouped = set([(k, '/{0}'.format(k), codes[k], codes['/{0}'.format(k)]) for k in codes if not k.star...
python
def list_tags(): """Lists the available tags. Returns: Tuple of tuples. Child tuples are four items: ('opening tag', 'closing tag', main ansi value, closing ansi value). """ codes = _AutoCodes() grouped = set([(k, '/{0}'.format(k), codes[k], codes['/{0}'.format(k)]) for k in codes if not k.star...
[ "def", "list_tags", "(", ")", ":", "codes", "=", "_AutoCodes", "(", ")", "grouped", "=", "set", "(", "[", "(", "k", ",", "'/{0}'", ".", "format", "(", "k", ")", ",", "codes", "[", "k", "]", ",", "codes", "[", "'/{0}'", ".", "format", "(", "k", ...
Lists the available tags. Returns: Tuple of tuples. Child tuples are four items: ('opening tag', 'closing tag', main ansi value, closing ansi value).
[ "Lists", "the", "available", "tags", "." ]
train
https://github.com/hkff/FodtlMon/blob/0c9015a1a1f0a4a64d52945c86b45441d5871c56/fodtlmon/tools/color.py#L287-L312
hkff/FodtlMon
fodtlmon/tools/color.py
Windows.disable
def disable(): """Restore sys.stderr and sys.stdout to their original objects. Resets colors to their original values.""" if os.name != 'nt' or not Windows.is_enabled(): return False getattr(sys.stderr, '_reset_colors', lambda: False)() getattr(sys.stdout, '_reset_colors', l...
python
def disable(): """Restore sys.stderr and sys.stdout to their original objects. Resets colors to their original values.""" if os.name != 'nt' or not Windows.is_enabled(): return False getattr(sys.stderr, '_reset_colors', lambda: False)() getattr(sys.stdout, '_reset_colors', l...
[ "def", "disable", "(", ")", ":", "if", "os", ".", "name", "!=", "'nt'", "or", "not", "Windows", ".", "is_enabled", "(", ")", ":", "return", "False", "getattr", "(", "sys", ".", "stderr", ",", "'_reset_colors'", ",", "lambda", ":", "False", ")", "(", ...
Restore sys.stderr and sys.stdout to their original objects. Resets colors to their original values.
[ "Restore", "sys", ".", "stderr", "and", "sys", ".", "stdout", "to", "their", "original", "objects", ".", "Resets", "colors", "to", "their", "original", "values", "." ]
train
https://github.com/hkff/FodtlMon/blob/0c9015a1a1f0a4a64d52945c86b45441d5871c56/fodtlmon/tools/color.py#L483-L496
hkff/FodtlMon
fodtlmon/tools/color.py
Windows.enable
def enable(auto_colors=False, reset_atexit=False): """Enables color text with print() or sys.stdout.write() (stderr too). Keyword arguments: auto_colors -- automatically selects dark or light colors based on current terminal's background color. Only works with {autored} and related ...
python
def enable(auto_colors=False, reset_atexit=False): """Enables color text with print() or sys.stdout.write() (stderr too). Keyword arguments: auto_colors -- automatically selects dark or light colors based on current terminal's background color. Only works with {autored} and related ...
[ "def", "enable", "(", "auto_colors", "=", "False", ",", "reset_atexit", "=", "False", ")", ":", "if", "os", ".", "name", "!=", "'nt'", ":", "return", "False", "# Overwrite stream references.", "if", "not", "isinstance", "(", "sys", ".", "stderr", ",", "_Wi...
Enables color text with print() or sys.stdout.write() (stderr too). Keyword arguments: auto_colors -- automatically selects dark or light colors based on current terminal's background color. Only works with {autored} and related tags. reset_atexit -- resets original colors upon Pyth...
[ "Enables", "color", "text", "with", "print", "()", "or", "sys", ".", "stdout", ".", "write", "()", "(", "stderr", "too", ")", "." ]
train
https://github.com/hkff/FodtlMon/blob/0c9015a1a1f0a4a64d52945c86b45441d5871c56/fodtlmon/tools/color.py#L504-L535
hkff/FodtlMon
fodtlmon/tools/color.py
_WindowsStream._get_colors
def _get_colors(self): """Returns a tuple of two integers representing current colors: (foreground, background).""" try: csbi = _WindowsCSBI.get_info(self.win32_stream_handle) return csbi['fg_color'], csbi['bg_color'] except IOError: return 7, 0
python
def _get_colors(self): """Returns a tuple of two integers representing current colors: (foreground, background).""" try: csbi = _WindowsCSBI.get_info(self.win32_stream_handle) return csbi['fg_color'], csbi['bg_color'] except IOError: return 7, 0
[ "def", "_get_colors", "(", "self", ")", ":", "try", ":", "csbi", "=", "_WindowsCSBI", ".", "get_info", "(", "self", ".", "win32_stream_handle", ")", "return", "csbi", "[", "'fg_color'", "]", ",", "csbi", "[", "'bg_color'", "]", "except", "IOError", ":", ...
Returns a tuple of two integers representing current colors: (foreground, background).
[ "Returns", "a", "tuple", "of", "two", "integers", "representing", "current", "colors", ":", "(", "foreground", "background", ")", "." ]
train
https://github.com/hkff/FodtlMon/blob/0c9015a1a1f0a4a64d52945c86b45441d5871c56/fodtlmon/tools/color.py#L693-L699
hkff/FodtlMon
fodtlmon/tools/color.py
_WindowsStream._set_color
def _set_color(self, color_code): """Changes the foreground and background colors for subsequently printed characters. Since setting a color requires including both foreground and background codes (merged), setting just the foreground color resets the background color to black, and vice versa. ...
python
def _set_color(self, color_code): """Changes the foreground and background colors for subsequently printed characters. Since setting a color requires including both foreground and background codes (merged), setting just the foreground color resets the background color to black, and vice versa. ...
[ "def", "_set_color", "(", "self", ",", "color_code", ")", ":", "# Get current color code.", "current_fg", ",", "current_bg", "=", "self", ".", "_get_colors", "(", ")", "# Handle special negative codes. Also determine the final color code.", "if", "color_code", "==", "-", ...
Changes the foreground and background colors for subsequently printed characters. Since setting a color requires including both foreground and background codes (merged), setting just the foreground color resets the background color to black, and vice versa. This function first gets the current...
[ "Changes", "the", "foreground", "and", "background", "colors", "for", "subsequently", "printed", "characters", "." ]
train
https://github.com/hkff/FodtlMon/blob/0c9015a1a1f0a4a64d52945c86b45441d5871c56/fodtlmon/tools/color.py#L705-L738
af/turrentine
turrentine/views.py
PageView.get_mimetype
def get_mimetype(self): """ Use the ending of the template name to infer response's Content-Type header. """ template_name = self.get_template_names()[0] for extension, mimetype in turrentine_settings.TURRENTINE_MIMETYPE_EXTENSIONS: if template_name.endswith(extension...
python
def get_mimetype(self): """ Use the ending of the template name to infer response's Content-Type header. """ template_name = self.get_template_names()[0] for extension, mimetype in turrentine_settings.TURRENTINE_MIMETYPE_EXTENSIONS: if template_name.endswith(extension...
[ "def", "get_mimetype", "(", "self", ")", ":", "template_name", "=", "self", ".", "get_template_names", "(", ")", "[", "0", "]", "for", "extension", ",", "mimetype", "in", "turrentine_settings", ".", "TURRENTINE_MIMETYPE_EXTENSIONS", ":", "if", "template_name", "...
Use the ending of the template name to infer response's Content-Type header.
[ "Use", "the", "ending", "of", "the", "template", "name", "to", "infer", "response", "s", "Content", "-", "Type", "header", "." ]
train
https://github.com/af/turrentine/blob/bbbd5139744ccc6264595cc8960784e5c308c009/turrentine/views.py#L37-L45
af/turrentine
turrentine/views.py
PageView.get
def get(self, request, *args, **kwargs): """ Check user authentication if the page requires a login. We could do this by overriding dispatch() instead, but we assume that only GET requests will be required by the CMS pages. """ try: page = self.object = self....
python
def get(self, request, *args, **kwargs): """ Check user authentication if the page requires a login. We could do this by overriding dispatch() instead, but we assume that only GET requests will be required by the CMS pages. """ try: page = self.object = self....
[ "def", "get", "(", "self", ",", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "try", ":", "page", "=", "self", ".", "object", "=", "self", ".", "get_object", "(", ")", "except", "Http404", ":", "# If APPEND_SLASH is set and our url has ...
Check user authentication if the page requires a login. We could do this by overriding dispatch() instead, but we assume that only GET requests will be required by the CMS pages.
[ "Check", "user", "authentication", "if", "the", "page", "requires", "a", "login", "." ]
train
https://github.com/af/turrentine/blob/bbbd5139744ccc6264595cc8960784e5c308c009/turrentine/views.py#L47-L76
af/turrentine
turrentine/views.py
PageView._try_url_with_appended_slash
def _try_url_with_appended_slash(self): """ Try our URL with an appended slash. If a CMS page is found at that URL, redirect to it. If no page is found at that URL, raise Http404. """ new_url_to_try = self.kwargs.get('path', '') + '/' if not new_url_to_try.startswith('/')...
python
def _try_url_with_appended_slash(self): """ Try our URL with an appended slash. If a CMS page is found at that URL, redirect to it. If no page is found at that URL, raise Http404. """ new_url_to_try = self.kwargs.get('path', '') + '/' if not new_url_to_try.startswith('/')...
[ "def", "_try_url_with_appended_slash", "(", "self", ")", ":", "new_url_to_try", "=", "self", ".", "kwargs", ".", "get", "(", "'path'", ",", "''", ")", "+", "'/'", "if", "not", "new_url_to_try", ".", "startswith", "(", "'/'", ")", ":", "new_url_to_try", "="...
Try our URL with an appended slash. If a CMS page is found at that URL, redirect to it. If no page is found at that URL, raise Http404.
[ "Try", "our", "URL", "with", "an", "appended", "slash", ".", "If", "a", "CMS", "page", "is", "found", "at", "that", "URL", "redirect", "to", "it", ".", "If", "no", "page", "is", "found", "at", "that", "URL", "raise", "Http404", "." ]
train
https://github.com/af/turrentine/blob/bbbd5139744ccc6264595cc8960784e5c308c009/turrentine/views.py#L78-L89
af/turrentine
turrentine/views.py
PageView._mark_html_fields_as_safe
def _mark_html_fields_as_safe(self, page): """ Mark the html content as safe so we don't have to use the safe template tag in all cms templates: """ page.title = mark_safe(page.title) page.content = mark_safe(page.content) return page
python
def _mark_html_fields_as_safe(self, page): """ Mark the html content as safe so we don't have to use the safe template tag in all cms templates: """ page.title = mark_safe(page.title) page.content = mark_safe(page.content) return page
[ "def", "_mark_html_fields_as_safe", "(", "self", ",", "page", ")", ":", "page", ".", "title", "=", "mark_safe", "(", "page", ".", "title", ")", "page", ".", "content", "=", "mark_safe", "(", "page", ".", "content", ")", "return", "page" ]
Mark the html content as safe so we don't have to use the safe template tag in all cms templates:
[ "Mark", "the", "html", "content", "as", "safe", "so", "we", "don", "t", "have", "to", "use", "the", "safe", "template", "tag", "in", "all", "cms", "templates", ":" ]
train
https://github.com/af/turrentine/blob/bbbd5139744ccc6264595cc8960784e5c308c009/turrentine/views.py#L91-L98
sveetch/py-css-styleguide
py_css_styleguide/serializer.py
ManifestSerializer.validate_rule_name
def validate_rule_name(self, name): """ Validate rule name. Arguments: name (string): Rule name. Returns: bool: ``True`` if rule name is valid. """ if not name: raise SerializerError("Rule name is empty".format(name)) if name...
python
def validate_rule_name(self, name): """ Validate rule name. Arguments: name (string): Rule name. Returns: bool: ``True`` if rule name is valid. """ if not name: raise SerializerError("Rule name is empty".format(name)) if name...
[ "def", "validate_rule_name", "(", "self", ",", "name", ")", ":", "if", "not", "name", ":", "raise", "SerializerError", "(", "\"Rule name is empty\"", ".", "format", "(", "name", ")", ")", "if", "name", "[", "0", "]", "not", "in", "RULE_ALLOWED_START", ":",...
Validate rule name. Arguments: name (string): Rule name. Returns: bool: ``True`` if rule name is valid.
[ "Validate", "rule", "name", "." ]
train
https://github.com/sveetch/py-css-styleguide/blob/5acc693f71b2fa7d944d7fed561ae0a7699ccd0f/py_css_styleguide/serializer.py#L46-L69
sveetch/py-css-styleguide
py_css_styleguide/serializer.py
ManifestSerializer.validate_variable_name
def validate_variable_name(self, name): """ Validate variable name. Arguments: name (string): Property name. Returns: bool: ``True`` if variable name is valid. """ if not name: raise SerializerError("Variable name is empty".format(nam...
python
def validate_variable_name(self, name): """ Validate variable name. Arguments: name (string): Property name. Returns: bool: ``True`` if variable name is valid. """ if not name: raise SerializerError("Variable name is empty".format(nam...
[ "def", "validate_variable_name", "(", "self", ",", "name", ")", ":", "if", "not", "name", ":", "raise", "SerializerError", "(", "\"Variable name is empty\"", ".", "format", "(", "name", ")", ")", "if", "name", "[", "0", "]", "not", "in", "PROPERTY_ALLOWED_ST...
Validate variable name. Arguments: name (string): Property name. Returns: bool: ``True`` if variable name is valid.
[ "Validate", "variable", "name", "." ]
train
https://github.com/sveetch/py-css-styleguide/blob/5acc693f71b2fa7d944d7fed561ae0a7699ccd0f/py_css_styleguide/serializer.py#L71-L94
sveetch/py-css-styleguide
py_css_styleguide/serializer.py
ManifestSerializer.value_splitter
def value_splitter(self, reference, prop, value, mode): """ Split a string into a list items. Default behavior is to split on white spaces. Arguments: reference (string): Reference name used when raising possible error. prop (string): Property n...
python
def value_splitter(self, reference, prop, value, mode): """ Split a string into a list items. Default behavior is to split on white spaces. Arguments: reference (string): Reference name used when raising possible error. prop (string): Property n...
[ "def", "value_splitter", "(", "self", ",", "reference", ",", "prop", ",", "value", ",", "mode", ")", ":", "items", "=", "[", "]", "if", "mode", "==", "'json-list'", ":", "try", ":", "items", "=", "json", ".", "loads", "(", "value", ")", "except", "...
Split a string into a list items. Default behavior is to split on white spaces. Arguments: reference (string): Reference name used when raising possible error. prop (string): Property name used when raising possible error. value (string): Property v...
[ "Split", "a", "string", "into", "a", "list", "items", "." ]
train
https://github.com/sveetch/py-css-styleguide/blob/5acc693f71b2fa7d944d7fed561ae0a7699ccd0f/py_css_styleguide/serializer.py#L96-L134
sveetch/py-css-styleguide
py_css_styleguide/serializer.py
ManifestSerializer.serialize_to_json
def serialize_to_json(self, name, datas): """ Serialize given datas to any object from assumed JSON string. Arguments: name (string): Name only used inside possible exception message. datas (dict): Datas to serialize. Returns: object: Object dependin...
python
def serialize_to_json(self, name, datas): """ Serialize given datas to any object from assumed JSON string. Arguments: name (string): Name only used inside possible exception message. datas (dict): Datas to serialize. Returns: object: Object dependin...
[ "def", "serialize_to_json", "(", "self", ",", "name", ",", "datas", ")", ":", "data_object", "=", "datas", ".", "get", "(", "'object'", ",", "None", ")", "if", "data_object", "is", "None", ":", "msg", "=", "(", "\"JSON reference '{}' lacks of required 'object'...
Serialize given datas to any object from assumed JSON string. Arguments: name (string): Name only used inside possible exception message. datas (dict): Datas to serialize. Returns: object: Object depending from JSON content.
[ "Serialize", "given", "datas", "to", "any", "object", "from", "assumed", "JSON", "string", "." ]
train
https://github.com/sveetch/py-css-styleguide/blob/5acc693f71b2fa7d944d7fed561ae0a7699ccd0f/py_css_styleguide/serializer.py#L136-L159
sveetch/py-css-styleguide
py_css_styleguide/serializer.py
ManifestSerializer.serialize_to_nested
def serialize_to_nested(self, name, datas): """ Serialize given datas to a nested structure where each key create an item and each other variable is stored as a subitem with corresponding value (according to key index position). Arguments: name (string): Name only us...
python
def serialize_to_nested(self, name, datas): """ Serialize given datas to a nested structure where each key create an item and each other variable is stored as a subitem with corresponding value (according to key index position). Arguments: name (string): Name only us...
[ "def", "serialize_to_nested", "(", "self", ",", "name", ",", "datas", ")", ":", "keys", "=", "datas", ".", "get", "(", "'keys'", ",", "None", ")", "splitter", "=", "datas", ".", "get", "(", "'splitter'", ",", "self", ".", "_DEFAULT_SPLITTER", ")", "if"...
Serialize given datas to a nested structure where each key create an item and each other variable is stored as a subitem with corresponding value (according to key index position). Arguments: name (string): Name only used inside possible exception message. datas (dict): ...
[ "Serialize", "given", "datas", "to", "a", "nested", "structure", "where", "each", "key", "create", "an", "item", "and", "each", "other", "variable", "is", "stored", "as", "a", "subitem", "with", "corresponding", "value", "(", "according", "to", "key", "index...
train
https://github.com/sveetch/py-css-styleguide/blob/5acc693f71b2fa7d944d7fed561ae0a7699ccd0f/py_css_styleguide/serializer.py#L161-L205
sveetch/py-css-styleguide
py_css_styleguide/serializer.py
ManifestSerializer.serialize_to_flat
def serialize_to_flat(self, name, datas): """ Serialize given datas to a flat structure ``KEY:VALUE`` where ``KEY`` comes from ``keys`` variable and ``VALUE`` comes from ``values`` variable. This means both ``keys`` and ``values`` are required variable to be correctly fi...
python
def serialize_to_flat(self, name, datas): """ Serialize given datas to a flat structure ``KEY:VALUE`` where ``KEY`` comes from ``keys`` variable and ``VALUE`` comes from ``values`` variable. This means both ``keys`` and ``values`` are required variable to be correctly fi...
[ "def", "serialize_to_flat", "(", "self", ",", "name", ",", "datas", ")", ":", "keys", "=", "datas", ".", "get", "(", "'keys'", ",", "None", ")", "values", "=", "datas", ".", "get", "(", "'values'", ",", "None", ")", "splitter", "=", "datas", ".", "...
Serialize given datas to a flat structure ``KEY:VALUE`` where ``KEY`` comes from ``keys`` variable and ``VALUE`` comes from ``values`` variable. This means both ``keys`` and ``values`` are required variable to be correctly filled (each one is a string of item separated with an empty ...
[ "Serialize", "given", "datas", "to", "a", "flat", "structure", "KEY", ":", "VALUE", "where", "KEY", "comes", "from", "keys", "variable", "and", "VALUE", "comes", "from", "values", "variable", "." ]
train
https://github.com/sveetch/py-css-styleguide/blob/5acc693f71b2fa7d944d7fed561ae0a7699ccd0f/py_css_styleguide/serializer.py#L207-L247
sveetch/py-css-styleguide
py_css_styleguide/serializer.py
ManifestSerializer.serialize_to_list
def serialize_to_list(self, name, datas): """ Serialize given datas to a list structure. List structure is very simple and only require a variable ``--items`` which is a string of values separated with an empty space. Every other properties are ignored. Arguments: ...
python
def serialize_to_list(self, name, datas): """ Serialize given datas to a list structure. List structure is very simple and only require a variable ``--items`` which is a string of values separated with an empty space. Every other properties are ignored. Arguments: ...
[ "def", "serialize_to_list", "(", "self", ",", "name", ",", "datas", ")", ":", "items", "=", "datas", ".", "get", "(", "'items'", ",", "None", ")", "splitter", "=", "datas", ".", "get", "(", "'splitter'", ",", "self", ".", "_DEFAULT_SPLITTER", ")", "if"...
Serialize given datas to a list structure. List structure is very simple and only require a variable ``--items`` which is a string of values separated with an empty space. Every other properties are ignored. Arguments: name (string): Name only used inside possible exception...
[ "Serialize", "given", "datas", "to", "a", "list", "structure", "." ]
train
https://github.com/sveetch/py-css-styleguide/blob/5acc693f71b2fa7d944d7fed561ae0a7699ccd0f/py_css_styleguide/serializer.py#L249-L274
sveetch/py-css-styleguide
py_css_styleguide/serializer.py
ManifestSerializer.serialize_to_string
def serialize_to_string(self, name, datas): """ Serialize given datas to a string. Simply return the value from required variable``value``. Arguments: name (string): Name only used inside possible exception message. datas (dict): Datas to serialize. Ret...
python
def serialize_to_string(self, name, datas): """ Serialize given datas to a string. Simply return the value from required variable``value``. Arguments: name (string): Name only used inside possible exception message. datas (dict): Datas to serialize. Ret...
[ "def", "serialize_to_string", "(", "self", ",", "name", ",", "datas", ")", ":", "value", "=", "datas", ".", "get", "(", "'value'", ",", "None", ")", "if", "value", "is", "None", ":", "msg", "=", "(", "\"String reference '{}' lacks of required 'value' variable ...
Serialize given datas to a string. Simply return the value from required variable``value``. Arguments: name (string): Name only used inside possible exception message. datas (dict): Datas to serialize. Returns: string: Value.
[ "Serialize", "given", "datas", "to", "a", "string", "." ]
train
https://github.com/sveetch/py-css-styleguide/blob/5acc693f71b2fa7d944d7fed561ae0a7699ccd0f/py_css_styleguide/serializer.py#L276-L296
sveetch/py-css-styleguide
py_css_styleguide/serializer.py
ManifestSerializer.get_meta_references
def get_meta_references(self, datas): """ Get manifest enabled references declaration This required declaration is readed from ``styleguide-metas-references`` rule that require either a ``--names`` or ``--auto`` variable, each one define the mode to enable reference: Ma...
python
def get_meta_references(self, datas): """ Get manifest enabled references declaration This required declaration is readed from ``styleguide-metas-references`` rule that require either a ``--names`` or ``--auto`` variable, each one define the mode to enable reference: Ma...
[ "def", "get_meta_references", "(", "self", ",", "datas", ")", ":", "rule", "=", "datas", ".", "get", "(", "RULE_META_REFERENCES", ",", "{", "}", ")", "if", "not", "rule", ":", "msg", "=", "\"Manifest lacks of '.{}' or is empty\"", "raise", "SerializerError", "...
Get manifest enabled references declaration This required declaration is readed from ``styleguide-metas-references`` rule that require either a ``--names`` or ``--auto`` variable, each one define the mode to enable reference: Manually Using ``--names`` which define a list o...
[ "Get", "manifest", "enabled", "references", "declaration" ]
train
https://github.com/sveetch/py-css-styleguide/blob/5acc693f71b2fa7d944d7fed561ae0a7699ccd0f/py_css_styleguide/serializer.py#L298-L344
sveetch/py-css-styleguide
py_css_styleguide/serializer.py
ManifestSerializer.get_reference
def get_reference(self, datas, name): """ Get serialized reference datas Because every reference is turned to a dict (that stands on ``keys`` variable that is a list of key names), every variables must have the same exact length of word than the key name list. A referen...
python
def get_reference(self, datas, name): """ Get serialized reference datas Because every reference is turned to a dict (that stands on ``keys`` variable that is a list of key names), every variables must have the same exact length of word than the key name list. A referen...
[ "def", "get_reference", "(", "self", ",", "datas", ",", "name", ")", ":", "rule_name", "=", "'-'", ".", "join", "(", "(", "RULE_REFERENCE", ",", "name", ")", ")", "structure_mode", "=", "'nested'", "if", "rule_name", "not", "in", "datas", ":", "msg", "...
Get serialized reference datas Because every reference is turned to a dict (that stands on ``keys`` variable that is a list of key names), every variables must have the same exact length of word than the key name list. A reference name starts with 'styleguide-reference-' followed by ...
[ "Get", "serialized", "reference", "datas" ]
train
https://github.com/sveetch/py-css-styleguide/blob/5acc693f71b2fa7d944d7fed561ae0a7699ccd0f/py_css_styleguide/serializer.py#L346-L410
sveetch/py-css-styleguide
py_css_styleguide/serializer.py
ManifestSerializer.get_available_references
def get_available_references(self, datas): """ Get available manifest reference names. Every rules starting with prefix from ``nomenclature.RULE_REFERENCE`` are available references. Only name validation is performed on these references. Arguments: datas (d...
python
def get_available_references(self, datas): """ Get available manifest reference names. Every rules starting with prefix from ``nomenclature.RULE_REFERENCE`` are available references. Only name validation is performed on these references. Arguments: datas (d...
[ "def", "get_available_references", "(", "self", ",", "datas", ")", ":", "names", "=", "[", "]", "for", "k", ",", "v", "in", "datas", ".", "items", "(", ")", ":", "if", "k", ".", "startswith", "(", "RULE_REFERENCE", ")", ":", "names", ".", "append", ...
Get available manifest reference names. Every rules starting with prefix from ``nomenclature.RULE_REFERENCE`` are available references. Only name validation is performed on these references. Arguments: datas (dict): Data where to search for reference declarations. ...
[ "Get", "available", "manifest", "reference", "names", "." ]
train
https://github.com/sveetch/py-css-styleguide/blob/5acc693f71b2fa7d944d7fed561ae0a7699ccd0f/py_css_styleguide/serializer.py#L412-L434
sveetch/py-css-styleguide
py_css_styleguide/serializer.py
ManifestSerializer.get_enabled_references
def get_enabled_references(self, datas, meta_references): """ Get enabled manifest references declarations. Enabled references are defined through meta references declaration, every other references are ignored. Arguments: datas (dict): Data where to search for refe...
python
def get_enabled_references(self, datas, meta_references): """ Get enabled manifest references declarations. Enabled references are defined through meta references declaration, every other references are ignored. Arguments: datas (dict): Data where to search for refe...
[ "def", "get_enabled_references", "(", "self", ",", "datas", ",", "meta_references", ")", ":", "references", "=", "OrderedDict", "(", ")", "for", "section", "in", "meta_references", ":", "references", "[", "section", "]", "=", "self", ".", "get_reference", "(",...
Get enabled manifest references declarations. Enabled references are defined through meta references declaration, every other references are ignored. Arguments: datas (dict): Data where to search for reference declarations. This is commonly the fully parsed manifest...
[ "Get", "enabled", "manifest", "references", "declarations", "." ]
train
https://github.com/sveetch/py-css-styleguide/blob/5acc693f71b2fa7d944d7fed561ae0a7699ccd0f/py_css_styleguide/serializer.py#L436-L456
sveetch/py-css-styleguide
py_css_styleguide/serializer.py
ManifestSerializer.serialize
def serialize(self, datas): """ Serialize datas to manifest structure with metas and references. Only references are returned, metas are assigned to attribute ``ManifestSerializer._metas``. Arguments: datas (dict): Data where to search for reference declarations. Th...
python
def serialize(self, datas): """ Serialize datas to manifest structure with metas and references. Only references are returned, metas are assigned to attribute ``ManifestSerializer._metas``. Arguments: datas (dict): Data where to search for reference declarations. Th...
[ "def", "serialize", "(", "self", ",", "datas", ")", ":", "self", ".", "_metas", "=", "OrderedDict", "(", "{", "'references'", ":", "self", ".", "get_meta_references", "(", "datas", ")", ",", "}", ")", "return", "self", ".", "get_enabled_references", "(", ...
Serialize datas to manifest structure with metas and references. Only references are returned, metas are assigned to attribute ``ManifestSerializer._metas``. Arguments: datas (dict): Data where to search for reference declarations. This is commonly the fully parsed ...
[ "Serialize", "datas", "to", "manifest", "structure", "with", "metas", "and", "references", "." ]
train
https://github.com/sveetch/py-css-styleguide/blob/5acc693f71b2fa7d944d7fed561ae0a7699ccd0f/py_css_styleguide/serializer.py#L458-L476
aganezov/gos
gos/configuration.py
Configuration.update_with_default_values
def update_with_default_values(self): """ Goes through all the configuration fields and predefines empty ones with default values Top level: `dir` field is predefined with current working directory value, in case of empty string or `None` `io_silent_fail` field if predefined wit...
python
def update_with_default_values(self): """ Goes through all the configuration fields and predefines empty ones with default values Top level: `dir` field is predefined with current working directory value, in case of empty string or `None` `io_silent_fail` field if predefined wit...
[ "def", "update_with_default_values", "(", "self", ")", ":", "if", "self", "[", "self", ".", "DIR", "]", "in", "(", "\"\"", ",", "None", ")", ":", "self", "[", "self", ".", "DIR", "]", "=", "os", ".", "getcwd", "(", ")", "if", "self", "[", "self",...
Goes through all the configuration fields and predefines empty ones with default values Top level: `dir` field is predefined with current working directory value, in case of empty string or `None` `io_silent_fail` field if predefined with :attr:`Configuration.DEFAULT_IOSF` in case of No...
[ "Goes", "through", "all", "the", "configuration", "fields", "and", "predefines", "empty", "ones", "with", "default", "values" ]
train
https://github.com/aganezov/gos/blob/fb4d210284f3037c5321250cb95f3901754feb6b/gos/configuration.py#L256-L436
minhhoit/yacms
yacms/generic/fields.py
BaseGenericRelation.contribute_to_class
def contribute_to_class(self, cls, name): """ Add each of the names and fields in the ``fields`` attribute to the model the relationship field is applied to, and set up the related item save and delete signals for calling ``related_items_changed``. """ for field i...
python
def contribute_to_class(self, cls, name): """ Add each of the names and fields in the ``fields`` attribute to the model the relationship field is applied to, and set up the related item save and delete signals for calling ``related_items_changed``. """ for field i...
[ "def", "contribute_to_class", "(", "self", ",", "cls", ",", "name", ")", ":", "for", "field", "in", "cls", ".", "_meta", ".", "many_to_many", ":", "if", "isinstance", "(", "field", ",", "self", ".", "__class__", ")", ":", "e", "=", "\"Multiple %s fields ...
Add each of the names and fields in the ``fields`` attribute to the model the relationship field is applied to, and set up the related item save and delete signals for calling ``related_items_changed``.
[ "Add", "each", "of", "the", "names", "and", "fields", "in", "the", "fields", "attribute", "to", "the", "model", "the", "relationship", "field", "is", "applied", "to", "and", "set", "up", "the", "related", "item", "save", "and", "delete", "signals", "for", ...
train
https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/generic/fields.py#L57-L90
minhhoit/yacms
yacms/generic/fields.py
BaseGenericRelation._related_items_changed
def _related_items_changed(self, **kwargs): """ Ensure that the given related item is actually for the model this field applies to, and pass the instance to the real ``related_items_changed`` handler. """ for_model = kwargs["instance"].content_type.model_class() i...
python
def _related_items_changed(self, **kwargs): """ Ensure that the given related item is actually for the model this field applies to, and pass the instance to the real ``related_items_changed`` handler. """ for_model = kwargs["instance"].content_type.model_class() i...
[ "def", "_related_items_changed", "(", "self", ",", "*", "*", "kwargs", ")", ":", "for_model", "=", "kwargs", "[", "\"instance\"", "]", ".", "content_type", ".", "model_class", "(", ")", "if", "for_model", "and", "issubclass", "(", "for_model", ",", "self", ...
Ensure that the given related item is actually for the model this field applies to, and pass the instance to the real ``related_items_changed`` handler.
[ "Ensure", "that", "the", "given", "related", "item", "is", "actually", "for", "the", "model", "this", "field", "applies", "to", "and", "pass", "the", "instance", "to", "the", "real", "related_items_changed", "handler", "." ]
train
https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/generic/fields.py#L92-L109
minhhoit/yacms
yacms/generic/fields.py
CommentsField.related_items_changed
def related_items_changed(self, instance, related_manager): """ Stores the number of comments. A custom ``count_filter`` queryset gets checked for, allowing managers to implement custom count logic. """ try: count = related_manager.count_queryset() exc...
python
def related_items_changed(self, instance, related_manager): """ Stores the number of comments. A custom ``count_filter`` queryset gets checked for, allowing managers to implement custom count logic. """ try: count = related_manager.count_queryset() exc...
[ "def", "related_items_changed", "(", "self", ",", "instance", ",", "related_manager", ")", ":", "try", ":", "count", "=", "related_manager", ".", "count_queryset", "(", ")", "except", "AttributeError", ":", "count", "=", "related_manager", ".", "count", "(", "...
Stores the number of comments. A custom ``count_filter`` queryset gets checked for, allowing managers to implement custom count logic.
[ "Stores", "the", "number", "of", "comments", ".", "A", "custom", "count_filter", "queryset", "gets", "checked", "for", "allowing", "managers", "to", "implement", "custom", "count", "logic", "." ]
train
https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/generic/fields.py#L138-L151
minhhoit/yacms
yacms/generic/fields.py
KeywordsField.formfield
def formfield(self, **kwargs): """ Provide the custom form widget for the admin, since there isn't a form field mapped to ``GenericRelation`` model fields. """ from yacms.generic.forms import KeywordsWidget kwargs["widget"] = KeywordsWidget return super(KeywordsFi...
python
def formfield(self, **kwargs): """ Provide the custom form widget for the admin, since there isn't a form field mapped to ``GenericRelation`` model fields. """ from yacms.generic.forms import KeywordsWidget kwargs["widget"] = KeywordsWidget return super(KeywordsFi...
[ "def", "formfield", "(", "self", ",", "*", "*", "kwargs", ")", ":", "from", "yacms", ".", "generic", ".", "forms", "import", "KeywordsWidget", "kwargs", "[", "\"widget\"", "]", "=", "KeywordsWidget", "return", "super", "(", "KeywordsField", ",", "self", ")...
Provide the custom form widget for the admin, since there isn't a form field mapped to ``GenericRelation`` model fields.
[ "Provide", "the", "custom", "form", "widget", "for", "the", "admin", "since", "there", "isn", "t", "a", "form", "field", "mapped", "to", "GenericRelation", "model", "fields", "." ]
train
https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/generic/fields.py#L174-L181
minhhoit/yacms
yacms/generic/fields.py
KeywordsField.save_form_data
def save_form_data(self, instance, data): """ The ``KeywordsWidget`` field will return data as a string of comma separated IDs for the ``Keyword`` model - convert these into actual ``AssignedKeyword`` instances. Also delete ``Keyword`` instances if their last related ``AssignedKe...
python
def save_form_data(self, instance, data): """ The ``KeywordsWidget`` field will return data as a string of comma separated IDs for the ``Keyword`` model - convert these into actual ``AssignedKeyword`` instances. Also delete ``Keyword`` instances if their last related ``AssignedKe...
[ "def", "save_form_data", "(", "self", ",", "instance", ",", "data", ")", ":", "from", "yacms", ".", "generic", ".", "models", "import", "Keyword", "related_manager", "=", "getattr", "(", "instance", ",", "self", ".", "name", ")", "# Get a list of Keyword IDs b...
The ``KeywordsWidget`` field will return data as a string of comma separated IDs for the ``Keyword`` model - convert these into actual ``AssignedKeyword`` instances. Also delete ``Keyword`` instances if their last related ``AssignedKeyword`` instance is being removed.
[ "The", "KeywordsWidget", "field", "will", "return", "data", "as", "a", "string", "of", "comma", "separated", "IDs", "for", "the", "Keyword", "model", "-", "convert", "these", "into", "actual", "AssignedKeyword", "instances", ".", "Also", "delete", "Keyword", "...
train
https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/generic/fields.py#L183-L204
minhhoit/yacms
yacms/generic/fields.py
KeywordsField.contribute_to_class
def contribute_to_class(self, cls, name): """ Swap out any reference to ``KeywordsField`` with the ``KEYWORDS_FIELD_string`` field in ``search_fields``. """ super(KeywordsField, self).contribute_to_class(cls, name) string_field_name = list(self.fields.keys())[0] % \ ...
python
def contribute_to_class(self, cls, name): """ Swap out any reference to ``KeywordsField`` with the ``KEYWORDS_FIELD_string`` field in ``search_fields``. """ super(KeywordsField, self).contribute_to_class(cls, name) string_field_name = list(self.fields.keys())[0] % \ ...
[ "def", "contribute_to_class", "(", "self", ",", "cls", ",", "name", ")", ":", "super", "(", "KeywordsField", ",", "self", ")", ".", "contribute_to_class", "(", "cls", ",", "name", ")", "string_field_name", "=", "list", "(", "self", ".", "fields", ".", "k...
Swap out any reference to ``KeywordsField`` with the ``KEYWORDS_FIELD_string`` field in ``search_fields``.
[ "Swap", "out", "any", "reference", "to", "KeywordsField", "with", "the", "KEYWORDS_FIELD_string", "field", "in", "search_fields", "." ]
train
https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/generic/fields.py#L206-L226
minhhoit/yacms
yacms/generic/fields.py
KeywordsField.related_items_changed
def related_items_changed(self, instance, related_manager): """ Stores the keywords as a single string for searching. """ assigned = related_manager.select_related("keyword") keywords = " ".join([str(a.keyword) for a in assigned]) string_field_name = list(self.fields.keys...
python
def related_items_changed(self, instance, related_manager): """ Stores the keywords as a single string for searching. """ assigned = related_manager.select_related("keyword") keywords = " ".join([str(a.keyword) for a in assigned]) string_field_name = list(self.fields.keys...
[ "def", "related_items_changed", "(", "self", ",", "instance", ",", "related_manager", ")", ":", "assigned", "=", "related_manager", ".", "select_related", "(", "\"keyword\"", ")", "keywords", "=", "\" \"", ".", "join", "(", "[", "str", "(", "a", ".", "keywor...
Stores the keywords as a single string for searching.
[ "Stores", "the", "keywords", "as", "a", "single", "string", "for", "searching", "." ]
train
https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/generic/fields.py#L228-L238
minhhoit/yacms
yacms/generic/fields.py
RatingField.related_items_changed
def related_items_changed(self, instance, related_manager): """ Calculates and saves the average rating. """ ratings = [r.value for r in related_manager.all()] count = len(ratings) _sum = sum(ratings) average = _sum / count if count > 0 else 0 setattr(inst...
python
def related_items_changed(self, instance, related_manager): """ Calculates and saves the average rating. """ ratings = [r.value for r in related_manager.all()] count = len(ratings) _sum = sum(ratings) average = _sum / count if count > 0 else 0 setattr(inst...
[ "def", "related_items_changed", "(", "self", ",", "instance", ",", "related_manager", ")", ":", "ratings", "=", "[", "r", ".", "value", "for", "r", "in", "related_manager", ".", "all", "(", ")", "]", "count", "=", "len", "(", "ratings", ")", "_sum", "=...
Calculates and saves the average rating.
[ "Calculates", "and", "saves", "the", "average", "rating", "." ]
train
https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/generic/fields.py#L253-L264
jaraco/jaraco.apt
jaraco/apt.py
parse_new_packages
def parse_new_packages(apt_output, include_automatic=False): """ Given the output from an apt or aptitude command, determine which packages are newly-installed. """ pat = r'^The following NEW packages will be installed:[\r\n]+(.*?)[\r\n]\w' matcher = re.search(pat, apt_output, re.DOTALL | re.MUL...
python
def parse_new_packages(apt_output, include_automatic=False): """ Given the output from an apt or aptitude command, determine which packages are newly-installed. """ pat = r'^The following NEW packages will be installed:[\r\n]+(.*?)[\r\n]\w' matcher = re.search(pat, apt_output, re.DOTALL | re.MUL...
[ "def", "parse_new_packages", "(", "apt_output", ",", "include_automatic", "=", "False", ")", ":", "pat", "=", "r'^The following NEW packages will be installed:[\\r\\n]+(.*?)[\\r\\n]\\w'", "matcher", "=", "re", ".", "search", "(", "pat", ",", "apt_output", ",", "re", "...
Given the output from an apt or aptitude command, determine which packages are newly-installed.
[ "Given", "the", "output", "from", "an", "apt", "or", "aptitude", "command", "determine", "which", "packages", "are", "newly", "-", "installed", "." ]
train
https://github.com/jaraco/jaraco.apt/blob/bf36fc1966c0a633bc509a37617afd5eead66525/jaraco/apt.py#L20-L33
pjuren/pyokit
src/pyokit/scripts/join.py
file_iterator
def file_iterator(filehandle, verbose=False): """Iterate over a file and yield stripped lines. Optionally show progress.""" if type(filehandle).__name__ == "str": filehandle = open(filehandle) if verbose: try: pind = ProgressIndicator(totalToDo=os.path.getsize(filehandle.name), ...
python
def file_iterator(filehandle, verbose=False): """Iterate over a file and yield stripped lines. Optionally show progress.""" if type(filehandle).__name__ == "str": filehandle = open(filehandle) if verbose: try: pind = ProgressIndicator(totalToDo=os.path.getsize(filehandle.name), ...
[ "def", "file_iterator", "(", "filehandle", ",", "verbose", "=", "False", ")", ":", "if", "type", "(", "filehandle", ")", ".", "__name__", "==", "\"str\"", ":", "filehandle", "=", "open", "(", "filehandle", ")", "if", "verbose", ":", "try", ":", "pind", ...
Iterate over a file and yield stripped lines. Optionally show progress.
[ "Iterate", "over", "a", "file", "and", "yield", "stripped", "lines", ".", "Optionally", "show", "progress", "." ]
train
https://github.com/pjuren/pyokit/blob/fddae123b5d817daa39496183f19c000d9c3791f/src/pyokit/scripts/join.py#L273-L298
pjuren/pyokit
src/pyokit/scripts/join.py
_build_entry
def _build_entry(parts, existing_list_d, key_value, key_field_num, key_is_field_number, header=None, output_type=OutputType.error_on_dups, ignore_missing_keys=False, keep_key_col=False): """ Build and add an entry to existing_list_d. If the key is a field number...
python
def _build_entry(parts, existing_list_d, key_value, key_field_num, key_is_field_number, header=None, output_type=OutputType.error_on_dups, ignore_missing_keys=False, keep_key_col=False): """ Build and add an entry to existing_list_d. If the key is a field number...
[ "def", "_build_entry", "(", "parts", ",", "existing_list_d", ",", "key_value", ",", "key_field_num", ",", "key_is_field_number", ",", "header", "=", "None", ",", "output_type", "=", "OutputType", ".", "error_on_dups", ",", "ignore_missing_keys", "=", "False", ",",...
Build and add an entry to existing_list_d. If the key is a field number, the entry added will be a list of lists. The inner list contains one item per column. and the outer list allows more than one entry to be stored per key (but if allow_duplicates is false, an exception will be raised if more than one needs...
[ "Build", "and", "add", "an", "entry", "to", "existing_list_d", "." ]
train
https://github.com/pjuren/pyokit/blob/fddae123b5d817daa39496183f19c000d9c3791f/src/pyokit/scripts/join.py#L320-L378
pjuren/pyokit
src/pyokit/scripts/join.py
__output_unpaired_vals
def __output_unpaired_vals(d_vals, used_ff_keys, f_f_header, sf_d, s_f_header, missing_val, out_handler, outfh, delim="\t"): """ Use an output handler to output keys that could not be paired. Go over the keys in d_vals and for any that were not used (i.e. not in used_ff_keys), build ...
python
def __output_unpaired_vals(d_vals, used_ff_keys, f_f_header, sf_d, s_f_header, missing_val, out_handler, outfh, delim="\t"): """ Use an output handler to output keys that could not be paired. Go over the keys in d_vals and for any that were not used (i.e. not in used_ff_keys), build ...
[ "def", "__output_unpaired_vals", "(", "d_vals", ",", "used_ff_keys", ",", "f_f_header", ",", "sf_d", ",", "s_f_header", ",", "missing_val", ",", "out_handler", ",", "outfh", ",", "delim", "=", "\"\\t\"", ")", ":", "if", "missing_val", "is", "None", ":", "rai...
Use an output handler to output keys that could not be paired. Go over the keys in d_vals and for any that were not used (i.e. not in used_ff_keys), build an output line using the values from d_vals, populated the missing columns with missing_val, and output these using the provided output hander.
[ "Use", "an", "output", "handler", "to", "output", "keys", "that", "could", "not", "be", "paired", "." ]
train
https://github.com/pjuren/pyokit/blob/fddae123b5d817daa39496183f19c000d9c3791f/src/pyokit/scripts/join.py#L418-L440
pjuren/pyokit
src/pyokit/scripts/join.py
get_key_field
def get_key_field(ui, ui_option_name, default_val=0, default_is_number=True): """ parse an option from a UI object as the name of a key field. If the named option is not set, return the default values for the tuple. :return: a tuple of two items, first is the value of the option, second is ...
python
def get_key_field(ui, ui_option_name, default_val=0, default_is_number=True): """ parse an option from a UI object as the name of a key field. If the named option is not set, return the default values for the tuple. :return: a tuple of two items, first is the value of the option, second is ...
[ "def", "get_key_field", "(", "ui", ",", "ui_option_name", ",", "default_val", "=", "0", ",", "default_is_number", "=", "True", ")", ":", "key", "=", "default_val", "key_is_field_number", "=", "default_is_number", "if", "ui", ".", "optionIsSet", "(", "ui_option_n...
parse an option from a UI object as the name of a key field. If the named option is not set, return the default values for the tuple. :return: a tuple of two items, first is the value of the option, second is a boolean value that indicates whether the value is a column name or a colu...
[ "parse", "an", "option", "from", "a", "UI", "object", "as", "the", "name", "of", "a", "key", "field", "." ]
train
https://github.com/pjuren/pyokit/blob/fddae123b5d817daa39496183f19c000d9c3791f/src/pyokit/scripts/join.py#L511-L530
pjuren/pyokit
src/pyokit/scripts/join.py
populate_unpaired_line
def populate_unpaired_line(d_vals, f_f_header, missing_val=None): """ used when a value in d_vals doesn't match anything in the other file. :return: a dictionary, indexed by key value, with the correct missing values populated for the other file. """ if missing_val is None: raise MissingValueE...
python
def populate_unpaired_line(d_vals, f_f_header, missing_val=None): """ used when a value in d_vals doesn't match anything in the other file. :return: a dictionary, indexed by key value, with the correct missing values populated for the other file. """ if missing_val is None: raise MissingValueE...
[ "def", "populate_unpaired_line", "(", "d_vals", ",", "f_f_header", ",", "missing_val", "=", "None", ")", ":", "if", "missing_val", "is", "None", ":", "raise", "MissingValueError", "(", "\"Need missing value to output \"", "+", "\" unpaired lines\"", ")", "if", "f_f_...
used when a value in d_vals doesn't match anything in the other file. :return: a dictionary, indexed by key value, with the correct missing values populated for the other file.
[ "used", "when", "a", "value", "in", "d_vals", "doesn", "t", "match", "anything", "in", "the", "other", "file", "." ]
train
https://github.com/pjuren/pyokit/blob/fddae123b5d817daa39496183f19c000d9c3791f/src/pyokit/scripts/join.py#L593-L609
pjuren/pyokit
src/pyokit/scripts/join.py
get_key_value
def get_key_value(parts, key_field_num, ignore_missing_keys, seen_keys, output_type): """ get the key value from the line and check it's not a dup. or missing. fields with only whitespace are considered empty (missing). :param ignore_missing_keys: if True, return None for missing keys. If fal...
python
def get_key_value(parts, key_field_num, ignore_missing_keys, seen_keys, output_type): """ get the key value from the line and check it's not a dup. or missing. fields with only whitespace are considered empty (missing). :param ignore_missing_keys: if True, return None for missing keys. If fal...
[ "def", "get_key_value", "(", "parts", ",", "key_field_num", ",", "ignore_missing_keys", ",", "seen_keys", ",", "output_type", ")", ":", "key_val", "=", "parts", "[", "key_field_num", "]", "if", "key_val", ".", "strip", "(", ")", "==", "\"\"", ":", "if", "n...
get the key value from the line and check it's not a dup. or missing. fields with only whitespace are considered empty (missing). :param ignore_missing_keys: if True, return None for missing keys. If false, missing keys cause an exception (MissingKeyError...
[ "get", "the", "key", "value", "from", "the", "line", "and", "check", "it", "s", "not", "a", "dup", ".", "or", "missing", ".", "fields", "with", "only", "whitespace", "are", "considered", "empty", "(", "missing", ")", "." ]
train
https://github.com/pjuren/pyokit/blob/fddae123b5d817daa39496183f19c000d9c3791f/src/pyokit/scripts/join.py#L626-L650
pjuren/pyokit
src/pyokit/scripts/join.py
process_without_storing
def process_without_storing(d_vals, s_f_strm, s_f_key, output_type, outfh, f_f_header=None, s_f_has_header=False, missing_val=None, delim=None, ignore_missing_keys=False, output_unpaired=False, verbose=False)...
python
def process_without_storing(d_vals, s_f_strm, s_f_key, output_type, outfh, f_f_header=None, s_f_has_header=False, missing_val=None, delim=None, ignore_missing_keys=False, output_unpaired=False, verbose=False)...
[ "def", "process_without_storing", "(", "d_vals", ",", "s_f_strm", ",", "s_f_key", ",", "output_type", ",", "outfh", ",", "f_f_header", "=", "None", ",", "s_f_has_header", "=", "False", ",", "missing_val", "=", "None", ",", "delim", "=", "None", ",", "ignore_...
Given a dictionary of values and (optionally) a header for a file, join with another file with a linear pass that does not store The file's values :param d_vals: dictionary of key-value pairs to match up with the lines in the second file. If header_f1 is None, the values should ...
[ "Given", "a", "dictionary", "of", "values", "and", "(", "optionally", ")", "a", "header", "for", "a", "file", "join", "with", "another", "file", "with", "a", "linear", "pass", "that", "does", "not", "store", "The", "file", "s", "values" ]
train
https://github.com/pjuren/pyokit/blob/fddae123b5d817daa39496183f19c000d9c3791f/src/pyokit/scripts/join.py#L653-L726
pjuren/pyokit
src/pyokit/scripts/join.py
build_mock_open_side_effect
def build_mock_open_side_effect(string_d, stream_d): """ Build a mock open side effect using a dictionary of content for the files. :param string_d: keys are file names, values are string file contents :param stream_d: keys are file names, values are stream of contents """ assert(len(set(string_d.keys()).i...
python
def build_mock_open_side_effect(string_d, stream_d): """ Build a mock open side effect using a dictionary of content for the files. :param string_d: keys are file names, values are string file contents :param stream_d: keys are file names, values are stream of contents """ assert(len(set(string_d.keys()).i...
[ "def", "build_mock_open_side_effect", "(", "string_d", ",", "stream_d", ")", ":", "assert", "(", "len", "(", "set", "(", "string_d", ".", "keys", "(", ")", ")", ".", "intersection", "(", "set", "(", "stream_d", ".", "keys", "(", ")", ")", ")", ")", "...
Build a mock open side effect using a dictionary of content for the files. :param string_d: keys are file names, values are string file contents :param stream_d: keys are file names, values are stream of contents
[ "Build", "a", "mock", "open", "side", "effect", "using", "a", "dictionary", "of", "content", "for", "the", "files", "." ]
train
https://github.com/pjuren/pyokit/blob/fddae123b5d817daa39496183f19c000d9c3791f/src/pyokit/scripts/join.py#L799-L815
pjuren/pyokit
src/pyokit/scripts/join.py
OutputHandlerBase.write_header
def write_header(self, out_strm, delim, f1_num_fields, f2_num_fields, f1_header=None, f2_header=None, missing_val=None): """ Write the header for a joined file. If headers are provided for one or more of the input files, then a header is generated for the output file. Otherwise, this ...
python
def write_header(self, out_strm, delim, f1_num_fields, f2_num_fields, f1_header=None, f2_header=None, missing_val=None): """ Write the header for a joined file. If headers are provided for one or more of the input files, then a header is generated for the output file. Otherwise, this ...
[ "def", "write_header", "(", "self", ",", "out_strm", ",", "delim", ",", "f1_num_fields", ",", "f2_num_fields", ",", "f1_header", "=", "None", ",", "f2_header", "=", "None", ",", "missing_val", "=", "None", ")", ":", "mm", "=", "f1_header", "!=", "f2_header...
Write the header for a joined file. If headers are provided for one or more of the input files, then a header is generated for the output file. Otherwise, this does not output anything. :param out_strm: write to this stream :param delim: :param f1_num_fields: the number of columns in the first file...
[ "Write", "the", "header", "for", "a", "joined", "file", ".", "If", "headers", "are", "provided", "for", "one", "or", "more", "of", "the", "input", "files", "then", "a", "header", "is", "generated", "for", "the", "output", "file", ".", "Otherwise", "this"...
train
https://github.com/pjuren/pyokit/blob/fddae123b5d817daa39496183f19c000d9c3791f/src/pyokit/scripts/join.py#L104-L137
ECESeniorDesign/lazy_record
lazy_record/base/validations.py
Validations.is_valid
def is_valid(self, attrs = None): """ Validate an object against the __validates__ class variable. Returns True if valid, and False if any validations fail. If passed (as a dict), +attrs+ will be populated with the invalid attributes. """ if attrs is None: rea...
python
def is_valid(self, attrs = None): """ Validate an object against the __validates__ class variable. Returns True if valid, and False if any validations fail. If passed (as a dict), +attrs+ will be populated with the invalid attributes. """ if attrs is None: rea...
[ "def", "is_valid", "(", "self", ",", "attrs", "=", "None", ")", ":", "if", "attrs", "is", "None", ":", "reason", "=", "{", "}", "else", ":", "reason", "=", "attrs", "valid", "=", "True", "for", "attr", ",", "validation", "in", "self", ".", "__class...
Validate an object against the __validates__ class variable. Returns True if valid, and False if any validations fail. If passed (as a dict), +attrs+ will be populated with the invalid attributes.
[ "Validate", "an", "object", "against", "the", "__validates__", "class", "variable", ".", "Returns", "True", "if", "valid", "and", "False", "if", "any", "validations", "fail", ".", "If", "passed", "(", "as", "a", "dict", ")", "+", "attrs", "+", "will", "b...
train
https://github.com/ECESeniorDesign/lazy_record/blob/929d3cc7c2538b0f792365c0d2b0e0d41084c2dd/lazy_record/base/validations.py#L7-L24
monkeython/scriba
scriba/schemes/scriba_mailto.py
write
def write(url, content, **args): """Put an object into a ftp URL.""" relay = urlparse.urlparse(args.pop('relay', 'lmtp://localhot')) try: smtplib_SMTPS = functools.partial(smtplib.SMTP_SSL, keyfile=args.pop('keyfile', None), ...
python
def write(url, content, **args): """Put an object into a ftp URL.""" relay = urlparse.urlparse(args.pop('relay', 'lmtp://localhot')) try: smtplib_SMTPS = functools.partial(smtplib.SMTP_SSL, keyfile=args.pop('keyfile', None), ...
[ "def", "write", "(", "url", ",", "content", ",", "*", "*", "args", ")", ":", "relay", "=", "urlparse", ".", "urlparse", "(", "args", ".", "pop", "(", "'relay'", ",", "'lmtp://localhot'", ")", ")", "try", ":", "smtplib_SMTPS", "=", "functools", ".", "...
Put an object into a ftp URL.
[ "Put", "an", "object", "into", "a", "ftp", "URL", "." ]
train
https://github.com/monkeython/scriba/blob/fb8e7636ed07c3d035433fdd153599ac8b24dfc4/scriba/schemes/scriba_mailto.py#L26-L70
emencia/emencia-django-forum
forum/markup.py
clean_restructuredtext
def clean_restructuredtext(form_instance, content): """ RST syntax validation """ if content: errors = SourceReporter(content) if errors: raise ValidationError(map(map_parsing_errors, errors)) return content
python
def clean_restructuredtext(form_instance, content): """ RST syntax validation """ if content: errors = SourceReporter(content) if errors: raise ValidationError(map(map_parsing_errors, errors)) return content
[ "def", "clean_restructuredtext", "(", "form_instance", ",", "content", ")", ":", "if", "content", ":", "errors", "=", "SourceReporter", "(", "content", ")", "if", "errors", ":", "raise", "ValidationError", "(", "map", "(", "map_parsing_errors", ",", "errors", ...
RST syntax validation
[ "RST", "syntax", "validation" ]
train
https://github.com/emencia/emencia-django-forum/blob/cda74ed7e5822675c340ee5ec71548d981bccd3b/forum/markup.py#L20-L28
MrKriss/vigilance
vigilance/decorators.py
accepts
def accepts(*checkers_args, **checkers_kws): """ Create a decorator for validating function parameters. Parameters ---------- checkers_args: positional args Functions to apply to the inputs of the decorated function. The position of the argument is assumed to match the position of ...
python
def accepts(*checkers_args, **checkers_kws): """ Create a decorator for validating function parameters. Parameters ---------- checkers_args: positional args Functions to apply to the inputs of the decorated function. The position of the argument is assumed to match the position of ...
[ "def", "accepts", "(", "*", "checkers_args", ",", "*", "*", "checkers_kws", ")", ":", "@", "decorator", "def", "run_checkers", "(", "func", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "all_args", "=", "inspect", ".", "getcallargs", "(", "func"...
Create a decorator for validating function parameters. Parameters ---------- checkers_args: positional args Functions to apply to the inputs of the decorated function. The position of the argument is assumed to match the position of the function in the decorator. checkers_kws: keyw...
[ "Create", "a", "decorator", "for", "validating", "function", "parameters", ".", "Parameters", "----------", "checkers_args", ":", "positional", "args", "Functions", "to", "apply", "to", "the", "inputs", "of", "the", "decorated", "function", ".", "The", "position",...
train
https://github.com/MrKriss/vigilance/blob/2946b09f524c042c12d796f111f287866e7a3c67/vigilance/decorators.py#L17-L51
MrKriss/vigilance
vigilance/decorators.py
returns
def returns(*checkers_args): """ Create a decorator for validating function return values. Parameters ---------- checkers_args: positional arguments A single functions to apply to the output of the decorated function. If a tuple is returned by the decorated function, multiple function ...
python
def returns(*checkers_args): """ Create a decorator for validating function return values. Parameters ---------- checkers_args: positional arguments A single functions to apply to the output of the decorated function. If a tuple is returned by the decorated function, multiple function ...
[ "def", "returns", "(", "*", "checkers_args", ")", ":", "@", "decorator", "def", "run_checkers", "(", "func", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "ret", "=", "func", "(", "*", "args", ",", "*", "*", "kwargs", ")", "if", "type", "(...
Create a decorator for validating function return values. Parameters ---------- checkers_args: positional arguments A single functions to apply to the output of the decorated function. If a tuple is returned by the decorated function, multiple function can be listed and are assumed to matc...
[ "Create", "a", "decorator", "for", "validating", "function", "return", "values", "." ]
train
https://github.com/MrKriss/vigilance/blob/2946b09f524c042c12d796f111f287866e7a3c67/vigilance/decorators.py#L54-L90
Jayin/ETipsService
service/subsystem.py
SubSystem.login
def login(self): """ 用户登陆 :return: true if login successfully """ self._cookies = self.__get_rndnum_cookies() # print self._cookies UserCode, UserPwd = self._userid, self._userpsw Validate = self._cookies['LogonNumber'] Submit = '%CC%E1+%BD%BB' ...
python
def login(self): """ 用户登陆 :return: true if login successfully """ self._cookies = self.__get_rndnum_cookies() # print self._cookies UserCode, UserPwd = self._userid, self._userpsw Validate = self._cookies['LogonNumber'] Submit = '%CC%E1+%BD%BB' ...
[ "def", "login", "(", "self", ")", ":", "self", ".", "_cookies", "=", "self", ".", "__get_rndnum_cookies", "(", ")", "# print self._cookies", "UserCode", ",", "UserPwd", "=", "self", ".", "_userid", ",", "self", ".", "_userpsw", "Validate", "=", "self", "."...
用户登陆 :return: true if login successfully
[ "用户登陆", ":", "return", ":", "true", "if", "login", "successfully" ]
train
https://github.com/Jayin/ETipsService/blob/1a42612a5e5d11bec0ec1a26c99dec6fe216fca4/service/subsystem.py#L27-L49
Jayin/ETipsService
service/subsystem.py
SubSystem.__get_course_html
def __get_course_html(self): """ 获得课表页面 :return: 已转码的html """ self._headers['Referer'] = 'http://jwc.wyu.edu.cn/student/menu.asp' r = requests.get('http://jwc.wyu.edu.cn/student/f3.asp', headers=self._headers, cookies=self._cookies) return r.content.decode(_.get_c...
python
def __get_course_html(self): """ 获得课表页面 :return: 已转码的html """ self._headers['Referer'] = 'http://jwc.wyu.edu.cn/student/menu.asp' r = requests.get('http://jwc.wyu.edu.cn/student/f3.asp', headers=self._headers, cookies=self._cookies) return r.content.decode(_.get_c...
[ "def", "__get_course_html", "(", "self", ")", ":", "self", ".", "_headers", "[", "'Referer'", "]", "=", "'http://jwc.wyu.edu.cn/student/menu.asp'", "r", "=", "requests", ".", "get", "(", "'http://jwc.wyu.edu.cn/student/f3.asp'", ",", "headers", "=", "self", ".", "...
获得课表页面 :return: 已转码的html
[ "获得课表页面", ":", "return", ":", "已转码的html" ]
train
https://github.com/Jayin/ETipsService/blob/1a42612a5e5d11bec0ec1a26c99dec6fe216fca4/service/subsystem.py#L51-L58
Jayin/ETipsService
service/subsystem.py
SubSystem.get_course
def get_course(self): """ 获得课表 :return: 课表 """ html = self.__get_course_html() soup = BeautifulSoup(markup=html) # tbodys[0]为学生信息,tbodys[1]课表,tbodys[2]为课程详情 tbodys = soup.find_all(name='tbody') result = [] day = 0 for index, x in e...
python
def get_course(self): """ 获得课表 :return: 课表 """ html = self.__get_course_html() soup = BeautifulSoup(markup=html) # tbodys[0]为学生信息,tbodys[1]课表,tbodys[2]为课程详情 tbodys = soup.find_all(name='tbody') result = [] day = 0 for index, x in e...
[ "def", "get_course", "(", "self", ")", ":", "html", "=", "self", ".", "__get_course_html", "(", ")", "soup", "=", "BeautifulSoup", "(", "markup", "=", "html", ")", "# tbodys[0]为学生信息,tbodys[1]课表,tbodys[2]为课程详情", "tbodys", "=", "soup", ".", "find_all", "(", "nam...
获得课表 :return: 课表
[ "获得课表", ":", "return", ":", "课表" ]
train
https://github.com/Jayin/ETipsService/blob/1a42612a5e5d11bec0ec1a26c99dec6fe216fca4/service/subsystem.py#L60-L101
Jayin/ETipsService
service/subsystem.py
SubSystem.get_score
def get_score(self): """ 获得成绩列表 :return: json array """ html = self.__get_score_html() soup = BeautifulSoup(html) div = soup.find_all('div', class_='Section1')[0] tag_ps = div.find_all('p') del tag_ps[0] result = [] ''' #one...
python
def get_score(self): """ 获得成绩列表 :return: json array """ html = self.__get_score_html() soup = BeautifulSoup(html) div = soup.find_all('div', class_='Section1')[0] tag_ps = div.find_all('p') del tag_ps[0] result = [] ''' #one...
[ "def", "get_score", "(", "self", ")", ":", "html", "=", "self", ".", "__get_score_html", "(", ")", "soup", "=", "BeautifulSoup", "(", "html", ")", "div", "=", "soup", ".", "find_all", "(", "'div'", ",", "class_", "=", "'Section1'", ")", "[", "0", "]"...
获得成绩列表 :return: json array
[ "获得成绩列表", ":", "return", ":", "json", "array" ]
train
https://github.com/Jayin/ETipsService/blob/1a42612a5e5d11bec0ec1a26c99dec6fe216fca4/service/subsystem.py#L120-L179
cirruscluster/cirruscluster
cirruscluster/ext/ansible/callbacks.py
regular_generic_msg
def regular_generic_msg(hostname, result, oneline, caption): ''' output on the result of a module run that is not command ''' if not oneline: return "%s | %s >> %s\n" % (hostname, caption, utils.jsonify(result,format=True)) else: return "%s | %s >> %s\n" % (hostname, caption, utils.jsonify(...
python
def regular_generic_msg(hostname, result, oneline, caption): ''' output on the result of a module run that is not command ''' if not oneline: return "%s | %s >> %s\n" % (hostname, caption, utils.jsonify(result,format=True)) else: return "%s | %s >> %s\n" % (hostname, caption, utils.jsonify(...
[ "def", "regular_generic_msg", "(", "hostname", ",", "result", ",", "oneline", ",", "caption", ")", ":", "if", "not", "oneline", ":", "return", "\"%s | %s >> %s\\n\"", "%", "(", "hostname", ",", "caption", ",", "utils", ".", "jsonify", "(", "result", ",", "...
output on the result of a module run that is not command
[ "output", "on", "the", "result", "of", "a", "module", "run", "that", "is", "not", "command" ]
train
https://github.com/cirruscluster/cirruscluster/blob/977409929dd81322d886425cdced10608117d5d7/cirruscluster/ext/ansible/callbacks.py#L115-L121
cirruscluster/cirruscluster
cirruscluster/ext/ansible/callbacks.py
command_generic_msg
def command_generic_msg(hostname, result, oneline, caption): ''' output the result of a command run ''' rc = result.get('rc', '0') stdout = result.get('stdout','') stderr = result.get('stderr', '') msg = result.get('msg', '') hostname = hostname.encode('utf-8') caption = caption.en...
python
def command_generic_msg(hostname, result, oneline, caption): ''' output the result of a command run ''' rc = result.get('rc', '0') stdout = result.get('stdout','') stderr = result.get('stderr', '') msg = result.get('msg', '') hostname = hostname.encode('utf-8') caption = caption.en...
[ "def", "command_generic_msg", "(", "hostname", ",", "result", ",", "oneline", ",", "caption", ")", ":", "rc", "=", "result", ".", "get", "(", "'rc'", ",", "'0'", ")", "stdout", "=", "result", ".", "get", "(", "'stdout'", ",", "''", ")", "stderr", "="...
output the result of a command run
[ "output", "the", "result", "of", "a", "command", "run" ]
train
https://github.com/cirruscluster/cirruscluster/blob/977409929dd81322d886425cdced10608117d5d7/cirruscluster/ext/ansible/callbacks.py#L134-L158
cirruscluster/cirruscluster
cirruscluster/ext/ansible/callbacks.py
host_report_msg
def host_report_msg(hostname, module_name, result, oneline): ''' summarize the JSON results for a particular host ''' failed = utils.is_failed(result) msg = '' if module_name in [ 'command', 'shell', 'raw' ] and 'ansible_job_id' not in result and result.get('parsed',True) != False: if not faile...
python
def host_report_msg(hostname, module_name, result, oneline): ''' summarize the JSON results for a particular host ''' failed = utils.is_failed(result) msg = '' if module_name in [ 'command', 'shell', 'raw' ] and 'ansible_job_id' not in result and result.get('parsed',True) != False: if not faile...
[ "def", "host_report_msg", "(", "hostname", ",", "module_name", ",", "result", ",", "oneline", ")", ":", "failed", "=", "utils", ".", "is_failed", "(", "result", ")", "msg", "=", "''", "if", "module_name", "in", "[", "'command'", ",", "'shell'", ",", "'ra...
summarize the JSON results for a particular host
[ "summarize", "the", "JSON", "results", "for", "a", "particular", "host" ]
train
https://github.com/cirruscluster/cirruscluster/blob/977409929dd81322d886425cdced10608117d5d7/cirruscluster/ext/ansible/callbacks.py#L160-L175
cirruscluster/cirruscluster
cirruscluster/ext/ansible/callbacks.py
AggregateStats._increment
def _increment(self, what, host): ''' helper function to bump a statistic ''' self.processed[host] = 1 prev = (getattr(self, what)).get(host, 0) getattr(self, what)[host] = prev+1
python
def _increment(self, what, host): ''' helper function to bump a statistic ''' self.processed[host] = 1 prev = (getattr(self, what)).get(host, 0) getattr(self, what)[host] = prev+1
[ "def", "_increment", "(", "self", ",", "what", ",", "host", ")", ":", "self", ".", "processed", "[", "host", "]", "=", "1", "prev", "=", "(", "getattr", "(", "self", ",", "what", ")", ")", ".", "get", "(", "host", ",", "0", ")", "getattr", "(",...
helper function to bump a statistic
[ "helper", "function", "to", "bump", "a", "statistic" ]
train
https://github.com/cirruscluster/cirruscluster/blob/977409929dd81322d886425cdced10608117d5d7/cirruscluster/ext/ansible/callbacks.py#L74-L79
cirruscluster/cirruscluster
cirruscluster/ext/ansible/callbacks.py
AggregateStats.compute
def compute(self, runner_results, setup=False, poll=False, ignore_errors=False): ''' walk through all results and increment stats ''' for (host, value) in runner_results.get('contacted', {}).iteritems(): if not ignore_errors and (('failed' in value and bool(value['failed'])) or ...
python
def compute(self, runner_results, setup=False, poll=False, ignore_errors=False): ''' walk through all results and increment stats ''' for (host, value) in runner_results.get('contacted', {}).iteritems(): if not ignore_errors and (('failed' in value and bool(value['failed'])) or ...
[ "def", "compute", "(", "self", ",", "runner_results", ",", "setup", "=", "False", ",", "poll", "=", "False", ",", "ignore_errors", "=", "False", ")", ":", "for", "(", "host", ",", "value", ")", "in", "runner_results", ".", "get", "(", "'contacted'", ",...
walk through all results and increment stats
[ "walk", "through", "all", "results", "and", "increment", "stats" ]
train
https://github.com/cirruscluster/cirruscluster/blob/977409929dd81322d886425cdced10608117d5d7/cirruscluster/ext/ansible/callbacks.py#L81-L99
cirruscluster/cirruscluster
cirruscluster/ext/ansible/callbacks.py
AggregateStats.summarize
def summarize(self, host): ''' return information about a particular host ''' return dict( ok = self.ok.get(host, 0), failures = self.failures.get(host, 0), unreachable = self.dark.get(host,0), changed = self.changed.get(host, 0), ...
python
def summarize(self, host): ''' return information about a particular host ''' return dict( ok = self.ok.get(host, 0), failures = self.failures.get(host, 0), unreachable = self.dark.get(host,0), changed = self.changed.get(host, 0), ...
[ "def", "summarize", "(", "self", ",", "host", ")", ":", "return", "dict", "(", "ok", "=", "self", ".", "ok", ".", "get", "(", "host", ",", "0", ")", ",", "failures", "=", "self", ".", "failures", ".", "get", "(", "host", ",", "0", ")", ",", "...
return information about a particular host
[ "return", "information", "about", "a", "particular", "host" ]
train
https://github.com/cirruscluster/cirruscluster/blob/977409929dd81322d886425cdced10608117d5d7/cirruscluster/ext/ansible/callbacks.py#L102-L111
ramrod-project/database-brain
schema/brain/connection.py
validate_get_dbs
def validate_get_dbs(connection): """ validates the connection object is capable of read access to rethink should be at least one test database by default :param connection: <rethinkdb.net.DefaultConnection> :return: <set> list of databases :raises: ReqlDriverError AssertionError """ r...
python
def validate_get_dbs(connection): """ validates the connection object is capable of read access to rethink should be at least one test database by default :param connection: <rethinkdb.net.DefaultConnection> :return: <set> list of databases :raises: ReqlDriverError AssertionError """ r...
[ "def", "validate_get_dbs", "(", "connection", ")", ":", "remote_dbs", "=", "set", "(", "rethinkdb", ".", "db_list", "(", ")", ".", "run", "(", "connection", ")", ")", "assert", "remote_dbs", "return", "remote_dbs" ]
validates the connection object is capable of read access to rethink should be at least one test database by default :param connection: <rethinkdb.net.DefaultConnection> :return: <set> list of databases :raises: ReqlDriverError AssertionError
[ "validates", "the", "connection", "object", "is", "capable", "of", "read", "access", "to", "rethink" ]
train
https://github.com/ramrod-project/database-brain/blob/b024cb44f34cabb9d80af38271ddb65c25767083/schema/brain/connection.py#L55-L67
ramrod-project/database-brain
schema/brain/connection.py
validate_brain_requirements
def validate_brain_requirements(connection, remote_dbs, requirements): """ validates the rethinkdb has the 'correct' databases and tables should get remote_dbs from brain.connection.validate_get_dbs :param connection: <rethinkdb.net.DefaultConnection> :param remote_dbs: <set> database names present...
python
def validate_brain_requirements(connection, remote_dbs, requirements): """ validates the rethinkdb has the 'correct' databases and tables should get remote_dbs from brain.connection.validate_get_dbs :param connection: <rethinkdb.net.DefaultConnection> :param remote_dbs: <set> database names present...
[ "def", "validate_brain_requirements", "(", "connection", ",", "remote_dbs", ",", "requirements", ")", ":", "for", "database", "in", "requirements", ":", "assert", "(", "database", "in", "remote_dbs", ")", ",", "\"database {} must exist\"", ".", "format", "(", "dat...
validates the rethinkdb has the 'correct' databases and tables should get remote_dbs from brain.connection.validate_get_dbs :param connection: <rethinkdb.net.DefaultConnection> :param remote_dbs: <set> database names present in remote database :param requirements: <dict> example(brain.connection.SELF_T...
[ "validates", "the", "rethinkdb", "has", "the", "correct", "databases", "and", "tables", "should", "get", "remote_dbs", "from", "brain", ".", "connection", ".", "validate_get_dbs" ]
train
https://github.com/ramrod-project/database-brain/blob/b024cb44f34cabb9d80af38271ddb65c25767083/schema/brain/connection.py#L70-L86
ramrod-project/database-brain
schema/brain/connection.py
validate_write_access
def validate_write_access(connection): """ verifies connection can write to rethink by: 1. Creating a test table 2. Adding a document to that table 3. destroying the test table :param connection: <rethinkdb.net.DefaultConnection> :return: <bool> True :raises: Reql*Error ...
python
def validate_write_access(connection): """ verifies connection can write to rethink by: 1. Creating a test table 2. Adding a document to that table 3. destroying the test table :param connection: <rethinkdb.net.DefaultConnection> :return: <bool> True :raises: Reql*Error ...
[ "def", "validate_write_access", "(", "connection", ")", ":", "test_table", "=", "\"test_table_{}\"", ".", "format", "(", "uuid4", "(", ")", ")", ".", "replace", "(", "\"-\"", ",", "\"\"", ")", "# '-' is not valid", "create_plugin", "(", "test_table", ",", "con...
verifies connection can write to rethink by: 1. Creating a test table 2. Adding a document to that table 3. destroying the test table :param connection: <rethinkdb.net.DefaultConnection> :return: <bool> True :raises: Reql*Error
[ "verifies", "connection", "can", "write", "to", "rethink", "by", ":", "1", ".", "Creating", "a", "test", "table", "2", ".", "Adding", "a", "document", "to", "that", "table", "3", ".", "destroying", "the", "test", "table" ]
train
https://github.com/ramrod-project/database-brain/blob/b024cb44f34cabb9d80af38271ddb65c25767083/schema/brain/connection.py#L89-L104
ramrod-project/database-brain
schema/brain/connection.py
brain_post
def brain_post(connection, requirements=None): """ Power On Self Test for the brain. Checks that the brain is appropriately seeded and ready for use. Raises AssertionError's if the brain is not ready. :param connection: <rethinkdb.net.DefaultConnection> :param requirements:<dict> keys=Requir...
python
def brain_post(connection, requirements=None): """ Power On Self Test for the brain. Checks that the brain is appropriately seeded and ready for use. Raises AssertionError's if the brain is not ready. :param connection: <rethinkdb.net.DefaultConnection> :param requirements:<dict> keys=Requir...
[ "def", "brain_post", "(", "connection", ",", "requirements", "=", "None", ")", ":", "assert", "isinstance", "(", "connection", ",", "DefaultConnection", ")", "remote_dbs", "=", "validate_get_dbs", "(", "connection", ")", "assert", "validate_brain_requirements", "(",...
Power On Self Test for the brain. Checks that the brain is appropriately seeded and ready for use. Raises AssertionError's if the brain is not ready. :param connection: <rethinkdb.net.DefaultConnection> :param requirements:<dict> keys=Required Databases, key-values=Required Tables in each database ...
[ "Power", "On", "Self", "Test", "for", "the", "brain", "." ]
train
https://github.com/ramrod-project/database-brain/blob/b024cb44f34cabb9d80af38271ddb65c25767083/schema/brain/connection.py#L123-L139
ramrod-project/database-brain
schema/brain/connection.py
connect
def connect(host=None, port=rethinkdb.DEFAULT_PORT, timeout=20, verify=True, **kwargs): """ RethinkDB semantic connection wrapper raises <brain.connection.BrainNotReady> if connection verification fails :param verify: <bool> (default True) whether to run...
python
def connect(host=None, port=rethinkdb.DEFAULT_PORT, timeout=20, verify=True, **kwargs): """ RethinkDB semantic connection wrapper raises <brain.connection.BrainNotReady> if connection verification fails :param verify: <bool> (default True) whether to run...
[ "def", "connect", "(", "host", "=", "None", ",", "port", "=", "rethinkdb", ".", "DEFAULT_PORT", ",", "timeout", "=", "20", ",", "verify", "=", "True", ",", "*", "*", "kwargs", ")", ":", "if", "not", "host", ":", "host", "=", "DEFAULT_HOSTS", ".", "...
RethinkDB semantic connection wrapper raises <brain.connection.BrainNotReady> if connection verification fails :param verify: <bool> (default True) whether to run POST :param timeout: <int> max time (s) to wait for connection :param kwargs: <dict> passthrough rethinkdb arguments :return:
[ "RethinkDB", "semantic", "connection", "wrapper" ]
train
https://github.com/ramrod-project/database-brain/blob/b024cb44f34cabb9d80af38271ddb65c25767083/schema/brain/connection.py#L142-L173
ramrod-project/database-brain
schema/brain/connection.py
_attempt_connect
def _attempt_connect(host, port, timeout, verify, **kwargs): """ Internal function to attempt :param host: <str> "localhost" or IPAddress :param port: <int> :param timeout: <int> :param verify: <bool> :param kwargs: <**dict> rethinkdb keyword args :return: <connection> or <NoneType> ...
python
def _attempt_connect(host, port, timeout, verify, **kwargs): """ Internal function to attempt :param host: <str> "localhost" or IPAddress :param port: <int> :param timeout: <int> :param verify: <bool> :param kwargs: <**dict> rethinkdb keyword args :return: <connection> or <NoneType> ...
[ "def", "_attempt_connect", "(", "host", ",", "port", ",", "timeout", ",", "verify", ",", "*", "*", "kwargs", ")", ":", "try", ":", "connection", "=", "rethinkdb", ".", "connect", "(", "host", ",", "port", ",", "timeout", "=", "timeout", ",", "*", "*"...
Internal function to attempt :param host: <str> "localhost" or IPAddress :param port: <int> :param timeout: <int> :param verify: <bool> :param kwargs: <**dict> rethinkdb keyword args :return: <connection> or <NoneType>
[ "Internal", "function", "to", "attempt", ":", "param", "host", ":", "<str", ">", "localhost", "or", "IPAddress", ":", "param", "port", ":", "<int", ">", ":", "param", "timeout", ":", "<int", ">", ":", "param", "verify", ":", "<bool", ">", ":", "param",...
train
https://github.com/ramrod-project/database-brain/blob/b024cb44f34cabb9d80af38271ddb65c25767083/schema/brain/connection.py#L176-L197
kervi/kervi-core
kervi/sensors/__init__.py
Sensor.link_to_dashboard
def link_to_dashboard(self, dashboard_id=None, panel_id=None, **kwargs): r""" Links the sensor to a dashboard. :param dashboard_id: Id of the dashboard to link to. Enter a * if the sensor should be linked to all dashboards. :type dashboard_id: ``str`` :param pan...
python
def link_to_dashboard(self, dashboard_id=None, panel_id=None, **kwargs): r""" Links the sensor to a dashboard. :param dashboard_id: Id of the dashboard to link to. Enter a * if the sensor should be linked to all dashboards. :type dashboard_id: ``str`` :param pan...
[ "def", "link_to_dashboard", "(", "self", ",", "dashboard_id", "=", "None", ",", "panel_id", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "self", ".", "_dimensions", "==", "1", ":", "self", ".", "_sensor_value", ".", "link_to_dashboard", "(", "da...
r""" Links the sensor to a dashboard. :param dashboard_id: Id of the dashboard to link to. Enter a * if the sensor should be linked to all dashboards. :type dashboard_id: ``str`` :param panel_id: Id of the panel to link to. This is the id of a panel you...
[ "r", "Links", "the", "sensor", "to", "a", "dashboard", "." ]
train
https://github.com/kervi/kervi-core/blob/3c1e3c8a17a7b4d085d8a28b99180ff2a96b0e23/kervi/sensors/__init__.py#L143-L184
kervi/kervi-core
kervi/sensors/__init__.py
Sensor._new_sensor_reading
def _new_sensor_reading(self, sensor_value): """ Call this method to signal a new sensor reading. This method handles DB storage and triggers different events. :param value: New value to be stored in the system. """ if not self._active and not self._enabled: ...
python
def _new_sensor_reading(self, sensor_value): """ Call this method to signal a new sensor reading. This method handles DB storage and triggers different events. :param value: New value to be stored in the system. """ if not self._active and not self._enabled: ...
[ "def", "_new_sensor_reading", "(", "self", ",", "sensor_value", ")", ":", "if", "not", "self", ".", "_active", "and", "not", "self", ".", "_enabled", ":", "return", "if", "self", ".", "_dimensions", ">", "1", ":", "for", "dimension", "in", "range", "(", ...
Call this method to signal a new sensor reading. This method handles DB storage and triggers different events. :param value: New value to be stored in the system.
[ "Call", "this", "method", "to", "signal", "a", "new", "sensor", "reading", ".", "This", "method", "handles", "DB", "storage", "and", "triggers", "different", "events", "." ]
train
https://github.com/kervi/kervi-core/blob/3c1e3c8a17a7b4d085d8a28b99180ff2a96b0e23/kervi/sensors/__init__.py#L216-L232
kervi/kervi-core
kervi/sensors/__init__.py
Sensor.add_value_event
def add_value_event(self, event_value, func, event_type=None, parameters=None, **kwargs): """ Add a function that is called when the value reach or pass the event_value. :param event_value: A single value or range specified as a tuple. If it is a range the function spec...
python
def add_value_event(self, event_value, func, event_type=None, parameters=None, **kwargs): """ Add a function that is called when the value reach or pass the event_value. :param event_value: A single value or range specified as a tuple. If it is a range the function spec...
[ "def", "add_value_event", "(", "self", ",", "event_value", ",", "func", ",", "event_type", "=", "None", ",", "parameters", "=", "None", ",", "*", "*", "kwargs", ")", ":", "self", ".", "_sensor_value", ".", "add_value_event", "(", "event_value", ",", "func"...
Add a function that is called when the value reach or pass the event_value. :param event_value: A single value or range specified as a tuple. If it is a range the function specified in func is called when the value enters the range. :type event_value: ``float``, ``string``, ``...
[ "Add", "a", "function", "that", "is", "called", "when", "the", "value", "reach", "or", "pass", "the", "event_value", "." ]
train
https://github.com/kervi/kervi-core/blob/3c1e3c8a17a7b4d085d8a28b99180ff2a96b0e23/kervi/sensors/__init__.py#L262-L284
koodaamo/iconframer
iconframer/iconframer.py
process_path
def process_path(label, pth): "check and expand paths" if pth is None: sys.exit("no %s path given" % label) if pth.startswith("/"): pass elif pth[0] in (".", "~"): pth = os.path.realpath(pth) else: pth = os.getcwd() + os.sep + pth if not os.path.exists(pth): ...
python
def process_path(label, pth): "check and expand paths" if pth is None: sys.exit("no %s path given" % label) if pth.startswith("/"): pass elif pth[0] in (".", "~"): pth = os.path.realpath(pth) else: pth = os.getcwd() + os.sep + pth if not os.path.exists(pth): ...
[ "def", "process_path", "(", "label", ",", "pth", ")", ":", "if", "pth", "is", "None", ":", "sys", ".", "exit", "(", "\"no %s path given\"", "%", "label", ")", "if", "pth", ".", "startswith", "(", "\"/\"", ")", ":", "pass", "elif", "pth", "[", "0", ...
check and expand paths
[ "check", "and", "expand", "paths" ]
train
https://github.com/koodaamo/iconframer/blob/58d71fd78bfe3893a7f20384f429592d033d802a/iconframer/iconframer.py#L23-L39
koodaamo/iconframer
iconframer/iconframer.py
convert_svg
def convert_svg(svgstr, size, filepath, target): "convert to PDF or PNG" # PREPARE CONVERSION PER TYPE if target == "PDF": img = cairo.PDFSurface(filepath, size, size) elif target == "PNG": img = cairo.ImageSurface(cairo.FORMAT_ARGB32, size, size) else: system.exit("unknown f...
python
def convert_svg(svgstr, size, filepath, target): "convert to PDF or PNG" # PREPARE CONVERSION PER TYPE if target == "PDF": img = cairo.PDFSurface(filepath, size, size) elif target == "PNG": img = cairo.ImageSurface(cairo.FORMAT_ARGB32, size, size) else: system.exit("unknown f...
[ "def", "convert_svg", "(", "svgstr", ",", "size", ",", "filepath", ",", "target", ")", ":", "# PREPARE CONVERSION PER TYPE", "if", "target", "==", "\"PDF\"", ":", "img", "=", "cairo", ".", "PDFSurface", "(", "filepath", ",", "size", ",", "size", ")", "elif...
convert to PDF or PNG
[ "convert", "to", "PDF", "or", "PNG" ]
train
https://github.com/koodaamo/iconframer/blob/58d71fd78bfe3893a7f20384f429592d033d802a/iconframer/iconframer.py#L138-L161
vistoyn/python-foruse
foruse/lib.py
var_dump
def var_dump(*obs): """ shows structured information of a object, list, tuple etc """ i = 0 for x in obs: str = var_dump_output(x, 0, ' ', '\n', True) print (str.strip()) #dump(x, 0, i, '', object) i += 1
python
def var_dump(*obs): """ shows structured information of a object, list, tuple etc """ i = 0 for x in obs: str = var_dump_output(x, 0, ' ', '\n', True) print (str.strip()) #dump(x, 0, i, '', object) i += 1
[ "def", "var_dump", "(", "*", "obs", ")", ":", "i", "=", "0", "for", "x", "in", "obs", ":", "str", "=", "var_dump_output", "(", "x", ",", "0", ",", "' '", ",", "'\\n'", ",", "True", ")", "print", "(", "str", ".", "strip", "(", ")", ")", "#dum...
shows structured information of a object, list, tuple etc
[ "shows", "structured", "information", "of", "a", "object", "list", "tuple", "etc" ]
train
https://github.com/vistoyn/python-foruse/blob/312588d25ac391aa7b3325b7cb4c8f8188b559c7/foruse/lib.py#L427-L438
veltzer/pypitools
pypitools/common.py
check_call_no_output
def check_call_no_output(args): """ Run a process and check that it returns an OK return code and has no output :param args: :return: """ logger = logging.getLogger(__name__) logger.debug("running %s", args) process = subprocess.Popen( args, stdout=subprocess.PIPE, ...
python
def check_call_no_output(args): """ Run a process and check that it returns an OK return code and has no output :param args: :return: """ logger = logging.getLogger(__name__) logger.debug("running %s", args) process = subprocess.Popen( args, stdout=subprocess.PIPE, ...
[ "def", "check_call_no_output", "(", "args", ")", ":", "logger", "=", "logging", ".", "getLogger", "(", "__name__", ")", "logger", ".", "debug", "(", "\"running %s\"", ",", "args", ")", "process", "=", "subprocess", ".", "Popen", "(", "args", ",", "stdout",...
Run a process and check that it returns an OK return code and has no output :param args: :return:
[ "Run", "a", "process", "and", "check", "that", "it", "returns", "an", "OK", "return", "code", "and", "has", "no", "output", ":", "param", "args", ":", ":", "return", ":" ]
train
https://github.com/veltzer/pypitools/blob/5f097be21e9bc65578eed5b6b7855c1945540701/pypitools/common.py#L22-L42
veltzer/pypitools
pypitools/common.py
ConfigData.read_config
def read_config(self): """ Read all configuration data :return: """ section = "pypitools" # read setup.cfg config file config = configparser.ConfigParser() homedir_filename = os.path.expanduser("~/.setup.cfg") if os.path.isfile(homedir_filename): ...
python
def read_config(self): """ Read all configuration data :return: """ section = "pypitools" # read setup.cfg config file config = configparser.ConfigParser() homedir_filename = os.path.expanduser("~/.setup.cfg") if os.path.isfile(homedir_filename): ...
[ "def", "read_config", "(", "self", ")", ":", "section", "=", "\"pypitools\"", "# read setup.cfg config file", "config", "=", "configparser", ".", "ConfigParser", "(", ")", "homedir_filename", "=", "os", ".", "path", ".", "expanduser", "(", "\"~/.setup.cfg\"", ")",...
Read all configuration data :return:
[ "Read", "all", "configuration", "data", ":", "return", ":" ]
train
https://github.com/veltzer/pypitools/blob/5f097be21e9bc65578eed5b6b7855c1945540701/pypitools/common.py#L95-L121
veltzer/pypitools
pypitools/common.py
ConfigData.get_package_version
def get_package_version(self): """ Get the version of the package :return: """ output = subprocess.check_output([ '{}'.format(self.python), 'setup.py', '--version', ]).decode() return output.rstrip()
python
def get_package_version(self): """ Get the version of the package :return: """ output = subprocess.check_output([ '{}'.format(self.python), 'setup.py', '--version', ]).decode() return output.rstrip()
[ "def", "get_package_version", "(", "self", ")", ":", "output", "=", "subprocess", ".", "check_output", "(", "[", "'{}'", ".", "format", "(", "self", ".", "python", ")", ",", "'setup.py'", ",", "'--version'", ",", "]", ")", ".", "decode", "(", ")", "ret...
Get the version of the package :return:
[ "Get", "the", "version", "of", "the", "package", ":", "return", ":" ]
train
https://github.com/veltzer/pypitools/blob/5f097be21e9bc65578eed5b6b7855c1945540701/pypitools/common.py#L123-L133
veltzer/pypitools
pypitools/common.py
ConfigData.upload_by_twine
def upload_by_twine(self): """ upload by twine :return: """ check_call_no_output([ '{}'.format(self.python), 'setup.py', 'sdist', ]) filename = self.get_package_filename() check_call_no_output([ 'twine', ...
python
def upload_by_twine(self): """ upload by twine :return: """ check_call_no_output([ '{}'.format(self.python), 'setup.py', 'sdist', ]) filename = self.get_package_filename() check_call_no_output([ 'twine', ...
[ "def", "upload_by_twine", "(", "self", ")", ":", "check_call_no_output", "(", "[", "'{}'", ".", "format", "(", "self", ".", "python", ")", ",", "'setup.py'", ",", "'sdist'", ",", "]", ")", "filename", "=", "self", ".", "get_package_filename", "(", ")", "...
upload by twine :return:
[ "upload", "by", "twine", ":", "return", ":" ]
train
https://github.com/veltzer/pypitools/blob/5f097be21e9bc65578eed5b6b7855c1945540701/pypitools/common.py#L168-L185
veltzer/pypitools
pypitools/common.py
ConfigData.upload_by_gemfury
def upload_by_gemfury(self): """ upload to gemfury :return: """ check_call_no_output([ '{}'.format(self.python), 'setup.py', 'sdist', ]) filename = self.get_package_filename() # The command line is the one recommended by...
python
def upload_by_gemfury(self): """ upload to gemfury :return: """ check_call_no_output([ '{}'.format(self.python), 'setup.py', 'sdist', ]) filename = self.get_package_filename() # The command line is the one recommended by...
[ "def", "upload_by_gemfury", "(", "self", ")", ":", "check_call_no_output", "(", "[", "'{}'", ".", "format", "(", "self", ".", "python", ")", ",", "'setup.py'", ",", "'sdist'", ",", "]", ")", "filename", "=", "self", ".", "get_package_filename", "(", ")", ...
upload to gemfury :return:
[ "upload", "to", "gemfury", ":", "return", ":" ]
train
https://github.com/veltzer/pypitools/blob/5f097be21e9bc65578eed5b6b7855c1945540701/pypitools/common.py#L187-L205
veltzer/pypitools
pypitools/common.py
ConfigData.upload
def upload(self): """ upload via the method configured :return: """ if self.upload_method == "setup": self.upload_by_setup() if self.upload_method == "twine": self.upload_by_twine() if self.upload_method == "gemfury": self.uploa...
python
def upload(self): """ upload via the method configured :return: """ if self.upload_method == "setup": self.upload_by_setup() if self.upload_method == "twine": self.upload_by_twine() if self.upload_method == "gemfury": self.uploa...
[ "def", "upload", "(", "self", ")", ":", "if", "self", ".", "upload_method", "==", "\"setup\"", ":", "self", ".", "upload_by_setup", "(", ")", "if", "self", ".", "upload_method", "==", "\"twine\"", ":", "self", ".", "upload_by_twine", "(", ")", "if", "sel...
upload via the method configured :return:
[ "upload", "via", "the", "method", "configured", ":", "return", ":" ]
train
https://github.com/veltzer/pypitools/blob/5f097be21e9bc65578eed5b6b7855c1945540701/pypitools/common.py#L207-L217
veltzer/pypitools
pypitools/common.py
ConfigData.register
def register(self): """ Register via the method configured :return: """ if self.register_method == "twine": self.register_by_twine() if self.register_method == "setup": self.register_by_setup() if self.register_method == "upload": ...
python
def register(self): """ Register via the method configured :return: """ if self.register_method == "twine": self.register_by_twine() if self.register_method == "setup": self.register_by_setup() if self.register_method == "upload": ...
[ "def", "register", "(", "self", ")", ":", "if", "self", ".", "register_method", "==", "\"twine\"", ":", "self", ".", "register_by_twine", "(", ")", "if", "self", ".", "register_method", "==", "\"setup\"", ":", "self", ".", "register_by_setup", "(", ")", "i...
Register via the method configured :return:
[ "Register", "via", "the", "method", "configured", ":", "return", ":" ]
train
https://github.com/veltzer/pypitools/blob/5f097be21e9bc65578eed5b6b7855c1945540701/pypitools/common.py#L219-L229
veltzer/pypitools
pypitools/common.py
ConfigData.register_by_twine
def register_by_twine(self): """ register via the twine method :return: """ check_call_no_output([ '{}'.format(self.python), 'setup.py', 'bdist_wheel', ]) # at this point there should be only one file in the 'dist' folder ...
python
def register_by_twine(self): """ register via the twine method :return: """ check_call_no_output([ '{}'.format(self.python), 'setup.py', 'bdist_wheel', ]) # at this point there should be only one file in the 'dist' folder ...
[ "def", "register_by_twine", "(", "self", ")", ":", "check_call_no_output", "(", "[", "'{}'", ".", "format", "(", "self", ".", "python", ")", ",", "'setup.py'", ",", "'bdist_wheel'", ",", "]", ")", "# at this point there should be only one file in the 'dist' folder", ...
register via the twine method :return:
[ "register", "via", "the", "twine", "method", ":", "return", ":" ]
train
https://github.com/veltzer/pypitools/blob/5f097be21e9bc65578eed5b6b7855c1945540701/pypitools/common.py#L244-L261
rsc-dev/pyciagi
pyciagi/__init__.py
difficulties_by_voivodeship
def difficulties_by_voivodeship(voivodeship, dt=datetime.now()): """ Get difficulties in voivodeship. :param voivodeship: Voivodeship numeric value. :param dt: Datetime for data. Default: datetime.now() :return: List of difficulties by voivodeship. """ session = requests.Session() sess...
python
def difficulties_by_voivodeship(voivodeship, dt=datetime.now()): """ Get difficulties in voivodeship. :param voivodeship: Voivodeship numeric value. :param dt: Datetime for data. Default: datetime.now() :return: List of difficulties by voivodeship. """ session = requests.Session() sess...
[ "def", "difficulties_by_voivodeship", "(", "voivodeship", ",", "dt", "=", "datetime", ".", "now", "(", ")", ")", ":", "session", "=", "requests", ".", "Session", "(", ")", "session", ".", "headers", ".", "update", "(", "{", "'User-Agent'", ":", "USER_AGENT...
Get difficulties in voivodeship. :param voivodeship: Voivodeship numeric value. :param dt: Datetime for data. Default: datetime.now() :return: List of difficulties by voivodeship.
[ "Get", "difficulties", "in", "voivodeship", "." ]
train
https://github.com/rsc-dev/pyciagi/blob/cf430442e7fb6c1126fdb0e0e990fc629ba2df3b/pyciagi/__init__.py#L39-L58
treycucco/bidon
bidon/util/terminal.py
table_to_string
def table_to_string(headers, table, align="", *, lines=("-", "-+-", " | ")): """Write a list of headers and a table of rows to the terminal in a nice format. Parameters: - headers: a list of strings that are the headers of the table - table: a list of lists, the actual data to be printed. - align: a string w...
python
def table_to_string(headers, table, align="", *, lines=("-", "-+-", " | ")): """Write a list of headers and a table of rows to the terminal in a nice format. Parameters: - headers: a list of strings that are the headers of the table - table: a list of lists, the actual data to be printed. - align: a string w...
[ "def", "table_to_string", "(", "headers", ",", "table", ",", "align", "=", "\"\"", ",", "*", ",", "lines", "=", "(", "\"-\"", ",", "\"-+-\"", ",", "\" | \"", ")", ")", ":", "header_separator", ",", "header_junction", ",", "row_separator", "=", "lines", "...
Write a list of headers and a table of rows to the terminal in a nice format. Parameters: - headers: a list of strings that are the headers of the table - table: a list of lists, the actual data to be printed. - align: a string whose elements are in the set {'<', '^', '>'}. These define how the values ...
[ "Write", "a", "list", "of", "headers", "and", "a", "table", "of", "rows", "to", "the", "terminal", "in", "a", "nice", "format", "." ]
train
https://github.com/treycucco/bidon/blob/d9f24596841d0e69e8ac70a1d1a1deecea95e340/bidon/util/terminal.py#L115-L140
treycucco/bidon
bidon/util/terminal.py
ProgressPrinter.increment
def increment(self, amount=1, output=True): """Increment progress by a given amount (defaults to 1) and (optionally) output the progress status. """ self._current += amount if output: # NOTE: This algorithm averages out the time it has taken to get to the current / total to # deter...
python
def increment(self, amount=1, output=True): """Increment progress by a given amount (defaults to 1) and (optionally) output the progress status. """ self._current += amount if output: # NOTE: This algorithm averages out the time it has taken to get to the current / total to # deter...
[ "def", "increment", "(", "self", ",", "amount", "=", "1", ",", "output", "=", "True", ")", ":", "self", ".", "_current", "+=", "amount", "if", "output", ":", "# NOTE: This algorithm averages out the time it has taken to get to the current / total to", "# determine...
Increment progress by a given amount (defaults to 1) and (optionally) output the progress status.
[ "Increment", "progress", "by", "a", "given", "amount", "(", "defaults", "to", "1", ")", "and", "(", "optionally", ")", "output", "the", "progress", "status", "." ]
train
https://github.com/treycucco/bidon/blob/d9f24596841d0e69e8ac70a1d1a1deecea95e340/bidon/util/terminal.py#L35-L64
treycucco/bidon
bidon/util/terminal.py
ProgressPrinter.ratio_and_percentage
def ratio_and_percentage(current, total, time_remaining): """Returns the progress ratio and percentage.""" return "{} / {} ({}% completed)".format(current, total, int(current / total * 100))
python
def ratio_and_percentage(current, total, time_remaining): """Returns the progress ratio and percentage.""" return "{} / {} ({}% completed)".format(current, total, int(current / total * 100))
[ "def", "ratio_and_percentage", "(", "current", ",", "total", ",", "time_remaining", ")", ":", "return", "\"{} / {} ({}% completed)\"", ".", "format", "(", "current", ",", "total", ",", "int", "(", "current", "/", "total", "*", "100", ")", ")" ]
Returns the progress ratio and percentage.
[ "Returns", "the", "progress", "ratio", "and", "percentage", "." ]
train
https://github.com/treycucco/bidon/blob/d9f24596841d0e69e8ac70a1d1a1deecea95e340/bidon/util/terminal.py#L86-L88
treycucco/bidon
bidon/util/terminal.py
ProgressPrinter.ratio_and_percentage_with_time_remaining
def ratio_and_percentage_with_time_remaining(current, total, time_remaining): """Returns the progress ratio, percentage and time remaining.""" return "{} / {} ({}% completed) (~{} remaining)".format( current, total, int(current / total * 100), time_remaining)
python
def ratio_and_percentage_with_time_remaining(current, total, time_remaining): """Returns the progress ratio, percentage and time remaining.""" return "{} / {} ({}% completed) (~{} remaining)".format( current, total, int(current / total * 100), time_remaining)
[ "def", "ratio_and_percentage_with_time_remaining", "(", "current", ",", "total", ",", "time_remaining", ")", ":", "return", "\"{} / {} ({}% completed) (~{} remaining)\"", ".", "format", "(", "current", ",", "total", ",", "int", "(", "current", "/", "total", "*", "10...
Returns the progress ratio, percentage and time remaining.
[ "Returns", "the", "progress", "ratio", "percentage", "and", "time", "remaining", "." ]
train
https://github.com/treycucco/bidon/blob/d9f24596841d0e69e8ac70a1d1a1deecea95e340/bidon/util/terminal.py#L101-L107
AshleySetter/frange
frange/frange/frange.py
drange
def drange(start, stop, step): """ A generator that yields successive samples from start (inclusive) to stop (exclusive) in step intervals. Parameters ---------- start : float starting point stop : float stopping point step : float stepping interval Yields ...
python
def drange(start, stop, step): """ A generator that yields successive samples from start (inclusive) to stop (exclusive) in step intervals. Parameters ---------- start : float starting point stop : float stopping point step : float stepping interval Yields ...
[ "def", "drange", "(", "start", ",", "stop", ",", "step", ")", ":", "x", "=", "start", "if", "step", ">", "0", ":", "while", "x", "+", "step", "<=", "stop", ":", "# produces same behaviour as numpy.arange", "yield", "x", "x", "+=", "step", "elif", "step...
A generator that yields successive samples from start (inclusive) to stop (exclusive) in step intervals. Parameters ---------- start : float starting point stop : float stopping point step : float stepping interval Yields ------ x : float next sampl...
[ "A", "generator", "that", "yields", "successive", "samples", "from", "start", "(", "inclusive", ")", "to", "stop", "(", "exclusive", ")", "in", "step", "intervals", "." ]
train
https://github.com/AshleySetter/frange/blob/6b0412d0584fce04c870af82d3e0bf90ed60fb5b/frange/frange/frange.py#L92-L121
AshleySetter/frange
frange/frange/frange.py
frange.get_generator
def get_generator(self): """ Returns a generator for the frange object instance. Returns ------- gen : generator A generator that yields successive samples from start (inclusive) to stop (exclusive) in step steps. """ s = self.slice ...
python
def get_generator(self): """ Returns a generator for the frange object instance. Returns ------- gen : generator A generator that yields successive samples from start (inclusive) to stop (exclusive) in step steps. """ s = self.slice ...
[ "def", "get_generator", "(", "self", ")", ":", "s", "=", "self", ".", "slice", "gen", "=", "drange", "(", "s", ".", "start", ",", "s", ".", "stop", ",", "s", ".", "step", ")", "# intialises the generator", "return", "gen" ]
Returns a generator for the frange object instance. Returns ------- gen : generator A generator that yields successive samples from start (inclusive) to stop (exclusive) in step steps.
[ "Returns", "a", "generator", "for", "the", "frange", "object", "instance", "." ]
train
https://github.com/AshleySetter/frange/blob/6b0412d0584fce04c870af82d3e0bf90ed60fb5b/frange/frange/frange.py#L55-L67
AshleySetter/frange
frange/frange/frange.py
frange.get_array
def get_array(self): """ Returns an numpy array containing the values from start (inclusive) to stop (exclusive) in step steps. Returns ------- array : ndarray Array of values from start (inclusive) to stop (exclusive) in step steps. """ ...
python
def get_array(self): """ Returns an numpy array containing the values from start (inclusive) to stop (exclusive) in step steps. Returns ------- array : ndarray Array of values from start (inclusive) to stop (exclusive) in step steps. """ ...
[ "def", "get_array", "(", "self", ")", ":", "s", "=", "self", ".", "slice", "array", "=", "_np", ".", "arange", "(", "s", ".", "start", ",", "s", ".", "stop", ",", "s", ".", "step", ")", "return", "array" ]
Returns an numpy array containing the values from start (inclusive) to stop (exclusive) in step steps. Returns ------- array : ndarray Array of values from start (inclusive) to stop (exclusive) in step steps.
[ "Returns", "an", "numpy", "array", "containing", "the", "values", "from", "start", "(", "inclusive", ")", "to", "stop", "(", "exclusive", ")", "in", "step", "steps", "." ]
train
https://github.com/AshleySetter/frange/blob/6b0412d0584fce04c870af82d3e0bf90ed60fb5b/frange/frange/frange.py#L69-L82
solocompt/plugs-filter
plugs_filter/utils.py
get_field_lookups
def get_field_lookups(field_type, nullable): """ Return lookup table value and append isnull if this is a nullable field """ return LOOKUP_TABLE.get(field_type) + ['isnull'] if nullable else LOOKUP_TABLE.get(field_type)
python
def get_field_lookups(field_type, nullable): """ Return lookup table value and append isnull if this is a nullable field """ return LOOKUP_TABLE.get(field_type) + ['isnull'] if nullable else LOOKUP_TABLE.get(field_type)
[ "def", "get_field_lookups", "(", "field_type", ",", "nullable", ")", ":", "return", "LOOKUP_TABLE", ".", "get", "(", "field_type", ")", "+", "[", "'isnull'", "]", "if", "nullable", "else", "LOOKUP_TABLE", ".", "get", "(", "field_type", ")" ]
Return lookup table value and append isnull if this is a nullable field
[ "Return", "lookup", "table", "value", "and", "append", "isnull", "if", "this", "is", "a", "nullable", "field" ]
train
https://github.com/solocompt/plugs-filter/blob/cb34c7d662d3f96c07c10b3ed0a34bafef78b52c/plugs_filter/utils.py#L14-L19
solocompt/plugs-filter
plugs_filter/utils.py
match_field
def match_field(field_class): """ Iterates the field_classes and returns the first match """ for cls in field_class.mro(): if cls in list(LOOKUP_TABLE.keys()): return cls # could not match the field class raise Exception('{0} None Found '.format(field_class))
python
def match_field(field_class): """ Iterates the field_classes and returns the first match """ for cls in field_class.mro(): if cls in list(LOOKUP_TABLE.keys()): return cls # could not match the field class raise Exception('{0} None Found '.format(field_class))
[ "def", "match_field", "(", "field_class", ")", ":", "for", "cls", "in", "field_class", ".", "mro", "(", ")", ":", "if", "cls", "in", "list", "(", "LOOKUP_TABLE", ".", "keys", "(", ")", ")", ":", "return", "cls", "# could not match the field class", "raise"...
Iterates the field_classes and returns the first match
[ "Iterates", "the", "field_classes", "and", "returns", "the", "first", "match" ]
train
https://github.com/solocompt/plugs-filter/blob/cb34c7d662d3f96c07c10b3ed0a34bafef78b52c/plugs_filter/utils.py#L21-L30