_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q9100 | Search.charges | train | def charges(self, num, charge_id=None, **kwargs):
"""Search for charges against a company by company number.
Args:
num (str): Company number to search on.
transaction (Optional[str]): Filing record number.
kwargs (dict): additional keywords passed into
requests.s... | python | {
"resource": ""
} |
q9101 | Search.officers | train | def officers(self, num, **kwargs):
"""Search for a company's registered officers by company number.
Args:
num (str): Company number to search on.
kwargs (dict): additional keywords passed into
requests.session.get *params* keyword.
"""
baseuri = self._BAS... | python | {
"resource": ""
} |
q9102 | Search.disqualified | train | def disqualified(self, num, natural=True, **kwargs):
"""Search for disqualified officers by officer ID.
Searches for natural disqualifications by default. Specify
natural=False to search for corporate disqualifications.
Args:
num (str): Company number to search on.
... | python | {
"resource": ""
} |
q9103 | Search.persons_significant_control | train | def persons_significant_control(self, num, statements=False, **kwargs):
"""Search for a list of persons with significant control.
Searches for persons of significant control based on company number for
a specified company. Specify statements=True to only search for
officers with stateme... | python | {
"resource": ""
} |
q9104 | Search.significant_control | train | def significant_control(self,
num,
entity_id,
entity_type='individual',
**kwargs):
"""Get details of a specific entity with significant control.
Args:
num (str, int): Company numb... | python | {
"resource": ""
} |
q9105 | Search.document | train | def document(self, document_id, **kwargs):
"""Requests for a document by the document id.
Normally the response.content can be saved as a pdf file
Args:
document_id (str): The id of the document retrieved.
kwargs (dict): additional keywords passed into
reque... | python | {
"resource": ""
} |
q9106 | Plate.get_node_label | train | def get_node_label(self, model):
"""
Defines how labels are constructed from models.
Default - uses verbose name, lines breaks where sensible
"""
if model.is_proxy:
label = "(P) %s" % (model.name.title())
else:
label = "%s" % (model.name.title())
... | python | {
"resource": ""
} |
q9107 | get_version | train | def get_version(release_level=True):
"""
Return the formatted version information
"""
vers = ["%(major)i.%(minor)i.%(micro)i" % __version_info__]
if release_level and __version_info__['releaselevel'] != 'final':
vers.append('%(releaselevel)s%(serial)i' % __version_info__)
return ''.join(... | python | {
"resource": ""
} |
q9108 | _sslobj | train | def _sslobj(sock):
"""Returns the underlying PySLLSocket object with which the C extension
functions interface.
"""
pass
if isinstance(sock._sslobj, _ssl._SSLSocket):
return sock._sslobj
else:
return sock._sslobj._sslobj | python | {
"resource": ""
} |
q9109 | _colorize | train | def _colorize(val, color):
"""Colorize a string using termcolor or colorama.
If any of them are available.
"""
if termcolor is not None:
val = termcolor.colored(val, color)
elif colorama is not None:
val = TERMCOLOR2COLORAMA[color] + val + colorama.Style.RESET_ALL
return val | python | {
"resource": ""
} |
q9110 | TimerPlugin._parse_time | train | def _parse_time(self, value):
"""Parse string time representation to get number of milliseconds.
Raises the ``ValueError`` for invalid format.
"""
try:
# Default time unit is a second, we should convert it to milliseconds.
return int(value) * 1000
except V... | python | {
"resource": ""
} |
q9111 | TimerPlugin.configure | train | def configure(self, options, config):
"""Configures the test timer plugin."""
super(TimerPlugin, self).configure(options, config)
self.config = config
if self.enabled:
self.timer_top_n = int(options.timer_top_n)
self.timer_ok = self._parse_time(options.timer_ok)
... | python | {
"resource": ""
} |
q9112 | TimerPlugin.report | train | def report(self, stream):
"""Report the test times."""
if not self.enabled:
return
# if multiprocessing plugin enabled - get items from results queue
if self.multiprocessing_enabled:
for i in range(_results_queue.qsize()):
try:
... | python | {
"resource": ""
} |
q9113 | TimerPlugin._get_result_color | train | def _get_result_color(self, time_taken):
"""Get time taken result color."""
time_taken_ms = time_taken * 1000
if time_taken_ms <= self.timer_ok:
color = 'green'
elif time_taken_ms <= self.timer_warning:
color = 'yellow'
else:
color = 'red'
... | python | {
"resource": ""
} |
q9114 | TimerPlugin._colored_time | train | def _colored_time(self, time_taken, color=None):
"""Get formatted and colored string for a given time taken."""
if self.timer_no_color:
return "{0:0.4f}s".format(time_taken)
return _colorize("{0:0.4f}s".format(time_taken), color) | python | {
"resource": ""
} |
q9115 | TimerPlugin._format_report_line | train | def _format_report_line(self, test, time_taken, color, status, percent):
"""Format a single report line."""
return "[{0}] {3:04.2f}% {1}: {2}".format(
status, test, self._colored_time(time_taken, color), percent
) | python | {
"resource": ""
} |
q9116 | TimerPlugin.addSuccess | train | def addSuccess(self, test, capt=None):
"""Called when a test passes."""
time_taken = self._register_time(test, 'success')
if self.timer_fail is not None and time_taken * 1000.0 > self.threshold:
test.fail('Test was too slow (took {0:0.4f}s, threshold was '
'{1:0... | python | {
"resource": ""
} |
q9117 | TextRankSummarizer.summarize | train | def summarize(self, text, length=5, weighting='frequency', norm=None):
"""
Implements the TextRank summarization algorithm, which follows closely to the PageRank algorithm for ranking
web pages.
:param text: a string of text to be summarized, path to a text file, or URL starting with ht... | python | {
"resource": ""
} |
q9118 | Tokenizer.remove_stopwords | train | def remove_stopwords(self, tokens):
"""Remove all stopwords from a list of word tokens or a string of text."""
if isinstance(tokens, (list, tuple)):
return [word for word in tokens if word.lower() not in self._stopwords]
else:
return ' '.join(
[word for wo... | python | {
"resource": ""
} |
q9119 | Tokenizer.stem | train | def stem(self, word):
"""Perform stemming on an input word."""
if self.stemmer:
return unicode_to_ascii(self._stemmer.stem(word))
else:
return word | python | {
"resource": ""
} |
q9120 | Tokenizer.strip_punctuation | train | def strip_punctuation(text, exclude='', include=''):
"""Strip leading and trailing punctuation from an input string."""
chars_to_strip = ''.join(
set(list(punctuation)).union(set(list(include))) - set(list(exclude))
)
return text.strip(chars_to_strip) | python | {
"resource": ""
} |
q9121 | Tokenizer._remove_whitespace | train | def _remove_whitespace(text):
"""Remove excess whitespace from the ends of a given input string."""
# while True:
# old_text = text
# text = text.replace(' ', ' ')
# if text == old_text:
# return text
non_spaces = re.finditer(r'[^ ]', text)
... | python | {
"resource": ""
} |
q9122 | Tokenizer.tokenize_sentences | train | def tokenize_sentences(self, text, word_threshold=5):
"""
Returns a list of sentences given an input string of text.
:param text: input string
:param word_threshold: number of significant words that a sentence must contain to be counted
(to count all sentences set equal to 1; 5 ... | python | {
"resource": ""
} |
q9123 | Tokenizer.tokenize_paragraphs | train | def tokenize_paragraphs(cls, text):
"""Convert an input string into a list of paragraphs."""
paragraphs = []
paragraphs_first_pass = text.split('\n')
for p in paragraphs_first_pass:
paragraphs_second_pass = re.split('\s{4,}', p)
paragraphs += paragraphs_second_pas... | python | {
"resource": ""
} |
q9124 | BaseLsaSummarizer._svd | train | def _svd(cls, matrix, num_concepts=5):
"""
Perform singular value decomposition for dimensionality reduction of the input matrix.
"""
u, s, v = svds(matrix, k=num_concepts)
return u, s, v | python | {
"resource": ""
} |
q9125 | SepaDD.add_payment | train | def add_payment(self, payment):
"""
Function to add payments
@param payment: The payment dict
@raise exception: when payment is invalid
"""
if self.clean:
from text_unidecode import unidecode
payment['name'] = unidecode(payment['name'])[:70]
... | python | {
"resource": ""
} |
q9126 | SepaDD._create_TX_node | train | def _create_TX_node(self, bic=True):
"""
Method to create the blank transaction nodes as a dict. If bic is True,
the BIC node will also be created.
"""
ED = dict()
ED['DrctDbtTxInfNode'] = ET.Element("DrctDbtTxInf")
ED['PmtIdNode'] = ET.Element("PmtId")
ED... | python | {
"resource": ""
} |
q9127 | SepaTransfer.check_config | train | def check_config(self, config):
"""
Check the config file for required fields and validity.
@param config: The config dict.
@return: True if valid, error string if invalid paramaters where
encountered.
"""
validation = ""
required = ["name", "currency", "I... | python | {
"resource": ""
} |
q9128 | SepaTransfer._add_batch | train | def _add_batch(self, TX_nodes, payment):
"""
Method to add a payment as a batch. The transaction details are already
present. Will fold the nodes accordingly and the call the
_add_to_batch_list function to store the batch.
"""
TX_nodes['PmtIdNode'].append(TX_nodes['EndToE... | python | {
"resource": ""
} |
q9129 | SepaTransfer._add_to_batch_list | train | def _add_to_batch_list(self, TX, payment):
"""
Method to add a transaction to the batch list. The correct batch will
be determined by the payment dict and the batch will be created if
not existant. This will also add the payment amount to the respective
batch total.
"""
... | python | {
"resource": ""
} |
q9130 | BaseSummarizer._compute_matrix | train | def _compute_matrix(cls, sentences, weighting='frequency', norm=None):
"""
Compute the matrix of term frequencies given a list of sentences
"""
if norm not in ('l1', 'l2', None):
raise ValueError('Parameter "norm" can only take values "l1", "l2" or None')
# Initiali... | python | {
"resource": ""
} |
q9131 | SepaPaymentInitn._prepare_document | train | def _prepare_document(self):
"""
Build the main document node and set xml namespaces.
"""
self._xml = ET.Element("Document")
self._xml.set("xmlns",
"urn:iso:std:iso:20022:tech:xsd:" + self.schema)
self._xml.set("xmlns:xsi",
"htt... | python | {
"resource": ""
} |
q9132 | get_rand_string | train | def get_rand_string(length=12, allowed_chars='0123456789abcdef'):
"""
Returns a securely generated random string. Taken from the Django project
The default length of 12 with the a-z, A-Z, 0-9 character set returns
a 71-bit value. log_2((26+26+10)^12) =~ 71 bits
"""
if not using_sysrandom:
... | python | {
"resource": ""
} |
q9133 | make_msg_id | train | def make_msg_id():
"""
Create a semi random message id, by using 12 char random hex string and
a timestamp.
@return: string consisting of timestamp, -, random value
"""
random_string = get_rand_string(12)
timestamp = time.strftime("%Y%m%d%I%M%S")
msg_id = timestamp + "-" + random_string
... | python | {
"resource": ""
} |
q9134 | make_id | train | def make_id(name):
"""
Create a random id combined with the creditor name.
@return string consisting of name (truncated at 22 chars), -,
12 char rand hex string.
"""
name = re.sub(r'[^a-zA-Z0-9]', '', name)
r = get_rand_string(12)
if len(name) > 22:
name = name[:22]
return na... | python | {
"resource": ""
} |
q9135 | mapping_get | train | def mapping_get(uri, mapping):
"""Look up the URI in the given mapping and return the result.
Throws KeyError if no matching mapping was found.
"""
ln = localname(uri)
# 1. try to match URI keys
for k, v in mapping.items():
if k == uri:
return v
# 2. try to match local ... | python | {
"resource": ""
} |
q9136 | mapping_match | train | def mapping_match(uri, mapping):
"""Determine whether the given URI matches one of the given mappings.
Returns True if a match was found, False otherwise.
"""
try:
val = mapping_get(uri, mapping)
return True
except KeyError:
return False | python | {
"resource": ""
} |
q9137 | in_general_ns | train | def in_general_ns(uri):
"""Return True iff the URI is in a well-known general RDF namespace.
URI namespaces considered well-known are RDF, RDFS, OWL, SKOS and DC."""
RDFuri = RDF.uri
RDFSuri = RDFS.uri
for ns in (RDFuri, RDFSuri, OWL, SKOS, DC):
if uri.startswith(ns):
return Tr... | python | {
"resource": ""
} |
q9138 | detect_namespace | train | def detect_namespace(rdf):
"""Try to automatically detect the URI namespace of the vocabulary.
Return namespace as URIRef.
"""
# pick a concept
conc = rdf.value(None, RDF.type, SKOS.Concept, any=True)
if conc is None:
logging.critical(
"Namespace auto-detection failed. "
... | python | {
"resource": ""
} |
q9139 | transform_sparql_update | train | def transform_sparql_update(rdf, update_query):
"""Perform a SPARQL Update transformation on the RDF data."""
logging.debug("performing SPARQL Update transformation")
if update_query[0] == '@': # actual query should be read from file
update_query = file(update_query[1:]).read()
logging.debug... | python | {
"resource": ""
} |
q9140 | transform_sparql_construct | train | def transform_sparql_construct(rdf, construct_query):
"""Perform a SPARQL CONSTRUCT query on the RDF data and return a new graph."""
logging.debug("performing SPARQL CONSTRUCT transformation")
if construct_query[0] == '@': # actual query should be read from file
construct_query = file(construct_q... | python | {
"resource": ""
} |
q9141 | transform_concepts | train | def transform_concepts(rdf, typemap):
"""Transform Concepts into new types, as defined by the config file."""
# find out all the types used in the model
types = set()
for s, o in rdf.subject_objects(RDF.type):
if o not in typemap and in_general_ns(o):
continue
types.add(o)
... | python | {
"resource": ""
} |
q9142 | transform_literals | train | def transform_literals(rdf, literalmap):
"""Transform literal properties of Concepts, as defined by config file."""
affected_types = (SKOS.Concept, SKOS.Collection,
SKOSEXT.DeprecatedConcept)
props = set()
for t in affected_types:
for conc in rdf.subjects(RDF.type, t):
... | python | {
"resource": ""
} |
q9143 | transform_relations | train | def transform_relations(rdf, relationmap):
"""Transform YSO-style concept relations into SKOS equivalents."""
affected_types = (SKOS.Concept, SKOS.Collection,
SKOSEXT.DeprecatedConcept)
props = set()
for t in affected_types:
for conc in rdf.subjects(RDF.type, t):
... | python | {
"resource": ""
} |
q9144 | transform_deprecated_concepts | train | def transform_deprecated_concepts(rdf, cs):
"""Transform deprecated concepts so they are in their own concept
scheme."""
deprecated_concepts = []
for conc in rdf.subjects(RDF.type, SKOSEXT.DeprecatedConcept):
rdf.add((conc, RDF.type, SKOS.Concept))
rdf.add((conc, OWL.deprecated, Litera... | python | {
"resource": ""
} |
q9145 | enrich_relations | train | def enrich_relations(rdf, enrich_mappings, use_narrower, use_transitive):
"""Enrich the SKOS relations according to SKOS semantics, including
subproperties of broader and symmetric related properties. If use_narrower
is True, include inverse narrower relations for all broader relations. If
use_narrower ... | python | {
"resource": ""
} |
q9146 | setup_concept_scheme | train | def setup_concept_scheme(rdf, defaultcs):
"""Make sure all concepts have an inScheme property, using the given
default concept scheme if necessary."""
for conc in rdf.subjects(RDF.type, SKOS.Concept):
# check concept scheme
cs = rdf.value(conc, SKOS.inScheme, None, any=True)
if cs is... | python | {
"resource": ""
} |
q9147 | cleanup_properties | train | def cleanup_properties(rdf):
"""Remove unnecessary property definitions.
Reemoves SKOS and DC property definitions and definitions of unused
properties."""
for t in (RDF.Property, OWL.DatatypeProperty, OWL.ObjectProperty,
OWL.SymmetricProperty, OWL.TransitiveProperty,
OWL.In... | python | {
"resource": ""
} |
q9148 | find_reachable | train | def find_reachable(rdf, res):
"""Return the set of reachable resources starting from the given resource,
excluding the seen set of resources.
Note that the seen set is modified
in-place to reflect the ongoing traversal.
"""
starttime = time.time()
# This is almost a non-recursive breadth... | python | {
"resource": ""
} |
q9149 | cleanup_unreachable | train | def cleanup_unreachable(rdf):
"""Remove triples which cannot be reached from the concepts by graph
traversal."""
all_subjects = set(rdf.subjects())
logging.debug("total subject resources: %d", len(all_subjects))
reachable = find_reachable(rdf, SKOS.Concept)
nonreachable = all_subjects - reach... | python | {
"resource": ""
} |
q9150 | replace_subject | train | def replace_subject(rdf, fromuri, touri):
"""Replace occurrences of fromuri as subject with touri in given model.
If touri=None, will delete all occurrences of fromuri instead.
If touri is a list or tuple of URIRefs, all values will be inserted.
"""
if fromuri == touri:
return
for p, o... | python | {
"resource": ""
} |
q9151 | replace_predicate | train | def replace_predicate(rdf, fromuri, touri, subjecttypes=None, inverse=False):
"""Replace occurrences of fromuri as predicate with touri in given model.
If touri=None, will delete all occurrences of fromuri instead.
If touri is a list or tuple of URIRef, all values will be inserted. If
touri is a list o... | python | {
"resource": ""
} |
q9152 | replace_object | train | def replace_object(rdf, fromuri, touri, predicate=None):
"""Replace all occurrences of fromuri as object with touri in the given
model.
If touri=None, will delete all occurrences of fromuri instead.
If touri is a list or tuple of URIRef, all values will be inserted.
If predicate is given, modify on... | python | {
"resource": ""
} |
q9153 | replace_uri | train | def replace_uri(rdf, fromuri, touri):
"""Replace all occurrences of fromuri with touri in the given model.
If touri is a list or tuple of URIRef, all values will be inserted.
If touri=None, will delete all occurrences of fromuri instead.
"""
replace_subject(rdf, fromuri, touri)
replace_predica... | python | {
"resource": ""
} |
q9154 | rdfs_classes | train | def rdfs_classes(rdf):
"""Perform RDFS subclass inference.
Mark all resources with a subclass type with the upper class."""
# find out the subclass mappings
upperclasses = {} # key: class val: set([superclass1, superclass2..])
for s, o in rdf.subject_objects(RDFS.subClassOf):
upperclasses... | python | {
"resource": ""
} |
q9155 | rdfs_properties | train | def rdfs_properties(rdf):
"""Perform RDFS subproperty inference.
Add superproperties where subproperties have been used."""
# find out the subproperty mappings
superprops = {} # key: property val: set([superprop1, superprop2..])
for s, o in rdf.subject_objects(RDFS.subPropertyOf):
superpr... | python | {
"resource": ""
} |
q9156 | OverExtendsNode.get_parent | train | def get_parent(self, context):
"""
Load the parent template using our own ``find_template``, which
will cause its absolute path to not be used again. Then peek at
the first node, and if its parent arg is the same as the
current parent arg, we know circular inheritance is going to... | python | {
"resource": ""
} |
q9157 | main | train | def main():
"""Read command line parameters and make a transform based on them."""
config = Config()
# additional options for command line client only
defaults = vars(config)
defaults['to_format'] = None
defaults['output'] = '-'
defaults['log'] = None
defaults['debug'] = False
opt... | python | {
"resource": ""
} |
q9158 | H2Protocol.set_handler | train | def set_handler(self, handler):
"""
Connect with a coroutine, which is scheduled when connection is made.
This function will create a task, and when connection is closed,
the task will be canceled.
:param handler:
:return: None
"""
if self._handler:
... | python | {
"resource": ""
} |
q9159 | H2Protocol.start_request | train | def start_request(self, headers, *, end_stream=False):
"""
Start a request by sending given headers on a new stream, and return
the ID of the new stream.
This may block until the underlying transport becomes writable, and
the number of concurrent outbound requests (open outbound... | python | {
"resource": ""
} |
q9160 | H2Protocol.start_response | train | def start_response(self, stream_id, headers, *, end_stream=False):
"""
Start a response by sending given headers on the given stream.
This may block until the underlying transport becomes writable.
:param stream_id: Which stream to send response on.
:param headers: A list of ke... | python | {
"resource": ""
} |
q9161 | H2Protocol.send_data | train | def send_data(self, stream_id, data, *, end_stream=False):
"""
Send request or response body on the given stream.
This will block until either whole data is sent, or the stream gets
closed. Meanwhile, a paused underlying transport or a closed flow
control window will also help w... | python | {
"resource": ""
} |
q9162 | H2Protocol.send_trailers | train | def send_trailers(self, stream_id, headers):
"""
Send trailers on the given stream, closing the stream locally.
This may block until the underlying transport becomes writable, or
other coroutines release the wlock on this stream.
:param stream_id: Which stream to send trailers ... | python | {
"resource": ""
} |
q9163 | H2Protocol.end_stream | train | def end_stream(self, stream_id):
"""
Close the given stream locally.
This may block until the underlying transport becomes writable, or
other coroutines release the wlock on this stream.
:param stream_id: Which stream to close.
"""
with (yield from self._get_str... | python | {
"resource": ""
} |
q9164 | H2Protocol.read_stream | train | def read_stream(self, stream_id, size=None):
"""
Read data from the given stream.
By default (`size=None`), this returns all data left in current HTTP/2
frame. In other words, default behavior is to receive frame by frame.
If size is given a number above zero, method will try t... | python | {
"resource": ""
} |
q9165 | H2Protocol.wait_functional | train | def wait_functional(self):
"""
Wait until the connection becomes functional.
The connection is count functional if it was active within last few
seconds (defined by `functional_timeout`), where a newly-made
connection and received data indicate activeness.
:return: Most... | python | {
"resource": ""
} |
q9166 | H2Protocol.reprioritize | train | def reprioritize(self, stream_id,
depends_on=None, weight=16, exclusive=False):
"""
Update the priority status of an existing stream.
:param stream_id: The stream ID of the stream being updated.
:param depends_on: (optional) The ID of the stream that the stream now
... | python | {
"resource": ""
} |
q9167 | superuser_required | train | def superuser_required(view_func=None, redirect_field_name=REDIRECT_FIELD_NAME,
login_url='admin:login'):
"""
Decorator for views that checks that the user is logged in and is a superuser
member, redirecting to the login page if necessary.
"""
actual_decorator = user_passes_te... | python | {
"resource": ""
} |
q9168 | SqlAggregate._condition_as_sql | train | def _condition_as_sql(self, qn, connection):
'''
Return sql for condition.
'''
def escape(value):
if isinstance(value, bool):
value = str(int(value))
if isinstance(value, six.string_types):
# Escape params used with LIKE
... | python | {
"resource": ""
} |
q9169 | build_messages_metrics | train | def build_messages_metrics(messages):
"""Build reports's metrics"""
count_types = collections.Counter(
line.get('type') or None
for line in messages)
count_modules = collections.Counter(
line.get('module') or None
for line in messages)
count_symbols = collections.Counter(... | python | {
"resource": ""
} |
q9170 | build_messages_modules | train | def build_messages_modules(messages):
"""Build and yield sorted list of messages per module.
:param list messages: List of dict of messages
:return: Tuple of 2 values: first is the module info, second is the list
of messages sorted by line number
"""
data = collections.defaultdict(list... | python | {
"resource": ""
} |
q9171 | stats_evaluation | train | def stats_evaluation(stats):
"""Generate an evaluation for the given pylint ``stats``."""
statement = stats.get('statement')
error = stats.get('error', 0)
warning = stats.get('warning', 0)
refactor = stats.get('refactor', 0)
convention = stats.get('convention', 0)
if not statement or statem... | python | {
"resource": ""
} |
q9172 | build_command_parser | train | def build_command_parser():
"""Build command parser using ``argparse`` module."""
parser = argparse.ArgumentParser(
description='Transform Pylint JSON report to HTML')
parser.add_argument(
'filename',
metavar='FILENAME',
type=argparse.FileType('r'),
nargs='?',
... | python | {
"resource": ""
} |
q9173 | main | train | def main():
"""Pylint JSON to HTML Main Entry Point"""
parser = build_command_parser()
options = parser.parse_args()
file_pointer = options.filename
input_format = options.input_format
with file_pointer:
json_data = json.load(file_pointer)
if input_format == SIMPLE_JSON:
re... | python | {
"resource": ""
} |
q9174 | Report.render | train | def render(self):
"""Render report to HTML"""
template = self.get_template()
return template.render(
messages=self._messages,
metrics=self.metrics,
report=self) | python | {
"resource": ""
} |
q9175 | JsonExtendedReporter.handle_message | train | def handle_message(self, msg):
"""Store new message for later use.
.. seealso:: :meth:`~JsonExtendedReporter.on_close`
"""
self._messages.append({
'type': msg.category,
'module': msg.module,
'obj': msg.obj,
'line': msg.line,
'c... | python | {
"resource": ""
} |
q9176 | JsonExtendedReporter.on_close | train | def on_close(self, stats, previous_stats):
"""Print the extended JSON report to reporter's output.
:param dict stats: Metrics for the current pylint run
:param dict previous_stats: Metrics for the previous pylint run
"""
reports = {
'messages': self._messages,
... | python | {
"resource": ""
} |
q9177 | triangulate | train | def triangulate(points):
"""
Connects an input list of xy tuples with lines forming a set of
smallest possible Delauney triangles between them.
Arguments:
- **points**: A list of xy or xyz point tuples to triangulate.
Returns:
- A list of triangle polygons. If the input coordinate po... | python | {
"resource": ""
} |
q9178 | voronoi | train | def voronoi(points, buffer_percent=100):
"""
Surrounds each point in an input list of xy tuples with a
unique Voronoi polygon.
Arguments:
- **points**: A list of xy or xyz point tuples to triangulate.
- **buffer_percent** (optional): Controls how much bigger than
the original bbox... | python | {
"resource": ""
} |
q9179 | equals | train | def equals(val1, val2):
"""
Returns True if the two strings are equal, False otherwise.
The time taken is independent of the number of characters that match.
For the sake of simplicity, this function executes in constant time only
when the two strings have the same length. It short-circuits when t... | python | {
"resource": ""
} |
q9180 | _encode_uvarint | train | def _encode_uvarint(data, n):
''' Encodes integer into variable-length format into data.'''
if n < 0:
raise ValueError('only support positive integer')
while True:
this_byte = n & 0x7f
n >>= 7
if n == 0:
data.append(this_byte)
break
data.append... | python | {
"resource": ""
} |
q9181 | BinarySerializer._parse_section_v2 | train | def _parse_section_v2(self, data):
''' Parses a sequence of packets in data.
The sequence is terminated by a packet with a field type of EOS
:param data bytes to be deserialized.
:return: the rest of data and an array of packet V2
'''
from pymacaroons.exceptions import ... | python | {
"resource": ""
} |
q9182 | BinarySerializer._parse_packet_v2 | train | def _parse_packet_v2(self, data):
''' Parses a V2 data packet at the start of the given data.
The format of a packet is as follows:
field_type(varint) payload_len(varint) data[payload_len bytes]
apart from EOS which has no payload_en or data (it's a single zero
byte).
... | python | {
"resource": ""
} |
q9183 | Macaroon.prepare_for_request | train | def prepare_for_request(self, discharge_macaroon):
''' Return a new discharge macaroon bound to the receiving macaroon's
current signature so that it can be used in a request.
This must be done before a discharge macaroon is sent to a server.
:param discharge_macaroon:
:return:... | python | {
"resource": ""
} |
q9184 | _caveat_v1_to_dict | train | def _caveat_v1_to_dict(c):
''' Return a caveat as a dictionary for export as the JSON
macaroon v1 format.
'''
serialized = {}
if len(c.caveat_id) > 0:
serialized['cid'] = c.caveat_id
if c.verification_key_id:
serialized['vid'] = utils.raw_urlsafe_b64encode(
c.verifica... | python | {
"resource": ""
} |
q9185 | _caveat_v2_to_dict | train | def _caveat_v2_to_dict(c):
''' Return a caveat as a dictionary for export as the JSON
macaroon v2 format.
'''
serialized = {}
if len(c.caveat_id_bytes) > 0:
_add_json_binary_field(c.caveat_id_bytes, serialized, 'i')
if c.verification_key_id:
_add_json_binary_field(c.verification_... | python | {
"resource": ""
} |
q9186 | _read_json_binary_field | train | def _read_json_binary_field(deserialized, field):
''' Read the value of a JSON field that may be string or base64-encoded.
'''
val = deserialized.get(field)
if val is not None:
return utils.convert_to_bytes(val)
val = deserialized.get(field + '64')
if val is None:
return None
... | python | {
"resource": ""
} |
q9187 | JsonSerializer.serialize | train | def serialize(self, m):
'''Serialize the macaroon in JSON format indicated by the version field.
@param macaroon the macaroon to serialize.
@return JSON macaroon.
'''
from pymacaroons import macaroon
if m.version == macaroon.MACAROON_V1:
return self._serializ... | python | {
"resource": ""
} |
q9188 | JsonSerializer._serialize_v1 | train | def _serialize_v1(self, macaroon):
'''Serialize the macaroon in JSON format v1.
@param macaroon the macaroon to serialize.
@return JSON macaroon.
'''
serialized = {
'identifier': utils.convert_to_string(macaroon.identifier),
'signature': macaroon.signatur... | python | {
"resource": ""
} |
q9189 | JsonSerializer._serialize_v2 | train | def _serialize_v2(self, macaroon):
'''Serialize the macaroon in JSON format v2.
@param macaroon the macaroon to serialize.
@return JSON macaroon in v2 format.
'''
serialized = {}
_add_json_binary_field(macaroon.identifier_bytes, serialized, 'i')
_add_json_binary_... | python | {
"resource": ""
} |
q9190 | JsonSerializer.deserialize | train | def deserialize(self, serialized):
'''Deserialize a JSON macaroon depending on the format.
@param serialized the macaroon in JSON format.
@return the macaroon object.
'''
deserialized = json.loads(serialized)
if deserialized.get('identifier') is None:
return ... | python | {
"resource": ""
} |
q9191 | JsonSerializer._deserialize_v1 | train | def _deserialize_v1(self, deserialized):
'''Deserialize a JSON macaroon in v1 format.
@param serialized the macaroon in v1 JSON format.
@return the macaroon object.
'''
from pymacaroons.macaroon import Macaroon, MACAROON_V1
from pymacaroons.caveat import Caveat
... | python | {
"resource": ""
} |
q9192 | JsonSerializer._deserialize_v2 | train | def _deserialize_v2(self, deserialized):
'''Deserialize a JSON macaroon v2.
@param serialized the macaroon in JSON format v2.
@return the macaroon object.
'''
from pymacaroons.macaroon import Macaroon, MACAROON_V2
from pymacaroons.caveat import Caveat
caveats = [... | python | {
"resource": ""
} |
q9193 | ProjectPreferences.save_settings | train | def save_settings(cls, project=None, user=None, settings=None):
"""
Save settings for a user without first fetching their preferences.
- **user** and **project** can be either a :py:class:`.User` and
:py:class:`.Project` instance respectively, or they can be given as
IDs. If... | python | {
"resource": ""
} |
q9194 | Subject.async_saves | train | def async_saves(cls):
"""
Returns a context manager to allow asynchronously creating subjects.
Using this context manager will create a pool of threads which will
create multiple subjects at once and upload any local files
simultaneously.
The recommended way to use this ... | python | {
"resource": ""
} |
q9195 | Subject.async_save_result | train | def async_save_result(self):
"""
Retrieves the result of this subject's asynchronous save.
- Returns `True` if the subject was saved successfully.
- Raises `concurrent.futures.CancelledError` if the save was cancelled.
- If the save failed, raises the relevant exception.
... | python | {
"resource": ""
} |
q9196 | Subject.add_location | train | def add_location(self, location):
"""
Add a media location to this subject.
- **location** can be an open :py:class:`file` object, a path to a
local file, or a :py:class:`dict` containing MIME types and URLs for
remote media.
Examples::
subject.add_loca... | python | {
"resource": ""
} |
q9197 | Exportable.wait_export | train | def wait_export(
self,
export_type,
timeout=None,
):
"""
Blocks until an in-progress export is ready.
- **export_type** is a string specifying which type of export to wait
for.
- **timeout** is the maximum number of seconds to wait.
If ``ti... | python | {
"resource": ""
} |
q9198 | Exportable.generate_export | train | def generate_export(self, export_type):
"""
Start a new export.
- **export_type** is a string specifying which type of export to start.
Returns a :py:class:`dict` containing metadata for the new export.
"""
if export_type in TALK_EXPORT_TYPES:
return talk.p... | python | {
"resource": ""
} |
q9199 | Exportable.describe_export | train | def describe_export(self, export_type):
"""
Fetch metadata for an export.
- **export_type** is a string specifying which type of export to look
up.
Returns a :py:class:`dict` containing metadata for the export.
"""
if export_type in TALK_EXPORT_TYPES:
... | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.