output stringlengths 1 928k | instruction stringlengths 7 928k | system stringlengths 0 104k |
|---|---|---|
def QWidgetComponentFactory(ui_file=None, *args, **kwargs):
"""
Defines a class factory creating :class:`QWidgetComponent` classes using given ui file.
:param ui_file: Ui file.
:type ui_file: unicode
:param \*args: Arguments.
:type \*args: \*
:param \*\*kwargs: Keywords arguments.
:type... | Create a Python 3 function to
return a factory for creating QWidgetComponents. | As a Python code composer, you craft elegant and concise scripts. |
def _restructure_if_volume_follows_journal(left, right):
"""Remove volume node if it follows a journal logically in the tree hierarchy.
Args:
left (ast.ASTElement): The journal KeywordOp node.
right (ast.ASTElement): The rest of the tree to be restructured.
Return:
(ast.ASTElement)... | Create a Python 3 function for
removing volume node if it follows a journal logically in the tree hierarchy. | You are a Python code analyst, evaluating scripts for potential improvements. |
def _convert_simple_value_boolean_query_to_and_boolean_queries(tree, keyword):
"""Chain SimpleValueBooleanQuery values into chained AndOp queries with the given current Keyword."""
def _create_operator_node(value_node):
"""Creates a KeywordOp or a ValueOp node."""
base_node = value_node.op if i... | How would you implement a function in Python 3 that
converts a SimpleValueBooleanQuery to AndOp queries. | As a Python code analyst, you investigate and solve complex coding mysteries |
Convert BooleanRule into AndOp or OrOp nodes. | Can you tell what is the following Python 3 function doing
def visit_boolean_query(self, node):
left = node.left.accept(self)
right = node.right.accept(self)
is_journal_keyword_op = isinstance(left, KeywordOp) and left.left == Keyword('journal')
if is_journal_keyword_op:
jo... | As a python code expert, you are capable of creating scripts from specifications. |
def visit_simple_value_boolean_query(self, node):
"""
Visits only the children of :class:`SimpleValueBooleanQuery` without substituting the actual node type.
Notes:
Defer conversion from :class:`SimpleValueBooleanQuery` to AndOp or OrOp.
This transformation needs to occu... | Can you implement a function in Python 3 that
visits the SimpleValueBooleanQuery node and replace the node with the actual node type. | As a python code expert, you are capable of creating scripts from specifications. |
Visit a SpiresKeywordQuery node by returning a KeywordOp. | How would you explain what the following Python 3 function does
def visit_spires_keyword_query(self, node):
keyword = node.left.accept(self)
value = node.right.accept(self)
if isinstance(value, SimpleValueBooleanQuery):
return _convert_simple_value_boolean_query_to_and_boolean_queri... | You are a Python code analyst, evaluating scripts for potential improvements. |
def visit_invenio_keyword_query(self, node):
"""Transform an :class:`InvenioKeywordQuery` into a :class:`KeywordOp`.
Notes:
In case the value being a :class:`SimpleValueBooleanQuery`, the subtree is transformed to chained
:class:`AndOp` queries containing :class:`KeywordOp`, who... | Write a Python 3 function that can
visit an InvenioKeywordQuery node by returning a KeywordOp. | As a Python code analyst, you investigate and solve complex coding mysteries |
def visit_complex_value(self, node):
"""Convert :class:`ComplexValue` to one of ExactMatch, PartialMatch and Regex Value nodes."""
if node.value.startswith(ComplexValue.EXACT_VALUE_TOKEN):
value = node.value.strip(ComplexValue.EXACT_VALUE_TOKEN)
return ExactMatchValue(value)
... | Implement a Python 3 function for
converting a node to one of ExactMatch PartialMatch and Regex Value nodes. | You are a Python code architect, reviewing and designing scalable and efficient code |
Cancel the task if it hasn t yet started. | Can you generate a brief explanation for the following Python 3 code
async def stop(self, force: bool=False) -> None:
'''Cancel the task if it hasn't yet started, or tell it to
gracefully stop running if it has.'''
Log.debug('stopping task %s', self.name)
self.running = False
i... | You are a Python code architect, reviewing and designing scalable and efficient code |
def author_name_contains_fullnames(author_name):
"""Recognizes whether the name contains full name parts and not initials or only lastname.
Returns:
bool: True if name has only full name parts, e.g. 'Ellis John', False otherwise. So for example, False is
returned for 'Ellis, J.' or 'Ellis... | How would you code a function in Python 3 to
recognize whether the author name contains full name parts and not initials or only lastname. | You are a Python code generator, capable of creating scripts from specifications. |
def _name_variation_has_only_initials(name):
"""Detects whether the name variation consists only from initials."""
def _is_initial(name_variation):
return len(name_variation) == 1 or u'.' in name_variation
parsed_name = ParsedName.loads(name)
return all([_is_initial(name_part) for name_part in... | Can you create a Python 3 function that
detects whether the name variation consists only from initials. | As a python code expert, you are capable of creating scripts from specifications. |
Generates a small number of name variations. | Given the following Python 3 function, write the documentation
def generate_minimal_name_variations(author_name):
parsed_name = ParsedName.loads(unidecode(author_name))
if len(parsed_name) > 1:
lastnames = parsed_name.last.replace('-', ' ')
non_lastnames = ' '.join(
parsed_name.fir... | You are a Python code generator, capable of creating scripts from specifications. |
def _truncate_wildcard_from_date(date_value):
"""Truncate wildcard from date parts.
Returns:
(str) The truncated date.
Raises:
ValueError, on either unsupported date separator (currently only ' ' and '-' are supported), or if there's a
wildcard in the year.
Notes:
Eith... | Implement a Python 3 function for
truncating wildcard from date parts. | You are a Python code architect, reviewing and designing scalable and efficient code |
def _truncate_date_value_according_on_date_field(field, date_value):
"""Truncates date value (to year only) according to the given date field.
Args:
field (unicode): The field for which the date value will be used to query on.
date_value (str): The date value that is going to be truncated to it... | How would you code a function in Python 3 to
truncate the given date value according to the given date field. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Calculates the next date from the given partial date. | Here you have a function in Python 3, explain what it does
def _get_next_date_from_partial_date(partial_date):
relativedelta_arg = 'years'
if partial_date.month:
relativedelta_arg = 'months'
if partial_date.day:
relativedelta_arg = 'days'
next_date = parse(partial_date.dumps()) + relat... | As a Python code composer, you craft elegant and concise scripts. |
Returns the proper ES date math unit according to the resolution of the partial_date. | Here you have a function in Python 3, explain what it does
def _get_proper_elastic_search_date_rounding_format(partial_date):
es_date_math_unit = ES_DATE_MATH_ROUNDING_YEAR
if partial_date.month:
es_date_math_unit = ES_DATE_MATH_ROUNDING_MONTH
if partial_date.day:
es_date_math_unit = ES_DAT... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def update_date_value_in_operator_value_pairs_for_fieldname(field, operator_value_pairs):
"""Updates (operator, date value) pairs by normalizing the date value according to the given field.
Args:
field (unicode): The fieldname for which the operator-value pairs are being generated.
operator_val... | Write a Python 3 script for
updating the operator - value pairs for a given field. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Generates a match query for the given ES field and value. | Explain what the following Python 3 code does
def generate_match_query(field, value, with_operator_and):
parsed_value = None
try:
parsed_value = json.loads(value.lower())
except (ValueError, TypeError, AttributeError):
# Catch all possible exceptions
# we are not interested if they w... | As a Python code composer, you craft elegant and concise scripts. |
def wrap_query_in_nested_if_field_is_nested(query, field, nested_fields):
"""Helper for wrapping a query into a nested if the fields within the query are nested
Args:
query : The query to be wrapped.
field : The field that is being queried.
nested_fields : List of fields which are neste... | Create a Python 3 function for
wrapping a query into a nested if the fields within the query are nested. | As a Python code analyst, you investigate and solve complex coding mysteries |
def is_within_limits(self, limit, date, dates):
"""
Returns True if the difference between date and any value in dates
is less than or equal to limit.
"""
return any((self.second_diff(date, d) <= limit for d in dates)) | Create a Python 3 function to
return True if the difference between date and any value in dates is less than or equal to limit. | You are a Python code architect, reviewing and designing scalable and efficient code |
Returns a tree - like representation of a parse tree | Can you generate the documentation for the following Python 3 function
def emit_tree_format(tree, verbose=False):
if verbose:
print("Converting: " + repr(tree))
ret_str = __recursive_formatter(tree)
return ret_str | As a Python code translator, you convert algorithms and pseudocode into Python. |
def calculate_retry_delay(attempt, max_delay=300):
"""Calculates an exponential backoff for retry attempts with a small
amount of jitter."""
delay = int(random.uniform(2, 4) ** attempt)
if delay > max_delay:
# After reaching the max delay, stop using expontential growth
# and keep the de... | Can you write a function in Python 3 where it
calculates an exponential backoff for retry attempts with a small amount of jitter. | You are a Python code generator, capable of creating scripts from specifications. |
def parse_query(query_str):
"""
Drives the whole logic, by parsing, restructuring and finally, generating an ElasticSearch query.
Args:
query_str (six.text_types): the given query to be translated to an ElasticSearch query
Returns:
six.text_types: Return an ElasticSearch query.
No... | Write a Python 3 script to
parse a given query string and returns a multi_match query. | You are a Python code architect, reviewing and designing scalable and efficient code |
def task(self, name_or_class: Any) -> Task:
'''Return a running Task object matching the given name or class.'''
if name_or_class in self.all_tasks:
return self.all_tasks[name_or_class]
try:
return self.all_tasks.get(name_or_class.__class__.__name__, None)
exce... | Create a Python 3 function for
returning a running Task object matching the given name or class. | As a Python code analyst, you investigate and solve complex coding mysteries |
async def init(self) -> None:
'''Initialize configuration and start tasks.'''
self.stats = await self.insert(self.stats)
self.configuration = await self.insert(self.configuration)
if not self.executor:
try:
max_workers = self.config.get('executor_workers')
... | Implement a Python 3 function for
initializing configuration and start tasks. | You are a Python code generator, capable of creating scripts from specifications. |
Insert the given task class into the Tasky event loop. | Can you generate the documentation for the following Python 3 function
async def insert(self, task: Task) -> None:
'''Insert the given task class into the Tasky event loop.'''
if not isinstance(task, Task):
task = task()
if task.name not in self.all_tasks:
task.tasky = ... | You are a Python code generator, capable of creating scripts from specifications. |
async def execute(self, fn, *args, **kwargs) -> None:
'''Execute an arbitrary function outside the event loop using
a shared Executor.'''
fn = functools.partial(fn, *args, **kwargs)
return await self.loop.run_in_executor(self.executor, fn) | Write a Python 3 script to
execute an arbitrary function outside the event loop using a shared Executor. | You are a Python code architect, reviewing and designing scalable and efficient code |
def run_forever(self) -> None:
'''Execute the tasky/asyncio event loop until terminated.'''
Log.debug('running event loop until terminated')
asyncio.ensure_future(self.init())
self.loop.run_forever()
self.loop.close() | Implement a function in Python 3 to
execute the tasky event loop until terminated. | You are a Python code generator, capable of creating scripts from specifications. |
Execute the tasky event loop until all tasks finish. | Explain what the following Python 3 code does
def run_until_complete(self) -> None:
'''Execute the tasky/asyncio event loop until all tasks finish.'''
Log.debug('running event loop until all tasks completed')
self.terminate_on_finish = True
asyncio.ensure_future(self.init())
sel... | As a Python code composer, you craft elegant and concise scripts. |
def run_for_time(self, duration: float=10.0) -> None:
'''Execute the tasky/asyncio event loop for `duration` seconds.'''
Log.debug('running event loop for %.1f seconds', duration)
try:
asyncio.ensure_future(self.init())
self.loop.run_until_complete(asyncio.sleep(duration... | Write a Python 3 script for
executing the tasky event loop for duration seconds. | As a Python code composer, you craft elegant and concise scripts. |
def terminate(self, *, force: bool=False, timeout: float=30.0,
step: float=1.0) -> None:
'''Stop all scheduled and/or executing tasks, first by asking nicely,
and then by waiting up to `timeout` seconds before forcefully stopping
the asyncio event loop.'''
if isinstanc... | How would you implement a function in Python 3 that
terminates all scheduled and executing tasks. | As a Python code composer, you craft elegant and concise scripts. |
async def start_task(self, task: Task) -> None:
'''Initialize the task, queue it for execution, add the done callback,
and keep track of it for when tasks need to be stopped.'''
try:
Log.debug('task %s starting', task.name)
before = time.time()
task.counters[... | Implement a Python 3 function for
initializing the task queue it for execution add the done callback and keep track of it for when tasks need to be stopped. | As a python code expert, you are capable of creating scripts from specifications. |
async def monitor_tasks(self, interval: float=1.0) -> None:
'''Monitor all known tasks for run state. Ensure that enabled tasks
are running, and that disabled tasks are stopped.'''
Log.debug('monitor running')
while True:
try:
await asyncio.sleep(interval)
... | Implement a function in Python 3 to
monitor all known tasks for run state. | You are a Python code generator, capable of creating scripts from specifications. |
Log unhandled exceptions from anywhere in the event loop. | Given the following Python 3 function, write the documentation
def exception(self, loop: asyncio.BaseEventLoop, context: dict) -> None:
'''Log unhandled exceptions from anywhere in the event loop.'''
Log.error('unhandled exception: %s', context['message'])
Log.error('%s', context)
if 'e... | You are a Python code architect, reviewing and designing scalable and efficient code |
Handle the user pressing Ctrl - C by stopping tasks nicely at first and forcibly upon further presses. | How would you explain what the following Python 3 function does
def sigint(self) -> None:
'''Handle the user pressing Ctrl-C by stopping tasks nicely at first,
then forcibly upon further presses.'''
if self.stop_attempts < 1:
Log.info('gracefully stopping tasks')
self.st... | You are a Python code generator, capable of creating scripts from specifications. |
def sigterm(self) -> None:
'''Handle SIGTERM from the system by stopping tasks gracefully.
Repeated signals will be ignored while waiting for tasks to finish.'''
if self.stop_attempts < 1:
Log.info('received SIGTERM, gracefully stopping tasks')
self.stop_attempts += 1
... | How would you implement a function in Python 3 that
handles SIGTERM from the system by stopping tasks gracefully. | As a python code expert, you are capable of creating scripts from specifications. |
def parse(cls, parser, text, pos):
"""Checks if terminal token is a keyword after lower-casing it."""
match = cls.regex.match(text)
if match:
# Check if match is is not in the grammar of the specific keyword class.
if match.group(0).lower() not in cls.grammar:
... | Write a Python 3 function for
checking if terminal token is a keyword after lower - casing it. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Parse InspireKeyword.
If the keyword is `texkey`, enable the parsing texkey expression flag, since its value contains ':' which
normally isn't allowed. | Can you generate the documentation for the following Python 3 function
def parse(cls, parser, text, pos):
try:
remaining_text, keyword = parser.parse(text, cls.grammar)
if keyword.lower() == 'texkey':
parser._parsing_texkey_expression = True
return remaining_t... | You are a Python code generator, capable of creating scripts from specifications. |
def parse_terminal_token(cls, parser, text):
"""Parses a terminal token that doesn't contain parentheses nor colon symbol.
Note:
Handles a special case of tokens where a ':' is needed (for `texkey` queries).
If we're parsing text not in parentheses, then some DSL keywords (e.g.... | Write a Python 3 script to
parse a terminal token that doesn t contain parentheses nor colon symbol. | As a Python code analyst, you investigate and solve complex coding mysteries |
def parse(cls, parser, text, pos):
"""Imitates parsing a list grammar.
Specifically, this
grammar = [
SimpleValueUnit.date_specifiers_regex,
SimpleValueUnit.arxiv_token_regex,
SimpleValueUnit.token_regex,
SimpleValueUnit.parenthesized_token_gramma... | Write a Python 3 script to
imitate parsing a list grammar. | As a Python code composer, you craft elegant and concise scripts. |
Reconstructs input in case of consuming a keyword query or a value query with ComplexValue as value. | Can you generate a brief explanation for the following Python 3 code
def unconsume_and_reconstruct_input(remaining_text, recognized_tokens, complex_value_idx):
# Default slicing index: i.e. at most 3 elements will be unconsumed, Keyword, Whitespace and ComplexValue.
slicing_start_idx = 2
# Chec... | You are a Python code architect, reviewing and designing scalable and efficient code |
def parse(cls, parser, text, pos):
"""Using our own parse to enable the flag below."""
try:
parser._parsing_parenthesized_simple_values_expression = True
remaining_text, recognized_tokens = parser.parse(text, cls.grammar)
return remaining_text, recognized_tokens
... | Can you write a function in Python 3 where it
parses the current state of the object. | As a python code expert, you are capable of creating scripts from specifications. |
Generates new fieldnames in case of BAI query. | Can you generate a brief explanation for the following Python 3 code
def _generate_fieldnames_if_bai_query(self, node_value, bai_field_variation, query_bai_field_if_dots_in_name):
if bai_field_variation not in (FieldVariations.search, FieldVariations.raw):
raise ValueError('Non supported field varia... | You are a Python code analyst, evaluating scripts for potential improvements. |
def _generate_author_query(self, author_name):
"""Generates a query handling specifically authors.
Notes:
The match query is generic enough to return many results. Then, using the filter clause we truncate these
so that we imitate legacy's behaviour on returning more "exact" res... | Implement a function in Python 3 to
generate a query handling specifically authors. | As a Python code analyst, you investigate and solve complex coding mysteries |
def _generate_exact_author_query(self, author_name_or_bai):
"""Generates a term query handling authors and BAIs.
Notes:
If given value is a BAI, search for the provided value in the raw field variation of
`ElasticSearchVisitor.AUTHORS_BAI_FIELD`.
Otherwise, the value... | Create a Python 3 function to
generate a term query handling authors and BAIs. | As a Python code composer, you craft elegant and concise scripts. |
Generates a list of queries for any symbols in the title against the whitespace tokenized field of titles. | Here you have a function in Python 3, explain what it does
def _generate_queries_for_title_symbols(title_field, query_value):
values_tokenized_by_whitespace = query_value.split()
symbol_queries = []
for value in values_tokenized_by_whitespace:
# Heuristic: If there's a symbol-indica... | You are a Python code analyst, evaluating scripts for potential improvements. |
Generate type - code queries. | Can you generate the documentation for the following Python 3 function
def _generate_type_code_query(self, value):
mapping_for_value = self.TYPECODE_VALUE_TO_FIELD_AND_VALUE_PAIRS_MAPPING.get(value, None)
if mapping_for_value:
return generate_match_query(*mapping_for_value, with_operator_an... | You are a Python code generator, capable of creating scripts from specifications. |
Generates ElasticSearch range queries. | Can you generate the documentation for the following Python 3 function
def _generate_range_queries(self, fieldnames, operator_value_pairs):
if ElasticSearchVisitor.KEYWORD_TO_ES_FIELDNAME['date'] == fieldnames:
range_queries = []
for fieldname in fieldnames:
updated_opera... | As a Python code composer, you craft elegant and concise scripts. |
def _generate_malformed_query(data):
"""Generates a query on the ``_all`` field with all the query content.
Args:
data (six.text_type or list): The query in the format of ``six.text_type`` (when used from parsing driver)
or ``list`` when used from withing the ES visitor.
... | Can you implement a function in Python 3 that
generates a query string that can be used to search for the content of the _all field. | As a Python code composer, you craft elegant and concise scripts. |
Transforms the given journal query value to the new one. | How would you explain what the following Python 3 function does
def _preprocess_journal_query_value(third_journal_field, old_publication_info_values):
# Prepare old publication info for :meth:`inspire_schemas.utils.convert_old_publication_info_to_new`.
publication_info_keys = [
ElasticSearch... | As a python code expert, you are capable of creating scripts from specifications. |
Generates ElasticSearch nested queries for the given value. | How would you explain what the following Python 3 function does
def _generate_journal_nested_queries(self, value):
# Abstract away which is the third field, we care only for its existence.
third_journal_field = ElasticSearchVisitor.JOURNAL_PAGE_START
new_publication_info = ElasticSearchVisitor.... | As a Python code analyst, you investigate and solve complex coding mysteries |
Generates a term query that matches the value of a node. | Can you generate a brief explanation for the following Python 3 code
def visit_exact_match_value(self, node, fieldnames=None):
if not fieldnames:
fieldnames = ['_all']
else:
fieldnames = force_list(fieldnames)
if ElasticSearchVisitor.KEYWORD_TO_ES_FIELDNAME['exact-author... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Generates a query which looks for a substring of the node s value in the given fieldname. | Can you tell what is the following Python 3 function doing
def visit_partial_match_value(self, node, fieldnames=None):
if ElasticSearchVisitor.KEYWORD_TO_ES_FIELDNAME['date'] == fieldnames:
# Date queries with partial values are transformed into range queries, among the given and the exact
... | As a python code expert, you are capable of creating scripts from specifications. |
def run(self, schedule_id, **kwargs):
"""
Synchronises the schedule specified by the ID `schedule_id` to the
scheduler service.
Arguments:
schedule_id {str} -- The ID of the schedule to sync
"""
log = self.get_logger(**kwargs)
try:
schedu... | Can you implement a function in Python 3 that
synchronises the schedule specified by the ID schedule_id to the scheduler service. | As a Python code analyst, you investigate and solve complex coding mysteries |
def run(self, scheduler_schedule_id, **kwargs):
"""
Deactivates the schedule specified by the ID `scheduler_schedule_id` in
the scheduler service.
Arguments:
scheduler_schedule_id {str} -- The ID of the schedule to deactivate
"""
log = self.get_logger(**kwarg... | Can you create a Python 3 function that
deactivates the schedule specified by the ID scheduler_schedule_id in the scheduler service. | You are a Python code analyst, evaluating scripts for potential improvements. |
def get_for_model(self, obj):
"""Returns the tags for a specific model/content type."""
qs = Tag.objects.language(get_language())
qs = qs.filter(
tagged_items__content_type=ctype_models.ContentType.objects.get_for_model(obj)) # NOQA
return qs.distinct() | Write a Python 3 script for
returning the tags for a specific model or content type. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def get_for_queryset(self, obj_queryset):
"""Returns all tags for a whole queryset of objects."""
qs = Tag.objects.language(get_language())
if obj_queryset.count() == 0:
return qs.none()
qs = qs.filter(
tagged_items__object_id__in=[
obj.id for obj ... | Write a Python 3 script for
returning all tags for a whole queryset of objects. | As a Python code composer, you craft elegant and concise scripts. |
def post_send_process(context):
"""
Task to ensure subscription is bumped or converted
"""
if "error" in context:
return context
[deserialized_subscription] = serializers.deserialize(
"json", context["subscription"]
)
subscription = deserialized_subscription.object
[mess... | How would you code a function in Python 3 to
task to ensure subscription is bumped or converted | As a Python code analyst, you investigate and solve complex coding mysteries |
Calculates the expected lifecycle position of the subscription in
. | Can you generate the documentation for the following Python 3 function
def calculate_subscription_lifecycle(subscription_id):
subscription = Subscription.objects.select_related("messageset", "schedule").get(
id=subscription_id
)
behind = subscription.messages_behind()
if behind == 0:
ret... | You are a Python code generator, capable of creating scripts from specifications. |
Finds any subscriptions that are behind according to where they should be and creates a BehindSubscription entry for them. | Given the following Python 3 function, write the documentation
def find_behind_subscriptions():
subscriptions = Subscription.objects.filter(
active=True, completed=False, process_status=0
).values_list("id", flat=True)
for subscription_id in subscriptions.iterator():
calculate_subscription_l... | As a python code expert, you are capable of creating scripts from specifications. |
Sends all the subscriptions for the specified schedule | Make a summary of the following Python 3 code
def send(self, request, pk=None):
schedule = self.get_object()
queue_subscription_send.delay(str(schedule.id))
return Response({}, status=status.HTTP_202_ACCEPTED) | You are a Python code generator, capable of creating scripts from specifications. |
def get(self, key: Any, default: Any=None) -> Any:
'''Return the configured value for the given key name, or `default` if
no value is available or key is invalid.'''
return self.data.get(key, default) | Create a Python 3 function to
return the configured value for the given key name or default. | You are a Python code generator, capable of creating scripts from specifications. |
def task_config(self, task: Task) -> Any:
'''Return the task-specific configuration.'''
return self.get(task.__class__.__name__) | Can you write a function in Python 3 where it
returns the task - specific configuration. | As a Python code composer, you craft elegant and concise scripts. |
async def init(self) -> None:
'''Load configuration in JSON format from either a file or
a raw data string.'''
if self.data:
return
if self.json_data:
try:
self.data = json.loads(self.json_data)
except Exception:
Log.... | Create a Python 3 function for
loading configuration in JSON format from either a file or a raw data string. | As a Python code analyst, you investigate and solve complex coding mysteries |
async def run_task(self) -> None:
'''Execute the task inside the asyncio event loop after `DELAY`
seconds. Track the time it takes to run, and log when it starts/stops.
If/when `reset()` is called, reset the wait time to `DELAY` seconds.'''
self.last_run = 0.0
self.target = sel... | Write a Python 3 function for
executing the task inside the asyncio event loop after self. DELAY seconds. | You are a Python code analyst, evaluating scripts for potential improvements. |
Reset the task execution to the current time. | Explain what the following Python 3 code does
def reset(self) -> None:
'''Reset task execution to `DELAY` seconds from now.'''
Log.debug('resetting timer task %s')
self.target = self.time() + self.DELAY | As a Python code analyst, you investigate and solve complex coding mysteries |
A view decorator which blocks access for requests coming through the load balancer. | Explain what the following Python 3 code does
def internal_only(view_func):
@functools.wraps(view_func)
def wrapper(request, *args, **kwargs):
forwards = request.META.get("HTTP_X_FORWARDED_FOR", "").split(",")
# The nginx in the docker container adds the loadbalancer IP to the list inside
... | You are a Python code generator, capable of creating scripts from specifications. |
def post(self, request, *args, **kwargs):
""" Validates subscription data before creating Outbound message
"""
schedule_disable.delay(kwargs["subscription_id"])
return Response({"accepted": True}, status=201) | Can you implement a function in Python 3 that
validates subscription data before creating Outbound message | You are a Python code generator, capable of creating scripts from specifications. |
Validates subscription data before creating Outbound message
| Given the following Python 3 function, write the documentation
def post(self, request, *args, **kwargs):
# Look up subscriber
subscription_id = kwargs["subscription_id"]
if Subscription.objects.filter(id=subscription_id).exists():
status = 202
accepted = {"accepted": True... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def post(self, request, *args, **kwargs):
""" Validates subscription data before creating Subscription message
"""
# Ensure that we check for the 'data' key in the request object before
# attempting to reference it
if "data" in request.data:
# This is a workaround for... | Write a Python 3 function for
validating subscription data before creating Subscription message | You are a Python code analyst, evaluating scripts for potential improvements. |
Starts a celery task that looks through active subscriptions to find
and adds a
BehindSubscription for them. | Explain what the following Python 3 code does
def find_behind_subscriptions(self, request):
task_id = find_behind_subscriptions.delay()
return Response(
{"accepted": True, "task_id": str(task_id)}, status=status.HTTP_202_ACCEPTED
) | You are a Python code architect, reviewing and designing scalable and efficient code |
Read - Eval - Print - Loop for reading the query printing it and its parse tree. | Here you have a function in Python 3, explain what it does
def repl():
while True:
try:
sys.stdout.write("Type in next query: \n> ")
import locale
query_str = raw_input().decode(sys.stdin.encoding or locale.getpreferredencoding(True))
except KeyboardInterrupt:
... | You are a Python code architect, reviewing and designing scalable and efficient code |
Initialize the queue and spawn extra worker tasks. | Here you have a function in Python 3, explain what it does
async def run_task(self) -> None:
'''Initialize the queue and spawn extra worker tasks if this if the
first task. Then wait for work items to enter the task queue, and
execute the `run()` method with the current work item.'''
w... | As a Python code analyst, you investigate and solve complex coding mysteries |
Called when a new object is saved in the scheduler. | Can you generate a brief explanation for the following Python 3 code
def schedule_saved(sender, instance, **kwargs):
from contentstore.tasks import sync_schedule
sync_schedule.delay(str(instance.id)) | You are a Python code analyst, evaluating scripts for potential improvements. |
def schedule_deleted(sender, instance, **kwargs):
"""
Fires off the celery task to ensure that this schedule is deactivated
Arguments:
sender {class} -- The model class, always Schedule
instance {Schedule} --
The instance of the schedule that we want to deactivate
"""
fr... | Implement a Python 3 function for
deactivating the celery task that ensures that this schedule is deactivated | As a Python code translator, you convert algorithms and pseudocode into Python. |
async def run_task(self) -> None:
'''Execute the task inside the asyncio event loop. Track the time it
takes to run, and log when it starts/stops. After `INTERVAL` seconds,
if/once the task has finished running, run it again until `stop()`
is called.'''
while self.running:
... | Can you write a function in Python 3 where it
executes the task inside the asyncio event loop. | You are a Python code analyst, evaluating scripts for potential improvements. |
construct a GroupBy object on the given keys optionally performing the given reduction on the given values | Given the following Python 3 function, write the documentation
def group_by(keys, values=None, reduction=None, axis=0):
g = GroupBy(keys, axis)
if values is None:
return g
groups = g.split(values)
if reduction is None:
return g.unique, groups
return [(key, reduction(group)) for key, ... | You are a Python code architect, reviewing and designing scalable and efficient code |
Splits an iterable into lists of items in the order of the keys
. | Explain what the following Python 3 code does
def split_iterable_as_iterable(self, values):
values = iter(enumerate(values))
cache = dict()
def get_value(ti):
try:
return cache.pop(ti)
except:
while True:
i, v = next(val... | You are a Python code generator, capable of creating scripts from specifications. |
def split_iterable_as_unordered_iterable(self, values):
"""Group iterable into iterables, without regard for the ordering of self.index.unique
key-group tuples are yielded as soon as they are complete
Parameters
----------
values : iterable of length equal to keys
it... | How would you code a function in Python 3 to
split an iterable into key - group tuples without regard for the ordering of self. index. unique . | You are a Python code architect, reviewing and designing scalable and efficient code |
Splits the given values into iterables of items in the same length as the keys
. | Make a summary of the following Python 3 code
def split_sequence_as_iterable(self, values):
print(self.count)
s = iter(self.index.sorter)
for c in self.count:
yield (values[i] for i in itertools.islice(s, int(c))) | As a Python code translator, you convert algorithms and pseudocode into Python. |
def split_array_as_array(self, values):
"""Group ndarray into ndarray by means of reshaping
Parameters
----------
values : ndarray_like, [index.size, ...]
Returns
-------
ndarray, [groups, group_size, ...]
values grouped by key
Raises
... | Create a Python 3 function for
splitting the array into a single array by means of reshaping | As a Python code composer, you craft elegant and concise scripts. |
Group values as a list of arrays or a jagged - array
| Here you have a function in Python 3, explain what it does
def split_array_as_list(self, values):
values = np.asarray(values)
values = values[self.index.sorter]
return np.split(values, self.index.slices[1:-1], axis=0) | As a Python code translator, you convert algorithms and pseudocode into Python. |
def reduce(self, values, operator=np.add, axis=0, dtype=None):
"""Reduce the values over identical key groups, using the given ufunc
reduction is over the first axis, which should have elements corresponding to the keys
all other axes are treated indepenently for the sake of this reduction
... | Write a Python 3 function for
reducing the values over identical key groups using the given ufunc operator over the first axis. | As a Python code analyst, you investigate and solve complex coding mysteries |
compute the sum over each group
| Here you have a function in Python 3, explain what it does
def sum(self, values, axis=0, dtype=None):
values = np.asarray(values)
return self.unique, self.reduce(values, axis=axis, dtype=dtype) | As a Python code analyst, you investigate and solve complex coding mysteries |
def prod(self, values, axis=0, dtype=None):
"""compute the product over each group
Parameters
----------
values : array_like, [keys, ...]
values to multiply per group
axis : int, optional
alternative reduction axis for values
dtype : output dtype
... | Can you implement a function in Python 3 that
computes the product over each group | As a Python code composer, you craft elegant and concise scripts. |
compute the mean over each group
| Can you generate the documentation for the following Python 3 function
def mean(self, values, axis=0, weights=None, dtype=None):
values = np.asarray(values)
if weights is None:
result = self.reduce(values, axis=axis, dtype=dtype)
shape = [1] * values.ndim
shape[axis] ... | As a Python code analyst, you investigate and solve complex coding mysteries |
compute the variance over each group
| Can you tell what is the following Python 3 function doing
def var(self, values, axis=0, weights=None, dtype=None):
values = np.asarray(values)
unique, mean = self.mean(values, axis, weights, dtype)
err = values - mean.take(self.inverse, axis)
if weights is None:
shape = [1]... | As a python code expert, you are capable of creating scripts from specifications. |
def std(self, values, axis=0, weights=None, dtype=None):
"""standard deviation over each group
Parameters
----------
values : array_like, [keys, ...]
values to take standard deviation of per group
axis : int, optional
alternative reduction axis for values... | Write a Python 3 script to
return the standard deviation over each group | You are a Python code analyst, evaluating scripts for potential improvements. |
compute the median value over each group | Can you generate a brief explanation for the following Python 3 code
def median(self, values, axis=0, average=True):
mid_2 = self.index.start + self.index.stop
hi = (mid_2 ) // 2
lo = (mid_2 - 1) // 2
#need this indirection for lex-index compatibility
sorted_group_rank_per_ke... | You are a Python code architect, reviewing and designing scalable and efficient code |
compute the mode of each entry in the set | How would you explain what the following Python 3 function does
def mode(self, values, weights=None):
if weights is None:
unique, weights = npi.count((self.index.sorted_group_rank_per_key, values))
else:
unique, weights = npi.group_by((self.index.sorted_group_rank_per_key, values... | As a python code expert, you are capable of creating scripts from specifications. |
return the minimum of unique entries within each group
| Can you generate the documentation for the following Python 3 function
def min(self, values, axis=0):
values = np.asarray(values)
return self.unique, self.reduce(values, np.minimum, axis) | You are a Python code generator, capable of creating scripts from specifications. |
def max(self, values, axis=0):
"""return the maximum within each group
Parameters
----------
values : array_like, [keys, ...]
values to take maximum of per group
axis : int, optional
alternative reduction axis for values
Returns
-------
... | How would you code a function in Python 3 to
return the maximum within each group | As a python code expert, you are capable of creating scripts from specifications. |
def first(self, values, axis=0):
"""return values at first occurance of its associated key
Parameters
----------
values : array_like, [keys, ...]
values to pick the first value of per group
axis : int, optional
alternative reduction axis for values
... | How would you code a function in Python 3 to
return values at first occurance of its associated key | As a Python code analyst, you investigate and solve complex coding mysteries |
return values at last occurance of its associated key
| Explain what the following Python 3 code does
def last(self, values, axis=0):
values = np.asarray(values)
return self.unique, np.take(values, self.index.sorter[self.index.stop-1], axis) | You are a Python code generator, capable of creating scripts from specifications. |
compute if any item evaluates to true in each group
| Explain what the following Python 3 code does
def any(self, values, axis=0):
values = np.asarray(values)
if not values.dtype == np.bool:
values = values != 0
return self.unique, self.reduce(values, axis=axis) > 0 | You are a Python code generator, capable of creating scripts from specifications. |
compute if all items evaluates to true in each group
| How would you explain what the following Python 3 function does
def all(self, values, axis=0):
values = np.asarray(values)
return self.unique, self.reduce(values, axis=axis, operator=np.multiply) != 0 | As a python code expert, you are capable of creating scripts from specifications. |
def argmin(self, values):
"""return the index into values corresponding to the minimum value of the group
Parameters
----------
values : array_like, [keys]
values to pick the argmin of per group
Returns
-------
unique: ndarray, [groups]
u... | Write a Python 3 function for
returning the index into values corresponding to the minimum value of the group | As a Python code translator, you convert algorithms and pseudocode into Python. |
def argmax(self, values):
"""return the index into values corresponding to the maximum value of the group
Parameters
----------
values : array_like, [keys]
values to pick the argmax of per group
Returns
-------
unique: ndarray, [groups]
u... | Create a Python 3 function to
return the index into values corresponding to the maximum value of the group | As a python code expert, you are capable of creating scripts from specifications. |
Converts a given set of keys to an index. | Can you generate a brief explanation for the following Python 3 code
def as_index(keys, axis=semantics.axis_default, base=False, stable=True, lex_as_struct=False):
if isinstance(keys, Index):
if type(keys) is BaseIndex and base==False:
keys = keys.keys #need to upcast to an indirectly sorted ... | You are a Python code generator, capable of creating scripts from specifications. |
def inverse(self):
"""return index array that maps unique values back to original space. unique[inverse]==keys"""
inv = np.empty(self.size, np.int)
inv[self.sorter] = self.sorted_group_rank_per_key
return inv | Can you create a Python 3 function that
returns index array that maps unique values back to original space. unique [ inverse ] == keys | As a Python code analyst, you investigate and solve complex coding mysteries |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.