code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
keyword = node.left.accept(self)
value = node.right.accept(self)
if isinstance(value, SimpleValueBooleanQuery):
return _convert_simple_value_boolean_query_to_and_boolean_queries(value, keyword)
return KeywordOp(keyword, value) | def visit_spires_keyword_query(self, node) | Transform a :class:`SpiresKeywordQuery` 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`, whose keyword is the keyword of the current node and
... | 6.857183 | 3.743301 | 1.831854 |
try:
keyword = node.left.accept(self)
except AttributeError:
# The keywords whose values aren't an InspireKeyword are simple strings.
keyword = Keyword(node.left)
value = node.right.accept(self)
if isinstance(value, SimpleValueBooleanQuery):... | 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`, whose keyword is the keyword of the current node and
... | 7.909124 | 5.197559 | 1.5217 |
if node.value.startswith(ComplexValue.EXACT_VALUE_TOKEN):
value = node.value.strip(ComplexValue.EXACT_VALUE_TOKEN)
return ExactMatchValue(value)
elif node.value.startswith(ComplexValue.PARTIAL_VALUE_TOKEN):
value = node.value.strip(ComplexValue.PARTIAL_VALUE... | def visit_complex_value(self, node) | Convert :class:`ComplexValue` to one of ExactMatch, PartialMatch and Regex Value nodes. | 3.52079 | 3.107827 | 1.132878 |
'''Simple wrapper around `asyncio.sleep()`.'''
duration = max(0, duration)
if duration > 0:
Log.debug('sleeping task %s for %.1f seconds', self.name, duration)
await asyncio.sleep(duration) | async def sleep(self, duration: float=0.0) -> None | Simple wrapper around `asyncio.sleep()`. | 5.247898 | 4.279129 | 1.226394 |
'''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
if force:
self.task.cancel() | 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. | 7.764096 | 3.474828 | 2.234383 |
def _is_initial(name_part):
return len(name_part) == 1 or u'.' in name_part
parsed_name = ParsedName(author_name)
if len(parsed_name) == 1:
return False
elif any([_is_initial(name_part) for name_part in parsed_name]):
return False
return True | 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'. | 3.684424 | 3.53093 | 1.043471 |
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 parsed_name]) | def _name_variation_has_only_initials(name) | Detects whether the name variation consists only from initials. | 5.377667 | 4.862271 | 1.105999 |
parsed_name = ParsedName.loads(unidecode(author_name))
if len(parsed_name) > 1:
lastnames = parsed_name.last.replace('-', ' ')
non_lastnames = ' '.join(
parsed_name.first_list + parsed_name.suffix_list
)
# Strip extra whitespace added if any of middle_list and ... | def generate_minimal_name_variations(author_name) | Generate a small number of name variations.
Notes:
Unidecodes the name, so that we use its transliterated version, since this is how the field is being indexed.
For names with more than one part, {lastname} x {non lastnames, non lastnames initial} variations.
Additionally, it generates the... | 4.252081 | 3.812615 | 1.115266 |
def _decorator(func):
global DATE_SPECIFIERS_CONVERSION_HANDLERS
DATE_SPECIFIERS_CONVERSION_HANDLERS[DATE_SPECIFIERS_REGEXES[date_specifier_patterns]] = func
return func
return _decorator | def register_date_conversion_handler(date_specifier_patterns) | Decorator for registering handlers that convert text dates to dates.
Args:
date_specifier_patterns (str): the date specifier (in regex pattern format) for which the handler is registered | 3.961967 | 3.414379 | 1.160377 |
if ' ' in date_value:
date_parts = date_value.split(' ')
elif '-' in date_value:
date_parts = date_value.split('-')
else:
# Either unsupported separators or wildcard in year, e.g. '201*'.
raise ValueError("Erroneous date value: %s.", date_value)
if GenericValue.WILD... | 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:
Either whole date part is wildcard, in which we ignore it... | 4.262829 | 3.583611 | 1.189535 |
try:
partial_date = PartialDate.parse(date_value)
except ValueError:
return None
if field in ES_MAPPING_HEP_DATE_ONLY_YEAR:
truncated_date = PartialDate.from_parts(partial_date.year)
else:
truncated_date = partial_date
return truncated_date | 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 its year.
Returns:
PartialDate: The possibly truncated date, on s... | 5.263878 | 2.408711 | 2.185351 |
relativedelta_arg = 'years'
if partial_date.month:
relativedelta_arg = 'months'
if partial_date.day:
relativedelta_arg = 'days'
next_date = parse(partial_date.dumps()) + relativedelta(**{relativedelta_arg: 1})
return PartialDate.from_parts(
next_date.year,
next... | def _get_next_date_from_partial_date(partial_date) | Calculates the next date from the given partial date.
Args:
partial_date (inspire_utils.date.PartialDate): The partial date whose next date should be calculated.
Returns:
PartialDate: The next date from the given partial date. | 2.735882 | 2.879594 | 0.950093 |
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_DATE_MATH_ROUNDING_DAY
return es_date_math_unit | def _get_proper_elastic_search_date_rounding_format(partial_date) | Returns the proper ES date math unit according to the "resolution" of the partial_date.
Args:
partial_date (PartialDate): The partial date for which the date math unit is.
Returns:
(str): The ES date math unit format.
Notes:
This is needed for supporting range queries on dates, i.... | 2.515712 | 2.303594 | 1.092081 |
updated_operator_value_pairs = {}
for operator, value in operator_value_pairs.items():
modified_date = _truncate_date_value_according_on_date_field(field, value)
if not modified_date:
return {}
if operator == ES_RANGE_EQ_OPERATOR:
updated_operator_value_pair... | 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_value_pairs (dict): ES range operator {'gt', 'gte', 'lt', 'lte'} along with a value.
Add... | 2.796662 | 2.566873 | 1.089521 |
parsed_value = None
try:
parsed_value = json.loads(value.lower())
except (ValueError, TypeError, AttributeError):
# Catch all possible exceptions
# we are not interested if they will appear
pass
if isinstance(value, bool):
return {'match': {field: value}}
... | def generate_match_query(field, value, with_operator_and) | Helper for generating a match query.
Args:
field (six.text_type): The ES field to be queried.
value (six.text_type/bool): The value of the query (bool for the case of type-code query ["core: true"]).
with_operator_and (bool): Flag that signifies whether to generate the explicit notation of ... | 3.095421 | 3.287976 | 0.941437 |
if not queries:
return {}
if len(queries) == 1 and not preserve_bool_semantics_if_one_clause:
return queries[0]
return {
'bool': {
('must' if use_must_clause else 'should'): queries
}
} | def wrap_queries_in_bool_clauses_if_more_than_one(queries,
use_must_clause,
preserve_bool_semantics_if_one_clause=False) | Helper for wrapping a list of queries into a bool.{must, should} clause.
Args:
queries (list): List of queries to be wrapped in a bool.{must, should} clause.
use_must_clause (bool): Flag that signifies whether to use 'must' or 'should' clause.
preserve_bool_semantics_if_one_clause (bool): F... | 2.367537 | 2.366125 | 1.000597 |
for element in nested_fields:
match_pattern = r'^{}.'.format(element)
if re.match(match_pattern, field):
return generate_nested_query(element, query)
return query | 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 nested.
Returns:
(dict): The nested query | 4.188459 | 5.840528 | 0.717137 |
return any((self.second_diff(date, d) <= limit for d in dates)) | 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. | 11.018826 | 7.958075 | 1.384609 |
if verbose:
print("Converting: " + repr(tree))
ret_str = __recursive_formatter(tree)
return ret_str | def emit_tree_format(tree, verbose=False) | Returns a tree representation of a parse tree.
Arguments:
tree: the parse tree whose tree representation is to be generated
verbose (bool): if True prints the parse tree to be formatted
Returns:
str: tree-like representation of the parse tree | 7.603956 | 9.515096 | 0.799147 |
delay = int(random.uniform(2, 4) ** attempt)
if delay > max_delay:
# After reaching the max delay, stop using expontential growth
# and keep the delay nearby the max.
delay = int(random.uniform(max_delay - 20, max_delay + 20))
return delay | def calculate_retry_delay(attempt, max_delay=300) | Calculates an exponential backoff for retry attempts with a small
amount of jitter. | 5.481854 | 5.375664 | 1.019754 |
def _generate_match_all_fields_query():
# Strip colon character (special character for ES)
stripped_query_str = ' '.join(query_str.replace(':', ' ').split())
return {'multi_match': {'query': stripped_query_str, 'fields': ['_all'], 'zero_terms_query': 'all'}}
if not isinstance(query... | 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.
Notes:
In case there's an error, a... | 3.611573 | 3.448002 | 1.047439 |
'''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)
except AttributeError:
return None | def task(self, name_or_class: Any) -> Task | Return a running Task object matching the given name or class. | 3.143955 | 2.543616 | 1.236018 |
'''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')
except Exception:
... | async def init(self) -> None | Initialize configuration and start tasks. | 4.488695 | 4.131598 | 1.086431 |
'''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 = self
self.all_tasks[task.name] = task
await task.init()
elif task != self.all_tas... | async def insert(self, task: Task) -> None | Insert the given task class into the Tasky event loop. | 3.698402 | 2.900915 | 1.274909 |
'''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) | async def execute(self, fn, *args, **kwargs) -> None | Execute an arbitrary function outside the event loop using
a shared Executor. | 6.037632 | 3.218744 | 1.875772 |
'''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() | def run_forever(self) -> None | Execute the tasky/asyncio event loop until terminated. | 9.8287 | 4.976921 | 1.974856 |
'''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())
self.loop.run_forever()
self.loop.close() | def run_until_complete(self) -> None | Execute the tasky/asyncio event loop until all tasks finish. | 8.807638 | 5.030604 | 1.750811 |
'''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))
self.terminate()
self.loop.... | def run_for_time(self, duration: float=10.0) -> None | Execute the tasky/asyncio event loop for `duration` seconds. | 4.318817 | 3.196407 | 1.351147 |
'''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 isinstance(self.monitor, asyncio.Future):
Log.debug('cancelling task monitor')
self.monitor.... | 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. | 3.681987 | 2.709338 | 1.358999 |
'''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['last_run'] = before
task.running =... | 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. | 3.559633 | 2.578843 | 1.380322 |
'''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)
for name, task in self.all_tasks.items():
... | 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. | 3.371635 | 2.755319 | 1.223682 |
'''Log unhandled exceptions from anywhere in the event loop.'''
Log.error('unhandled exception: %s', context['message'])
Log.error('%s', context)
if 'exception' in context:
Log.error(' %s', context['exception']) | def exception(self, loop: asyncio.BaseEventLoop, context: dict) -> None | Log unhandled exceptions from anywhere in the event loop. | 5.529952 | 3.922326 | 1.409865 |
'''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.stop_attempts += 1
self.terminate()
elif self.stop_attempts < 2:
... | def sigint(self) -> None | Handle the user pressing Ctrl-C by stopping tasks nicely at first,
then forcibly upon further presses. | 6.236127 | 3.113515 | 2.002922 |
'''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
self.terminate()
... | def sigterm(self) -> None | Handle SIGTERM from the system by stopping tasks gracefully.
Repeated signals will be ignored while waiting for tasks to finish. | 9.411305 | 4.614799 | 2.039375 |
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:
result = text, SyntaxError(repr(match.group(0)) + " is not a member of " + repr(cls.grammar))
... | def parse(cls, parser, text, pos) | Checks if terminal token is a keyword after lower-casing it. | 4.12068 | 3.640698 | 1.131838 |
try:
remaining_text, keyword = parser.parse(text, cls.grammar)
if keyword.lower() == 'texkey':
parser._parsing_texkey_expression = True
return remaining_text, InspireKeyword(keyword)
except SyntaxError as e:
parser._parsing_texkey_... | def parse(cls, parser, text, pos) | Parse InspireKeyword.
If the keyword is `texkey`, enable the parsing texkey expression flag, since its value contains ':' which
normally isn't allowed. | 6.749646 | 3.791579 | 1.780168 |
token_regex = cls.token_regex
if parser._parsing_texkey_expression:
token_regex = cls.texkey_token_regex
parser._parsing_texkey_expression = False
match = token_regex.match(text)
if match:
matched_token = match.group(0)
# Check i... | 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. And, Or, Not, defined above) should
not be ... | 6.990776 | 5.542003 | 1.261417 |
found = False
# Attempt to parse date specifier
match = cls.date_specifiers_regex.match(text)
if match:
remaining_text, token, found = text[len(match.group(0)):], match.group(0), True
else:
# Attempt to parse arxiv identifier
match = ... | 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_grammar
].
Parses plaintext which m... | 4.547869 | 3.45144 | 1.317673 |
# Default slicing index: i.e. at most 3 elements will be unconsumed, Keyword, Whitespace and ComplexValue.
slicing_start_idx = 2
# Check whether the 3rd element from the end is an InspireKeyword. If not, a Value query with ComplexValue
# was consumed.
if not INSPIRE_PAR... | def unconsume_and_reconstruct_input(remaining_text, recognized_tokens, complex_value_idx) | Reconstruct input in case of consuming a keyword query or a value query with ComplexValue as value.
Un-consuming at most 3 elements and specifically (Keyword,) Whitespace and ComplexValue, while also
reconstructing parser's input text.
Example:
Given this query "author foo t 'bar'"... | 5.341992 | 4.544851 | 1.175394 |
try:
parser._parsing_parenthesized_simple_values_expression = True
remaining_text, recognized_tokens = parser.parse(text, cls.grammar)
return remaining_text, recognized_tokens
except SyntaxError as e:
return text, e
finally:
pa... | def parse(cls, parser, text, pos) | Using our own parse to enable the flag below. | 5.847898 | 5.182626 | 1.128366 |
if bai_field_variation not in (FieldVariations.search, FieldVariations.raw):
raise ValueError('Non supported field variation "{}".'.format(bai_field_variation))
normalized_author_name = normalize_name(node_value).strip('.')
if ElasticSearchVisitor.KEYWORD_TO_ES_FIELDNAME['... | def _generate_fieldnames_if_bai_query(self, node_value, bai_field_variation, query_bai_field_if_dots_in_name) | Generates new fieldnames in case of BAI query.
Args:
node_value (six.text_type): The node's value (i.e. author name).
bai_field_variation (six.text_type): Which field variation to query ('search' or 'raw').
query_bai_field_if_dots_in_name (bool): Whether to query BAI field (... | 4.104839 | 3.562506 | 1.152233 |
name_variations = [name_variation.lower()
for name_variation
in generate_minimal_name_variations(author_name)]
# When the query contains sufficient data, i.e. full names, e.g. ``Mele, Salvatore`` (and not ``Mele, S`` or
# ``Mele``) ... | 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" results. E.g. Searching for `Smith, John`
shouldn... | 4.93617 | 4.919394 | 1.00341 |
if ElasticSearchVisitor.BAI_REGEX.match(author_name_or_bai):
bai = author_name_or_bai.lower()
query = self._generate_term_query(
'.'.join((ElasticSearchVisitor.AUTHORS_BAI_FIELD, FieldVariations.search)),
bai
)
else:
... | 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 will be procesed in the same way as the indexed value (i.e. lowercased... | 4.553977 | 3.621226 | 1.257579 |
if date_value.endswith(ast.GenericValue.WILDCARD_TOKEN):
try:
date_value = _truncate_wildcard_from_date(date_value)
except ValueError:
# Drop date query.
return {}
return self._generate_range_queries(self.KEYWORD_TO_ES... | def _generate_date_with_wildcard_query(self, date_value) | Helper for generating a date keyword query containing a wildcard.
Returns:
(dict): The date query containing the wildcard or an empty dict in case the date value is malformed.
The policy followed here is quite conservative on what it accepts as valid input. Look into
:meth:`inspire... | 8.568748 | 6.766909 | 1.266272 |
values_tokenized_by_whitespace = query_value.split()
symbol_queries = []
for value in values_tokenized_by_whitespace:
# Heuristic: If there's a symbol-indicating-character in the value, it signifies terms that should be
# queried against the whitespace-tokenized... | def _generate_queries_for_title_symbols(title_field, query_value) | Generate queries for any symbols in the title against the whitespace tokenized field of titles.
Returns:
(dict): The query or queries for the whitespace tokenized field of titles. If none such tokens exist, then
returns an empty dict.
Notes:
Splits the value ... | 7.35091 | 5.977267 | 1.229811 |
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_and=True)
else:
return {
'bool': {
'minimum_should_m... | def _generate_type_code_query(self, value) | Generate type-code queries.
Notes:
If the value of the type-code query exists in `TYPECODE_VALUE_TO_FIELD_AND_VALUE_PAIRS_MAPPING, then we
query the specified field, along with the given value according to the mapping.
See: https://github.com/inspirehep/inspire-query-parser/... | 3.641313 | 2.284994 | 1.593577 |
if ElasticSearchVisitor.KEYWORD_TO_ES_FIELDNAME['date'] == fieldnames:
range_queries = []
for fieldname in fieldnames:
updated_operator_value_pairs = \
update_date_value_in_operator_value_pairs_for_fieldname(fieldname, operator_value_pairs)
... | def _generate_range_queries(self, fieldnames, operator_value_pairs) | Generates ElasticSearch range queries.
Args:
fieldnames (list): The fieldnames on which the search is the range query is targeted on,
operator_value_pairs (dict): Contains (range_operator, value) pairs.
The range_operator should be one of those supported by ElasticSearch... | 3.516466 | 2.929883 | 1.200207 |
if isinstance(data, six.text_type):
# Remove colon character (special character for ES)
query_str = data.replace(':', ' ')
else:
query_str = ' '.join([word.strip(':') for word in data.children])
return {
'simple_query_string': {
... | 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. | 4.725365 | 4.416037 | 1.070047 |
# Prepare old publication info for :meth:`inspire_schemas.utils.convert_old_publication_info_to_new`.
publication_info_keys = [
ElasticSearchVisitor.JOURNAL_TITLE,
ElasticSearchVisitor.JOURNAL_VOLUME,
third_journal_field,
]
values_list = [
... | def _preprocess_journal_query_value(third_journal_field, old_publication_info_values) | Transforms the given journal query value (old publication info) to the new one.
Args:
third_journal_field (six.text_type): The final field to be used for populating the old publication info.
old_publication_info_values (six.text_type): The old publication info. It must be one of {only t... | 4.475924 | 4.341874 | 1.030874 |
# Abstract away which is the third field, we care only for its existence.
third_journal_field = ElasticSearchVisitor.JOURNAL_PAGE_START
new_publication_info = ElasticSearchVisitor._preprocess_journal_query_value(third_journal_field, value)
# We always expect a journal title, o... | def _generate_journal_nested_queries(self, value) | Generates ElasticSearch nested query(s).
Args:
value (string): Contains the journal_title, journal_volume and artid or start_page separated by a comma.
This value should be of type string.
Notes:
The value contains at least one of the 3 mentioned ite... | 3.259129 | 2.895579 | 1.125553 |
if not fieldnames:
fieldnames = ['_all']
else:
fieldnames = force_list(fieldnames)
if ElasticSearchVisitor.KEYWORD_TO_ES_FIELDNAME['exact-author'] == fieldnames[0]:
return self._generate_exact_author_query(node.value)
elif ElasticSearchVisit... | def visit_exact_match_value(self, node, fieldnames=None) | Generates a term query (exact search in ElasticSearch). | 3.556092 | 3.445861 | 1.03199 |
if ElasticSearchVisitor.KEYWORD_TO_ES_FIELDNAME['date'] == fieldnames:
# Date queries with partial values are transformed into range queries, among the given and the exact
# next date, according to the granularity of the given date.
if node.contains_wildcard:
... | def visit_partial_match_value(self, node, fieldnames=None) | Generates a query which looks for a substring of the node's value in the given fieldname. | 4.250057 | 4.163772 | 1.020723 |
subscriptions = Subscription.objects.filter(
schedule_id=schedule_id, active=True, completed=False, process_status=0
).values("id")
for subscription in subscriptions.iterator():
send_next_message.delay(str(subscription["id"])) | def run(self, schedule_id, **kwargs) | Arguments:
schedule_id {int} -- The schedule to send messages for | 5.454364 | 5.458504 | 0.999241 |
log = self.get_logger(**kwargs)
try:
schedule = Schedule.objects.get(id=schedule_id)
except Schedule.DoesNotExist:
log.error("Missing Schedule %s", schedule_id, exc_info=True)
if schedule.scheduler_schedule_id is None:
# Create the new sched... | 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 | 2.398041 | 2.499758 | 0.95931 |
log = self.get_logger(**kwargs)
self.scheduler.update_schedule(scheduler_schedule_id, {"active": False})
log.info(
"Deactivated schedule %s in the scheduler service", scheduler_schedule_id
) | 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 | 4.905947 | 4.674764 | 1.049453 |
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() | def get_for_model(self, obj) | Returns the tags for a specific model/content type. | 4.928329 | 4.322049 | 1.140276 |
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 in obj_queryset],
tagged_items__content_type=ctype_models.ContentType.objects.get_for... | def get_for_queryset(self, obj_queryset) | Returns all tags for a whole queryset of objects. | 3.28125 | 2.952106 | 1.111495 |
if "error" in context:
return context
[deserialized_subscription] = serializers.deserialize(
"json", context["subscription"]
)
subscription = deserialized_subscription.object
[messageset] = serializers.deserialize("json", context["messageset"])
messageset = messageset.objec... | def post_send_process(context) | Task to ensure subscription is bumped or converted | 3.368675 | 3.297179 | 1.021684 |
subscription = Subscription.objects.select_related("messageset", "schedule").get(
id=subscription_id
)
behind = subscription.messages_behind()
if behind == 0:
return
current_messageset = subscription.messageset
current_sequence_number = subscription.next_sequence_number
... | def calculate_subscription_lifecycle(subscription_id) | Calculates the expected lifecycle position the subscription in
subscription_ids, and creates a BehindSubscription entry for them.
Args:
subscription_id (str): ID of subscription to calculate lifecycle for | 3.493103 | 3.400512 | 1.027229 |
subscriptions = Subscription.objects.filter(
active=True, completed=False, process_status=0
).values_list("id", flat=True)
for subscription_id in subscriptions.iterator():
calculate_subscription_lifecycle.delay(str(subscription_id)) | def find_behind_subscriptions() | Finds any subscriptions that are behind according to where they should be,
and creates a BehindSubscription entry for them. | 5.174366 | 5.517882 | 0.937745 |
schedule = self.get_object()
queue_subscription_send.delay(str(schedule.id))
return Response({}, status=status.HTTP_202_ACCEPTED) | def send(self, request, pk=None) | Sends all the subscriptions for the specified schedule | 5.194291 | 3.823442 | 1.358538 |
'''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) | 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. | 8.707987 | 2.756433 | 3.15915 |
'''Return the task-specific configuration.'''
return self.get(task.__class__.__name__) | def task_config(self, task: Task) -> Any | Return the task-specific configuration. | 14.169224 | 13.144526 | 1.077956 |
'''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.exception('Falied to load raw ... | async def init(self) -> None | Load configuration in JSON format from either a file or
a raw data string. | 3.623484 | 2.637934 | 1.373607 |
'''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 = self.time() + self.DELAY
whi... | 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. | 3.574439 | 2.310539 | 1.547015 |
'''Reset task execution to `DELAY` seconds from now.'''
Log.debug('resetting timer task %s')
self.target = self.time() + self.DELAY | def reset(self) -> None | Reset task execution to `DELAY` seconds from now. | 27.646595 | 13.610659 | 2.031246 |
@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
# X-Forwarded-For, so if the list contains more than a single item, ... | def internal_only(view_func) | A view decorator which blocks access for requests coming through the load balancer. | 4.508949 | 3.883554 | 1.161037 |
schedule_disable.delay(kwargs["subscription_id"])
return Response({"accepted": True}, status=201) | def post(self, request, *args, **kwargs) | Validates subscription data before creating Outbound message | 13.837184 | 11.431915 | 1.210399 |
# Look up subscriber
subscription_id = kwargs["subscription_id"]
if Subscription.objects.filter(id=subscription_id).exists():
status = 202
accepted = {"accepted": True}
store_resend_request.apply_async(args=[subscription_id])
else:
... | def post(self, request, *args, **kwargs) | Validates subscription data before creating Outbound message | 3.635389 | 3.507256 | 1.036534 |
# 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 JSONField not liking blank/null refs
if "metadata" not in request.data["data"]:
request.data[... | def post(self, request, *args, **kwargs) | Validates subscription data before creating Subscription message | 3.411221 | 3.111912 | 1.096182 |
task_id = find_behind_subscriptions.delay()
return Response(
{"accepted": True, "task_id": str(task_id)}, status=status.HTTP_202_ACCEPTED
) | def find_behind_subscriptions(self, request) | Starts a celery task that looks through active subscriptions to find
and subscriptions that are behind where they should be, and adds a
BehindSubscription for them. | 3.886822 | 3.135783 | 1.239506 |
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:
break
if u'quit' in query_str:
break... | def repl() | Read-Eval-Print-Loop for reading the query, printing it and its parse tree.
Exit the loop either with an interrupt or "quit". | 5.32365 | 4.282351 | 1.243161 |
'''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.'''
while self.running:
try:
item = self.QUEUE.get_nowait()
... | 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. | 4.731339 | 2.614027 | 1.809981 |
from contentstore.tasks import sync_schedule
sync_schedule.delay(str(instance.id)) | def schedule_saved(sender, instance, **kwargs) | Fires off the celery task to ensure that this schedule is in the scheduler
Arguments:
sender {class} -- The model class, always Schedule
instance {Schedule} --
The instance of the Schedule that we want to sync | 9.585527 | 10.691042 | 0.896594 |
from contentstore.tasks import deactivate_schedule
deactivate_schedule.delay(str(instance.scheduler_schedule_id)) | 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 | 12.749559 | 13.607436 | 0.936955 |
'''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:
try:
Log.... | 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. | 4.567081 | 2.208641 | 2.067824 |
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, group in zip(g.unique, groups)] | def group_by(keys, values=None, reduction=None, axis=0) | construct a grouping object on the given keys, optionally performing the given reduction on the given values
Parameters
----------
keys : indexable object
keys to group by
values : array_like, optional
sequence of values, of the same length as keys
if a reduction function is pro... | 4.50915 | 4.363743 | 1.033322 |
values = iter(enumerate(values))
cache = dict()
def get_value(ti):
try:
return cache.pop(ti)
except:
while True:
i, v = next(values)
if i==ti:
return v
... | def split_iterable_as_iterable(self, values) | Group iterable into iterables, in the order of the keys
Parameters
----------
values : iterable of length equal to keys
iterable of values to be grouped
Yields
------
iterable of items in values
Notes
-----
Memory consumption depends... | 4.409736 | 4.122709 | 1.069621 |
from collections import defaultdict
cache = defaultdict(list)
count = self.count
unique = self.unique
key = (lambda i: unique[i]) if isinstance(unique, np.ndarray) else (lambda i: tuple(c[i] for c in unique))
for i,v in zip(self.inverse, values):
cach... | 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
iterable of values to be grouped
Yields
------
... | 4.103571 | 3.830564 | 1.071271 |
print(self.count)
s = iter(self.index.sorter)
for c in self.count:
yield (values[i] for i in itertools.islice(s, int(c))) | def split_sequence_as_iterable(self, values) | Group sequence into iterables
Parameters
----------
values : iterable of length equal to keys
iterable of values to be grouped
Yields
------
iterable of items in values
Notes
-----
This is the preferred method if values has random ac... | 7.654294 | 8.487247 | 0.901858 |
if not self.index.uniform:
raise ValueError("Array can only be split as array if all groups have the same size")
values = np.asarray(values)
values = values[self.index.sorter]
return values.reshape(self.groups, -1, *values.shape[1:]) | 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
------
AssertionError
This op... | 5.463642 | 3.958609 | 1.380192 |
values = np.asarray(values)
values = values[self.index.sorter]
return np.split(values, self.index.slices[1:-1], axis=0) | def split_array_as_list(self, values) | Group values as a list of arrays, or a jagged-array
Parameters
----------
values : ndarray, [keys, ...]
Returns
-------
list of length self.groups of ndarray, [key_count, ...] | 5.277308 | 6.317961 | 0.835287 |
values = np.take(values, self.index.sorter, axis=axis)
return operator.reduceat(values, self.index.start, axis=axis, dtype=dtype) | 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
Parameters
----------
values : ndarray, [keys, ...]
... | 4.611724 | 5.934854 | 0.777058 |
values = np.asarray(values)
return self.unique, self.reduce(values, axis=axis, dtype=dtype) | def sum(self, values, axis=0, dtype=None) | compute the sum over each group
Parameters
----------
values : array_like, [keys, ...]
values to sum per group
axis : int, optional
alternative reduction axis for values
dtype : output dtype
Returns
-------
unique: ndarray, [group... | 6.64158 | 5.759283 | 1.153196 |
values = np.asarray(values)
return self.unique, self.reduce(values, axis=axis, dtype=dtype, operator=np.multiply) | 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
Returns
-------
unique: ndarra... | 6.834907 | 6.283486 | 1.087757 |
values = np.asarray(values)
if weights is None:
result = self.reduce(values, axis=axis, dtype=dtype)
shape = [1] * values.ndim
shape[axis] = self.groups
weights = self.count.reshape(shape)
else:
weights = np.asarray(weights)
... | def mean(self, values, axis=0, weights=None, dtype=None) | compute the mean over each group
Parameters
----------
values : array_like, [keys, ...]
values to take average of per group
axis : int, optional
alternative reduction axis for values
weights : ndarray, [keys, ...], optional
weight to use for e... | 2.792167 | 2.670251 | 1.045657 |
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] * values.ndim
shape[axis] = self.groups
group_weights = self.count.reshape(shape)
... | def var(self, values, axis=0, weights=None, dtype=None) | compute the variance over each group
Parameters
----------
values : array_like, [keys, ...]
values to take variance of per group
axis : int, optional
alternative reduction axis for values
Returns
-------
unique: ndarray, [groups]
... | 3.204327 | 3.145631 | 1.01866 |
unique, var = self.var(values, axis, weights, dtype)
return unique, np.sqrt(var) | 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
Returns
-------
unique: ndarray, [groups]
... | 5.882706 | 6.530941 | 0.900744 |
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_key = self.index.sorted_group_rank_per_key
def median1d(slc):
#place values at correct ke... | def median(self, values, axis=0, average=True) | compute the median value over each group.
Parameters
----------
values : array_like, [keys, ...]
values to compute the median of per group
axis : int, optional
alternative reduction axis for values
average : bool, optional
when average is true... | 7.595531 | 7.182209 | 1.057548 |
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)).sum(weights)
x, bin = npi.group_by(unique[0]).argmax(weights)
return x, u... | def mode(self, values, weights=None) | compute the mode within each group.
Parameters
----------
values : array_like, [keys, ...]
values to compute the mode of per group
weights : array_like, [keys], float, optional
optional weight associated with each entry in values
Returns
-------
... | 6.686583 | 6.858802 | 0.974891 |
values = np.asarray(values)
return self.unique, self.reduce(values, np.minimum, axis) | def min(self, values, axis=0) | return the minimum within each group
Parameters
----------
values : array_like, [keys, ...]
values to take minimum of per group
axis : int, optional
alternative reduction axis for values
Returns
-------
unique: ndarray, [groups]
... | 9.101725 | 8.853308 | 1.028059 |
values = np.asarray(values)
return self.unique, self.reduce(values, np.maximum, axis) | 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
-------
unique: ndarray, [groups]
... | 9.016212 | 9.079217 | 0.99306 |
values = np.asarray(values)
return self.unique, np.take(values, self.index.sorter[self.index.start], axis) | 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
Returns
-------
unique: n... | 9.551604 | 10.091555 | 0.946495 |
values = np.asarray(values)
return self.unique, np.take(values, self.index.sorter[self.index.stop-1], axis) | def last(self, values, axis=0) | return values at last occurance of its associated key
Parameters
----------
values : array_like, [keys, ...]
values to pick the last value of per group
axis : int, optional
alternative reduction axis for values
Returns
-------
unique: nda... | 8.647885 | 9.018907 | 0.958862 |
values = np.asarray(values)
if not values.dtype == np.bool:
values = values != 0
return self.unique, self.reduce(values, axis=axis) > 0 | def any(self, values, axis=0) | compute if any item evaluates to true in each group
Parameters
----------
values : array_like, [keys, ...]
values to take boolean predicate over per group
axis : int, optional
alternative reduction axis for values
Returns
-------
unique: ... | 5.47394 | 6.654923 | 0.82254 |
values = np.asarray(values)
return self.unique, self.reduce(values, axis=axis, operator=np.multiply) != 0 | def all(self, values, axis=0) | compute if all items evaluates to true in each group
Parameters
----------
values : array_like, [keys, ...]
values to take boolean predicate over per group
axis : int, optional
alternative reduction axis for values
Returns
-------
unique:... | 10.77634 | 12.466162 | 0.864447 |
keys, minima = self.min(values)
minima = minima[self.inverse]
# select the first occurence of the minimum in each group
index = as_index((self.inverse, values == minima))
return keys, index.sorter[index.start[-self.groups:]] | 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]
unique keys
argmin : ndarray, ... | 13.769462 | 13.130122 | 1.048693 |
keys, maxima = self.max(values)
maxima = maxima[self.inverse]
# select the first occurence of the maximum in each group
index = as_index((self.inverse, values == maxima))
return keys, index.sorter[index.start[-self.groups:]] | 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]
unique keys
argmax : ndarray, ... | 13.029943 | 13.307775 | 0.979123 |
if isinstance(keys, Index):
if type(keys) is BaseIndex and base==False:
keys = keys.keys #need to upcast to an indirectly sorted index type
else:
return keys #already done here
if isinstance(keys, tuple):
if lex_as_struct:
keys = as_str... | def as_index(keys, axis=semantics.axis_default, base=False, stable=True, lex_as_struct=False) | casting rules for a keys object to an index object
the preferred semantics is that keys is a sequence of key objects,
except when keys is an instance of tuple,
in which case the zipped elements of the tuple are the key objects
the axis keyword specifies the axis which enumerates the keys
if axis i... | 4.70841 | 4.240545 | 1.110331 |
inv = np.empty(self.size, np.int)
inv[self.sorter] = self.sorted_group_rank_per_key
return inv | def inverse(self) | return index array that maps unique values back to original space. unique[inverse]==keys | 11.700298 | 8.97777 | 1.303252 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.