_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q9000 | _serialize_argument | train | def _serialize_argument(rargname, value, varprops):
"""Serialize an MRS argument into the SimpleMRS format."""
_argument = '{rargname}: {value}{props}'
if rargname == CONSTARG_ROLE:
value = '"{}"'.format(value)
props = ''
if value in varprops:
props = ' [ {} ]'.format(
' ... | python | {
"resource": ""
} |
q9001 | _serialize_ep | train | def _serialize_ep(ep, varprops, version=_default_version):
"""Serialize an Elementary Predication into the SimpleMRS encoding."""
# ('nodeid', 'pred', 'label', 'args', 'lnk', 'surface', 'base')
args = ep[3]
arglist = ' '.join([_serialize_argument(rarg, args[rarg], varprops)
for r... | python | {
"resource": ""
} |
q9002 | _serialize_lnk | train | def _serialize_lnk(lnk):
"""Serialize a predication lnk to surface form into the SimpleMRS
encoding."""
s = ""
if lnk is not None:
s = '<'
if lnk.type == Lnk.CHARSPAN:
cfrom, cto = lnk.data
s += ''.join([str(cfrom), ':', str(cto)])
elif lnk.type == Lnk.... | python | {
"resource": ""
} |
q9003 | _UdfNodeBase.to_dict | train | def to_dict(self, fields=_all_fields, labels=None):
"""
Encode the node as a dictionary suitable for JSON serialization.
Args:
fields: if given, this is a whitelist of fields to include
on nodes (`daughters` and `form` are always shown)
labels: optional l... | python | {
"resource": ""
} |
q9004 | UdfNode.is_head | train | def is_head(self):
"""
Return `True` if the node is a head.
A node is a head if it is marked as a head in the UDX format or
it has no siblings. `False` is returned if the node is known
to not be a head (has a sibling that is a head). Otherwise it
is indeterminate whether... | python | {
"resource": ""
} |
q9005 | Derivation.from_string | train | def from_string(cls, s):
"""
Instantiate a `Derivation` from a UDF or UDX string representation.
The UDF/UDX representations are as output by a processor like the
`LKB <http://moin.delph-in.net/LkbTop>`_ or
`ACE <http://sweaglesw.org/linguistics/ace/>`_, or from the
:met... | python | {
"resource": ""
} |
q9006 | loads | train | def loads(s, model):
"""
Deserialize PENMAN graphs from a string
Args:
s (str): serialized PENMAN graphs
model: Xmrs subclass instantiated from decoded triples
Returns:
a list of objects (of class *model*)
"""
graphs = penman.loads(s, cls=XMRSCodec)
xs = [model.from_... | python | {
"resource": ""
} |
q9007 | calc_path_and_create_folders | train | def calc_path_and_create_folders(folder, import_path):
""" calculate the path and create the needed folders """
file_path = abspath(path_join(folder, import_path[:import_path.rfind(".")].replace(".", folder_seperator) + ".py"))
mkdir_p(dirname(file_path))
return file_path | python | {
"resource": ""
} |
q9008 | _peek | train | def _peek(tokens, n=0):
"""peek and drop comments"""
return tokens.peek(n=n, skip=_is_comment, drop=True) | python | {
"resource": ""
} |
q9009 | _shift | train | def _shift(tokens):
"""pop the next token, then peek the gid of the following"""
after = tokens.peek(n=1, skip=_is_comment, drop=True)
tok = tokens._buffer.popleft()
return tok[0], tok[1], tok[2], after[0] | python | {
"resource": ""
} |
q9010 | _accumulate | train | def _accumulate(lexitems):
"""
Yield lists of tokens based on very simple parsing that checks the
level of nesting within a structure. This is probably much faster
than the LookaheadIterator method, but it is less safe; an unclosed
list or AVM may cause it to build a list including the rest of the
... | python | {
"resource": ""
} |
q9011 | _lex | train | def _lex(stream):
"""
Lex the input stream according to _tdl_lex_re.
Yields
(gid, token, line_number)
"""
lines = enumerate(stream, 1)
line_no = pos = 0
try:
while True:
if pos == 0:
line_no, line = next(lines)
matches = _tdl_lex_re.fi... | python | {
"resource": ""
} |
q9012 | format | train | def format(obj, indent=0):
"""
Serialize TDL objects to strings.
Args:
obj: instance of :class:`Term`, :class:`Conjunction`, or
:class:`TypeDefinition` classes or subclasses
indent (int): number of spaces to indent the formatted object
Returns:
str: serialized form o... | python | {
"resource": ""
} |
q9013 | AVM.normalize | train | def normalize(self):
"""
Reduce trivial AVM conjunctions to just the AVM.
For example, in `[ ATTR1 [ ATTR2 val ] ]` the value of `ATTR1`
could be a conjunction with the sub-AVM `[ ATTR2 val ]`. This
method removes the conjunction so the sub-AVM nests directly
(equivalent... | python | {
"resource": ""
} |
q9014 | ConsList.values | train | def values(self):
"""
Return the list of values in the ConsList feature structure.
"""
if self._avm is None:
return []
else:
vals = [val for _, val in _collect_list_items(self)]
# the < a . b > notation puts b on the last REST path,
... | python | {
"resource": ""
} |
q9015 | ConsList.append | train | def append(self, value):
"""
Append an item to the end of an open ConsList.
Args:
value (:class:`Conjunction`, :class:`Term`): item to add
Raises:
:class:`TdlError`: when appending to a closed list
"""
if self._avm is not None and not self.termina... | python | {
"resource": ""
} |
q9016 | ConsList.terminate | train | def terminate(self, end):
"""
Set the value of the tail of the list.
Adding values via :meth:`append` places them on the `FIRST`
feature of some level of the feature structure (e.g.,
`REST.FIRST`), while :meth:`terminate` places them on the
final `REST` feature (e.g., `R... | python | {
"resource": ""
} |
q9017 | Conjunction.normalize | train | def normalize(self):
"""
Rearrange the conjunction to a conventional form.
This puts any coreference(s) first, followed by type terms,
then followed by AVM(s) (including lists). AVMs are
normalized via :meth:`AVM.normalize`.
"""
corefs = []
types = []
... | python | {
"resource": ""
} |
q9018 | Conjunction.add | train | def add(self, term):
"""
Add a term to the conjunction.
Args:
term (:class:`Term`, :class:`Conjunction`): term to add;
if a :class:`Conjunction`, all of its terms are added
to the current conjunction.
Raises:
:class:`TypeError`: wh... | python | {
"resource": ""
} |
q9019 | Conjunction.types | train | def types(self):
"""Return the list of type terms in the conjunction."""
return [term for term in self._terms
if isinstance(term, (TypeIdentifier, String, Regex))] | python | {
"resource": ""
} |
q9020 | Conjunction.features | train | def features(self, expand=False):
"""Return the list of feature-value pairs in the conjunction."""
featvals = []
for term in self._terms:
if isinstance(term, AVM):
featvals.extend(term.features(expand=expand))
return featvals | python | {
"resource": ""
} |
q9021 | Conjunction.string | train | def string(self):
"""
Return the first string term in the conjunction, or `None`.
"""
for term in self._terms:
if isinstance(term, String):
return str(term)
return None | python | {
"resource": ""
} |
q9022 | TypeDefinition.documentation | train | def documentation(self, level='first'):
"""
Return the documentation of the type.
By default, this is the first docstring on a top-level term.
By setting *level* to `"top"`, the list of all docstrings on
top-level terms is returned, including the type's `docstring`
value... | python | {
"resource": ""
} |
q9023 | TdlDefinition.local_constraints | train | def local_constraints(self):
"""
Return the constraints defined in the local AVM.
"""
cs = []
for feat, val in self._avm.items():
try:
if val.supertypes and not val._avm:
cs.append((feat, val))
else:
... | python | {
"resource": ""
} |
q9024 | TdlConsList.values | train | def values(self):
"""
Return the list of values.
"""
def collect(d):
if d is None or d.get('FIRST') is None:
return []
vals = [d['FIRST']]
vals.extend(collect(d.get('REST')))
return vals
return collect(self) | python | {
"resource": ""
} |
q9025 | Variable.from_dict | train | def from_dict(cls, d):
"""Instantiate a Variable from a dictionary representation."""
return cls(
d['type'], tuple(d['parents']), list(d['properties'].items())
) | python | {
"resource": ""
} |
q9026 | Role.from_dict | train | def from_dict(cls, d):
"""Instantiate a Role from a dictionary representation."""
return cls(
d['rargname'],
d['value'],
list(d.get('properties', {}).items()),
d.get('optional', False)
) | python | {
"resource": ""
} |
q9027 | Role.to_dict | train | def to_dict(self):
"""Return a dictionary representation of the Role."""
d = {'rargname': self.rargname, 'value': self.value}
if self.properties:
d['properties'] = self.properties
if self.optional:
d['optional'] = self.optional
return d | python | {
"resource": ""
} |
q9028 | Predicate.from_dict | train | def from_dict(cls, d):
"""Instantiate a Predicate from a dictionary representation."""
synopses = [tuple(map(Role.from_dict, synopsis))
for synopsis in d.get('synopses', [])]
return cls(d['predicate'], tuple(d['parents']), synopses) | python | {
"resource": ""
} |
q9029 | Predicate.to_dict | train | def to_dict(self):
"""Return a dictionary representation of the Predicate."""
return {
'predicate': self.predicate,
'parents': list(self.supertypes),
'synopses': [[role.to_dict() for role in synopsis]
for synopsis in self.synopses]
} | python | {
"resource": ""
} |
q9030 | SemI.from_dict | train | def from_dict(cls, d):
"""Instantiate a SemI from a dictionary representation."""
read = lambda cls: (lambda pair: (pair[0], cls.from_dict(pair[1])))
return cls(
variables=map(read(Variable), d.get('variables', {}).items()),
properties=map(read(Property), d.get('propertie... | python | {
"resource": ""
} |
q9031 | SemI.to_dict | train | def to_dict(self):
"""Return a dictionary representation of the SemI."""
make = lambda pair: (pair[0], pair[1].to_dict())
return dict(
variables=dict(make(v) for v in self.variables.items()),
properties=dict(make(p) for p in self.properties.items()),
roles=dic... | python | {
"resource": ""
} |
q9032 | sort_vid_split | train | def sort_vid_split(vs):
"""
Split a valid variable string into its variable sort and id.
Examples:
>>> sort_vid_split('h3')
('h', '3')
>>> sort_vid_split('ref-ind12')
('ref-ind', '12')
"""
match = var_re.match(vs)
if match is None:
raise ValueError('Inval... | python | {
"resource": ""
} |
q9033 | Lnk.charspan | train | def charspan(cls, start, end):
"""
Create a Lnk object for a character span.
Args:
start: the initial character position (cfrom)
end: the final character position (cto)
"""
return cls(Lnk.CHARSPAN, (int(start), int(end))) | python | {
"resource": ""
} |
q9034 | Lnk.chartspan | train | def chartspan(cls, start, end):
"""
Create a Lnk object for a chart span.
Args:
start: the initial chart vertex
end: the final chart vertex
"""
return cls(Lnk.CHARTSPAN, (int(start), int(end))) | python | {
"resource": ""
} |
q9035 | Lnk.tokens | train | def tokens(cls, tokens):
"""
Create a Lnk object for a token range.
Args:
tokens: a list of token identifiers
"""
return cls(Lnk.TOKENS, tuple(map(int, tokens))) | python | {
"resource": ""
} |
q9036 | _LnkMixin.cfrom | train | def cfrom(self):
"""
The initial character position in the surface string.
Defaults to -1 if there is no valid cfrom value.
"""
cfrom = -1
try:
if self.lnk.type == Lnk.CHARSPAN:
cfrom = self.lnk.data[0]
except AttributeError:
... | python | {
"resource": ""
} |
q9037 | _LnkMixin.cto | train | def cto(self):
"""
The final character position in the surface string.
Defaults to -1 if there is no valid cto value.
"""
cto = -1
try:
if self.lnk.type == Lnk.CHARSPAN:
cto = self.lnk.data[1]
except AttributeError:
pass #... | python | {
"resource": ""
} |
q9038 | Pred.surface | train | def surface(cls, predstr):
"""Instantiate a Pred from its quoted string representation."""
lemma, pos, sense, _ = split_pred_string(predstr)
return cls(Pred.SURFACE, lemma, pos, sense, predstr) | python | {
"resource": ""
} |
q9039 | Pred.abstract | train | def abstract(cls, predstr):
"""Instantiate a Pred from its symbol string."""
lemma, pos, sense, _ = split_pred_string(predstr)
return cls(Pred.ABSTRACT, lemma, pos, sense, predstr) | python | {
"resource": ""
} |
q9040 | Pred.surface_or_abstract | train | def surface_or_abstract(cls, predstr):
"""Instantiate a Pred from either its surface or abstract symbol."""
if predstr.strip('"').lstrip("'").startswith('_'):
return cls.surface(predstr)
else:
return cls.abstract(predstr) | python | {
"resource": ""
} |
q9041 | Pred.realpred | train | def realpred(cls, lemma, pos, sense=None):
"""Instantiate a Pred from its components."""
string_tokens = [lemma]
if pos is not None:
string_tokens.append(pos)
if sense is not None:
sense = str(sense)
string_tokens.append(sense)
predstr = '_'.jo... | python | {
"resource": ""
} |
q9042 | Node.properties | train | def properties(self):
"""
Morphosemantic property mapping.
Unlike :attr:`sortinfo`, this does not include `cvarsort`.
"""
d = dict(self.sortinfo)
if CVARSORT in d:
del d[CVARSORT]
return d | python | {
"resource": ""
} |
q9043 | EntityRepresentation.update_get_params | train | def update_get_params(self):
"""Update HTTP GET params with the given fields that user wants to fetch."""
if isinstance(self._fields, (tuple, list)): # tuples & lists > x,y,z
self.get_params["fields"] = ",".join([str(_) for _ in self._fields])
elif isinstance(self._fields, str):
... | python | {
"resource": ""
} |
q9044 | EntityRepresentation._fetch_meta_data | train | def _fetch_meta_data(self):
"""Makes an API call to fetch meta data for the given probe and stores the raw data."""
is_success, meta_data = AtlasRequest(
url_path=self.API_META_URL.format(self.id),
key=self.api_key,
server=self.server,
verify=self.verify,
... | python | {
"resource": ""
} |
q9045 | Probe._populate_data | train | def _populate_data(self):
"""Assing some probe's raw meta data from API response to instance properties"""
if self.id is None:
self.id = self.meta_data.get("id")
self.is_anchor = self.meta_data.get("is_anchor")
self.country_code = self.meta_data.get("country_code")
se... | python | {
"resource": ""
} |
q9046 | Measurement._populate_data | train | def _populate_data(self):
"""Assinging some measurement's raw meta data from API response to instance properties"""
if self.id is None:
self.id = self.meta_data.get("id")
self.stop_time = None
self.creation_time = None
self.start_time = None
self.populate_tim... | python | {
"resource": ""
} |
q9047 | Measurement.get_type | train | def get_type(self):
"""
Getting type of measurement keeping backwards compatibility for
v2 API output changes.
"""
mtype = None
if "type" not in self.meta_data:
return mtype
mtype = self.meta_data["type"]
if isinstance(mtype, dict):
... | python | {
"resource": ""
} |
q9048 | Measurement.populate_times | train | def populate_times(self):
"""
Populates all different meta data times that comes with measurement if
they are present.
"""
stop_time = self.meta_data.get("stop_time")
if stop_time:
stop_naive = datetime.utcfromtimestamp(stop_time)
self.stop_time = ... | python | {
"resource": ""
} |
q9049 | AtlasChangeSource.set_action | train | def set_action(self, value):
"""Setter for action attribute"""
if value not in ("remove", "add"):
log = "Sources field 'action' should be 'remove' or 'add'."
raise MalFormattedSource(log)
self._action = value | python | {
"resource": ""
} |
q9050 | AtlasChangeSource.build_api_struct | train | def build_api_struct(self):
"""
Calls parent's method and just adds the addtional field 'action', that
is required to form the structure that Atlas API is accepting.
"""
data = super(AtlasChangeSource, self).build_api_struct()
data.update({"action": self._action})
... | python | {
"resource": ""
} |
q9051 | AtlasMeasurement.add_option | train | def add_option(self, **options):
"""
Adds an option and its value to the class as an attribute and stores it
to the used options set.
"""
for option, value in options.items():
setattr(self, option, value)
self._store_option(option) | python | {
"resource": ""
} |
q9052 | AtlasMeasurement.v2_translator | train | def v2_translator(self, option):
"""
This is a temporary function that helps move from v1 API to v2 without
breaking already running script and keep backwards compatibility.
Translates option name from API v1 to renamed one of v2 API.
"""
new_option = option
new_v... | python | {
"resource": ""
} |
q9053 | AtlasStream.connect | train | def connect(self):
"""Initiate the channel we want to start streams from."""
self.socketIO = SocketIO(
host=self.iosocket_server,
port=80,
resource=self.iosocket_resource,
proxies=self.proxies,
headers=self.headers,
transports=["web... | python | {
"resource": ""
} |
q9054 | AtlasStream.bind_channel | train | def bind_channel(self, channel, callback):
"""Bind given channel with the given callback"""
# Remove the following list when deprecation time expires
if channel in self.CHANNELS:
warning = (
"The event name '{}' will soon be deprecated. Use "
"the rea... | python | {
"resource": ""
} |
q9055 | AtlasStream.start_stream | train | def start_stream(self, stream_type, **stream_parameters):
"""Starts new stream for given type with given parameters"""
if stream_type:
self.subscribe(stream_type, **stream_parameters)
else:
self.handle_error("You need to set a stream type") | python | {
"resource": ""
} |
q9056 | AtlasStream.subscribe | train | def subscribe(self, stream_type, **parameters):
"""Subscribe to stream with give parameters."""
parameters["stream_type"] = stream_type
if (stream_type == "result") and ("buffering" not in parameters):
parameters["buffering"] = True
self.socketIO.emit(self.EVENT_NAME_SUBSCR... | python | {
"resource": ""
} |
q9057 | AtlasStream.timeout | train | def timeout(self, seconds=None):
"""
Times out all streams after n seconds or wait forever if seconds is
None
"""
if seconds is None:
self.socketIO.wait()
else:
self.socketIO.wait(seconds=seconds) | python | {
"resource": ""
} |
q9058 | RequestGenerator.build_url | train | def build_url(self):
"""Build the url path based on the filter options."""
if not self.api_filters:
return self.url
# Reduce complex objects to simpler strings
for k, v in self.api_filters.items():
if isinstance(v, datetime): # datetime > UNIX timestamp
... | python | {
"resource": ""
} |
q9059 | RequestGenerator.build_url_chunks | train | def build_url_chunks(self):
"""
If url is too big because of id filter is huge, break id and construct
several urls to call them in order to abstract this complexity from user.
"""
CHUNK_SIZE = 500
id_filter = str(self.api_filters.pop(self.id_filter)).split(',')
... | python | {
"resource": ""
} |
q9060 | RequestGenerator.next_batch | train | def next_batch(self):
"""
Querying API for the next batch of objects and store next url and
batch of objects.
"""
is_success, results = AtlasRequest(
url_path=self.atlas_url,
user_agent=self._user_agent,
server=self.server,
verify=s... | python | {
"resource": ""
} |
q9061 | RequestGenerator.build_next_url | train | def build_next_url(self, url):
"""Builds next url in a format compatible with cousteau. Path + query"""
if not url:
if self.split_urls: # If we had a long request give the next part
self.total_count_flag = False # Reset flag for count
return self.split_urls.... | python | {
"resource": ""
} |
q9062 | RequestGenerator.set_total_count | train | def set_total_count(self, value):
"""Setter for count attribute. Set should append only one count per splitted url."""
if not self.total_count_flag and value:
self._count.append(int(value))
self.total_count_flag = True | python | {
"resource": ""
} |
q9063 | AtlasRequest.get_headers | train | def get_headers(self):
"""Return header for the HTTP request."""
headers = {
"User-Agent": self.http_agent,
"Content-Type": "application/json",
"Accept": "application/json"
}
if self.headers:
headers.update(self.headers)
return hea... | python | {
"resource": ""
} |
q9064 | AtlasRequest.http_method | train | def http_method(self, method):
"""
Execute the given HTTP method and returns if it's success or not
and the response as a string if not success and as python object after
unjson if it's success.
"""
self.build_url()
try:
response = self.get_http_metho... | python | {
"resource": ""
} |
q9065 | AtlasRequest.get_http_method | train | def get_http_method(self, method):
"""Gets the http method that will be called from the requests library"""
return self.http_methods[method](self.url, **self.http_method_args) | python | {
"resource": ""
} |
q9066 | AtlasRequest.get | train | def get(self, **url_params):
"""
Makes the HTTP GET to the url.
"""
if url_params:
self.http_method_args["params"].update(url_params)
return self.http_method("GET") | python | {
"resource": ""
} |
q9067 | AtlasRequest.post | train | def post(self):
"""
Makes the HTTP POST to the url sending post_data.
"""
self._construct_post_data()
post_args = {"json": self.post_data}
self.http_method_args.update(post_args)
return self.http_method("POST") | python | {
"resource": ""
} |
q9068 | AtlasRequest.clean_time | train | def clean_time(self, time):
"""
Transform time field to datetime object if there is any.
"""
if isinstance(time, int):
time = datetime.utcfromtimestamp(time)
elif isinstance(time, str):
time = parser.parse(time)
return time | python | {
"resource": ""
} |
q9069 | AtlasCreateRequest._construct_post_data | train | def _construct_post_data(self):
"""
Constructs the data structure that is required from the atlas API based
on measurements, sources and times user has specified.
"""
definitions = [msm.build_api_struct() for msm in self.measurements]
probes = [source.build_api_struct() f... | python | {
"resource": ""
} |
q9070 | AtlasResultsRequest.clean_probes | train | def clean_probes(self, probe_ids):
"""
Checks format of probe ids and transform it to something API
understands.
"""
if isinstance(probe_ids, (tuple, list)): # tuples & lists > x,y,z
probe_ids = ",".join([str(_) for _ in probe_ids])
return probe_ids | python | {
"resource": ""
} |
q9071 | AtlasResultsRequest.update_http_method_params | train | def update_http_method_params(self):
"""
Update HTTP url parameters based on msm_id and query filters if
there are any.
"""
url_params = {}
if self.start:
url_params.update(
{"start": int(calendar.timegm(self.start.timetuple()))}
)... | python | {
"resource": ""
} |
q9072 | SearchInterface.lookup | train | def lookup(self, id, service=None, media=None, extended=None, **kwargs):
"""Lookup items by their Trakt, IMDB, TMDB, TVDB, or TVRage ID.
**Note:** If you lookup an identifier without a :code:`media` type specified it
might return multiple items if the :code:`service` is not globally unique.
... | python | {
"resource": ""
} |
q9073 | SearchInterface.query | train | def query(self, query, media=None, year=None, fields=None, extended=None, **kwargs):
"""Search by titles, descriptions, translated titles, aliases, and people.
**Note:** Results are ordered by the most relevant score.
:param query: Search title or description
:type query: :class:`~pyth... | python | {
"resource": ""
} |
q9074 | Season.to_identifier | train | def to_identifier(self):
"""Return the season identifier which is compatible with requests that require season definitions.
:return: Season identifier/definition
:rtype: :class:`~python:dict`
"""
return {
'number': self.pk,
'episodes': [
... | python | {
"resource": ""
} |
q9075 | Season.to_dict | train | def to_dict(self):
"""Dump season to a dictionary.
:return: Season dictionary
:rtype: :class:`~python:dict`
"""
result = self.to_identifier()
result.update({
'ids': dict([
(key, value) for (key, value) in self.keys[1:] # NOTE: keys[0] is th... | python | {
"resource": ""
} |
q9076 | Episode.to_dict | train | def to_dict(self):
"""Dump episode to a dictionary.
:return: Episode dictionary
:rtype: :class:`~python:dict`
"""
result = self.to_identifier()
result.update({
'title': self.title,
'watched': 1 if self.is_watched else 0,
'collected'... | python | {
"resource": ""
} |
q9077 | Application.on_aborted | train | def on_aborted(self):
"""Device authentication aborted.
Triggered when device authentication was aborted (either with `DeviceOAuthPoller.stop()`
or via the "poll" event)
"""
print('Authentication aborted')
# Authentication aborted
self.is_authenticating.acquire... | python | {
"resource": ""
} |
q9078 | Application.on_authenticated | train | def on_authenticated(self, authorization):
"""Device authenticated.
:param authorization: Authentication token details
:type authorization: dict
"""
# Acquire condition
self.is_authenticating.acquire()
# Store authorization for future calls
self.authori... | python | {
"resource": ""
} |
q9079 | Application.on_expired | train | def on_expired(self):
"""Device authentication expired."""
print('Authentication expired')
# Authentication expired
self.is_authenticating.acquire()
self.is_authenticating.notify_all()
self.is_authenticating.release() | python | {
"resource": ""
} |
q9080 | DeviceOAuthInterface.poll | train | def poll(self, device_code, expires_in, interval, **kwargs):
"""Construct the device authentication poller.
:param device_code: Device authentication code
:type device_code: str
:param expires_in: Device authentication code expiry (in seconds)
:type in: int
:pa... | python | {
"resource": ""
} |
q9081 | Movie.to_dict | train | def to_dict(self):
"""Dump movie to a dictionary.
:return: Movie dictionary
:rtype: :class:`~python:dict`
"""
result = self.to_identifier()
result.update({
'watched': 1 if self.is_watched else 0,
'collected': 1 if self.is_collected else 0,
... | python | {
"resource": ""
} |
q9082 | Progress.to_dict | train | def to_dict(self):
"""Dump progress to a dictionary.
:return: Progress dictionary
:rtype: :class:`~python:dict`
"""
result = super(Progress, self).to_dict()
label = LABELS['last_progress_change'][self.progress_type]
result[label] = to_iso8601_datetime(self.last... | python | {
"resource": ""
} |
q9083 | ScrobbleInterface.action | train | def action(self, action, movie=None, show=None, episode=None, progress=0.0, **kwargs):
"""Perform scrobble action.
:param action: Action to perform (either :code:`start`, :code:`pause` or :code:`stop`)
:type action: :class:`~python:str`
:param movie: Movie definition (or `None`)
... | python | {
"resource": ""
} |
q9084 | ScrobbleInterface.start | train | def start(self, movie=None, show=None, episode=None, progress=0.0, **kwargs):
"""Send the scrobble "start" action.
Use this method when the video initially starts playing or is un-paused. This will
remove any playback progress if it exists.
**Note:** A watching status will auto expire ... | python | {
"resource": ""
} |
q9085 | ScrobbleInterface.pause | train | def pause(self, movie=None, show=None, episode=None, progress=0.0, **kwargs):
"""Send the scrobble "pause' action.
Use this method when the video is paused. The playback progress will be saved and
:code:`Trakt['sync/playback'].get()` can be used to resume the video from this exact
posit... | python | {
"resource": ""
} |
q9086 | ScrobbleInterface.stop | train | def stop(self, movie=None, show=None, episode=None, progress=0.0, **kwargs):
"""Send the scrobble "stop" action.
Use this method when the video is stopped or finishes playing on its own. If the
progress is above 80%, the video will be scrobbled and the :code:`action` will be set
to **sc... | python | {
"resource": ""
} |
q9087 | CustomList.delete | train | def delete(self, **kwargs):
"""Delete the list.
:param kwargs: Extra request options
:type kwargs: :class:`~python:dict`
:return: Boolean to indicate if the request was successful
:rtype: :class:`~python:bool`
"""
return self._client['users/*/lists/*'].delete(s... | python | {
"resource": ""
} |
q9088 | CustomList.update | train | def update(self, **kwargs):
"""Update the list with the current object attributes.
:param kwargs: Extra request options
:type kwargs: :class:`~python:dict`
:return: Boolean to indicate if the request was successful
:rtype: :class:`~python:bool`
"""
item = self.... | python | {
"resource": ""
} |
q9089 | CustomList.remove | train | def remove(self, items, **kwargs):
"""Remove specified items from the list.
:param items: Items that should be removed from the list
:type items: :class:`~python:list`
:param kwargs: Extra request options
:type kwargs: :class:`~python:dict`
:return: Response
:r... | python | {
"resource": ""
} |
q9090 | CustomList.like | train | def like(self, **kwargs):
"""Like the list.
:param kwargs: Extra request options
:type kwargs: :class:`~python:dict`
:return: Boolean to indicate if the request was successful
:rtype: :class:`~python:bool`
"""
return self._client['users/*/lists/*'].like(self.us... | python | {
"resource": ""
} |
q9091 | CustomList.unlike | train | def unlike(self, **kwargs):
"""Un-like the list.
:param kwargs: Extra request options
:type kwargs: :class:`~python:dict`
:return: Boolean to indicate if the request was successful
:rtype: :class:`~python:bool`
"""
return self._client['users/*/lists/*'].unlike(... | python | {
"resource": ""
} |
q9092 | Base.get | train | def get(self, source, media, collection=None, start_date=None, days=None, query=None, years=None, genres=None,
languages=None, countries=None, runtimes=None, ratings=None, certifications=None, networks=None,
status=None, **kwargs):
"""Retrieve calendar items.
The `all` calendar ... | python | {
"resource": ""
} |
q9093 | Show.episodes | train | def episodes(self):
"""Return a flat episode iterator.
:returns: Iterator :code:`((season_num, episode_num), Episode)`
:rtype: iterator
"""
for sk, season in iteritems(self.seasons):
# Yield each episode in season
for ek, episode in iteritems(season.epis... | python | {
"resource": ""
} |
q9094 | Show.to_dict | train | def to_dict(self):
"""Dump show to a dictionary.
:return: Show dictionary
:rtype: :class:`~python:dict`
"""
result = self.to_identifier()
result['seasons'] = [
season.to_dict()
for season in self.seasons.values()
]
result['in_wa... | python | {
"resource": ""
} |
q9095 | TraktRequest.construct_url | train | def construct_url(self):
"""Construct a full trakt request URI, with `params` and `query`."""
path = [self.path]
path.extend(self.params)
# Build URL
url = self.client.base_url + '/'.join(
str(value) for value in path
if value
)
# Append ... | python | {
"resource": ""
} |
q9096 | Search.search_officers | train | def search_officers(self, term, disqualified=False, **kwargs):
"""Search for officers by name.
Args:
term (str): Officer name to search on.
disqualified (Optional[bool]): True to search for disqualified
officers
kwargs (dict): additional keywords passed into
... | python | {
"resource": ""
} |
q9097 | Search.address | train | def address(self, num):
"""Search for company addresses by company number.
Args:
num (str): Company number to search on.
"""
url_root = "company/{}/registered-office-address"
baseuri = self._BASE_URI + url_root.format(num)
res = self.session.get(baseuri)
... | python | {
"resource": ""
} |
q9098 | Search.profile | train | def profile(self, num):
"""Search for company profile by company number.
Args:
num (str): Company number to search on.
"""
baseuri = self._BASE_URI + "company/{}".format(num)
res = self.session.get(baseuri)
self.handle_http_error(res)
return res | python | {
"resource": ""
} |
q9099 | Search.filing_history | train | def filing_history(self, num, transaction=None, **kwargs):
"""Search for a company's filling history by company number.
Args:
num (str): Company number to search on.
transaction (Optional[str]): Filing record number.
kwargs (dict): additional keywords passed into
... | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.