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 |
|---|---|---|---|---|---|---|---|---|---|---|
hobson/pug-dj | pug/dj/miner/views.py | stats | def stats(request, date_offset=0, fields=None, title_prefix=None, model='WikiItem'):
"""
In addition to chart data in data['chart'], send statistics data to view in data['stats']
"""
data = {}
modified_chart_data = data['chart']['chartdata']
if 'y2' in data['chart']['chartdata']:
matrix... | python | def stats(request, date_offset=0, fields=None, title_prefix=None, model='WikiItem'):
"""
In addition to chart data in data['chart'], send statistics data to view in data['stats']
"""
data = {}
modified_chart_data = data['chart']['chartdata']
if 'y2' in data['chart']['chartdata']:
matrix... | [
"def",
"stats",
"(",
"request",
",",
"date_offset",
"=",
"0",
",",
"fields",
"=",
"None",
",",
"title_prefix",
"=",
"None",
",",
"model",
"=",
"'WikiItem'",
")",
":",
"data",
"=",
"{",
"}",
"modified_chart_data",
"=",
"data",
"[",
"'chart'",
"]",
"[",
... | In addition to chart data in data['chart'], send statistics data to view in data['stats'] | [
"In",
"addition",
"to",
"chart",
"data",
"in",
"data",
"[",
"chart",
"]",
"send",
"statistics",
"data",
"to",
"view",
"in",
"data",
"[",
"stats",
"]"
] | train | https://github.com/hobson/pug-dj/blob/55678b08755a55366ce18e7d3b8ea8fa4491ab04/pug/dj/miner/views.py#L65-L95 |
hobson/pug-dj | pug/dj/miner/views.py | context_from_request | def context_from_request(request, context=None, Form=GetLagForm, delim=',', verbosity=0, **kwargs):
"""Process GET query request to normalize query arguments (split lists, etc)
TODO: Generalize this for any list of API variables/strings and separators for lists
Returns context dict with these updated elem... | python | def context_from_request(request, context=None, Form=GetLagForm, delim=',', verbosity=0, **kwargs):
"""Process GET query request to normalize query arguments (split lists, etc)
TODO: Generalize this for any list of API variables/strings and separators for lists
Returns context dict with these updated elem... | [
"def",
"context_from_request",
"(",
"request",
",",
"context",
"=",
"None",
",",
"Form",
"=",
"GetLagForm",
",",
"delim",
"=",
"','",
",",
"verbosity",
"=",
"0",
",",
"*",
"*",
"kwargs",
")",
":",
"context",
"=",
"context",
"or",
"RequestContext",
"(",
... | Process GET query request to normalize query arguments (split lists, etc)
TODO: Generalize this for any list of API variables/strings and separators for lists
Returns context dict with these updated elements:
context['form'] a Form object populated with the normalized form field values from... | [
"Process",
"GET",
"query",
"request",
"to",
"normalize",
"query",
"arguments",
"(",
"split",
"lists",
"etc",
")"
] | train | https://github.com/hobson/pug-dj/blob/55678b08755a55366ce18e7d3b8ea8fa4491ab04/pug/dj/miner/views.py#L146-L321 |
hobson/pug-dj | pug/dj/miner/views.py | follow_double_underscores | def follow_double_underscores(obj, field_name=None, excel_dialect=True, eval_python=False, index_error_value=None):
'''Like getattr(obj, field_name) only follows model relationships through "__" or "." as link separators
>>> from django.contrib.auth.models import Permission
>>> import math
>>> p = Perm... | python | def follow_double_underscores(obj, field_name=None, excel_dialect=True, eval_python=False, index_error_value=None):
'''Like getattr(obj, field_name) only follows model relationships through "__" or "." as link separators
>>> from django.contrib.auth.models import Permission
>>> import math
>>> p = Perm... | [
"def",
"follow_double_underscores",
"(",
"obj",
",",
"field_name",
"=",
"None",
",",
"excel_dialect",
"=",
"True",
",",
"eval_python",
"=",
"False",
",",
"index_error_value",
"=",
"None",
")",
":",
"if",
"not",
"obj",
":",
"return",
"obj",
"if",
"isinstance"... | Like getattr(obj, field_name) only follows model relationships through "__" or "." as link separators
>>> from django.contrib.auth.models import Permission
>>> import math
>>> p = Permission.objects.all()[0]
>>> follow_double_underscores(p, 'content_type__name') == p.content_type.name
True
>>> ... | [
"Like",
"getattr",
"(",
"obj",
"field_name",
")",
"only",
"follows",
"model",
"relationships",
"through",
"__",
"or",
".",
"as",
"link",
"separators"
] | train | https://github.com/hobson/pug-dj/blob/55678b08755a55366ce18e7d3b8ea8fa4491ab04/pug/dj/miner/views.py#L411-L452 |
hobson/pug-dj | pug/dj/miner/views.py | table_generator_from_list_of_instances | def table_generator_from_list_of_instances(data, field_names=None, excluded_field_names=None, sort=True, excel_dialect=True, eval_python=False):
'''Return an iterator over the model instances (or queryset) that yeilds lists of values
This forms a table suitable for output as a csv
FIXME: allow specificati... | python | def table_generator_from_list_of_instances(data, field_names=None, excluded_field_names=None, sort=True, excel_dialect=True, eval_python=False):
'''Return an iterator over the model instances (or queryset) that yeilds lists of values
This forms a table suitable for output as a csv
FIXME: allow specificati... | [
"def",
"table_generator_from_list_of_instances",
"(",
"data",
",",
"field_names",
"=",
"None",
",",
"excluded_field_names",
"=",
"None",
",",
"sort",
"=",
"True",
",",
"excel_dialect",
"=",
"True",
",",
"eval_python",
"=",
"False",
")",
":",
"excluded_field_names"... | Return an iterator over the model instances (or queryset) that yeilds lists of values
This forms a table suitable for output as a csv
FIXME: allow specification of related field values with double_underscore
>>> from django.contrib.auth.models import Permission
>>> from django.db.models.base import M... | [
"Return",
"an",
"iterator",
"over",
"the",
"model",
"instances",
"(",
"or",
"queryset",
")",
"that",
"yeilds",
"lists",
"of",
"values"
] | train | https://github.com/hobson/pug-dj/blob/55678b08755a55366ce18e7d3b8ea8fa4491ab04/pug/dj/miner/views.py#L455-L495 |
hobson/pug-dj | pug/dj/miner/views.py | csv_response_from_context | def csv_response_from_context(context=None, filename=None, field_names=None, null_string='', eval_python=True):
"""Generate the response for a Download CSV button from data within the context dict
The CSV data must be in one of these places/formats:
* context as a list of lists of python values (strings f... | python | def csv_response_from_context(context=None, filename=None, field_names=None, null_string='', eval_python=True):
"""Generate the response for a Download CSV button from data within the context dict
The CSV data must be in one of these places/formats:
* context as a list of lists of python values (strings f... | [
"def",
"csv_response_from_context",
"(",
"context",
"=",
"None",
",",
"filename",
"=",
"None",
",",
"field_names",
"=",
"None",
",",
"null_string",
"=",
"''",
",",
"eval_python",
"=",
"True",
")",
":",
"filename",
"=",
"filename",
"or",
"context",
".",
"ge... | Generate the response for a Download CSV button from data within the context dict
The CSV data must be in one of these places/formats:
* context as a list of lists of python values (strings for headers in first list)
* context['data']['d3data'] as a string in json format (python) for a list of lists of re... | [
"Generate",
"the",
"response",
"for",
"a",
"Download",
"CSV",
"button",
"from",
"data",
"within",
"the",
"context",
"dict"
] | train | https://github.com/hobson/pug-dj/blob/55678b08755a55366ce18e7d3b8ea8fa4491ab04/pug/dj/miner/views.py#L541-L592 |
hobson/pug-dj | pug/dj/miner/views.py | JSONView.render_to_response | def render_to_response(self, context, indent=None):
"Returns a JSON response containing 'context' as payload"
return self.get_json_response(self.convert_context_to_json(context, indent=indent)) | python | def render_to_response(self, context, indent=None):
"Returns a JSON response containing 'context' as payload"
return self.get_json_response(self.convert_context_to_json(context, indent=indent)) | [
"def",
"render_to_response",
"(",
"self",
",",
"context",
",",
"indent",
"=",
"None",
")",
":",
"return",
"self",
".",
"get_json_response",
"(",
"self",
".",
"convert_context_to_json",
"(",
"context",
",",
"indent",
"=",
"indent",
")",
")"
] | Returns a JSON response containing 'context' as payload | [
"Returns",
"a",
"JSON",
"response",
"containing",
"context",
"as",
"payload"
] | train | https://github.com/hobson/pug-dj/blob/55678b08755a55366ce18e7d3b8ea8fa4491ab04/pug/dj/miner/views.py#L126-L128 |
pavelsof/ipalint | ipalint/strnorm.py | Normaliser.normalise | def normalise(self, string, line_num):
"""
Strips the whitespace and applies Unicode normalisation to the given
string. The second arg is used as an ID of the string when reporting
its lint errors (if such).
"""
stripped = string.strip()
if stripped != string:
self.strip_errors.append(line_num)
nfc_... | python | def normalise(self, string, line_num):
"""
Strips the whitespace and applies Unicode normalisation to the given
string. The second arg is used as an ID of the string when reporting
its lint errors (if such).
"""
stripped = string.strip()
if stripped != string:
self.strip_errors.append(line_num)
nfc_... | [
"def",
"normalise",
"(",
"self",
",",
"string",
",",
"line_num",
")",
":",
"stripped",
"=",
"string",
".",
"strip",
"(",
")",
"if",
"stripped",
"!=",
"string",
":",
"self",
".",
"strip_errors",
".",
"append",
"(",
"line_num",
")",
"nfc_pos",
"=",
"[",
... | Strips the whitespace and applies Unicode normalisation to the given
string. The second arg is used as an ID of the string when reporting
its lint errors (if such). | [
"Strips",
"the",
"whitespace",
"and",
"applies",
"Unicode",
"normalisation",
"to",
"the",
"given",
"string",
".",
"The",
"second",
"arg",
"is",
"used",
"as",
"an",
"ID",
"of",
"the",
"string",
"when",
"reporting",
"its",
"lint",
"errors",
"(",
"if",
"such"... | train | https://github.com/pavelsof/ipalint/blob/763e5979ede6980cbfc746b06fd007b379762eeb/ipalint/strnorm.py#L28-L60 |
pavelsof/ipalint | ipalint/strnorm.py | Normaliser.report | def report(self, reporter, ignore_nfd=False, ignore_ws=False):
"""
Adds the problems that have been found so far to the given Reporter
instance. The two keyword args can be used to restrict the error types
to be reported.
"""
if self.strip_errors and not ignore_ws:
reporter.add(self.strip_errors, 'leadin... | python | def report(self, reporter, ignore_nfd=False, ignore_ws=False):
"""
Adds the problems that have been found so far to the given Reporter
instance. The two keyword args can be used to restrict the error types
to be reported.
"""
if self.strip_errors and not ignore_ws:
reporter.add(self.strip_errors, 'leadin... | [
"def",
"report",
"(",
"self",
",",
"reporter",
",",
"ignore_nfd",
"=",
"False",
",",
"ignore_ws",
"=",
"False",
")",
":",
"if",
"self",
".",
"strip_errors",
"and",
"not",
"ignore_ws",
":",
"reporter",
".",
"add",
"(",
"self",
".",
"strip_errors",
",",
... | Adds the problems that have been found so far to the given Reporter
instance. The two keyword args can be used to restrict the error types
to be reported. | [
"Adds",
"the",
"problems",
"that",
"have",
"been",
"found",
"so",
"far",
"to",
"the",
"given",
"Reporter",
"instance",
".",
"The",
"two",
"keyword",
"args",
"can",
"be",
"used",
"to",
"restrict",
"the",
"error",
"types",
"to",
"be",
"reported",
"."
] | train | https://github.com/pavelsof/ipalint/blob/763e5979ede6980cbfc746b06fd007b379762eeb/ipalint/strnorm.py#L63-L73 |
peepall/FancyLogger | FancyLogger/processing/__init__.py | MultiprocessingLogger.set_configuration | def set_configuration(self, command):
"""
Defines the current configuration of the logger. Can be used at any moment during runtime to modify the logger
behavior.
:param command: The command object that holds all the necessary information from the remote process.
"""
self... | python | def set_configuration(self, command):
"""
Defines the current configuration of the logger. Can be used at any moment during runtime to modify the logger
behavior.
:param command: The command object that holds all the necessary information from the remote process.
"""
self... | [
"def",
"set_configuration",
"(",
"self",
",",
"command",
")",
":",
"self",
".",
"permanent_progressbar_slots",
"=",
"command",
".",
"permanent_progressbar_slots",
"self",
".",
"redraw_frequency_millis",
"=",
"command",
".",
"redraw_frequency_millis",
"self",
".",
"con... | Defines the current configuration of the logger. Can be used at any moment during runtime to modify the logger
behavior.
:param command: The command object that holds all the necessary information from the remote process. | [
"Defines",
"the",
"current",
"configuration",
"of",
"the",
"logger",
".",
"Can",
"be",
"used",
"at",
"any",
"moment",
"during",
"runtime",
"to",
"modify",
"the",
"logger",
"behavior",
".",
":",
"param",
"command",
":",
"The",
"command",
"object",
"that",
"... | train | https://github.com/peepall/FancyLogger/blob/7f13f1397e76ed768fb6b6358194118831fafc6d/FancyLogger/processing/__init__.py#L155-L223 |
peepall/FancyLogger | FancyLogger/processing/__init__.py | MultiprocessingLogger.run | def run(self):
"""
The main loop for the logger process. Will receive remote processes orders one by one and wait for the next one.
Then return from this method when the main application calls for exit, which is a regular command.
"""
# Initialize the file logger
self.log... | python | def run(self):
"""
The main loop for the logger process. Will receive remote processes orders one by one and wait for the next one.
Then return from this method when the main application calls for exit, which is a regular command.
"""
# Initialize the file logger
self.log... | [
"def",
"run",
"(",
"self",
")",
":",
"# Initialize the file logger",
"self",
".",
"log",
"=",
"getLogger",
"(",
")",
"# Deserialize configuration",
"self",
".",
"set_config_command",
"=",
"dill",
".",
"loads",
"(",
"self",
".",
"set_config_command",
")",
"self",... | The main loop for the logger process. Will receive remote processes orders one by one and wait for the next one.
Then return from this method when the main application calls for exit, which is a regular command. | [
"The",
"main",
"loop",
"for",
"the",
"logger",
"process",
".",
"Will",
"receive",
"remote",
"processes",
"orders",
"one",
"by",
"one",
"and",
"wait",
"for",
"the",
"next",
"one",
".",
"Then",
"return",
"from",
"this",
"method",
"when",
"the",
"main",
"ap... | train | https://github.com/peepall/FancyLogger/blob/7f13f1397e76ed768fb6b6358194118831fafc6d/FancyLogger/processing/__init__.py#L225-L283 |
peepall/FancyLogger | FancyLogger/processing/__init__.py | MultiprocessingLogger.longest_bar_prefix_value | def longest_bar_prefix_value(self):
"""
Calculates the longest progress bar prefix in order to keep all progress bars left-aligned.
:return: Length of the longest task prefix in character unit.
"""
longest = 0
for key, t in self.tasks.items():
size = len(t.pre... | python | def longest_bar_prefix_value(self):
"""
Calculates the longest progress bar prefix in order to keep all progress bars left-aligned.
:return: Length of the longest task prefix in character unit.
"""
longest = 0
for key, t in self.tasks.items():
size = len(t.pre... | [
"def",
"longest_bar_prefix_value",
"(",
"self",
")",
":",
"longest",
"=",
"0",
"for",
"key",
",",
"t",
"in",
"self",
".",
"tasks",
".",
"items",
"(",
")",
":",
"size",
"=",
"len",
"(",
"t",
".",
"prefix",
")",
"if",
"size",
">",
"longest",
":",
"... | Calculates the longest progress bar prefix in order to keep all progress bars left-aligned.
:return: Length of the longest task prefix in character unit. | [
"Calculates",
"the",
"longest",
"progress",
"bar",
"prefix",
"in",
"order",
"to",
"keep",
"all",
"progress",
"bars",
"left",
"-",
"aligned",
".",
":",
"return",
":",
"Length",
"of",
"the",
"longest",
"task",
"prefix",
"in",
"character",
"unit",
"."
] | train | https://github.com/peepall/FancyLogger/blob/7f13f1397e76ed768fb6b6358194118831fafc6d/FancyLogger/processing/__init__.py#L285-L296 |
peepall/FancyLogger | FancyLogger/processing/__init__.py | MultiprocessingLogger.millis_to_human_readable | def millis_to_human_readable(time_millis):
"""
Calculates the equivalent time of the given milliseconds into a human readable string from seconds to weeks.
:param time_millis: Time in milliseconds using python time library.
:return: Human readable time string. Example: 2 min 3... | python | def millis_to_human_readable(time_millis):
"""
Calculates the equivalent time of the given milliseconds into a human readable string from seconds to weeks.
:param time_millis: Time in milliseconds using python time library.
:return: Human readable time string. Example: 2 min 3... | [
"def",
"millis_to_human_readable",
"(",
"time_millis",
")",
":",
"weeks",
"=",
"0",
"days",
"=",
"0",
"hours",
"=",
"0",
"minutes",
"=",
"0",
"seconds",
"=",
"round",
"(",
"time_millis",
"/",
"1000",
")",
"while",
"seconds",
">",
"59",
":",
"seconds",
... | Calculates the equivalent time of the given milliseconds into a human readable string from seconds to weeks.
:param time_millis: Time in milliseconds using python time library.
:return: Human readable time string. Example: 2 min 3 s. | [
"Calculates",
"the",
"equivalent",
"time",
"of",
"the",
"given",
"milliseconds",
"into",
"a",
"human",
"readable",
"string",
"from",
"seconds",
"to",
"weeks",
".",
":",
"param",
"time_millis",
":",
"Time",
"in",
"milliseconds",
"using",
"python",
"time",
"libr... | train | https://github.com/peepall/FancyLogger/blob/7f13f1397e76ed768fb6b6358194118831fafc6d/FancyLogger/processing/__init__.py#L299-L340 |
peepall/FancyLogger | FancyLogger/processing/__init__.py | MultiprocessingLogger.print_progress_bar | def print_progress_bar(self, task):
"""
Draws a progress bar on screen based on the given information using standard output (stdout).
:param task: TaskProgress object containing all required information to draw a progress bar at the given state.
"""
str_format = "{0:." + str(task... | python | def print_progress_bar(self, task):
"""
Draws a progress bar on screen based on the given information using standard output (stdout).
:param task: TaskProgress object containing all required information to draw a progress bar at the given state.
"""
str_format = "{0:." + str(task... | [
"def",
"print_progress_bar",
"(",
"self",
",",
"task",
")",
":",
"str_format",
"=",
"\"{0:.\"",
"+",
"str",
"(",
"task",
".",
"decimals",
")",
"+",
"\"f}\"",
"percents",
"=",
"str_format",
".",
"format",
"(",
"100",
"*",
"(",
"task",
".",
"progress",
"... | Draws a progress bar on screen based on the given information using standard output (stdout).
:param task: TaskProgress object containing all required information to draw a progress bar at the given state. | [
"Draws",
"a",
"progress",
"bar",
"on",
"screen",
"based",
"on",
"the",
"given",
"information",
"using",
"standard",
"output",
"(",
"stdout",
")",
".",
":",
"param",
"task",
":",
"TaskProgress",
"object",
"containing",
"all",
"required",
"information",
"to",
... | train | https://github.com/peepall/FancyLogger/blob/7f13f1397e76ed768fb6b6358194118831fafc6d/FancyLogger/processing/__init__.py#L342-L384 |
peepall/FancyLogger | FancyLogger/processing/__init__.py | MultiprocessingLogger.redraw | def redraw(self):
"""
Clears the console and performs a complete redraw of all progress bars and then awaiting logger messages if the
minimum time elapsed since the last redraw is enough.
"""
# Check if the refresh time lapse has elapsed and if a change requires to redraw
... | python | def redraw(self):
"""
Clears the console and performs a complete redraw of all progress bars and then awaiting logger messages if the
minimum time elapsed since the last redraw is enough.
"""
# Check if the refresh time lapse has elapsed and if a change requires to redraw
... | [
"def",
"redraw",
"(",
"self",
")",
":",
"# Check if the refresh time lapse has elapsed and if a change requires to redraw",
"lapse_since_last_refresh",
"=",
"millis",
"(",
")",
"-",
"self",
".",
"refresh_timer",
"if",
"not",
"lapse_since_last_refresh",
">",
"self",
".",
"... | Clears the console and performs a complete redraw of all progress bars and then awaiting logger messages if the
minimum time elapsed since the last redraw is enough. | [
"Clears",
"the",
"console",
"and",
"performs",
"a",
"complete",
"redraw",
"of",
"all",
"progress",
"bars",
"and",
"then",
"awaiting",
"logger",
"messages",
"if",
"the",
"minimum",
"time",
"elapsed",
"since",
"the",
"last",
"redraw",
"is",
"enough",
"."
] | train | https://github.com/peepall/FancyLogger/blob/7f13f1397e76ed768fb6b6358194118831fafc6d/FancyLogger/processing/__init__.py#L386-L455 |
peepall/FancyLogger | FancyLogger/processing/__init__.py | MultiprocessingLogger.append_message | def append_message(self,
message):
"""
Appends the given message at the end of the message list and delete the oldest one (top most).
:param message: The formatted text to log.
"""
# Delete the first message of the list
if len(self.messages) > 0:
... | python | def append_message(self,
message):
"""
Appends the given message at the end of the message list and delete the oldest one (top most).
:param message: The formatted text to log.
"""
# Delete the first message of the list
if len(self.messages) > 0:
... | [
"def",
"append_message",
"(",
"self",
",",
"message",
")",
":",
"# Delete the first message of the list",
"if",
"len",
"(",
"self",
".",
"messages",
")",
">",
"0",
":",
"del",
"self",
".",
"messages",
"[",
"0",
"]",
"# Append the new message at the end",
"self",... | Appends the given message at the end of the message list and delete the oldest one (top most).
:param message: The formatted text to log. | [
"Appends",
"the",
"given",
"message",
"at",
"the",
"end",
"of",
"the",
"message",
"list",
"and",
"delete",
"the",
"oldest",
"one",
"(",
"top",
"most",
")",
".",
":",
"param",
"message",
":",
"The",
"formatted",
"text",
"to",
"log",
"."
] | train | https://github.com/peepall/FancyLogger/blob/7f13f1397e76ed768fb6b6358194118831fafc6d/FancyLogger/processing/__init__.py#L457-L472 |
peepall/FancyLogger | FancyLogger/processing/__init__.py | MultiprocessingLogger.append_exception | def append_exception(self,
stacktrace):
"""
Appends the given exception at the top of the exception list and delete the oldest one (bottom most).
:param stacktrace: Stacktrace string as returned by 'traceback.format_exc()' in an 'except' block.
"""
# Dele... | python | def append_exception(self,
stacktrace):
"""
Appends the given exception at the top of the exception list and delete the oldest one (bottom most).
:param stacktrace: Stacktrace string as returned by 'traceback.format_exc()' in an 'except' block.
"""
# Dele... | [
"def",
"append_exception",
"(",
"self",
",",
"stacktrace",
")",
":",
"# Delete the last message of the list",
"if",
"len",
"(",
"self",
".",
"exceptions",
")",
">",
"0",
":",
"del",
"self",
".",
"exceptions",
"[",
"-",
"1",
"]",
"# Append the new message at the ... | Appends the given exception at the top of the exception list and delete the oldest one (bottom most).
:param stacktrace: Stacktrace string as returned by 'traceback.format_exc()' in an 'except' block. | [
"Appends",
"the",
"given",
"exception",
"at",
"the",
"top",
"of",
"the",
"exception",
"list",
"and",
"delete",
"the",
"oldest",
"one",
"(",
"bottom",
"most",
")",
".",
":",
"param",
"stacktrace",
":",
"Stacktrace",
"string",
"as",
"returned",
"by",
"traceb... | train | https://github.com/peepall/FancyLogger/blob/7f13f1397e76ed768fb6b6358194118831fafc6d/FancyLogger/processing/__init__.py#L474-L489 |
peepall/FancyLogger | FancyLogger/processing/__init__.py | MultiprocessingLogger.set_level | def set_level(self, command):
"""
Defines the logging level (from standard logging module) for log messages.
:param command: The command object that holds all the necessary information from the remote process.
"""
if not command.console_only:
self.log.setLevel(command... | python | def set_level(self, command):
"""
Defines the logging level (from standard logging module) for log messages.
:param command: The command object that holds all the necessary information from the remote process.
"""
if not command.console_only:
self.log.setLevel(command... | [
"def",
"set_level",
"(",
"self",
",",
"command",
")",
":",
"if",
"not",
"command",
".",
"console_only",
":",
"self",
".",
"log",
".",
"setLevel",
"(",
"command",
".",
"level",
")",
"self",
".",
"console_level",
"=",
"command",
".",
"level"
] | Defines the logging level (from standard logging module) for log messages.
:param command: The command object that holds all the necessary information from the remote process. | [
"Defines",
"the",
"logging",
"level",
"(",
"from",
"standard",
"logging",
"module",
")",
"for",
"log",
"messages",
".",
":",
"param",
"command",
":",
"The",
"command",
"object",
"that",
"holds",
"all",
"the",
"necessary",
"information",
"from",
"the",
"remot... | train | https://github.com/peepall/FancyLogger/blob/7f13f1397e76ed768fb6b6358194118831fafc6d/FancyLogger/processing/__init__.py#L517-L525 |
peepall/FancyLogger | FancyLogger/processing/__init__.py | MultiprocessingLogger.set_task | def set_task(self, command):
"""
Defines a new progress bar with the given information.
:param command: The command object that holds all the necessary information from the remote process.
"""
self.tasks[command.task_id] = command.task
self.longest_bar_prefix_size = self... | python | def set_task(self, command):
"""
Defines a new progress bar with the given information.
:param command: The command object that holds all the necessary information from the remote process.
"""
self.tasks[command.task_id] = command.task
self.longest_bar_prefix_size = self... | [
"def",
"set_task",
"(",
"self",
",",
"command",
")",
":",
"self",
".",
"tasks",
"[",
"command",
".",
"task_id",
"]",
"=",
"command",
".",
"task",
"self",
".",
"longest_bar_prefix_size",
"=",
"self",
".",
"longest_bar_prefix_value",
"(",
")",
"# Redraw",
"s... | Defines a new progress bar with the given information.
:param command: The command object that holds all the necessary information from the remote process. | [
"Defines",
"a",
"new",
"progress",
"bar",
"with",
"the",
"given",
"information",
".",
":",
"param",
"command",
":",
"The",
"command",
"object",
"that",
"holds",
"all",
"the",
"necessary",
"information",
"from",
"the",
"remote",
"process",
"."
] | train | https://github.com/peepall/FancyLogger/blob/7f13f1397e76ed768fb6b6358194118831fafc6d/FancyLogger/processing/__init__.py#L527-L538 |
peepall/FancyLogger | FancyLogger/processing/__init__.py | MultiprocessingLogger.update | def update(self, command):
"""
Defines the current progress for this progress bar id in iteration units (not percent).
If the given id does not exist or the given progress is identical to the current, then does nothing.
Logger uses a redraw rate because of console flickering. That means ... | python | def update(self, command):
"""
Defines the current progress for this progress bar id in iteration units (not percent).
If the given id does not exist or the given progress is identical to the current, then does nothing.
Logger uses a redraw rate because of console flickering. That means ... | [
"def",
"update",
"(",
"self",
",",
"command",
")",
":",
"if",
"command",
".",
"task_id",
"in",
"self",
".",
"tasks",
"and",
"self",
".",
"tasks",
"[",
"command",
".",
"task_id",
"]",
".",
"set_progress",
"(",
"command",
".",
"progress",
")",
":",
"# ... | Defines the current progress for this progress bar id in iteration units (not percent).
If the given id does not exist or the given progress is identical to the current, then does nothing.
Logger uses a redraw rate because of console flickering. That means it will not draw new messages or progress
... | [
"Defines",
"the",
"current",
"progress",
"for",
"this",
"progress",
"bar",
"id",
"in",
"iteration",
"units",
"(",
"not",
"percent",
")",
".",
"If",
"the",
"given",
"id",
"does",
"not",
"exist",
"or",
"the",
"given",
"progress",
"is",
"identical",
"to",
"... | train | https://github.com/peepall/FancyLogger/blob/7f13f1397e76ed768fb6b6358194118831fafc6d/FancyLogger/processing/__init__.py#L540-L554 |
peepall/FancyLogger | FancyLogger/processing/__init__.py | MultiprocessingLogger.debug | def debug(self, command):
"""
Posts a debug message adding a timestamp and logging level to it for both file and console handlers.
Logger uses a redraw rate because of console flickering. That means it will not draw new messages or progress
at the very time they are being logged but thei... | python | def debug(self, command):
"""
Posts a debug message adding a timestamp and logging level to it for both file and console handlers.
Logger uses a redraw rate because of console flickering. That means it will not draw new messages or progress
at the very time they are being logged but thei... | [
"def",
"debug",
"(",
"self",
",",
"command",
")",
":",
"if",
"self",
".",
"console_level",
"==",
"logging",
".",
"DEBUG",
":",
"message",
"=",
"self",
".",
"get_format",
"(",
")",
"message",
"=",
"message",
".",
"replace",
"(",
"'{L}'",
",",
"'DEBUG'",... | Posts a debug message adding a timestamp and logging level to it for both file and console handlers.
Logger uses a redraw rate because of console flickering. That means it will not draw new messages or progress
at the very time they are being logged but their timestamp will be captured at the right time... | [
"Posts",
"a",
"debug",
"message",
"adding",
"a",
"timestamp",
"and",
"logging",
"level",
"to",
"it",
"for",
"both",
"file",
"and",
"console",
"handlers",
".",
"Logger",
"uses",
"a",
"redraw",
"rate",
"because",
"of",
"console",
"flickering",
".",
"That",
"... | train | https://github.com/peepall/FancyLogger/blob/7f13f1397e76ed768fb6b6358194118831fafc6d/FancyLogger/processing/__init__.py#L556-L577 |
peepall/FancyLogger | FancyLogger/processing/__init__.py | MultiprocessingLogger.throw | def throw(self, command):
"""
Posts an exception's stacktrace string as returned by 'traceback.format_exc()' in an 'except' block.
:param command: The command object that holds all the necessary information from the remote process.
"""
exception_message = '[Process {}{}]:\n{}'.fo... | python | def throw(self, command):
"""
Posts an exception's stacktrace string as returned by 'traceback.format_exc()' in an 'except' block.
:param command: The command object that holds all the necessary information from the remote process.
"""
exception_message = '[Process {}{}]:\n{}'.fo... | [
"def",
"throw",
"(",
"self",
",",
"command",
")",
":",
"exception_message",
"=",
"'[Process {}{}]:\\n{}'",
".",
"format",
"(",
"command",
".",
"pid",
",",
"' - {}'",
".",
"format",
"(",
"command",
".",
"process_title",
")",
"if",
"command",
".",
"process_tit... | Posts an exception's stacktrace string as returned by 'traceback.format_exc()' in an 'except' block.
:param command: The command object that holds all the necessary information from the remote process. | [
"Posts",
"an",
"exception",
"s",
"stacktrace",
"string",
"as",
"returned",
"by",
"traceback",
".",
"format_exc",
"()",
"in",
"an",
"except",
"block",
".",
":",
"param",
"command",
":",
"The",
"command",
"object",
"that",
"holds",
"all",
"the",
"necessary",
... | train | https://github.com/peepall/FancyLogger/blob/7f13f1397e76ed768fb6b6358194118831fafc6d/FancyLogger/processing/__init__.py#L681-L700 |
esterhui/pypu | pypu/servicemanager.py | servicemanager.GetServices | def GetServices(self,filename):
"""Returns a list of service objects handling this file type"""
objlist=[]
for sobj in self.services:
if sobj.KnowsFile(filename) :
objlist.append(sobj)
if len(objlist)==0:
return None
return objlist | python | def GetServices(self,filename):
"""Returns a list of service objects handling this file type"""
objlist=[]
for sobj in self.services:
if sobj.KnowsFile(filename) :
objlist.append(sobj)
if len(objlist)==0:
return None
return objlist | [
"def",
"GetServices",
"(",
"self",
",",
"filename",
")",
":",
"objlist",
"=",
"[",
"]",
"for",
"sobj",
"in",
"self",
".",
"services",
":",
"if",
"sobj",
".",
"KnowsFile",
"(",
"filename",
")",
":",
"objlist",
".",
"append",
"(",
"sobj",
")",
"if",
... | Returns a list of service objects handling this file type | [
"Returns",
"a",
"list",
"of",
"service",
"objects",
"handling",
"this",
"file",
"type"
] | train | https://github.com/esterhui/pypu/blob/cc3e259d59f024c2c4c0fbb9c8a1547e51de75ec/pypu/servicemanager.py#L13-L23 |
esterhui/pypu | pypu/servicemanager.py | servicemanager.GetServiceObj | def GetServiceObj(self,servicename):
"""Given a service name string, returns
the object that corresponds to the service"""
for sobj in self.services:
if sobj.GetName().lower()==servicename.lower():
return sobj
return None | python | def GetServiceObj(self,servicename):
"""Given a service name string, returns
the object that corresponds to the service"""
for sobj in self.services:
if sobj.GetName().lower()==servicename.lower():
return sobj
return None | [
"def",
"GetServiceObj",
"(",
"self",
",",
"servicename",
")",
":",
"for",
"sobj",
"in",
"self",
".",
"services",
":",
"if",
"sobj",
".",
"GetName",
"(",
")",
".",
"lower",
"(",
")",
"==",
"servicename",
".",
"lower",
"(",
")",
":",
"return",
"sobj",
... | Given a service name string, returns
the object that corresponds to the service | [
"Given",
"a",
"service",
"name",
"string",
"returns",
"the",
"object",
"that",
"corresponds",
"to",
"the",
"service"
] | train | https://github.com/esterhui/pypu/blob/cc3e259d59f024c2c4c0fbb9c8a1547e51de75ec/pypu/servicemanager.py#L25-L32 |
fictorial/filesysdb | filesysdb/__init__.py | object_path | def object_path(collection, id):
"""Returns path to the backing file of the object
with the given ``id`` in the given ``collection``.
Note that the ``id`` is made filesystem-safe by
"normalizing" its string representation."""
_logger.debug(type(id))
_logger.debug(id)
if isinstance(id, dict) ... | python | def object_path(collection, id):
"""Returns path to the backing file of the object
with the given ``id`` in the given ``collection``.
Note that the ``id`` is made filesystem-safe by
"normalizing" its string representation."""
_logger.debug(type(id))
_logger.debug(id)
if isinstance(id, dict) ... | [
"def",
"object_path",
"(",
"collection",
",",
"id",
")",
":",
"_logger",
".",
"debug",
"(",
"type",
"(",
"id",
")",
")",
"_logger",
".",
"debug",
"(",
"id",
")",
"if",
"isinstance",
"(",
"id",
",",
"dict",
")",
"and",
"'id'",
"in",
"id",
":",
"id... | Returns path to the backing file of the object
with the given ``id`` in the given ``collection``.
Note that the ``id`` is made filesystem-safe by
"normalizing" its string representation. | [
"Returns",
"path",
"to",
"the",
"backing",
"file",
"of",
"the",
"object",
"with",
"the",
"given",
"id",
"in",
"the",
"given",
"collection",
".",
"Note",
"that",
"the",
"id",
"is",
"made",
"filesystem",
"-",
"safe",
"by",
"normalizing",
"its",
"string",
"... | train | https://github.com/fictorial/filesysdb/blob/bbf1e32218b71c7c15c33ada660433fffc6fa6ab/filesysdb/__init__.py#L49-L60 |
fictorial/filesysdb | filesysdb/__init__.py | load_object_at_path | def load_object_at_path(path):
"""Load an object from disk at explicit path"""
with open(path, 'r') as f:
data = _deserialize(f.read())
return aadict(data) | python | def load_object_at_path(path):
"""Load an object from disk at explicit path"""
with open(path, 'r') as f:
data = _deserialize(f.read())
return aadict(data) | [
"def",
"load_object_at_path",
"(",
"path",
")",
":",
"with",
"open",
"(",
"path",
",",
"'r'",
")",
"as",
"f",
":",
"data",
"=",
"_deserialize",
"(",
"f",
".",
"read",
"(",
")",
")",
"return",
"aadict",
"(",
"data",
")"
] | Load an object from disk at explicit path | [
"Load",
"an",
"object",
"from",
"disk",
"at",
"explicit",
"path"
] | train | https://github.com/fictorial/filesysdb/blob/bbf1e32218b71c7c15c33ada660433fffc6fa6ab/filesysdb/__init__.py#L68-L72 |
fictorial/filesysdb | filesysdb/__init__.py | add_collection | def add_collection(collection,
cache_size=1000,
cache_cls=LRUCache,
**cache_args):
"""Add a collection named ``collection``."""
assert collection not in _db
cache = cache_cls(maxsize=cache_size,
missing=lambda id: load_object(col... | python | def add_collection(collection,
cache_size=1000,
cache_cls=LRUCache,
**cache_args):
"""Add a collection named ``collection``."""
assert collection not in _db
cache = cache_cls(maxsize=cache_size,
missing=lambda id: load_object(col... | [
"def",
"add_collection",
"(",
"collection",
",",
"cache_size",
"=",
"1000",
",",
"cache_cls",
"=",
"LRUCache",
",",
"*",
"*",
"cache_args",
")",
":",
"assert",
"collection",
"not",
"in",
"_db",
"cache",
"=",
"cache_cls",
"(",
"maxsize",
"=",
"cache_size",
... | Add a collection named ``collection``. | [
"Add",
"a",
"collection",
"named",
"collection",
"."
] | train | https://github.com/fictorial/filesysdb/blob/bbf1e32218b71c7c15c33ada660433fffc6fa6ab/filesysdb/__init__.py#L87-L96 |
fictorial/filesysdb | filesysdb/__init__.py | prepare | def prepare(base_path='data',
serialize=json.dumps,
deserialize=json.loads,
file_ext='json'):
"""After you have added your collections, prepare the database
for use."""
global _basepath, _deserialize, _serialize, _ext
_basepath = base_path
assert callable(serializ... | python | def prepare(base_path='data',
serialize=json.dumps,
deserialize=json.loads,
file_ext='json'):
"""After you have added your collections, prepare the database
for use."""
global _basepath, _deserialize, _serialize, _ext
_basepath = base_path
assert callable(serializ... | [
"def",
"prepare",
"(",
"base_path",
"=",
"'data'",
",",
"serialize",
"=",
"json",
".",
"dumps",
",",
"deserialize",
"=",
"json",
".",
"loads",
",",
"file_ext",
"=",
"'json'",
")",
":",
"global",
"_basepath",
",",
"_deserialize",
",",
"_serialize",
",",
"... | After you have added your collections, prepare the database
for use. | [
"After",
"you",
"have",
"added",
"your",
"collections",
"prepare",
"the",
"database",
"for",
"use",
"."
] | train | https://github.com/fictorial/filesysdb/blob/bbf1e32218b71c7c15c33ada660433fffc6fa6ab/filesysdb/__init__.py#L103-L123 |
fictorial/filesysdb | filesysdb/__init__.py | each_object | def each_object(collection):
"""Yields each object in the given ``collection``.
The objects are loaded from cache and failing that,
from disk."""
c_path = collection_path(collection)
paths = glob('%s/*.%s' % (c_path, _ext))
for path in paths:
yield load_object_at_path(path) | python | def each_object(collection):
"""Yields each object in the given ``collection``.
The objects are loaded from cache and failing that,
from disk."""
c_path = collection_path(collection)
paths = glob('%s/*.%s' % (c_path, _ext))
for path in paths:
yield load_object_at_path(path) | [
"def",
"each_object",
"(",
"collection",
")",
":",
"c_path",
"=",
"collection_path",
"(",
"collection",
")",
"paths",
"=",
"glob",
"(",
"'%s/*.%s'",
"%",
"(",
"c_path",
",",
"_ext",
")",
")",
"for",
"path",
"in",
"paths",
":",
"yield",
"load_object_at_path... | Yields each object in the given ``collection``.
The objects are loaded from cache and failing that,
from disk. | [
"Yields",
"each",
"object",
"in",
"the",
"given",
"collection",
".",
"The",
"objects",
"are",
"loaded",
"from",
"cache",
"and",
"failing",
"that",
"from",
"disk",
"."
] | train | https://github.com/fictorial/filesysdb/blob/bbf1e32218b71c7c15c33ada660433fffc6fa6ab/filesysdb/__init__.py#L131-L138 |
fictorial/filesysdb | filesysdb/__init__.py | each_object_id | def each_object_id(collection):
"""Yields each object ID in the given ``collection``.
The objects are not loaded."""
c_path = collection_path(collection)
paths = glob('%s/*.%s' % (c_path, _ext))
for path in paths:
match = regex.match(r'.+/(.+)\.%s$' % _ext, path)
yield match.groups()... | python | def each_object_id(collection):
"""Yields each object ID in the given ``collection``.
The objects are not loaded."""
c_path = collection_path(collection)
paths = glob('%s/*.%s' % (c_path, _ext))
for path in paths:
match = regex.match(r'.+/(.+)\.%s$' % _ext, path)
yield match.groups()... | [
"def",
"each_object_id",
"(",
"collection",
")",
":",
"c_path",
"=",
"collection_path",
"(",
"collection",
")",
"paths",
"=",
"glob",
"(",
"'%s/*.%s'",
"%",
"(",
"c_path",
",",
"_ext",
")",
")",
"for",
"path",
"in",
"paths",
":",
"match",
"=",
"regex",
... | Yields each object ID in the given ``collection``.
The objects are not loaded. | [
"Yields",
"each",
"object",
"ID",
"in",
"the",
"given",
"collection",
".",
"The",
"objects",
"are",
"not",
"loaded",
"."
] | train | https://github.com/fictorial/filesysdb/blob/bbf1e32218b71c7c15c33ada660433fffc6fa6ab/filesysdb/__init__.py#L141-L148 |
fictorial/filesysdb | filesysdb/__init__.py | save_object | def save_object(collection, obj):
"""Save an object ``obj`` to the given ``collection``.
``obj.id`` must be unique across all other existing objects in
the given collection. If ``id`` is not present in the object, a
*UUID* is assigned as the object's ``id``.
Indexes already defined on the ``colle... | python | def save_object(collection, obj):
"""Save an object ``obj`` to the given ``collection``.
``obj.id`` must be unique across all other existing objects in
the given collection. If ``id`` is not present in the object, a
*UUID* is assigned as the object's ``id``.
Indexes already defined on the ``colle... | [
"def",
"save_object",
"(",
"collection",
",",
"obj",
")",
":",
"if",
"'id'",
"not",
"in",
"obj",
":",
"obj",
".",
"id",
"=",
"uuid",
"(",
")",
"id",
"=",
"obj",
".",
"id",
"path",
"=",
"object_path",
"(",
"collection",
",",
"id",
")",
"temp_path",
... | Save an object ``obj`` to the given ``collection``.
``obj.id`` must be unique across all other existing objects in
the given collection. If ``id`` is not present in the object, a
*UUID* is assigned as the object's ``id``.
Indexes already defined on the ``collection`` are updated after
the object ... | [
"Save",
"an",
"object",
"obj",
"to",
"the",
"given",
"collection",
"."
] | train | https://github.com/fictorial/filesysdb/blob/bbf1e32218b71c7c15c33ada660433fffc6fa6ab/filesysdb/__init__.py#L152-L176 |
fictorial/filesysdb | filesysdb/__init__.py | add_index | def add_index(collection,
name,
fields,
transformer=None,
unique=False,
case_insensitive=False):
"""
Add a secondary index for a collection ``collection`` on one or
more ``fields``.
The values at each of the ``fields`` are loaded fro... | python | def add_index(collection,
name,
fields,
transformer=None,
unique=False,
case_insensitive=False):
"""
Add a secondary index for a collection ``collection`` on one or
more ``fields``.
The values at each of the ``fields`` are loaded fro... | [
"def",
"add_index",
"(",
"collection",
",",
"name",
",",
"fields",
",",
"transformer",
"=",
"None",
",",
"unique",
"=",
"False",
",",
"case_insensitive",
"=",
"False",
")",
":",
"assert",
"len",
"(",
"name",
")",
">",
"0",
"assert",
"len",
"(",
"fields... | Add a secondary index for a collection ``collection`` on one or
more ``fields``.
The values at each of the ``fields`` are loaded from existing
objects and their object ids added to the index.
You can later iterate the objects of an index via
``each_indexed_object``.
If you update an object an... | [
"Add",
"a",
"secondary",
"index",
"for",
"a",
"collection",
"collection",
"on",
"one",
"or",
"more",
"fields",
"."
] | train | https://github.com/fictorial/filesysdb/blob/bbf1e32218b71c7c15c33ada660433fffc6fa6ab/filesysdb/__init__.py#L198-L247 |
fictorial/filesysdb | filesysdb/__init__.py | _add_to_index | def _add_to_index(index, obj):
"""Adds the given object ``obj`` to the given ``index``"""
id_set = index.value_map.setdefault(indexed_value(index, obj), set())
if index.unique:
if len(id_set) > 0:
raise UniqueConstraintError()
id_set.add(obj.id) | python | def _add_to_index(index, obj):
"""Adds the given object ``obj`` to the given ``index``"""
id_set = index.value_map.setdefault(indexed_value(index, obj), set())
if index.unique:
if len(id_set) > 0:
raise UniqueConstraintError()
id_set.add(obj.id) | [
"def",
"_add_to_index",
"(",
"index",
",",
"obj",
")",
":",
"id_set",
"=",
"index",
".",
"value_map",
".",
"setdefault",
"(",
"indexed_value",
"(",
"index",
",",
"obj",
")",
",",
"set",
"(",
")",
")",
"if",
"index",
".",
"unique",
":",
"if",
"len",
... | Adds the given object ``obj`` to the given ``index`` | [
"Adds",
"the",
"given",
"object",
"obj",
"to",
"the",
"given",
"index"
] | train | https://github.com/fictorial/filesysdb/blob/bbf1e32218b71c7c15c33ada660433fffc6fa6ab/filesysdb/__init__.py#L250-L256 |
fictorial/filesysdb | filesysdb/__init__.py | _remove_from_index | def _remove_from_index(index, obj):
"""Removes object ``obj`` from the ``index``."""
try:
index.value_map[indexed_value(index, obj)].remove(obj.id)
except KeyError:
pass | python | def _remove_from_index(index, obj):
"""Removes object ``obj`` from the ``index``."""
try:
index.value_map[indexed_value(index, obj)].remove(obj.id)
except KeyError:
pass | [
"def",
"_remove_from_index",
"(",
"index",
",",
"obj",
")",
":",
"try",
":",
"index",
".",
"value_map",
"[",
"indexed_value",
"(",
"index",
",",
"obj",
")",
"]",
".",
"remove",
"(",
"obj",
".",
"id",
")",
"except",
"KeyError",
":",
"pass"
] | Removes object ``obj`` from the ``index``. | [
"Removes",
"object",
"obj",
"from",
"the",
"index",
"."
] | train | https://github.com/fictorial/filesysdb/blob/bbf1e32218b71c7c15c33ada660433fffc6fa6ab/filesysdb/__init__.py#L259-L264 |
fictorial/filesysdb | filesysdb/__init__.py | each_indexed_object | def each_indexed_object(collection, index_name, **where):
"""Yields each object indexed by the index with
name ``name`` with ``values`` matching on indexed
field values."""
index = _db[collection].indexes[index_name]
for id in index.value_map.get(indexed_value(index, where), []):
yield get_o... | python | def each_indexed_object(collection, index_name, **where):
"""Yields each object indexed by the index with
name ``name`` with ``values`` matching on indexed
field values."""
index = _db[collection].indexes[index_name]
for id in index.value_map.get(indexed_value(index, where), []):
yield get_o... | [
"def",
"each_indexed_object",
"(",
"collection",
",",
"index_name",
",",
"*",
"*",
"where",
")",
":",
"index",
"=",
"_db",
"[",
"collection",
"]",
".",
"indexes",
"[",
"index_name",
"]",
"for",
"id",
"in",
"index",
".",
"value_map",
".",
"get",
"(",
"i... | Yields each object indexed by the index with
name ``name`` with ``values`` matching on indexed
field values. | [
"Yields",
"each",
"object",
"indexed",
"by",
"the",
"index",
"with",
"name",
"name",
"with",
"values",
"matching",
"on",
"indexed",
"field",
"values",
"."
] | train | https://github.com/fictorial/filesysdb/blob/bbf1e32218b71c7c15c33ada660433fffc6fa6ab/filesysdb/__init__.py#L267-L273 |
fictorial/filesysdb | filesysdb/__init__.py | _update_indexes_for_mutated_object | def _update_indexes_for_mutated_object(collection, obj):
"""If an object is updated, this will simply remove
it and re-add it to the indexes defined on the
collection."""
for index in _db[collection].indexes.values():
_remove_from_index(index, obj)
_add_to_index(index, obj) | python | def _update_indexes_for_mutated_object(collection, obj):
"""If an object is updated, this will simply remove
it and re-add it to the indexes defined on the
collection."""
for index in _db[collection].indexes.values():
_remove_from_index(index, obj)
_add_to_index(index, obj) | [
"def",
"_update_indexes_for_mutated_object",
"(",
"collection",
",",
"obj",
")",
":",
"for",
"index",
"in",
"_db",
"[",
"collection",
"]",
".",
"indexes",
".",
"values",
"(",
")",
":",
"_remove_from_index",
"(",
"index",
",",
"obj",
")",
"_add_to_index",
"("... | If an object is updated, this will simply remove
it and re-add it to the indexes defined on the
collection. | [
"If",
"an",
"object",
"is",
"updated",
"this",
"will",
"simply",
"remove",
"it",
"and",
"re",
"-",
"add",
"it",
"to",
"the",
"indexes",
"defined",
"on",
"the",
"collection",
"."
] | train | https://github.com/fictorial/filesysdb/blob/bbf1e32218b71c7c15c33ada660433fffc6fa6ab/filesysdb/__init__.py#L276-L282 |
fictorial/filesysdb | filesysdb/__init__.py | _update_indexes_for_deleted_object | def _update_indexes_for_deleted_object(collection, obj):
"""If an object is deleted, it should no longer be
indexed so this removes the object from all indexes
on the given collection."""
for index in _db[collection].indexes.values():
_remove_from_index(index, obj) | python | def _update_indexes_for_deleted_object(collection, obj):
"""If an object is deleted, it should no longer be
indexed so this removes the object from all indexes
on the given collection."""
for index in _db[collection].indexes.values():
_remove_from_index(index, obj) | [
"def",
"_update_indexes_for_deleted_object",
"(",
"collection",
",",
"obj",
")",
":",
"for",
"index",
"in",
"_db",
"[",
"collection",
"]",
".",
"indexes",
".",
"values",
"(",
")",
":",
"_remove_from_index",
"(",
"index",
",",
"obj",
")"
] | If an object is deleted, it should no longer be
indexed so this removes the object from all indexes
on the given collection. | [
"If",
"an",
"object",
"is",
"deleted",
"it",
"should",
"no",
"longer",
"be",
"indexed",
"so",
"this",
"removes",
"the",
"object",
"from",
"all",
"indexes",
"on",
"the",
"given",
"collection",
"."
] | train | https://github.com/fictorial/filesysdb/blob/bbf1e32218b71c7c15c33ada660433fffc6fa6ab/filesysdb/__init__.py#L285-L290 |
JNRowe/jnrbase | jnrbase/iso_8601.py | parse_delta | def parse_delta(__string: str) -> datetime.timedelta:
"""Parse ISO-8601 duration string.
Args:
__string: Duration string to parse
Returns:
Parsed delta object
"""
if not __string:
return datetime.timedelta(0)
match = re.fullmatch(r"""
P
((?P<days>\d+)D)?
... | python | def parse_delta(__string: str) -> datetime.timedelta:
"""Parse ISO-8601 duration string.
Args:
__string: Duration string to parse
Returns:
Parsed delta object
"""
if not __string:
return datetime.timedelta(0)
match = re.fullmatch(r"""
P
((?P<days>\d+)D)?
... | [
"def",
"parse_delta",
"(",
"__string",
":",
"str",
")",
"->",
"datetime",
".",
"timedelta",
":",
"if",
"not",
"__string",
":",
"return",
"datetime",
".",
"timedelta",
"(",
"0",
")",
"match",
"=",
"re",
".",
"fullmatch",
"(",
"r\"\"\"\n P\n ((?P... | Parse ISO-8601 duration string.
Args:
__string: Duration string to parse
Returns:
Parsed delta object | [
"Parse",
"ISO",
"-",
"8601",
"duration",
"string",
"."
] | train | https://github.com/JNRowe/jnrbase/blob/ae505ef69a9feb739b5f4e62c5a8e6533104d3ea/jnrbase/iso_8601.py#L27-L48 |
JNRowe/jnrbase | jnrbase/iso_8601.py | format_delta | def format_delta(__timedelta: datetime.timedelta) -> str:
"""Format ISO-8601 duration string.
Args:
__timedelta: Duration to process
Returns:
ISO-8601 representation of duration
"""
if __timedelta == datetime.timedelta(0):
return ''
days_s = '{}D'.format(__timedelta.days... | python | def format_delta(__timedelta: datetime.timedelta) -> str:
"""Format ISO-8601 duration string.
Args:
__timedelta: Duration to process
Returns:
ISO-8601 representation of duration
"""
if __timedelta == datetime.timedelta(0):
return ''
days_s = '{}D'.format(__timedelta.days... | [
"def",
"format_delta",
"(",
"__timedelta",
":",
"datetime",
".",
"timedelta",
")",
"->",
"str",
":",
"if",
"__timedelta",
"==",
"datetime",
".",
"timedelta",
"(",
"0",
")",
":",
"return",
"''",
"days_s",
"=",
"'{}D'",
".",
"format",
"(",
"__timedelta",
"... | Format ISO-8601 duration string.
Args:
__timedelta: Duration to process
Returns:
ISO-8601 representation of duration | [
"Format",
"ISO",
"-",
"8601",
"duration",
"string",
"."
] | train | https://github.com/JNRowe/jnrbase/blob/ae505ef69a9feb739b5f4e62c5a8e6533104d3ea/jnrbase/iso_8601.py#L51-L69 |
JNRowe/jnrbase | jnrbase/iso_8601.py | parse_datetime | def parse_datetime(__string: str) -> datetime.datetime:
"""Parse ISO-8601 datetime string.
Args:
__string: Datetime string to parse
Returns:
Parsed datetime object
"""
if not __string:
datetime_ = datetime.datetime.now(datetime.timezone.utc)
else:
# pylint: disab... | python | def parse_datetime(__string: str) -> datetime.datetime:
"""Parse ISO-8601 datetime string.
Args:
__string: Datetime string to parse
Returns:
Parsed datetime object
"""
if not __string:
datetime_ = datetime.datetime.now(datetime.timezone.utc)
else:
# pylint: disab... | [
"def",
"parse_datetime",
"(",
"__string",
":",
"str",
")",
"->",
"datetime",
".",
"datetime",
":",
"if",
"not",
"__string",
":",
"datetime_",
"=",
"datetime",
".",
"datetime",
".",
"now",
"(",
"datetime",
".",
"timezone",
".",
"utc",
")",
"else",
":",
... | Parse ISO-8601 datetime string.
Args:
__string: Datetime string to parse
Returns:
Parsed datetime object | [
"Parse",
"ISO",
"-",
"8601",
"datetime",
"string",
"."
] | train | https://github.com/JNRowe/jnrbase/blob/ae505ef69a9feb739b5f4e62c5a8e6533104d3ea/jnrbase/iso_8601.py#L72-L87 |
shreyaspotnis/rampage | rampage/daq/daq.py | print_device_info | def print_device_info(dev_name):
"""Prints information about the given device.
Usage:
print_device_info("Dev1")
"""
string_buffer = ctypes.create_string_buffer(1024)
attributes = [pydaq.DAQmx_Dev_ProductType, pydaq.DAQmx_Dev_SerialNum,
pydaq.DAQmx_Dev_AO_PhysicalChans,
... | python | def print_device_info(dev_name):
"""Prints information about the given device.
Usage:
print_device_info("Dev1")
"""
string_buffer = ctypes.create_string_buffer(1024)
attributes = [pydaq.DAQmx_Dev_ProductType, pydaq.DAQmx_Dev_SerialNum,
pydaq.DAQmx_Dev_AO_PhysicalChans,
... | [
"def",
"print_device_info",
"(",
"dev_name",
")",
":",
"string_buffer",
"=",
"ctypes",
".",
"create_string_buffer",
"(",
"1024",
")",
"attributes",
"=",
"[",
"pydaq",
".",
"DAQmx_Dev_ProductType",
",",
"pydaq",
".",
"DAQmx_Dev_SerialNum",
",",
"pydaq",
".",
"DAQ... | Prints information about the given device.
Usage:
print_device_info("Dev1") | [
"Prints",
"information",
"about",
"the",
"given",
"device",
"."
] | train | https://github.com/shreyaspotnis/rampage/blob/e2565aef7ee16ee06523de975e8aa41aca14e3b2/rampage/daq/daq.py#L28-L53 |
shreyaspotnis/rampage | rampage/daq/daq.py | get_device_name_list | def get_device_name_list():
"""Returns a list of device names installed."""
dev_names = ctypes.create_string_buffer(1024)
pydaq.DAQmxGetSysDevNames(dev_names, len(dev_names))
return dev_names.value.split(', ') | python | def get_device_name_list():
"""Returns a list of device names installed."""
dev_names = ctypes.create_string_buffer(1024)
pydaq.DAQmxGetSysDevNames(dev_names, len(dev_names))
return dev_names.value.split(', ') | [
"def",
"get_device_name_list",
"(",
")",
":",
"dev_names",
"=",
"ctypes",
".",
"create_string_buffer",
"(",
"1024",
")",
"pydaq",
".",
"DAQmxGetSysDevNames",
"(",
"dev_names",
",",
"len",
"(",
"dev_names",
")",
")",
"return",
"dev_names",
".",
"value",
".",
... | Returns a list of device names installed. | [
"Returns",
"a",
"list",
"of",
"device",
"names",
"installed",
"."
] | train | https://github.com/shreyaspotnis/rampage/blob/e2565aef7ee16ee06523de975e8aa41aca14e3b2/rampage/daq/daq.py#L56-L60 |
shreyaspotnis/rampage | rampage/daq/daq.py | reset_analog_sample_clock | def reset_analog_sample_clock(state=False):
"""Reset the clock line.
Use this just before starting a run to avoid timing issues.
"""
set_digital_line_state(expt_settings.dev1_clock_out_name, state)
set_digital_line_state(expt_settings.dev2_clock_out_name, state)
set_digital_line_state(expt_sett... | python | def reset_analog_sample_clock(state=False):
"""Reset the clock line.
Use this just before starting a run to avoid timing issues.
"""
set_digital_line_state(expt_settings.dev1_clock_out_name, state)
set_digital_line_state(expt_settings.dev2_clock_out_name, state)
set_digital_line_state(expt_sett... | [
"def",
"reset_analog_sample_clock",
"(",
"state",
"=",
"False",
")",
":",
"set_digital_line_state",
"(",
"expt_settings",
".",
"dev1_clock_out_name",
",",
"state",
")",
"set_digital_line_state",
"(",
"expt_settings",
".",
"dev2_clock_out_name",
",",
"state",
")",
"set... | Reset the clock line.
Use this just before starting a run to avoid timing issues. | [
"Reset",
"the",
"clock",
"line",
"."
] | train | https://github.com/shreyaspotnis/rampage/blob/e2565aef7ee16ee06523de975e8aa41aca14e3b2/rampage/daq/daq.py#L69-L77 |
shreyaspotnis/rampage | rampage/daq/daq.py | set_digital_line_state | def set_digital_line_state(line_name, state):
"""Set the state of a single digital line.
line_name (str) - The physical name of the line.
e.g line_name="Dev1/port0/line3"
This should be a single digital line. Specifying more than one would
result in unexpected behaviour. For example "De... | python | def set_digital_line_state(line_name, state):
"""Set the state of a single digital line.
line_name (str) - The physical name of the line.
e.g line_name="Dev1/port0/line3"
This should be a single digital line. Specifying more than one would
result in unexpected behaviour. For example "De... | [
"def",
"set_digital_line_state",
"(",
"line_name",
",",
"state",
")",
":",
"# get the line number from the line name. Thats the number of bits to shift",
"bits_to_shift",
"=",
"int",
"(",
"line_name",
".",
"split",
"(",
"'line'",
")",
"[",
"-",
"1",
"]",
")",
"dig_dat... | Set the state of a single digital line.
line_name (str) - The physical name of the line.
e.g line_name="Dev1/port0/line3"
This should be a single digital line. Specifying more than one would
result in unexpected behaviour. For example "Dev1/port0/line0:5" is
not allowed.
see... | [
"Set",
"the",
"state",
"of",
"a",
"single",
"digital",
"line",
"."
] | train | https://github.com/shreyaspotnis/rampage/blob/e2565aef7ee16ee06523de975e8aa41aca14e3b2/rampage/daq/daq.py#L80-L100 |
shreyaspotnis/rampage | rampage/daq/daq.py | p24_pulse_train | def p24_pulse_train(n_samples=100):
"""Sends a pulse train of on-off in Dev1/port0/line24.
This function creates a task, starts it and waits until it is over.
Uses expt_settings.external_clock_line as a clock.
n_samples - number of on off samples.
"""
samples = (np.arange(n_samples, dtype="uin... | python | def p24_pulse_train(n_samples=100):
"""Sends a pulse train of on-off in Dev1/port0/line24.
This function creates a task, starts it and waits until it is over.
Uses expt_settings.external_clock_line as a clock.
n_samples - number of on off samples.
"""
samples = (np.arange(n_samples, dtype="uin... | [
"def",
"p24_pulse_train",
"(",
"n_samples",
"=",
"100",
")",
":",
"samples",
"=",
"(",
"np",
".",
"arange",
"(",
"n_samples",
",",
"dtype",
"=",
"\"uint32\"",
")",
"%",
"2",
")",
"*",
"(",
"2",
"**",
"24",
")",
"samples",
"[",
"-",
"1",
"]",
"=",... | Sends a pulse train of on-off in Dev1/port0/line24.
This function creates a task, starts it and waits until it is over.
Uses expt_settings.external_clock_line as a clock.
n_samples - number of on off samples. | [
"Sends",
"a",
"pulse",
"train",
"of",
"on",
"-",
"off",
"in",
"Dev1",
"/",
"port0",
"/",
"line24",
"."
] | train | https://github.com/shreyaspotnis/rampage/blob/e2565aef7ee16ee06523de975e8aa41aca14e3b2/rampage/daq/daq.py#L407-L417 |
shreyaspotnis/rampage | rampage/daq/daq.py | DigitalOutputTask.StartAndWait | def StartAndWait(self):
"""Starts the task and waits until it is done."""
self.StartTask()
self.WaitUntilTaskDone(pydaq.DAQmx_Val_WaitInfinitely)
self.ClearTask() | python | def StartAndWait(self):
"""Starts the task and waits until it is done."""
self.StartTask()
self.WaitUntilTaskDone(pydaq.DAQmx_Val_WaitInfinitely)
self.ClearTask() | [
"def",
"StartAndWait",
"(",
"self",
")",
":",
"self",
".",
"StartTask",
"(",
")",
"self",
".",
"WaitUntilTaskDone",
"(",
"pydaq",
".",
"DAQmx_Val_WaitInfinitely",
")",
"self",
".",
"ClearTask",
"(",
")"
] | Starts the task and waits until it is done. | [
"Starts",
"the",
"task",
"and",
"waits",
"until",
"it",
"is",
"done",
"."
] | train | https://github.com/shreyaspotnis/rampage/blob/e2565aef7ee16ee06523de975e8aa41aca14e3b2/rampage/daq/daq.py#L164-L168 |
shreyaspotnis/rampage | rampage/daq/daq.py | DigitalOutputTask.isDone | def isDone(self):
"""Returns true if task is done."""
done = pydaq.bool32()
self.IsTaskDone(ctypes.byref(done))
return done.value | python | def isDone(self):
"""Returns true if task is done."""
done = pydaq.bool32()
self.IsTaskDone(ctypes.byref(done))
return done.value | [
"def",
"isDone",
"(",
"self",
")",
":",
"done",
"=",
"pydaq",
".",
"bool32",
"(",
")",
"self",
".",
"IsTaskDone",
"(",
"ctypes",
".",
"byref",
"(",
"done",
")",
")",
"return",
"done",
".",
"value"
] | Returns true if task is done. | [
"Returns",
"true",
"if",
"task",
"is",
"done",
"."
] | train | https://github.com/shreyaspotnis/rampage/blob/e2565aef7ee16ee06523de975e8aa41aca14e3b2/rampage/daq/daq.py#L170-L174 |
shreyaspotnis/rampage | rampage/daq/daq.py | DigitalOutputTaskWithCallbacks.padDigitalData | def padDigitalData(self, dig_data, n):
"""Pad dig_data with its last element so that the new array is a
multiple of n.
"""
n = int(n)
l0 = len(dig_data)
if l0 % n == 0:
return dig_data # no need of padding
else:
ladd = n - (l0 % n)
... | python | def padDigitalData(self, dig_data, n):
"""Pad dig_data with its last element so that the new array is a
multiple of n.
"""
n = int(n)
l0 = len(dig_data)
if l0 % n == 0:
return dig_data # no need of padding
else:
ladd = n - (l0 % n)
... | [
"def",
"padDigitalData",
"(",
"self",
",",
"dig_data",
",",
"n",
")",
":",
"n",
"=",
"int",
"(",
"n",
")",
"l0",
"=",
"len",
"(",
"dig_data",
")",
"if",
"l0",
"%",
"n",
"==",
"0",
":",
"return",
"dig_data",
"# no need of padding",
"else",
":",
"lad... | Pad dig_data with its last element so that the new array is a
multiple of n. | [
"Pad",
"dig_data",
"with",
"its",
"last",
"element",
"so",
"that",
"the",
"new",
"array",
"is",
"a",
"multiple",
"of",
"n",
"."
] | train | https://github.com/shreyaspotnis/rampage/blob/e2565aef7ee16ee06523de975e8aa41aca14e3b2/rampage/daq/daq.py#L255-L267 |
shreyaspotnis/rampage | rampage/daq/daq.py | DigitalOutputTaskWithCallbacks.EveryNCallback | def EveryNCallback(self):
"""Called by PyDAQmx whenever a callback event occurs."""
# print('ncall ', self.n_callbacks)
if self.do_callbacks:
if self.n_callbacks >= self.callback_step:
# print('n_callbacks', self.n_callbacks)
for func, func_dict in sel... | python | def EveryNCallback(self):
"""Called by PyDAQmx whenever a callback event occurs."""
# print('ncall ', self.n_callbacks)
if self.do_callbacks:
if self.n_callbacks >= self.callback_step:
# print('n_callbacks', self.n_callbacks)
for func, func_dict in sel... | [
"def",
"EveryNCallback",
"(",
"self",
")",
":",
"# print('ncall ', self.n_callbacks)",
"if",
"self",
".",
"do_callbacks",
":",
"if",
"self",
".",
"n_callbacks",
">=",
"self",
".",
"callback_step",
":",
"# print('n_callbacks', self.n_callbacks)",
"for",
"func",
",",
... | Called by PyDAQmx whenever a callback event occurs. | [
"Called",
"by",
"PyDAQmx",
"whenever",
"a",
"callback",
"event",
"occurs",
"."
] | train | https://github.com/shreyaspotnis/rampage/blob/e2565aef7ee16ee06523de975e8aa41aca14e3b2/rampage/daq/daq.py#L269-L292 |
bsvetchine/django-payzen | django_payzen/tools.py | get_vads_trans_id | def get_vads_trans_id(vads_site_id, vads_trans_date):
"""
Returns a default value for vads_trans_id field.
vads_trans_id field is mandatory. It is composed by 6 numeric
characters that identifies the transaction. There is a unicity contraint
between vads_site_id and vads_trans_date (the first 8 cha... | python | def get_vads_trans_id(vads_site_id, vads_trans_date):
"""
Returns a default value for vads_trans_id field.
vads_trans_id field is mandatory. It is composed by 6 numeric
characters that identifies the transaction. There is a unicity contraint
between vads_site_id and vads_trans_date (the first 8 cha... | [
"def",
"get_vads_trans_id",
"(",
"vads_site_id",
",",
"vads_trans_date",
")",
":",
"vads_trans_id",
"=",
"\"\"",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"6",
")",
":",
"vads_trans_id",
"+=",
"str",
"(",
"random",
".",
"randint",
"(",
"0",
",",
"9",
"... | Returns a default value for vads_trans_id field.
vads_trans_id field is mandatory. It is composed by 6 numeric
characters that identifies the transaction. There is a unicity contraint
between vads_site_id and vads_trans_date (the first 8 characters
representing the transaction date).
We consider t... | [
"Returns",
"a",
"default",
"value",
"for",
"vads_trans_id",
"field",
"."
] | train | https://github.com/bsvetchine/django-payzen/blob/944c3026120151495310cb1eb3c6370dc2db3db9/django_payzen/tools.py#L12-L26 |
bsvetchine/django-payzen | django_payzen/tools.py | get_signature | def get_signature(payment_request):
"""
Returns the signature for the transaction.
To compute the signature, first you have to get the value of all
the fields that starts by 'vads_', ordering them alphabetically.
All the values are separated by the '+' character. Then you add
the value of the p... | python | def get_signature(payment_request):
"""
Returns the signature for the transaction.
To compute the signature, first you have to get the value of all
the fields that starts by 'vads_', ordering them alphabetically.
All the values are separated by the '+' character. Then you add
the value of the p... | [
"def",
"get_signature",
"(",
"payment_request",
")",
":",
"vads_args",
"=",
"{",
"}",
"for",
"field",
"in",
"payment_request",
".",
"_meta",
".",
"fields",
":",
"if",
"field",
".",
"name",
"[",
":",
"5",
"]",
"==",
"'vads_'",
":",
"field_value",
"=",
"... | Returns the signature for the transaction.
To compute the signature, first you have to get the value of all
the fields that starts by 'vads_', ordering them alphabetically.
All the values are separated by the '+' character. Then you add
the value of the payzen certificate.
Finaly you hash the strin... | [
"Returns",
"the",
"signature",
"for",
"the",
"transaction",
"."
] | train | https://github.com/bsvetchine/django-payzen/blob/944c3026120151495310cb1eb3c6370dc2db3db9/django_payzen/tools.py#L60-L82 |
bsvetchine/django-payzen | django_payzen/tools.py | process_response | def process_response(data):
"""Process a payment response."""
# We check if the signature is valid. If not return
if not is_signature_valid(data):
logger.warning(
"Django-Payzen : Response signature detected as invalid",
extra={"stack": True}
)
return None
... | python | def process_response(data):
"""Process a payment response."""
# We check if the signature is valid. If not return
if not is_signature_valid(data):
logger.warning(
"Django-Payzen : Response signature detected as invalid",
extra={"stack": True}
)
return None
... | [
"def",
"process_response",
"(",
"data",
")",
":",
"# We check if the signature is valid. If not return",
"if",
"not",
"is_signature_valid",
"(",
"data",
")",
":",
"logger",
".",
"warning",
"(",
"\"Django-Payzen : Response signature detected as invalid\"",
",",
"extra",
"=",... | Process a payment response. | [
"Process",
"a",
"payment",
"response",
"."
] | train | https://github.com/bsvetchine/django-payzen/blob/944c3026120151495310cb1eb3c6370dc2db3db9/django_payzen/tools.py#L95-L129 |
fpoirotte/sphinxcontrib-varlinks | sphinxcontrib/varlinks.py | LinkSubstitutionPhase1.apply | def apply(self):
"""Create substitution nodes for hyperlinks"""
# In this phase, we look for hyperlinks (references nodes)
# that contain substitutions (of the form "|foo|").
# We then add actual "substitution"s nodes to those references,
# so that they can be replaced by the sub... | python | def apply(self):
"""Create substitution nodes for hyperlinks"""
# In this phase, we look for hyperlinks (references nodes)
# that contain substitutions (of the form "|foo|").
# We then add actual "substitution"s nodes to those references,
# so that they can be replaced by the sub... | [
"def",
"apply",
"(",
"self",
")",
":",
"# In this phase, we look for hyperlinks (references nodes)",
"# that contain substitutions (of the form \"|foo|\").",
"# We then add actual \"substitution\"s nodes to those references,",
"# so that they can be replaced by the substitution processor.",
"sub... | Create substitution nodes for hyperlinks | [
"Create",
"substitution",
"nodes",
"for",
"hyperlinks"
] | train | https://github.com/fpoirotte/sphinxcontrib-varlinks/blob/836899486e841fee4bac32a9d57da2786b2045c6/sphinxcontrib/varlinks.py#L36-L70 |
fpoirotte/sphinxcontrib-varlinks | sphinxcontrib/varlinks.py | LinkSubstitutionPhase2.apply | def apply(self):
"""Replace substitutions in hyperlinks with their contents"""
# In this phase, we replace the substitutions in hyperlinks
# with the contents of the sub-nodes introduced during phase 1.
# We also remove those temporary nodes from the tree.
subst_re = re.compile(s... | python | def apply(self):
"""Replace substitutions in hyperlinks with their contents"""
# In this phase, we replace the substitutions in hyperlinks
# with the contents of the sub-nodes introduced during phase 1.
# We also remove those temporary nodes from the tree.
subst_re = re.compile(s... | [
"def",
"apply",
"(",
"self",
")",
":",
"# In this phase, we replace the substitutions in hyperlinks",
"# with the contents of the sub-nodes introduced during phase 1.",
"# We also remove those temporary nodes from the tree.",
"subst_re",
"=",
"re",
".",
"compile",
"(",
"self",
".",
... | Replace substitutions in hyperlinks with their contents | [
"Replace",
"substitutions",
"in",
"hyperlinks",
"with",
"their",
"contents"
] | train | https://github.com/fpoirotte/sphinxcontrib-varlinks/blob/836899486e841fee4bac32a9d57da2786b2045c6/sphinxcontrib/varlinks.py#L92-L123 |
wtsi-hgi/python-baton-wrapper | baton/collections.py | IrodsMetadata.from_metadata | def from_metadata(metadata: Metadata) -> Any:
"""
Static factory method to create an equivalent instance of this type from the given `Metadata` instance.
:param metadata: the `Metadata` instance to create an instance of this class from
:return: the created instance of this class
... | python | def from_metadata(metadata: Metadata) -> Any:
"""
Static factory method to create an equivalent instance of this type from the given `Metadata` instance.
:param metadata: the `Metadata` instance to create an instance of this class from
:return: the created instance of this class
... | [
"def",
"from_metadata",
"(",
"metadata",
":",
"Metadata",
")",
"->",
"Any",
":",
"irods_metadata",
"=",
"IrodsMetadata",
"(",
")",
"for",
"key",
",",
"value",
"in",
"metadata",
".",
"items",
"(",
")",
":",
"irods_metadata",
"[",
"key",
"]",
"=",
"{",
"... | Static factory method to create an equivalent instance of this type from the given `Metadata` instance.
:param metadata: the `Metadata` instance to create an instance of this class from
:return: the created instance of this class | [
"Static",
"factory",
"method",
"to",
"create",
"an",
"equivalent",
"instance",
"of",
"this",
"type",
"from",
"the",
"given",
"Metadata",
"instance",
".",
":",
"param",
"metadata",
":",
"the",
"Metadata",
"instance",
"to",
"create",
"an",
"instance",
"of",
"t... | train | https://github.com/wtsi-hgi/python-baton-wrapper/blob/ae0c9e3630e2c4729a0614cc86f493688436b0b7/baton/collections.py#L18-L27 |
wtsi-hgi/python-baton-wrapper | baton/collections.py | IrodsMetadata.add | def add(self, key: str, value: str):
"""
Adds the given value to the set of data stored under the given key.
:param key: the set's key
:param value: the value to add in the set associated to the given key
"""
if key in self:
# Use super to get mutable set
... | python | def add(self, key: str, value: str):
"""
Adds the given value to the set of data stored under the given key.
:param key: the set's key
:param value: the value to add in the set associated to the given key
"""
if key in self:
# Use super to get mutable set
... | [
"def",
"add",
"(",
"self",
",",
"key",
":",
"str",
",",
"value",
":",
"str",
")",
":",
"if",
"key",
"in",
"self",
":",
"# Use super to get mutable set",
"super",
"(",
")",
".",
"__getitem__",
"(",
"key",
")",
".",
"add",
"(",
"value",
")",
"else",
... | Adds the given value to the set of data stored under the given key.
:param key: the set's key
:param value: the value to add in the set associated to the given key | [
"Adds",
"the",
"given",
"value",
"to",
"the",
"set",
"of",
"data",
"stored",
"under",
"the",
"given",
"key",
".",
":",
"param",
"key",
":",
"the",
"set",
"s",
"key",
":",
"param",
"value",
":",
"the",
"value",
"to",
"add",
"in",
"the",
"set",
"asso... | train | https://github.com/wtsi-hgi/python-baton-wrapper/blob/ae0c9e3630e2c4729a0614cc86f493688436b0b7/baton/collections.py#L41-L51 |
wtsi-hgi/python-baton-wrapper | baton/collections.py | DataObjectReplicaCollection.get_by_number | def get_by_number(self, number: int) -> Optional[DataObjectReplica]:
"""
Gets the data object replica in this collection with the given number. Will return `None` if such replica does
not exist.
:param number: the number of the data object replica to get
:return: the data object ... | python | def get_by_number(self, number: int) -> Optional[DataObjectReplica]:
"""
Gets the data object replica in this collection with the given number. Will return `None` if such replica does
not exist.
:param number: the number of the data object replica to get
:return: the data object ... | [
"def",
"get_by_number",
"(",
"self",
",",
"number",
":",
"int",
")",
"->",
"Optional",
"[",
"DataObjectReplica",
"]",
":",
"return",
"self",
".",
"_data",
".",
"get",
"(",
"number",
",",
"None",
")"
] | Gets the data object replica in this collection with the given number. Will return `None` if such replica does
not exist.
:param number: the number of the data object replica to get
:return: the data object replica in this collection with the given number | [
"Gets",
"the",
"data",
"object",
"replica",
"in",
"this",
"collection",
"with",
"the",
"given",
"number",
".",
"Will",
"return",
"None",
"if",
"such",
"replica",
"does",
"not",
"exist",
".",
":",
"param",
"number",
":",
"the",
"number",
"of",
"the",
"dat... | train | https://github.com/wtsi-hgi/python-baton-wrapper/blob/ae0c9e3630e2c4729a0614cc86f493688436b0b7/baton/collections.py#L79-L86 |
wtsi-hgi/python-baton-wrapper | baton/collections.py | DataObjectReplicaCollection.get_out_of_date | def get_out_of_date(self) -> Sequence[DataObjectReplica]:
"""
Gets any data object replica that are marked as out of date/not in date.
:return: the out of data object replica
"""
out_of_date = []
for number, data_object_replica in self._data.items():
if not da... | python | def get_out_of_date(self) -> Sequence[DataObjectReplica]:
"""
Gets any data object replica that are marked as out of date/not in date.
:return: the out of data object replica
"""
out_of_date = []
for number, data_object_replica in self._data.items():
if not da... | [
"def",
"get_out_of_date",
"(",
"self",
")",
"->",
"Sequence",
"[",
"DataObjectReplica",
"]",
":",
"out_of_date",
"=",
"[",
"]",
"for",
"number",
",",
"data_object_replica",
"in",
"self",
".",
"_data",
".",
"items",
"(",
")",
":",
"if",
"not",
"data_object_... | Gets any data object replica that are marked as out of date/not in date.
:return: the out of data object replica | [
"Gets",
"any",
"data",
"object",
"replica",
"that",
"are",
"marked",
"as",
"out",
"of",
"date",
"/",
"not",
"in",
"date",
".",
":",
"return",
":",
"the",
"out",
"of",
"data",
"object",
"replica"
] | train | https://github.com/wtsi-hgi/python-baton-wrapper/blob/ae0c9e3630e2c4729a0614cc86f493688436b0b7/baton/collections.py#L88-L97 |
wtsi-hgi/python-baton-wrapper | baton/collections.py | DataObjectReplicaCollection.add | def add(self, data_object_replica: DataObjectReplica):
"""
Adds the given data object replica to this collection. Will raise a `ValueError` if a data object replica with
the same number already exists.
:param data_object_replica: the data object replica to add
"""
if data... | python | def add(self, data_object_replica: DataObjectReplica):
"""
Adds the given data object replica to this collection. Will raise a `ValueError` if a data object replica with
the same number already exists.
:param data_object_replica: the data object replica to add
"""
if data... | [
"def",
"add",
"(",
"self",
",",
"data_object_replica",
":",
"DataObjectReplica",
")",
":",
"if",
"data_object_replica",
".",
"number",
"in",
"self",
".",
"_data",
":",
"raise",
"ValueError",
"(",
"\"Data object replica with number %d already exists in this collection\"",
... | Adds the given data object replica to this collection. Will raise a `ValueError` if a data object replica with
the same number already exists.
:param data_object_replica: the data object replica to add | [
"Adds",
"the",
"given",
"data",
"object",
"replica",
"to",
"this",
"collection",
".",
"Will",
"raise",
"a",
"ValueError",
"if",
"a",
"data",
"object",
"replica",
"with",
"the",
"same",
"number",
"already",
"exists",
".",
":",
"param",
"data_object_replica",
... | train | https://github.com/wtsi-hgi/python-baton-wrapper/blob/ae0c9e3630e2c4729a0614cc86f493688436b0b7/baton/collections.py#L99-L108 |
wtsi-hgi/python-baton-wrapper | baton/collections.py | DataObjectReplicaCollection.remove | def remove(self, identifier: Union[DataObjectReplica, int]):
"""
Removes a data object from this collection that has the given unique identifier. A `ValueError` will be raised
if a data object with the given identifier does not exist.
:param identifier: the identifier of the data object
... | python | def remove(self, identifier: Union[DataObjectReplica, int]):
"""
Removes a data object from this collection that has the given unique identifier. A `ValueError` will be raised
if a data object with the given identifier does not exist.
:param identifier: the identifier of the data object
... | [
"def",
"remove",
"(",
"self",
",",
"identifier",
":",
"Union",
"[",
"DataObjectReplica",
",",
"int",
"]",
")",
":",
"if",
"isinstance",
"(",
"identifier",
",",
"int",
")",
":",
"self",
".",
"_remove_by_number",
"(",
"identifier",
")",
"elif",
"isinstance",... | Removes a data object from this collection that has the given unique identifier. A `ValueError` will be raised
if a data object with the given identifier does not exist.
:param identifier: the identifier of the data object | [
"Removes",
"a",
"data",
"object",
"from",
"this",
"collection",
"that",
"has",
"the",
"given",
"unique",
"identifier",
".",
"A",
"ValueError",
"will",
"be",
"raised",
"if",
"a",
"data",
"object",
"with",
"the",
"given",
"identifier",
"does",
"not",
"exist",
... | train | https://github.com/wtsi-hgi/python-baton-wrapper/blob/ae0c9e3630e2c4729a0614cc86f493688436b0b7/baton/collections.py#L110-L121 |
wtsi-hgi/python-baton-wrapper | baton/collections.py | DataObjectReplicaCollection._remove_by_number | def _remove_by_number(self, number: int):
"""
Removes the data object from this collection with the given number. A `ValueError` will be raised if a data
object with the given number does not exist.
:param number: the number of the data object to remove
"""
if number not ... | python | def _remove_by_number(self, number: int):
"""
Removes the data object from this collection with the given number. A `ValueError` will be raised if a data
object with the given number does not exist.
:param number: the number of the data object to remove
"""
if number not ... | [
"def",
"_remove_by_number",
"(",
"self",
",",
"number",
":",
"int",
")",
":",
"if",
"number",
"not",
"in",
"self",
".",
"_data",
":",
"raise",
"ValueError",
"(",
"\"Data object replica number %d is not in this collection\"",
"%",
"number",
")",
"del",
"self",
".... | Removes the data object from this collection with the given number. A `ValueError` will be raised if a data
object with the given number does not exist.
:param number: the number of the data object to remove | [
"Removes",
"the",
"data",
"object",
"from",
"this",
"collection",
"with",
"the",
"given",
"number",
".",
"A",
"ValueError",
"will",
"be",
"raised",
"if",
"a",
"data",
"object",
"with",
"the",
"given",
"number",
"does",
"not",
"exist",
".",
":",
"param",
... | train | https://github.com/wtsi-hgi/python-baton-wrapper/blob/ae0c9e3630e2c4729a0614cc86f493688436b0b7/baton/collections.py#L123-L132 |
saltzm/yadi | yadi/datalog2sql/ast2sql/preprocessor.py | ConjunctiveQueryPreprocessor.get_safe_variables | def get_safe_variables(self,query,var_dict):
''' Create a list of safe variables: variables bounded to constants or
that occur in a positive goal '''
variables_bounded_to_constants = []
for constraint in query.constraints:
if (constraint.get_left_side().is_variable() and
... | python | def get_safe_variables(self,query,var_dict):
''' Create a list of safe variables: variables bounded to constants or
that occur in a positive goal '''
variables_bounded_to_constants = []
for constraint in query.constraints:
if (constraint.get_left_side().is_variable() and
... | [
"def",
"get_safe_variables",
"(",
"self",
",",
"query",
",",
"var_dict",
")",
":",
"variables_bounded_to_constants",
"=",
"[",
"]",
"for",
"constraint",
"in",
"query",
".",
"constraints",
":",
"if",
"(",
"constraint",
".",
"get_left_side",
"(",
")",
".",
"is... | Create a list of safe variables: variables bounded to constants or
that occur in a positive goal | [
"Create",
"a",
"list",
"of",
"safe",
"variables",
":",
"variables",
"bounded",
"to",
"constants",
"or",
"that",
"occur",
"in",
"a",
"positive",
"goal"
] | train | https://github.com/saltzm/yadi/blob/755790167c350e650c1e8b15c6f9209a97be9e42/yadi/datalog2sql/ast2sql/preprocessor.py#L212-L226 |
diffeo/yakonfig | yakonfig/yakonfig.py | set_global_config | def set_global_config(path_dict_or_stream):
'''Set the global configuration.
Call this from `main()` with a file system path, stream
object, or a dict. Calling it repeatedly with the same path is
safe. Calling it with a different path or repeatedly with a
stream or dict requires an explicit call ... | python | def set_global_config(path_dict_or_stream):
'''Set the global configuration.
Call this from `main()` with a file system path, stream
object, or a dict. Calling it repeatedly with the same path is
safe. Calling it with a different path or repeatedly with a
stream or dict requires an explicit call ... | [
"def",
"set_global_config",
"(",
"path_dict_or_stream",
")",
":",
"path",
"=",
"None",
"mapping",
"=",
"None",
"stream",
"=",
"None",
"global",
"_config_file_path",
"global",
"_config_cache",
"if",
"isinstance",
"(",
"path_dict_or_stream",
",",
"string_types",
")",
... | Set the global configuration.
Call this from `main()` with a file system path, stream
object, or a dict. Calling it repeatedly with the same path is
safe. Calling it with a different path or repeatedly with a
stream or dict requires an explicit call to :func:`clear_global_config`.
:param path_di... | [
"Set",
"the",
"global",
"configuration",
"."
] | train | https://github.com/diffeo/yakonfig/blob/412e195da29b4f4fc7b72967c192714a6f5eaeb5/yakonfig/yakonfig.py#L70-L114 |
diffeo/yakonfig | yakonfig/yakonfig.py | get_global_config | def get_global_config(*args):
'''Get (a subset of) the global configuration.
If no arguments are provided, returns the entire configuration.
Otherwise, start with the entire configuration, and get the item
named by the first parameter; then search that for the second
parameter; and so on.
:par... | python | def get_global_config(*args):
'''Get (a subset of) the global configuration.
If no arguments are provided, returns the entire configuration.
Otherwise, start with the entire configuration, and get the item
named by the first parameter; then search that for the second
parameter; and so on.
:par... | [
"def",
"get_global_config",
"(",
"*",
"args",
")",
":",
"global",
"_config_cache",
"c",
"=",
"_config_cache",
"if",
"c",
"is",
"None",
":",
"if",
"len",
"(",
"args",
")",
"==",
"0",
":",
"args",
"=",
"(",
"None",
",",
")",
"raise",
"KeyError",
"(",
... | Get (a subset of) the global configuration.
If no arguments are provided, returns the entire configuration.
Otherwise, start with the entire configuration, and get the item
named by the first parameter; then search that for the second
parameter; and so on.
:param args: configuration name path to f... | [
"Get",
"(",
"a",
"subset",
"of",
")",
"the",
"global",
"configuration",
"."
] | train | https://github.com/diffeo/yakonfig/blob/412e195da29b4f4fc7b72967c192714a6f5eaeb5/yakonfig/yakonfig.py#L117-L138 |
diffeo/yakonfig | yakonfig/yakonfig.py | _temporary_config | def _temporary_config():
'''Temporarily replace the global configuration.
Use this in a 'with' statement. The inner block may freely manipulate
the global configuration; the original global configuration is restored
at exit.
>>> with yakonfig.yakonfig._temporary_config():
... yakonfig.yakon... | python | def _temporary_config():
'''Temporarily replace the global configuration.
Use this in a 'with' statement. The inner block may freely manipulate
the global configuration; the original global configuration is restored
at exit.
>>> with yakonfig.yakonfig._temporary_config():
... yakonfig.yakon... | [
"def",
"_temporary_config",
"(",
")",
":",
"global",
"_config_cache",
",",
"_config_file_path",
"old_cc",
"=",
"_config_cache",
"old_cfp",
"=",
"_config_file_path",
"clear_global_config",
"(",
")",
"yield",
"_config_cache",
"=",
"old_cc",
"_config_file_path",
"=",
"ol... | Temporarily replace the global configuration.
Use this in a 'with' statement. The inner block may freely manipulate
the global configuration; the original global configuration is restored
at exit.
>>> with yakonfig.yakonfig._temporary_config():
... yakonfig.yakonfig.set_global_config({'a': 'b'}... | [
"Temporarily",
"replace",
"the",
"global",
"configuration",
"."
] | train | https://github.com/diffeo/yakonfig/blob/412e195da29b4f4fc7b72967c192714a6f5eaeb5/yakonfig/yakonfig.py#L142-L161 |
diffeo/yakonfig | yakonfig/yakonfig.py | Loader.include_yaml | def include_yaml(self, node):
'''
load another yaml file from the path specified by node's value
'''
filename = self.construct_scalar(node)
if not filename.startswith('/'):
if self._root is None:
raise Exception('!include_yaml %s is a relative path, '
... | python | def include_yaml(self, node):
'''
load another yaml file from the path specified by node's value
'''
filename = self.construct_scalar(node)
if not filename.startswith('/'):
if self._root is None:
raise Exception('!include_yaml %s is a relative path, '
... | [
"def",
"include_yaml",
"(",
"self",
",",
"node",
")",
":",
"filename",
"=",
"self",
".",
"construct_scalar",
"(",
"node",
")",
"if",
"not",
"filename",
".",
"startswith",
"(",
"'/'",
")",
":",
"if",
"self",
".",
"_root",
"is",
"None",
":",
"raise",
"... | load another yaml file from the path specified by node's value | [
"load",
"another",
"yaml",
"file",
"from",
"the",
"path",
"specified",
"by",
"node",
"s",
"value"
] | train | https://github.com/diffeo/yakonfig/blob/412e195da29b4f4fc7b72967c192714a6f5eaeb5/yakonfig/yakonfig.py#L39-L50 |
mrstephenneal/dirutility | dirutility/walk/sequential.py | Crawler.encompass | def encompass(self):
"""
Called when parallelize is False.
This function will generate the file names in a directory tree by walking the tree either top-down or
bottom-up. For each directory in the tree rooted at directory top (including top itself), it yields a 3-tuple
(dirpath,... | python | def encompass(self):
"""
Called when parallelize is False.
This function will generate the file names in a directory tree by walking the tree either top-down or
bottom-up. For each directory in the tree rooted at directory top (including top itself), it yields a 3-tuple
(dirpath,... | [
"def",
"encompass",
"(",
"self",
")",
":",
"self",
".",
"_printer",
"(",
"'Standard Walk'",
")",
"count",
"=",
"Counter",
"(",
"length",
"=",
"3",
")",
"for",
"directory",
"in",
"self",
".",
"directory",
":",
"for",
"root",
",",
"directories",
",",
"fi... | Called when parallelize is False.
This function will generate the file names in a directory tree by walking the tree either top-down or
bottom-up. For each directory in the tree rooted at directory top (including top itself), it yields a 3-tuple
(dirpath, dirnames, filenames). | [
"Called",
"when",
"parallelize",
"is",
"False",
".",
"This",
"function",
"will",
"generate",
"the",
"file",
"names",
"in",
"a",
"directory",
"tree",
"by",
"walking",
"the",
"tree",
"either",
"top",
"-",
"down",
"or",
"bottom",
"-",
"up",
".",
"For",
"eac... | train | https://github.com/mrstephenneal/dirutility/blob/339378659e2d7e09c53acfc51c5df745bb0cd517/dirutility/walk/sequential.py#L44-L60 |
mrstephenneal/dirutility | dirutility/walk/sequential.py | Crawler.filter | def filter(self):
"""
Called when parallelize is False.
This function will generate the file names in a directory tree by walking the tree either top-down or
bottom-up. For each directory in the tree rooted at directory top (including top itself), it yields a 3-tuple
(dirpath, di... | python | def filter(self):
"""
Called when parallelize is False.
This function will generate the file names in a directory tree by walking the tree either top-down or
bottom-up. For each directory in the tree rooted at directory top (including top itself), it yields a 3-tuple
(dirpath, di... | [
"def",
"filter",
"(",
"self",
")",
":",
"self",
".",
"_printer",
"(",
"'Standard Walk'",
")",
"count",
"=",
"Counter",
"(",
"length",
"=",
"3",
")",
"for",
"directory",
"in",
"self",
".",
"directory",
":",
"self",
".",
"_printer",
"(",
"'Searching '",
... | Called when parallelize is False.
This function will generate the file names in a directory tree by walking the tree either top-down or
bottom-up. For each directory in the tree rooted at directory top (including top itself), it yields a 3-tuple
(dirpath, dirnames, filenames). | [
"Called",
"when",
"parallelize",
"is",
"False",
".",
"This",
"function",
"will",
"generate",
"the",
"file",
"names",
"in",
"a",
"directory",
"tree",
"by",
"walking",
"the",
"tree",
"either",
"top",
"-",
"down",
"or",
"bottom",
"-",
"up",
".",
"For",
"eac... | train | https://github.com/mrstephenneal/dirutility/blob/339378659e2d7e09c53acfc51c5df745bb0cd517/dirutility/walk/sequential.py#L62-L93 |
mdeous/fatbotslim | fatbotslim/irc/colors.py | ColorMessage.colorize | def colorize(string, color='black', bold=False, underline=False, highlight=False):
"""
:param string: message to colorize.
:type string: unicode
:param color: one of :attr:`fatbotslim.irc.colors.ColorMessage._colors`.
:type color: str
:param bold: if the string has to be ... | python | def colorize(string, color='black', bold=False, underline=False, highlight=False):
"""
:param string: message to colorize.
:type string: unicode
:param color: one of :attr:`fatbotslim.irc.colors.ColorMessage._colors`.
:type color: str
:param bold: if the string has to be ... | [
"def",
"colorize",
"(",
"string",
",",
"color",
"=",
"'black'",
",",
"bold",
"=",
"False",
",",
"underline",
"=",
"False",
",",
"highlight",
"=",
"False",
")",
":",
"result",
"=",
"''",
"if",
"bold",
":",
"result",
"+=",
"ColorMessage",
".",
"_bold",
... | :param string: message to colorize.
:type string: unicode
:param color: one of :attr:`fatbotslim.irc.colors.ColorMessage._colors`.
:type color: str
:param bold: if the string has to be in bold.
:type bold: bool
:param underline: if the string has to be underlined.
... | [
":",
"param",
"string",
":",
"message",
"to",
"colorize",
".",
":",
"type",
"string",
":",
"unicode",
":",
"param",
"color",
":",
"one",
"of",
":",
"attr",
":",
"fatbotslim",
".",
"irc",
".",
"colors",
".",
"ColorMessage",
".",
"_colors",
".",
":",
"... | train | https://github.com/mdeous/fatbotslim/blob/341595d24454a79caee23750eac271f9d0626c88/fatbotslim/irc/colors.py#L87-L108 |
maxweisspoker/simplebitcoinfuncs | simplebitcoinfuncs/stealth.py | paystealth | def paystealth(stealthaddr,ephempriv=None,_doctest_nonce=-1):
'''
Input a stealth address, and optionally an ephemeral private key,
and generate a payment pubkey and stealth OP_RETURN data.
(The OP_RETURN data is just a nonce and the ephemeral public key.)
Works with standard single spend key stea... | python | def paystealth(stealthaddr,ephempriv=None,_doctest_nonce=-1):
'''
Input a stealth address, and optionally an ephemeral private key,
and generate a payment pubkey and stealth OP_RETURN data.
(The OP_RETURN data is just a nonce and the ephemeral public key.)
Works with standard single spend key stea... | [
"def",
"paystealth",
"(",
"stealthaddr",
",",
"ephempriv",
"=",
"None",
",",
"_doctest_nonce",
"=",
"-",
"1",
")",
":",
"if",
"ephempriv",
"is",
"None",
":",
"ephempriv",
"=",
"genkeyhex",
"(",
")",
"addrhex",
"=",
"b58d",
"(",
"stealthaddr",
")",
"asser... | Input a stealth address, and optionally an ephemeral private key,
and generate a payment pubkey and stealth OP_RETURN data.
(The OP_RETURN data is just a nonce and the ephemeral public key.)
Works with standard single spend key stealth addresses, which
begin with the '2a00' version bytes, and have 00-... | [
"Input",
"a",
"stealth",
"address",
"and",
"optionally",
"an",
"ephemeral",
"private",
"key",
"and",
"generate",
"a",
"payment",
"pubkey",
"and",
"stealth",
"OP_RETURN",
"data",
"."
] | train | https://github.com/maxweisspoker/simplebitcoinfuncs/blob/ad332433dfcc067e86d2e77fa0c8f1a27daffb63/simplebitcoinfuncs/stealth.py#L36-L117 |
maxweisspoker/simplebitcoinfuncs | simplebitcoinfuncs/stealth.py | receivestealth | def receivestealth(scanpriv,spendpriv,ephempub):
'''
Derive the private key for a stealth payment, using the scan and
spend private keys, and the ephemeral public key.
Input private keys should be 64-char hex strings, and ephemeral
public key should be a 66-char hex compressed public key.
>>> ... | python | def receivestealth(scanpriv,spendpriv,ephempub):
'''
Derive the private key for a stealth payment, using the scan and
spend private keys, and the ephemeral public key.
Input private keys should be 64-char hex strings, and ephemeral
public key should be a 66-char hex compressed public key.
>>> ... | [
"def",
"receivestealth",
"(",
"scanpriv",
",",
"spendpriv",
",",
"ephempub",
")",
":",
"return",
"addprivkeys",
"(",
"sha256",
"(",
"multiplypub",
"(",
"ephempub",
",",
"scanpriv",
",",
"True",
")",
")",
",",
"spendpriv",
")"
] | Derive the private key for a stealth payment, using the scan and
spend private keys, and the ephemeral public key.
Input private keys should be 64-char hex strings, and ephemeral
public key should be a 66-char hex compressed public key.
>>> receivestealth('af4afaeb40810e5f8abdbb177c31a2d310913f91cf556... | [
"Derive",
"the",
"private",
"key",
"for",
"a",
"stealth",
"payment",
"using",
"the",
"scan",
"and",
"spend",
"private",
"keys",
"and",
"the",
"ephemeral",
"public",
"key",
"."
] | train | https://github.com/maxweisspoker/simplebitcoinfuncs/blob/ad332433dfcc067e86d2e77fa0c8f1a27daffb63/simplebitcoinfuncs/stealth.py#L120-L134 |
oxalorg/ghPublish | ghPublish/preview.py | preview_file | def preview_file(post):
"""
Opens the rendered markdown file (as html) locally in a browser.
"""
with open(post) as f:
content = f.read()
title = os.path.basename(post)
Preview(title, content).preview() | python | def preview_file(post):
"""
Opens the rendered markdown file (as html) locally in a browser.
"""
with open(post) as f:
content = f.read()
title = os.path.basename(post)
Preview(title, content).preview() | [
"def",
"preview_file",
"(",
"post",
")",
":",
"with",
"open",
"(",
"post",
")",
"as",
"f",
":",
"content",
"=",
"f",
".",
"read",
"(",
")",
"title",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"post",
")",
"Preview",
"(",
"title",
",",
"content... | Opens the rendered markdown file (as html) locally in a browser. | [
"Opens",
"the",
"rendered",
"markdown",
"file",
"(",
"as",
"html",
")",
"locally",
"in",
"a",
"browser",
"."
] | train | https://github.com/oxalorg/ghPublish/blob/aa3ec8fd2187efd99cffc1a5a76eda4ff2a3b636/ghPublish/preview.py#L11-L18 |
ironfroggy/django-better-cache | bettercache/proxy.py | proxy | def proxy(request):
"""Pass an HTTP request on to another server."""
# TODO: don't hardcode http
uri = "http://" + HOST + request.META['PATH_INFO']
if request.META['QUERY_STRING']:
uri += '?' + request.META['QUERY_STRING']
headers = {}
for name, val in six.iteritems(request.environ):
... | python | def proxy(request):
"""Pass an HTTP request on to another server."""
# TODO: don't hardcode http
uri = "http://" + HOST + request.META['PATH_INFO']
if request.META['QUERY_STRING']:
uri += '?' + request.META['QUERY_STRING']
headers = {}
for name, val in six.iteritems(request.environ):
... | [
"def",
"proxy",
"(",
"request",
")",
":",
"# TODO: don't hardcode http",
"uri",
"=",
"\"http://\"",
"+",
"HOST",
"+",
"request",
".",
"META",
"[",
"'PATH_INFO'",
"]",
"if",
"request",
".",
"META",
"[",
"'QUERY_STRING'",
"]",
":",
"uri",
"+=",
"'?'",
"+",
... | Pass an HTTP request on to another server. | [
"Pass",
"an",
"HTTP",
"request",
"on",
"to",
"another",
"server",
"."
] | train | https://github.com/ironfroggy/django-better-cache/blob/5350e8c646cef1c1ca74eab176f856ddd9eaf5c3/bettercache/proxy.py#L37-L62 |
ironfroggy/django-better-cache | bettercache/proxy.py | header_name | def header_name(name):
"""Convert header name like HTTP_XXXX_XXX to Xxxx-Xxx:"""
words = name[5:].split('_')
for i in range(len(words)):
words[i] = words[i][0].upper() + words[i][1:].lower()
result = '-'.join(words)
return result | python | def header_name(name):
"""Convert header name like HTTP_XXXX_XXX to Xxxx-Xxx:"""
words = name[5:].split('_')
for i in range(len(words)):
words[i] = words[i][0].upper() + words[i][1:].lower()
result = '-'.join(words)
return result | [
"def",
"header_name",
"(",
"name",
")",
":",
"words",
"=",
"name",
"[",
"5",
":",
"]",
".",
"split",
"(",
"'_'",
")",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"words",
")",
")",
":",
"words",
"[",
"i",
"]",
"=",
"words",
"[",
"i",
"]",
"... | Convert header name like HTTP_XXXX_XXX to Xxxx-Xxx: | [
"Convert",
"header",
"name",
"like",
"HTTP_XXXX_XXX",
"to",
"Xxxx",
"-",
"Xxx",
":"
] | train | https://github.com/ironfroggy/django-better-cache/blob/5350e8c646cef1c1ca74eab176f856ddd9eaf5c3/bettercache/proxy.py#L65-L72 |
sunlightlabs/django-locksmith | locksmith/hub/common.py | cycle_generator | def cycle_generator(cycle, step=1, begin=(0, 0), end=None):
'''
Generates pairs of values representing a cycle. E.g. clock hours for a day could
could be generated with:
_cycle_generator(cycle=(1, 12), step=1, begin=(0, 1), end=(23, 12))
=> (0, 1), (0, 2) ... (0, 12), (1,... | python | def cycle_generator(cycle, step=1, begin=(0, 0), end=None):
'''
Generates pairs of values representing a cycle. E.g. clock hours for a day could
could be generated with:
_cycle_generator(cycle=(1, 12), step=1, begin=(0, 1), end=(23, 12))
=> (0, 1), (0, 2) ... (0, 12), (1,... | [
"def",
"cycle_generator",
"(",
"cycle",
",",
"step",
"=",
"1",
",",
"begin",
"=",
"(",
"0",
",",
"0",
")",
",",
"end",
"=",
"None",
")",
":",
"(",
"cycle_begin",
",",
"cycle_end",
")",
"=",
"cycle",
"(",
"major",
",",
"minor",
")",
"=",
"begin",
... | Generates pairs of values representing a cycle. E.g. clock hours for a day could
could be generated with:
_cycle_generator(cycle=(1, 12), step=1, begin=(0, 1), end=(23, 12))
=> (0, 1), (0, 2) ... (0, 12), (1, 1), (1, 2) | [
"Generates",
"pairs",
"of",
"values",
"representing",
"a",
"cycle",
".",
"E",
".",
"g",
".",
"clock",
"hours",
"for",
"a",
"day",
"could",
"could",
"be",
"generated",
"with",
":",
"_cycle_generator",
"(",
"cycle",
"=",
"(",
"1",
"12",
")",
"step",
"=",... | train | https://github.com/sunlightlabs/django-locksmith/blob/eef5b7c25404560aaad50b6e622594f89239b74b/locksmith/hub/common.py#L4-L22 |
mayfield/shellish | shellish/layout/table.py | tabulate | def tabulate(data, header=True, headers=None, accessors=None,
**table_options):
""" Shortcut function to produce tabular output of data without the
need to create and configure a Table instance directly. The function
does however return a table instance when it's done for any further use
by... | python | def tabulate(data, header=True, headers=None, accessors=None,
**table_options):
""" Shortcut function to produce tabular output of data without the
need to create and configure a Table instance directly. The function
does however return a table instance when it's done for any further use
by... | [
"def",
"tabulate",
"(",
"data",
",",
"header",
"=",
"True",
",",
"headers",
"=",
"None",
",",
"accessors",
"=",
"None",
",",
"*",
"*",
"table_options",
")",
":",
"if",
"header",
"and",
"not",
"headers",
":",
"data",
"=",
"iter",
"(",
"data",
")",
"... | Shortcut function to produce tabular output of data without the
need to create and configure a Table instance directly. The function
does however return a table instance when it's done for any further use
by the user. | [
"Shortcut",
"function",
"to",
"produce",
"tabular",
"output",
"of",
"data",
"without",
"the",
"need",
"to",
"create",
"and",
"configure",
"a",
"Table",
"instance",
"directly",
".",
"The",
"function",
"does",
"however",
"return",
"a",
"table",
"instance",
"when... | train | https://github.com/mayfield/shellish/blob/df0f0e4612d138c34d8cb99b66ab5b8e47f1414a/shellish/layout/table.py#L1018-L1041 |
mayfield/shellish | shellish/layout/table.py | Table.attach_arguments | def attach_arguments(cls, parser, prefix='--', skip_formats=False,
format_excludes=None, format_title=None,
format_desc=None, skip_render=False,
render_excludes=None, render_title=None,
render_desc=None, skip_filters=Fal... | python | def attach_arguments(cls, parser, prefix='--', skip_formats=False,
format_excludes=None, format_title=None,
format_desc=None, skip_render=False,
render_excludes=None, render_title=None,
render_desc=None, skip_filters=Fal... | [
"def",
"attach_arguments",
"(",
"cls",
",",
"parser",
",",
"prefix",
"=",
"'--'",
",",
"skip_formats",
"=",
"False",
",",
"format_excludes",
"=",
"None",
",",
"format_title",
"=",
"None",
",",
"format_desc",
"=",
"None",
",",
"skip_render",
"=",
"False",
"... | Attach argparse arguments to an argparse parser/group with table
options. These are renderer options and filtering options with the
ability to turn off headers and footers. The return value is function
that parses an argparse.Namespace object into keyword arguments for a
layout.Table c... | [
"Attach",
"argparse",
"arguments",
"to",
"an",
"argparse",
"parser",
"/",
"group",
"with",
"table",
"options",
".",
"These",
"are",
"renderer",
"options",
"and",
"filtering",
"options",
"with",
"the",
"ability",
"to",
"turn",
"off",
"headers",
"and",
"footers"... | train | https://github.com/mayfield/shellish/blob/df0f0e4612d138c34d8cb99b66ab5b8e47f1414a/shellish/layout/table.py#L207-L238 |
mayfield/shellish | shellish/layout/table.py | Table.make_accessors | def make_accessors(self, columns):
""" Accessors can be numeric keys for sequence row data, string keys
for mapping row data, or a callable function. For numeric and string
accessors they can be inside a 2 element tuple where the 2nd value is
the default value; Similar to dict.get(look... | python | def make_accessors(self, columns):
""" Accessors can be numeric keys for sequence row data, string keys
for mapping row data, or a callable function. For numeric and string
accessors they can be inside a 2 element tuple where the 2nd value is
the default value; Similar to dict.get(look... | [
"def",
"make_accessors",
"(",
"self",
",",
"columns",
")",
":",
"accessors",
"=",
"list",
"(",
"self",
".",
"accessors_def",
"or",
"range",
"(",
"columns",
")",
")",
"for",
"i",
",",
"x",
"in",
"enumerate",
"(",
"accessors",
")",
":",
"if",
"not",
"c... | Accessors can be numeric keys for sequence row data, string keys
for mapping row data, or a callable function. For numeric and string
accessors they can be inside a 2 element tuple where the 2nd value is
the default value; Similar to dict.get(lookup, default). | [
"Accessors",
"can",
"be",
"numeric",
"keys",
"for",
"sequence",
"row",
"data",
"string",
"keys",
"for",
"mapping",
"row",
"data",
"or",
"a",
"callable",
"function",
".",
"For",
"numeric",
"and",
"string",
"accessors",
"they",
"can",
"be",
"inside",
"a",
"2... | train | https://github.com/mayfield/shellish/blob/df0f0e4612d138c34d8cb99b66ab5b8e47f1414a/shellish/layout/table.py#L328-L349 |
mayfield/shellish | shellish/layout/table.py | Table.create_colspec | def create_colspec(self, columns, overflow_default=None):
""" Produce a full format columns spec dictionary. The overrides spec
can be a partial columns spec as described in the __init__ method's
depiction of the .columns attribute. """
spec = [{
"width": None,
"... | python | def create_colspec(self, columns, overflow_default=None):
""" Produce a full format columns spec dictionary. The overrides spec
can be a partial columns spec as described in the __init__ method's
depiction of the .columns attribute. """
spec = [{
"width": None,
"... | [
"def",
"create_colspec",
"(",
"self",
",",
"columns",
",",
"overflow_default",
"=",
"None",
")",
":",
"spec",
"=",
"[",
"{",
"\"width\"",
":",
"None",
",",
"\"minwidth\"",
":",
"self",
".",
"column_minwidth",
",",
"\"padding\"",
":",
"self",
".",
"column_p... | Produce a full format columns spec dictionary. The overrides spec
can be a partial columns spec as described in the __init__ method's
depiction of the .columns attribute. | [
"Produce",
"a",
"full",
"format",
"columns",
"spec",
"dictionary",
".",
"The",
"overrides",
"spec",
"can",
"be",
"a",
"partial",
"columns",
"spec",
"as",
"described",
"in",
"the",
"__init__",
"method",
"s",
"depiction",
"of",
"the",
".",
"columns",
"attribut... | train | https://github.com/mayfield/shellish/blob/df0f0e4612d138c34d8cb99b66ab5b8e47f1414a/shellish/layout/table.py#L351-L368 |
mayfield/shellish | shellish/layout/table.py | Table.print | def print(self, rows):
""" Write the data to our output stream (stdout). If the table is not
rendered yet, we will make a renderer instance which will freeze
state. """
if not self.default_renderer:
self.default_renderer = self.make_renderer()
self.default_renderer.p... | python | def print(self, rows):
""" Write the data to our output stream (stdout). If the table is not
rendered yet, we will make a renderer instance which will freeze
state. """
if not self.default_renderer:
self.default_renderer = self.make_renderer()
self.default_renderer.p... | [
"def",
"print",
"(",
"self",
",",
"rows",
")",
":",
"if",
"not",
"self",
".",
"default_renderer",
":",
"self",
".",
"default_renderer",
"=",
"self",
".",
"make_renderer",
"(",
")",
"self",
".",
"default_renderer",
".",
"print",
"(",
"rows",
")"
] | Write the data to our output stream (stdout). If the table is not
rendered yet, we will make a renderer instance which will freeze
state. | [
"Write",
"the",
"data",
"to",
"our",
"output",
"stream",
"(",
"stdout",
")",
".",
"If",
"the",
"table",
"is",
"not",
"rendered",
"yet",
"we",
"will",
"make",
"a",
"renderer",
"instance",
"which",
"will",
"freeze",
"state",
"."
] | train | https://github.com/mayfield/shellish/blob/df0f0e4612d138c34d8cb99b66ab5b8e47f1414a/shellish/layout/table.py#L376-L382 |
mayfield/shellish | shellish/layout/table.py | TableRenderer.render_filter | def render_filter(self, next_filter):
""" Produce formatted output from the raw data stream. """
next(next_filter)
while True:
data = (yield)
res = [self.cell_format(access(data)) for access in self.accessors]
next_filter.send(res) | python | def render_filter(self, next_filter):
""" Produce formatted output from the raw data stream. """
next(next_filter)
while True:
data = (yield)
res = [self.cell_format(access(data)) for access in self.accessors]
next_filter.send(res) | [
"def",
"render_filter",
"(",
"self",
",",
"next_filter",
")",
":",
"next",
"(",
"next_filter",
")",
"while",
"True",
":",
"data",
"=",
"(",
"yield",
")",
"res",
"=",
"[",
"self",
".",
"cell_format",
"(",
"access",
"(",
"data",
")",
")",
"for",
"acces... | Produce formatted output from the raw data stream. | [
"Produce",
"formatted",
"output",
"from",
"the",
"raw",
"data",
"stream",
"."
] | train | https://github.com/mayfield/shellish/blob/df0f0e4612d138c34d8cb99b66ab5b8e47f1414a/shellish/layout/table.py#L472-L478 |
mayfield/shellish | shellish/layout/table.py | VisualTableRenderer.viewable_width | def viewable_width(self):
""" The available combined character width when all padding is
removed. """
return sum(self.widths) + sum(x['padding'] for x in self.colspec) | python | def viewable_width(self):
""" The available combined character width when all padding is
removed. """
return sum(self.widths) + sum(x['padding'] for x in self.colspec) | [
"def",
"viewable_width",
"(",
"self",
")",
":",
"return",
"sum",
"(",
"self",
".",
"widths",
")",
"+",
"sum",
"(",
"x",
"[",
"'padding'",
"]",
"for",
"x",
"in",
"self",
".",
"colspec",
")"
] | The available combined character width when all padding is
removed. | [
"The",
"available",
"combined",
"character",
"width",
"when",
"all",
"padding",
"is",
"removed",
"."
] | train | https://github.com/mayfield/shellish/blob/df0f0e4612d138c34d8cb99b66ab5b8e47f1414a/shellish/layout/table.py#L543-L546 |
mayfield/shellish | shellish/layout/table.py | VisualTableRenderer.print_row | def print_row(self, row, rstrip=True):
""" Format and print the pre-rendered data to the output device. """
line = ''.join(map(str, row))
print(line.rstrip() if rstrip else line, file=self.table.file) | python | def print_row(self, row, rstrip=True):
""" Format and print the pre-rendered data to the output device. """
line = ''.join(map(str, row))
print(line.rstrip() if rstrip else line, file=self.table.file) | [
"def",
"print_row",
"(",
"self",
",",
"row",
",",
"rstrip",
"=",
"True",
")",
":",
"line",
"=",
"''",
".",
"join",
"(",
"map",
"(",
"str",
",",
"row",
")",
")",
"print",
"(",
"line",
".",
"rstrip",
"(",
")",
"if",
"rstrip",
"else",
"line",
",",... | Format and print the pre-rendered data to the output device. | [
"Format",
"and",
"print",
"the",
"pre",
"-",
"rendered",
"data",
"to",
"the",
"output",
"device",
"."
] | train | https://github.com/mayfield/shellish/blob/df0f0e4612d138c34d8cb99b66ab5b8e47f1414a/shellish/layout/table.py#L567-L570 |
mayfield/shellish | shellish/layout/table.py | VisualTableRenderer.format_row | def format_row(self, row):
""" Apply overflow, justification and padding to a row. Returns lines
(plural) of rendered text for the row. """
assert all(isinstance(x, VTMLBuffer) for x in row)
raw = (fn(x) for x, fn in zip(row, self.formatters))
for line in itertools.zip_longest(*... | python | def format_row(self, row):
""" Apply overflow, justification and padding to a row. Returns lines
(plural) of rendered text for the row. """
assert all(isinstance(x, VTMLBuffer) for x in row)
raw = (fn(x) for x, fn in zip(row, self.formatters))
for line in itertools.zip_longest(*... | [
"def",
"format_row",
"(",
"self",
",",
"row",
")",
":",
"assert",
"all",
"(",
"isinstance",
"(",
"x",
",",
"VTMLBuffer",
")",
"for",
"x",
"in",
"row",
")",
"raw",
"=",
"(",
"fn",
"(",
"x",
")",
"for",
"x",
",",
"fn",
"in",
"zip",
"(",
"row",
... | Apply overflow, justification and padding to a row. Returns lines
(plural) of rendered text for the row. | [
"Apply",
"overflow",
"justification",
"and",
"padding",
"to",
"a",
"row",
".",
"Returns",
"lines",
"(",
"plural",
")",
"of",
"rendered",
"text",
"for",
"the",
"row",
"."
] | train | https://github.com/mayfield/shellish/blob/df0f0e4612d138c34d8cb99b66ab5b8e47f1414a/shellish/layout/table.py#L583-L593 |
mayfield/shellish | shellish/layout/table.py | VisualTableRenderer.format_fullwidth | def format_fullwidth(self, value):
""" Return a full width column. Note that the padding is inherited
from the first cell which inherits from column_padding. """
assert isinstance(value, VTMLBuffer)
pad = self.colspec[0]['padding']
fmt = self.make_formatter(self.width - pad, pad,... | python | def format_fullwidth(self, value):
""" Return a full width column. Note that the padding is inherited
from the first cell which inherits from column_padding. """
assert isinstance(value, VTMLBuffer)
pad = self.colspec[0]['padding']
fmt = self.make_formatter(self.width - pad, pad,... | [
"def",
"format_fullwidth",
"(",
"self",
",",
"value",
")",
":",
"assert",
"isinstance",
"(",
"value",
",",
"VTMLBuffer",
")",
"pad",
"=",
"self",
".",
"colspec",
"[",
"0",
"]",
"[",
"'padding'",
"]",
"fmt",
"=",
"self",
".",
"make_formatter",
"(",
"sel... | Return a full width column. Note that the padding is inherited
from the first cell which inherits from column_padding. | [
"Return",
"a",
"full",
"width",
"column",
".",
"Note",
"that",
"the",
"padding",
"is",
"inherited",
"from",
"the",
"first",
"cell",
"which",
"inherits",
"from",
"column_padding",
"."
] | train | https://github.com/mayfield/shellish/blob/df0f0e4612d138c34d8cb99b66ab5b8e47f1414a/shellish/layout/table.py#L595-L602 |
mayfield/shellish | shellish/layout/table.py | VisualTableRenderer.make_formatter | def make_formatter(self, width, padding, alignment, overflow=None):
""" Create formatter function that factors the width and alignment
settings. """
if overflow is None:
overflow = self.overflow_default
if overflow == 'clip':
overflower = lambda x: [x.clip(width, ... | python | def make_formatter(self, width, padding, alignment, overflow=None):
""" Create formatter function that factors the width and alignment
settings. """
if overflow is None:
overflow = self.overflow_default
if overflow == 'clip':
overflower = lambda x: [x.clip(width, ... | [
"def",
"make_formatter",
"(",
"self",
",",
"width",
",",
"padding",
",",
"alignment",
",",
"overflow",
"=",
"None",
")",
":",
"if",
"overflow",
"is",
"None",
":",
"overflow",
"=",
"self",
".",
"overflow_default",
"if",
"overflow",
"==",
"'clip'",
":",
"o... | Create formatter function that factors the width and alignment
settings. | [
"Create",
"formatter",
"function",
"that",
"factors",
"the",
"width",
"and",
"alignment",
"settings",
"."
] | train | https://github.com/mayfield/shellish/blob/df0f0e4612d138c34d8cb99b66ab5b8e47f1414a/shellish/layout/table.py#L604-L619 |
mayfield/shellish | shellish/layout/table.py | VisualTableRenderer.make_formatters | def make_formatters(self):
""" Create a list formatter functions for each column. They can then
be stored in the render spec for faster justification processing. """
return [self.make_formatter(inner_w, spec['padding'], spec['align'],
spec['overflow'])
... | python | def make_formatters(self):
""" Create a list formatter functions for each column. They can then
be stored in the render spec for faster justification processing. """
return [self.make_formatter(inner_w, spec['padding'], spec['align'],
spec['overflow'])
... | [
"def",
"make_formatters",
"(",
"self",
")",
":",
"return",
"[",
"self",
".",
"make_formatter",
"(",
"inner_w",
",",
"spec",
"[",
"'padding'",
"]",
",",
"spec",
"[",
"'align'",
"]",
",",
"spec",
"[",
"'overflow'",
"]",
")",
"for",
"spec",
",",
"inner_w"... | Create a list formatter functions for each column. They can then
be stored in the render spec for faster justification processing. | [
"Create",
"a",
"list",
"formatter",
"functions",
"for",
"each",
"column",
".",
"They",
"can",
"then",
"be",
"stored",
"in",
"the",
"render",
"spec",
"for",
"faster",
"justification",
"processing",
"."
] | train | https://github.com/mayfield/shellish/blob/df0f0e4612d138c34d8cb99b66ab5b8e47f1414a/shellish/layout/table.py#L621-L626 |
mayfield/shellish | shellish/layout/table.py | VisualTableRenderer._uniform_dist | def _uniform_dist(self, spread, total):
""" Produce a uniform distribution of `total` across a list of
`spread` size. The result is non-random and uniform. """
fraction, fixed_increment = math.modf(total / spread)
fixed_increment = int(fixed_increment)
balance = 0
dist = ... | python | def _uniform_dist(self, spread, total):
""" Produce a uniform distribution of `total` across a list of
`spread` size. The result is non-random and uniform. """
fraction, fixed_increment = math.modf(total / spread)
fixed_increment = int(fixed_increment)
balance = 0
dist = ... | [
"def",
"_uniform_dist",
"(",
"self",
",",
"spread",
",",
"total",
")",
":",
"fraction",
",",
"fixed_increment",
"=",
"math",
".",
"modf",
"(",
"total",
"/",
"spread",
")",
"fixed_increment",
"=",
"int",
"(",
"fixed_increment",
")",
"balance",
"=",
"0",
"... | Produce a uniform distribution of `total` across a list of
`spread` size. The result is non-random and uniform. | [
"Produce",
"a",
"uniform",
"distribution",
"of",
"total",
"across",
"a",
"list",
"of",
"spread",
"size",
".",
"The",
"result",
"is",
"non",
"-",
"random",
"and",
"uniform",
"."
] | train | https://github.com/mayfield/shellish/blob/df0f0e4612d138c34d8cb99b66ab5b8e47f1414a/shellish/layout/table.py#L628-L641 |
mayfield/shellish | shellish/layout/table.py | VisualTableRenderer.get_filters | def get_filters(self):
""" Coroutine based filters for render pipeline. """
return [
self.compute_style_filter,
self.render_filter,
self.calc_widths_filter,
self.format_row_filter,
self.align_rows_filter,
] | python | def get_filters(self):
""" Coroutine based filters for render pipeline. """
return [
self.compute_style_filter,
self.render_filter,
self.calc_widths_filter,
self.format_row_filter,
self.align_rows_filter,
] | [
"def",
"get_filters",
"(",
"self",
")",
":",
"return",
"[",
"self",
".",
"compute_style_filter",
",",
"self",
".",
"render_filter",
",",
"self",
".",
"calc_widths_filter",
",",
"self",
".",
"format_row_filter",
",",
"self",
".",
"align_rows_filter",
",",
"]"
] | Coroutine based filters for render pipeline. | [
"Coroutine",
"based",
"filters",
"for",
"render",
"pipeline",
"."
] | train | https://github.com/mayfield/shellish/blob/df0f0e4612d138c34d8cb99b66ab5b8e47f1414a/shellish/layout/table.py#L643-L651 |
mayfield/shellish | shellish/layout/table.py | VisualTableRenderer.format_row_filter | def format_row_filter(self, next_filter):
""" Apply overflow, justification, padding and expansion to a row. """
next(next_filter)
while True:
items = (yield)
assert all(isinstance(x, VTMLBuffer) for x in items)
raw = (fn(x) for x, fn in zip(items, self.format... | python | def format_row_filter(self, next_filter):
""" Apply overflow, justification, padding and expansion to a row. """
next(next_filter)
while True:
items = (yield)
assert all(isinstance(x, VTMLBuffer) for x in items)
raw = (fn(x) for x, fn in zip(items, self.format... | [
"def",
"format_row_filter",
"(",
"self",
",",
"next_filter",
")",
":",
"next",
"(",
"next_filter",
")",
"while",
"True",
":",
"items",
"=",
"(",
"yield",
")",
"assert",
"all",
"(",
"isinstance",
"(",
"x",
",",
"VTMLBuffer",
")",
"for",
"x",
"in",
"item... | Apply overflow, justification, padding and expansion to a row. | [
"Apply",
"overflow",
"justification",
"padding",
"and",
"expansion",
"to",
"a",
"row",
"."
] | train | https://github.com/mayfield/shellish/blob/df0f0e4612d138c34d8cb99b66ab5b8e47f1414a/shellish/layout/table.py#L653-L661 |
mayfield/shellish | shellish/layout/table.py | VisualTableRenderer._column_pack_filter | def _column_pack_filter(self, next_filter):
""" Top-align column data irrespective of original row alignment. E.g.
INPUT: [
["1a", "2a"],
[None, "2b"],
["1b", "2c"],
[None, "2d"]
]
OUTPUT: [
["1a... | python | def _column_pack_filter(self, next_filter):
""" Top-align column data irrespective of original row alignment. E.g.
INPUT: [
["1a", "2a"],
[None, "2b"],
["1b", "2c"],
[None, "2d"]
]
OUTPUT: [
["1a... | [
"def",
"_column_pack_filter",
"(",
"self",
",",
"next_filter",
")",
":",
"next",
"(",
"next_filter",
")",
"col_count",
"=",
"len",
"(",
"self",
".",
"widths",
")",
"queues",
"=",
"[",
"collections",
".",
"deque",
"(",
")",
"for",
"_",
"in",
"range",
"(... | Top-align column data irrespective of original row alignment. E.g.
INPUT: [
["1a", "2a"],
[None, "2b"],
["1b", "2c"],
[None, "2d"]
]
OUTPUT: [
["1a", "2a"],
["1b", "2b"],
... | [
"Top",
"-",
"align",
"column",
"data",
"irrespective",
"of",
"original",
"row",
"alignment",
".",
"E",
".",
"g",
".",
"INPUT",
":",
"[",
"[",
"1a",
"2a",
"]",
"[",
"None",
"2b",
"]",
"[",
"1b",
"2c",
"]",
"[",
"None",
"2d",
"]",
"]",
"OUTPUT",
... | train | https://github.com/mayfield/shellish/blob/df0f0e4612d138c34d8cb99b66ab5b8e47f1414a/shellish/layout/table.py#L671-L702 |
mayfield/shellish | shellish/layout/table.py | VisualTableRenderer._column_pad_filter | def _column_pad_filter(self, next_filter):
""" Expand blank lines caused from overflow of other columns to blank
whitespace. E.g.
INPUT: [
["1a", "2a"],
[None, "2b"],
["1b", "2c"],
[None, "2d"]
]
OUTPUT:... | python | def _column_pad_filter(self, next_filter):
""" Expand blank lines caused from overflow of other columns to blank
whitespace. E.g.
INPUT: [
["1a", "2a"],
[None, "2b"],
["1b", "2c"],
[None, "2d"]
]
OUTPUT:... | [
"def",
"_column_pad_filter",
"(",
"self",
",",
"next_filter",
")",
":",
"next",
"(",
"next_filter",
")",
"while",
"True",
":",
"line",
"=",
"list",
"(",
"(",
"yield",
")",
")",
"for",
"i",
",",
"col",
"in",
"enumerate",
"(",
"line",
")",
":",
"if",
... | Expand blank lines caused from overflow of other columns to blank
whitespace. E.g.
INPUT: [
["1a", "2a"],
[None, "2b"],
["1b", "2c"],
[None, "2d"]
]
OUTPUT: [
["1a", "2a"],
[<blan... | [
"Expand",
"blank",
"lines",
"caused",
"from",
"overflow",
"of",
"other",
"columns",
"to",
"blank",
"whitespace",
".",
"E",
".",
"g",
".",
"INPUT",
":",
"[",
"[",
"1a",
"2a",
"]",
"[",
"None",
"2b",
"]",
"[",
"1b",
"2c",
"]",
"[",
"None",
"2d",
"]... | train | https://github.com/mayfield/shellish/blob/df0f0e4612d138c34d8cb99b66ab5b8e47f1414a/shellish/layout/table.py#L704-L726 |
mayfield/shellish | shellish/layout/table.py | VisualTableRenderer.width_normalize | def width_normalize(self, width):
""" Handle a width style, which can be a fractional number
representing a percentage of available width or positive integers
which indicate a fixed width. """
if width is not None:
if width > 0 and width < 1:
return int(width ... | python | def width_normalize(self, width):
""" Handle a width style, which can be a fractional number
representing a percentage of available width or positive integers
which indicate a fixed width. """
if width is not None:
if width > 0 and width < 1:
return int(width ... | [
"def",
"width_normalize",
"(",
"self",
",",
"width",
")",
":",
"if",
"width",
"is",
"not",
"None",
":",
"if",
"width",
">",
"0",
"and",
"width",
"<",
"1",
":",
"return",
"int",
"(",
"width",
"*",
"self",
".",
"usable_width",
")",
"else",
":",
"retu... | Handle a width style, which can be a fractional number
representing a percentage of available width or positive integers
which indicate a fixed width. | [
"Handle",
"a",
"width",
"style",
"which",
"can",
"be",
"a",
"fractional",
"number",
"representing",
"a",
"percentage",
"of",
"available",
"width",
"or",
"positive",
"integers",
"which",
"indicate",
"a",
"fixed",
"width",
"."
] | train | https://github.com/mayfield/shellish/blob/df0f0e4612d138c34d8cb99b66ab5b8e47f1414a/shellish/layout/table.py#L733-L741 |
mayfield/shellish | shellish/layout/table.py | VisualTableRenderer.calc_widths_filter | def calc_widths_filter(self, next_filter):
""" Coroutine to analyze the incoming data stream for creating optimal
column width choices. This may buffer some of the incoming stream if
there isn't enough information to make good choices about column
widths. Also it may resize widths if c... | python | def calc_widths_filter(self, next_filter):
""" Coroutine to analyze the incoming data stream for creating optimal
column width choices. This may buffer some of the incoming stream if
there isn't enough information to make good choices about column
widths. Also it may resize widths if c... | [
"def",
"calc_widths_filter",
"(",
"self",
",",
"next_filter",
")",
":",
"window_sent",
"=",
"not",
"not",
"self",
".",
"data_window",
"next_primed",
"=",
"False",
"genexit",
"=",
"None",
"if",
"not",
"self",
".",
"data_window",
":",
"start",
"=",
"time",
"... | Coroutine to analyze the incoming data stream for creating optimal
column width choices. This may buffer some of the incoming stream if
there isn't enough information to make good choices about column
widths. Also it may resize widths if certain conditions are met such
as the terminal ... | [
"Coroutine",
"to",
"analyze",
"the",
"incoming",
"data",
"stream",
"for",
"creating",
"optimal",
"column",
"width",
"choices",
".",
"This",
"may",
"buffer",
"some",
"of",
"the",
"incoming",
"stream",
"if",
"there",
"isn",
"t",
"enough",
"information",
"to",
... | train | https://github.com/mayfield/shellish/blob/df0f0e4612d138c34d8cb99b66ab5b8e47f1414a/shellish/layout/table.py#L743-L800 |
mayfield/shellish | shellish/layout/table.py | VisualTableRenderer.calc_flex | def calc_flex(self, data, max_width, cols, preformatted=None):
""" Scan data returning the best width for each column given the
max_width constraint. If some columns will overflow we calculate the
best concession widths. """
if preformatted is None:
preformatted = []
... | python | def calc_flex(self, data, max_width, cols, preformatted=None):
""" Scan data returning the best width for each column given the
max_width constraint. If some columns will overflow we calculate the
best concession widths. """
if preformatted is None:
preformatted = []
... | [
"def",
"calc_flex",
"(",
"self",
",",
"data",
",",
"max_width",
",",
"cols",
",",
"preformatted",
"=",
"None",
")",
":",
"if",
"preformatted",
"is",
"None",
":",
"preformatted",
"=",
"[",
"]",
"colstats",
"=",
"[",
"]",
"for",
"i",
"in",
"cols",
":",... | Scan data returning the best width for each column given the
max_width constraint. If some columns will overflow we calculate the
best concession widths. | [
"Scan",
"data",
"returning",
"the",
"best",
"width",
"for",
"each",
"column",
"given",
"the",
"max_width",
"constraint",
".",
"If",
"some",
"columns",
"will",
"overflow",
"we",
"calculate",
"the",
"best",
"concession",
"widths",
"."
] | train | https://github.com/mayfield/shellish/blob/df0f0e4612d138c34d8cb99b66ab5b8e47f1414a/shellish/layout/table.py#L802-L839 |
mayfield/shellish | shellish/layout/table.py | VisualTableRenderer.adjust_widths | def adjust_widths(self, max_width, colstats):
""" Adjust column widths based on the least negative affect it will
have on the viewing experience. We take note of the total character
mass that will be clipped when each column should be narrowed. The
actual score for clipping is based on... | python | def adjust_widths(self, max_width, colstats):
""" Adjust column widths based on the least negative affect it will
have on the viewing experience. We take note of the total character
mass that will be clipped when each column should be narrowed. The
actual score for clipping is based on... | [
"def",
"adjust_widths",
"(",
"self",
",",
"max_width",
",",
"colstats",
")",
":",
"adj_colstats",
"=",
"[",
"]",
"for",
"x",
"in",
"colstats",
":",
"if",
"not",
"x",
"[",
"'preformatted'",
"]",
":",
"adj_colstats",
".",
"append",
"(",
"x",
")",
"else",... | Adjust column widths based on the least negative affect it will
have on the viewing experience. We take note of the total character
mass that will be clipped when each column should be narrowed. The
actual score for clipping is based on percentage of total character
mass, which is the ... | [
"Adjust",
"column",
"widths",
"based",
"on",
"the",
"least",
"negative",
"affect",
"it",
"will",
"have",
"on",
"the",
"viewing",
"experience",
".",
"We",
"take",
"note",
"of",
"the",
"total",
"character",
"mass",
"that",
"will",
"be",
"clipped",
"when",
"e... | train | https://github.com/mayfield/shellish/blob/df0f0e4612d138c34d8cb99b66ab5b8e47f1414a/shellish/layout/table.py#L841-L868 |
mayfield/shellish | shellish/layout/table.py | JSONTableRenderer.make_key | def make_key(self, value):
""" Make camelCase variant of value. """
if value:
parts = [self.key_filter.sub('', x)
for x in self.key_split.split(value.lower())]
key = parts[0] + ''.join(map(str.capitalize, parts[1:]))
else:
key = ''
... | python | def make_key(self, value):
""" Make camelCase variant of value. """
if value:
parts = [self.key_filter.sub('', x)
for x in self.key_split.split(value.lower())]
key = parts[0] + ''.join(map(str.capitalize, parts[1:]))
else:
key = ''
... | [
"def",
"make_key",
"(",
"self",
",",
"value",
")",
":",
"if",
"value",
":",
"parts",
"=",
"[",
"self",
".",
"key_filter",
".",
"sub",
"(",
"''",
",",
"x",
")",
"for",
"x",
"in",
"self",
".",
"key_split",
".",
"split",
"(",
"value",
".",
"lower",
... | Make camelCase variant of value. | [
"Make",
"camelCase",
"variant",
"of",
"value",
"."
] | train | https://github.com/mayfield/shellish/blob/df0f0e4612d138c34d8cb99b66ab5b8e47f1414a/shellish/layout/table.py#L921-L935 |
thisfred/val | val/_val.py | _build_type_validator | def _build_type_validator(value_type):
"""Build a validator that only checks the type of a value."""
def type_validator(data):
"""Validate instances of a particular type."""
if isinstance(data, value_type):
return data
raise NotValid('%r is not of type %r' % (data, value_ty... | python | def _build_type_validator(value_type):
"""Build a validator that only checks the type of a value."""
def type_validator(data):
"""Validate instances of a particular type."""
if isinstance(data, value_type):
return data
raise NotValid('%r is not of type %r' % (data, value_ty... | [
"def",
"_build_type_validator",
"(",
"value_type",
")",
":",
"def",
"type_validator",
"(",
"data",
")",
":",
"\"\"\"Validate instances of a particular type.\"\"\"",
"if",
"isinstance",
"(",
"data",
",",
"value_type",
")",
":",
"return",
"data",
"raise",
"NotValid",
... | Build a validator that only checks the type of a value. | [
"Build",
"a",
"validator",
"that",
"only",
"checks",
"the",
"type",
"of",
"a",
"value",
"."
] | train | https://github.com/thisfred/val/blob/ba022e0c6c47acb3b8a45e7c44c84cc0f495c41c/val/_val.py#L25-L35 |
thisfred/val | val/_val.py | _build_static_validator | def _build_static_validator(exact_value):
"""Build a validator that checks if the data is equal to an exact value."""
def static_validator(data):
"""Validate by equality."""
if data == exact_value:
return data
raise NotValid('%r is not equal to %r' % (data, exact_value))
... | python | def _build_static_validator(exact_value):
"""Build a validator that checks if the data is equal to an exact value."""
def static_validator(data):
"""Validate by equality."""
if data == exact_value:
return data
raise NotValid('%r is not equal to %r' % (data, exact_value))
... | [
"def",
"_build_static_validator",
"(",
"exact_value",
")",
":",
"def",
"static_validator",
"(",
"data",
")",
":",
"\"\"\"Validate by equality.\"\"\"",
"if",
"data",
"==",
"exact_value",
":",
"return",
"data",
"raise",
"NotValid",
"(",
"'%r is not equal to %r'",
"%",
... | Build a validator that checks if the data is equal to an exact value. | [
"Build",
"a",
"validator",
"that",
"checks",
"if",
"the",
"data",
"is",
"equal",
"to",
"an",
"exact",
"value",
"."
] | train | https://github.com/thisfred/val/blob/ba022e0c6c47acb3b8a45e7c44c84cc0f495c41c/val/_val.py#L38-L48 |
thisfred/val | val/_val.py | _build_callable_validator | def _build_callable_validator(function):
"""Build a validator that checks the return value of function(data)."""
def callable_validator(data):
"""Validate by checking the return value of function(data)."""
try:
if function(data):
return data
except (TypeErro... | python | def _build_callable_validator(function):
"""Build a validator that checks the return value of function(data)."""
def callable_validator(data):
"""Validate by checking the return value of function(data)."""
try:
if function(data):
return data
except (TypeErro... | [
"def",
"_build_callable_validator",
"(",
"function",
")",
":",
"def",
"callable_validator",
"(",
"data",
")",
":",
"\"\"\"Validate by checking the return value of function(data).\"\"\"",
"try",
":",
"if",
"function",
"(",
"data",
")",
":",
"return",
"data",
"except",
... | Build a validator that checks the return value of function(data). | [
"Build",
"a",
"validator",
"that",
"checks",
"the",
"return",
"value",
"of",
"function",
"(",
"data",
")",
"."
] | train | https://github.com/thisfred/val/blob/ba022e0c6c47acb3b8a45e7c44c84cc0f495c41c/val/_val.py#L51-L65 |
thisfred/val | val/_val.py | _build_iterable_validator | def _build_iterable_validator(iterable):
"""Build a validator from an iterable."""
sub_schemas = [parse_schema(s) for s in iterable]
def item_validator(value):
"""Validate items in an iterable."""
for sub in sub_schemas:
try:
return sub(value)
except... | python | def _build_iterable_validator(iterable):
"""Build a validator from an iterable."""
sub_schemas = [parse_schema(s) for s in iterable]
def item_validator(value):
"""Validate items in an iterable."""
for sub in sub_schemas:
try:
return sub(value)
except... | [
"def",
"_build_iterable_validator",
"(",
"iterable",
")",
":",
"sub_schemas",
"=",
"[",
"parse_schema",
"(",
"s",
")",
"for",
"s",
"in",
"iterable",
"]",
"def",
"item_validator",
"(",
"value",
")",
":",
"\"\"\"Validate items in an iterable.\"\"\"",
"for",
"sub",
... | Build a validator from an iterable. | [
"Build",
"a",
"validator",
"from",
"an",
"iterable",
"."
] | train | https://github.com/thisfred/val/blob/ba022e0c6c47acb3b8a45e7c44c84cc0f495c41c/val/_val.py#L68-L90 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.