_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q235100 | PublishEventMixin.publish_event_from_dict | train | def publish_event_from_dict(self, event_type, data):
"""
Combine 'data' with self.additional_publish_event_data and publish an event
"""
for key, value in self.additional_publish_event_data.items():
if key in data:
return {'result': 'error', 'message': 'Key sh... | python | {
"resource": ""
} |
q235101 | child_isinstance | train | def child_isinstance(block, child_id, block_class_or_mixin):
"""
Efficiently check if a child of an XBlock is an instance of the given class.
Arguments:
block -- the parent (or ancestor) of the child block in question
child_id -- the usage key of the child block we are wondering about
block_cla... | python | {
"resource": ""
} |
q235102 | Tag.attr | train | def attr(self, *args, **kwargs):
"""Add an attribute to the element"""
kwargs.update({k: bool for k in args})
for key, value in kwargs.items():
if key == "klass":
self.attrs["klass"].update(value.split())
elif key == "style":
if isinstance(... | python | {
"resource": ""
} |
q235103 | Tag.remove_attr | train | def remove_attr(self, attr):
"""Removes an attribute."""
self._stable = False
self.attrs.pop(attr, None)
return self | python | {
"resource": ""
} |
q235104 | Tag.render_attrs | train | def render_attrs(self):
"""Renders the tag's attributes using the formats and performing special attributes name substitution."""
ret = []
for k, v in self.attrs.items():
if v:
if v is bool:
ret.append(" %s" % self._SPECIAL_ATTRS.get(k, k))
... | python | {
"resource": ""
} |
q235105 | Tag.toggle_class | train | def toggle_class(self, csscl):
"""Same as jQuery's toggleClass function. It toggles the css class on this element."""
self._stable = False
action = ("add", "remove")[self.has_class(csscl)]
return getattr(self.attrs["klass"], action)(csscl) | python | {
"resource": ""
} |
q235106 | Tag.add_class | train | def add_class(self, cssclass):
"""Adds a css class to this element."""
if self.has_class(cssclass):
return self
return self.toggle_class(cssclass) | python | {
"resource": ""
} |
q235107 | Tag.remove_class | train | def remove_class(self, cssclass):
"""Removes the given class from this element."""
if not self.has_class(cssclass):
return self
return self.toggle_class(cssclass) | python | {
"resource": ""
} |
q235108 | Tag.css | train | def css(self, *props, **kwprops):
"""Adds css properties to this element."""
self._stable = False
styles = {}
if props:
if len(props) == 1 and isinstance(props[0], Mapping):
styles = props[0]
else:
raise WrongContentError(self, prop... | python | {
"resource": ""
} |
q235109 | Tag.show | train | def show(self, display=None):
"""Removes the display style attribute.
If a display type is provided """
self._stable = False
if not display:
self.attrs["style"].pop("display")
else:
self.attrs["style"]["display"] = display
return self | python | {
"resource": ""
} |
q235110 | Tag.toggle | train | def toggle(self):
"""Same as jQuery's toggle, toggles the display attribute of this element."""
self._stable = False
return self.show() if self.attrs["style"]["display"] == "none" else self.hide() | python | {
"resource": ""
} |
q235111 | Tag.text | train | def text(self):
"""Renders the contents inside this element, without html tags."""
texts = []
for child in self.childs:
if isinstance(child, Tag):
texts.append(child.text())
elif isinstance(child, Content):
texts.append(child.render())
... | python | {
"resource": ""
} |
q235112 | Tag.render | train | def render(self, *args, **kwargs):
"""Renders the element and all his childrens."""
# args kwargs API provided for last minute content injection
# self._reverse_mro_func('pre_render')
pretty = kwargs.pop("pretty", False)
if pretty and self._stable != "pretty":
self._s... | python | {
"resource": ""
} |
q235113 | TempyParser._make_tempy_tag | train | def _make_tempy_tag(self, tag, attrs, void):
"""Searches in tempy.tags for the correct tag to use, if does not exists uses the TempyFactory to
create a custom tag."""
tempy_tag_cls = getattr(self.tempy_tags, tag.title(), None)
if not tempy_tag_cls:
unknow_maker = [self.unknow... | python | {
"resource": ""
} |
q235114 | TempyGod.from_string | train | def from_string(self, html_string):
"""Parses an html string and returns a list of Tempy trees."""
self._html_parser._reset().feed(html_string)
return self._html_parser.result | python | {
"resource": ""
} |
q235115 | TempyGod.dump | train | def dump(self, tempy_tree_list, filename, pretty=False):
"""Dumps a Tempy object to a python file"""
if not filename:
raise ValueError('"filename" argument should not be none.')
if len(filename.split(".")) > 1 and not filename.endswith(".py"):
raise ValueError(
... | python | {
"resource": ""
} |
q235116 | _filter_classes | train | def _filter_classes(cls_list, cls_type):
"""Filters a list of classes and yields TempyREPR subclasses"""
for cls in cls_list:
if isinstance(cls, type) and issubclass(cls, cls_type):
if cls_type == TempyPlace and cls._base_place:
pass
else:
yield cl... | python | {
"resource": ""
} |
q235117 | REPRFinder._evaluate_tempyREPR | train | def _evaluate_tempyREPR(self, child, repr_cls):
"""Assign a score ito a TempyRepr class.
The scores depends on the current scope and position of the object in which the TempyREPR is found."""
score = 0
if repr_cls.__name__ == self.__class__.__name__:
# One point if the REPR h... | python | {
"resource": ""
} |
q235118 | REPRFinder._search_for_view | train | def _search_for_view(self, obj):
"""Searches for TempyREPR class declarations in the child's class.
If at least one TempyREPR is found, it uses the best one to make a Tempy object.
Otherwise the original object is returned.
"""
evaluator = partial(self._evaluate_tempyREPR, obj)
... | python | {
"resource": ""
} |
q235119 | TempyTable.add_row | train | def add_row(self, row_data, resize_x=True):
"""Adds a row at the end of the table"""
if not resize_x:
self._check_row_size(row_data)
self.body(Tr()(Td()(cell) for cell in row_data))
return self | python | {
"resource": ""
} |
q235120 | TempyTable.pop_row | train | def pop_row(self, idr=None, tags=False):
"""Pops a row, default the last"""
idr = idr if idr is not None else len(self.body) - 1
row = self.body.pop(idr)
return row if tags else [cell.childs[0] for cell in row] | python | {
"resource": ""
} |
q235121 | TempyTable.pop_cell | train | def pop_cell(self, idy=None, idx=None, tags=False):
"""Pops a cell, default the last of the last row"""
idy = idy if idy is not None else len(self.body) - 1
idx = idx if idx is not None else len(self.body[idy]) - 1
cell = self.body[idy].pop(idx)
return cell if tags else cell.chil... | python | {
"resource": ""
} |
q235122 | Html.render | train | def render(self, *args, **kwargs):
"""Override so each html page served have a doctype"""
return self.doctype.render() + super().render(*args, **kwargs) | python | {
"resource": ""
} |
q235123 | DOMNavigator._find_content | train | def _find_content(self, cont_name):
"""Search for a content_name in the content data, if not found the parent is searched."""
try:
a = self.content_data[cont_name]
return a
except KeyError:
if self.parent:
return self.parent._find_content(cont_... | python | {
"resource": ""
} |
q235124 | DOMNavigator._get_non_tempy_contents | train | def _get_non_tempy_contents(self):
"""Returns rendered Contents and non-DOMElement stuff inside this Tag."""
for thing in filter(
lambda x: not issubclass(x.__class__, DOMElement), self.childs
):
yield thing | python | {
"resource": ""
} |
q235125 | DOMNavigator.siblings | train | def siblings(self):
"""Returns all the siblings of this element as a list."""
return list(filter(lambda x: id(x) != id(self), self.parent.childs)) | python | {
"resource": ""
} |
q235126 | DOMNavigator.bft | train | def bft(self):
""" Generator that returns each element of the tree in Breadth-first order"""
queue = deque([self])
while queue:
node = queue.pop()
yield node
if hasattr(node, "childs"):
queue.extendleft(node.childs) | python | {
"resource": ""
} |
q235127 | DOMModifier._insert | train | def _insert(self, dom_group, idx=None, prepend=False, name=None):
"""Inserts a DOMGroup inside this element.
If provided at the given index, if prepend at the start of the childs list, by default at the end.
If the child is a DOMElement, correctly links the child.
If the DOMGroup have a ... | python | {
"resource": ""
} |
q235128 | DOMModifier.after | train | def after(self, i, sibling, name=None):
"""Adds siblings after the current tag."""
self.parent._insert(sibling, idx=self._own_index + 1 + i, name=name)
return self | python | {
"resource": ""
} |
q235129 | DOMModifier.prepend | train | def prepend(self, _, child, name=None):
"""Adds childs to this tag, starting from the first position."""
self._insert(child, prepend=True, name=name)
return self | python | {
"resource": ""
} |
q235130 | DOMModifier.append | train | def append(self, _, child, name=None):
"""Adds childs to this tag, after the current existing childs."""
self._insert(child, name=name)
return self | python | {
"resource": ""
} |
q235131 | DOMModifier.wrap | train | def wrap(self, other):
"""Wraps this element inside another empty tag."""
if other.childs:
raise TagError(self, "Wrapping in a non empty Tag is forbidden.")
if self.parent:
self.before(other)
self.parent.pop(self._own_index)
other.append(self)
... | python | {
"resource": ""
} |
q235132 | DOMModifier.replace_with | train | def replace_with(self, other):
"""Replace this element with the given DOMElement."""
self.after(other)
self.parent.pop(self._own_index)
return other | python | {
"resource": ""
} |
q235133 | DOMModifier.remove | train | def remove(self):
"""Detach this element from his father."""
if self._own_index is not None and self.parent:
self.parent.pop(self._own_index)
return self | python | {
"resource": ""
} |
q235134 | DOMModifier._detach_childs | train | def _detach_childs(self, idx_from=None, idx_to=None):
"""Moves all the childs to a new father"""
idx_from = idx_from or 0
idx_to = idx_to or len(self.childs)
removed = self.childs[idx_from:idx_to]
for child in removed:
if issubclass(child.__class__, DOMElement):
... | python | {
"resource": ""
} |
q235135 | DOMModifier.move | train | def move(self, new_father, idx=None, prepend=None, name=None):
"""Moves this element from his father to the given one."""
self.parent.pop(self._own_index)
new_father._insert(self, idx=idx, prepend=prepend, name=name)
new_father._stable = False
return self | python | {
"resource": ""
} |
q235136 | run | train | def run(
target,
target_type,
tags=None,
ruleset_name=None,
ruleset_file=None,
ruleset=None,
logging_level=logging.WARNING,
checks_paths=None,
pull=None,
insecure=False,
skips=None,
timeout=None,
):
"""
Runs the sanity checks for the target.
:param timeout: t... | python | {
"resource": ""
} |
q235137 | get_checks | train | def get_checks(
target_type=None,
tags=None,
ruleset_name=None,
ruleset_file=None,
ruleset=None,
logging_level=logging.WARNING,
checks_paths=None,
skips=None,
):
"""
Get the sanity checks for the target.
:param skips: name of checks to skip
:param target_type: TargetType... | python | {
"resource": ""
} |
q235138 | _set_logging | train | def _set_logging(
logger_name="colin",
level=logging.INFO,
handler_class=logging.StreamHandler,
handler_kwargs=None,
format='%(asctime)s.%(msecs).03d %(filename)-17s %(levelname)-6s %(message)s',
date_format='%H:%M:%S'):
"""
Set personal logger for this library.
... | python | {
"resource": ""
} |
q235139 | check_label | train | def check_label(labels, required, value_regex, target_labels):
"""
Check if the label is required and match the regex
:param labels: [str]
:param required: bool (if the presence means pass or not)
:param value_regex: str (using search method)
:param target_labels: [str]
:return: bool (requi... | python | {
"resource": ""
} |
q235140 | AbstractCheck.json | train | def json(self):
"""
Get json representation of the check
:return: dict (str -> obj)
"""
return {
'name': self.name,
'message': self.message,
'description': self.description,
'reference_url': self.reference_url,
'tags': ... | python | {
"resource": ""
} |
q235141 | get_checks_paths | train | def get_checks_paths(checks_paths=None):
"""
Get path to checks.
:param checks_paths: list of str, directories where the checks are present
:return: list of str (absolute path of directory with checks)
"""
p = os.path.join(__file__, os.pardir, os.pardir, os.pardir, "checks")
p = os.path.abs... | python | {
"resource": ""
} |
q235142 | get_ruleset_file | train | def get_ruleset_file(ruleset=None):
"""
Get the ruleset file from name
:param ruleset: str
:return: str
"""
ruleset = ruleset or "default"
ruleset_dirs = get_ruleset_dirs()
for ruleset_directory in ruleset_dirs:
possible_ruleset_files = [os.path.join(ruleset_directory, ruleset ... | python | {
"resource": ""
} |
q235143 | get_rulesets | train | def get_rulesets():
""""
Get available rulesets.
"""
rulesets_dirs = get_ruleset_dirs()
ruleset_files = []
for rulesets_dir in rulesets_dirs:
for f in os.listdir(rulesets_dir):
for ext in EXTS:
file_path = os.path.join(rulesets_dir, f)
if os.pa... | python | {
"resource": ""
} |
q235144 | get_rpm_version | train | def get_rpm_version(package_name):
"""Get a version of the package with 'rpm -q' command."""
version_result = subprocess.run(["rpm", "-q", package_name],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
if version_result.returncode == 0:... | python | {
"resource": ""
} |
q235145 | is_rpm_installed | train | def is_rpm_installed():
"""Tests if the rpm command is present."""
try:
version_result = subprocess.run(["rpm", "--usage"],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
rpm_installed = not version_result.returncod... | python | {
"resource": ""
} |
q235146 | exit_after | train | def exit_after(s):
"""
Use as decorator to exit process if
function takes longer than s seconds.
Direct call is available via exit_after(TIMEOUT_IN_S)(fce)(args).
Inspired by https://stackoverflow.com/a/31667005
"""
def outer(fn):
def inner(*args, **kwargs):
timer = th... | python | {
"resource": ""
} |
q235147 | retry | train | def retry(retry_count=5, delay=2):
"""
Use as decorator to retry functions few times with delays
Exception will be raised if last call fails
:param retry_count: int could of retries in case of failures. It must be
a positive number
:param delay: int delay between retries
... | python | {
"resource": ""
} |
q235148 | ImageName.parse | train | def parse(cls, image_name):
"""
Get the instance of ImageName from the string representation.
:param image_name: str (any possible form of image name)
:return: ImageName instance
"""
result = cls()
# registry.org/namespace/repo:tag
s = image_name.split('... | python | {
"resource": ""
} |
q235149 | CheckStruct.other_attributes | train | def other_attributes(self):
""" return dict with all other data except for the described above"""
return {k: v for k, v in self.c.items() if
k not in ["name", "names", "tags", "additional_tags", "usable_targets"]} | python | {
"resource": ""
} |
q235150 | should_we_load | train | def should_we_load(kls):
""" should we load this class as a check? """
# we don't load abstract classes
if kls.__name__.endswith("AbstractCheck"):
return False
# and we only load checks
if not kls.__name__.endswith("Check"):
return False
mro = kls.__mro__
# and the class need... | python | {
"resource": ""
} |
q235151 | CheckLoader.obtain_check_classes | train | def obtain_check_classes(self):
""" find children of AbstractCheck class and return them as a list """
check_classes = set()
for path in self.paths:
for root, _, files in os.walk(path):
for fi in files:
if not fi.endswith(".py"):
... | python | {
"resource": ""
} |
q235152 | CheckLoader.import_class | train | def import_class(self, import_name):
"""
import selected class
:param import_name, str, e.g. some.module.MyClass
:return the class
"""
module_name, class_name = import_name.rsplit(".", 1)
mod = import_module(module_name)
check_class = getattr(mod, class_n... | python | {
"resource": ""
} |
q235153 | CheckResults._dict_of_results | train | def _dict_of_results(self):
"""
Get the dictionary representation of results
:return: dict (str -> dict (str -> str))
"""
result_json = {}
result_list = []
for r in self.results:
result_list.append({
'name': r.check_name,
... | python | {
"resource": ""
} |
q235154 | CheckResults.statistics | train | def statistics(self):
"""
Get the dictionary with the count of the check-statuses
:return: dict(str -> int)
"""
result = {}
for r in self.results:
result.setdefault(r.status, 0)
result[r.status] += 1
return result | python | {
"resource": ""
} |
q235155 | CheckResults.generate_pretty_output | train | def generate_pretty_output(self, stat, verbose, output_function, logs=True):
"""
Send the formated to the provided function
:param stat: if True print stat instead of full output
:param verbose: bool
:param output_function: function to send output to
"""
has_che... | python | {
"resource": ""
} |
q235156 | CheckResults.get_pretty_string | train | def get_pretty_string(self, stat, verbose):
"""
Pretty string representation of the results
:param stat: bool
:param verbose: bool
:return: str
"""
pretty_output = _PrettyOutputToStr()
self.generate_pretty_output(stat=stat,
... | python | {
"resource": ""
} |
q235157 | receive_fmf_metadata | train | def receive_fmf_metadata(name, path, object_list=False):
"""
search node identified by name fmfpath
:param path: path to filesystem
:param name: str - name as pattern to search - "/name" (prepended hierarchy item)
:param object_list: bool, if true, return whole list of found items
:return: Tree... | python | {
"resource": ""
} |
q235158 | list_checks | train | def list_checks(ruleset, ruleset_file, debug, json, skip, tag, verbose, checks_paths):
"""
Print the checks.
"""
if ruleset and ruleset_file:
raise click.BadOptionUsage(
"Options '--ruleset' and '--file-ruleset' cannot be used together.")
try:
if not debug:
l... | python | {
"resource": ""
} |
q235159 | list_rulesets | train | def list_rulesets(debug):
"""
List available rulesets.
"""
try:
rulesets = get_rulesets()
max_len = max([len(r[0]) for r in rulesets])
for r in rulesets:
click.echo('{0: <{1}} ({2})'.format(r[0], max_len, r[1]))
except Exception as ex:
logger.error("An err... | python | {
"resource": ""
} |
q235160 | info | train | def info():
"""
Show info about colin and its dependencies.
"""
installation_path = os.path.abspath(os.path.join(os.path.dirname(__file__), os.path.pardir))
click.echo("colin {} {}".format(__version__, installation_path))
click.echo("colin-cli {}\n".format(os.path.realpath(__file__)))
# cl... | python | {
"resource": ""
} |
q235161 | _print_results | train | def _print_results(results, stat=False, verbose=False):
"""
Prints the results to the stdout
:type verbose: bool
:param results: generator of results
:param stat: if True print stat instead of full output
"""
results.generate_pretty_output(stat=stat,
verbo... | python | {
"resource": ""
} |
q235162 | DockerfileTarget.labels | train | def labels(self):
"""
Get list of labels from the target instance.
:return: [str]
"""
if self._labels is None:
self._labels = self.instance.labels
return self._labels | python | {
"resource": ""
} |
q235163 | OstreeTarget.labels | train | def labels(self):
"""
Provide labels without the need of dockerd. Instead skopeo is being used.
:return: dict
"""
if self._labels is None:
cmd = ["skopeo", "inspect", self.skopeo_target]
self._labels = json.loads(subprocess.check_output(cmd))["Labels"]
... | python | {
"resource": ""
} |
q235164 | OstreeTarget.tmpdir | train | def tmpdir(self):
""" Temporary directory holding all the runtime data. """
if self._tmpdir is None:
self._tmpdir = mkdtemp(prefix="colin-", dir="/var/tmp")
return self._tmpdir | python | {
"resource": ""
} |
q235165 | OstreeTarget._checkout | train | def _checkout(self):
""" check out the image filesystem on self.mount_point """
cmd = ["atomic", "mount", "--storage", "ostree", self.ref_image_name, self.mount_point]
# self.mount_point has to be created by us
self._run_and_log(cmd, self.ostree_path,
"Failed to... | python | {
"resource": ""
} |
q235166 | OstreeTarget._run_and_log | train | def _run_and_log(cmd, ostree_repo_path, error_msg, wd=None):
""" run provided command and log all of its output; set path to ostree repo """
logger.debug("running command %s", cmd)
kwargs = {
"stderr": subprocess.STDOUT,
"env": os.environ.copy(),
}
if ostr... | python | {
"resource": ""
} |
q235167 | TodoistAPI.login_with_google | train | def login_with_google(self, email, oauth2_token, **kwargs):
"""Login to Todoist using Google's oauth2 authentication.
:param email: The user's Google email address.
:type email: str
:param oauth2_token: The user's Google oauth2 token.
:type oauth2_token: str
:param auto_... | python | {
"resource": ""
} |
q235168 | TodoistAPI.register | train | def register(self, email, full_name, password, **kwargs):
"""Register a new Todoist user.
:param email: The user's email.
:type email: str
:param full_name: The user's full name.
:type full_name: str
:param password: The user's password.
:type password: str
... | python | {
"resource": ""
} |
q235169 | TodoistAPI.delete_user | train | def delete_user(self, api_token, password, **kwargs):
"""Delete a registered Todoist user's account.
:param api_token: The user's login api_token.
:type api_token: str
:param password: The user's password.
:type password: str
:param reason_for_delete: The reason for dele... | python | {
"resource": ""
} |
q235170 | TodoistAPI.sync | train | def sync(self, api_token, sync_token, resource_types='["all"]', **kwargs):
"""Update and retrieve Todoist data.
:param api_token: The user's login api_token.
:type api_token: str
:param seq_no: The request sequence number. On initial request pass
``0``. On all others pass th... | python | {
"resource": ""
} |
q235171 | TodoistAPI.query | train | def query(self, api_token, queries, **kwargs):
"""Search all of a user's tasks using date, priority and label queries.
:param api_token: The user's login api_token.
:type api_token: str
:param queries: A JSON list of queries to search. See examples
`here <https://todoist.com... | python | {
"resource": ""
} |
q235172 | TodoistAPI.add_item | train | def add_item(self, api_token, content, **kwargs):
"""Add a task to a project.
:param token: The user's login token.
:type token: str
:param content: The task description.
:type content: str
:param project_id: The project to add the task to. Default is ``Inbox``
:... | python | {
"resource": ""
} |
q235173 | TodoistAPI.quick_add | train | def quick_add(self, api_token, text, **kwargs):
"""Add a task using the Todoist 'Quick Add Task' syntax.
:param api_token: The user's login api_token.
:type api_token: str
:param text: The text of the task that is parsed. A project
name starts with the `#` character, a label... | python | {
"resource": ""
} |
q235174 | TodoistAPI.get_all_completed_tasks | train | def get_all_completed_tasks(self, api_token, **kwargs):
"""Return a list of a user's completed tasks.
.. warning:: Requires Todoist premium.
:param api_token: The user's login api_token.
:type api_token: str
:param project_id: Filter the tasks by project.
:type project_... | python | {
"resource": ""
} |
q235175 | TodoistAPI.upload_file | train | def upload_file(self, api_token, file_path, **kwargs):
"""Upload a file suitable to be passed as a file_attachment.
:param api_token: The user's login api_token.
:type api_token: str
:param file_path: The path of the file to be uploaded.
:type file_path: str
:return: The... | python | {
"resource": ""
} |
q235176 | TodoistAPI.get_productivity_stats | train | def get_productivity_stats(self, api_token, **kwargs):
"""Return a user's productivity stats.
:param api_token: The user's login api_token.
:type api_token: str
:return: The HTTP response to the request.
:rtype: :class:`requests.Response`
"""
params = {
... | python | {
"resource": ""
} |
q235177 | TodoistAPI.update_notification_settings | train | def update_notification_settings(self, api_token, event,
service, should_notify):
"""Update a user's notification settings.
:param api_token: The user's login api_token.
:type api_token: str
:param event: Update the notification settings of this even... | python | {
"resource": ""
} |
q235178 | TodoistAPI._get | train | def _get(self, end_point, params=None, **kwargs):
"""Send a HTTP GET request to a Todoist API end-point.
:param end_point: The Todoist API end-point.
:type end_point: str
:param params: The required request parameters.
:type params: dict
:param kwargs: Any optional param... | python | {
"resource": ""
} |
q235179 | TodoistAPI._post | train | def _post(self, end_point, params=None, files=None, **kwargs):
"""Send a HTTP POST request to a Todoist API end-point.
:param end_point: The Todoist API end-point.
:type end_point: str
:param params: The required request parameters.
:type params: dict
:param files: Any f... | python | {
"resource": ""
} |
q235180 | TodoistAPI._request | train | def _request(self, req_func, end_point, params=None, files=None, **kwargs):
"""Send a HTTP request to a Todoist API end-point.
:param req_func: The request function to use e.g. get or post.
:type req_func: A request function from the :class:`requests` module.
:param end_point: The Todoi... | python | {
"resource": ""
} |
q235181 | login_with_api_token | train | def login_with_api_token(api_token):
"""Login to Todoist using a user's api token.
.. note:: It is up to you to obtain the api token.
:param api_token: A Todoist user's api token.
:type api_token: str
:return: The Todoist user.
:rtype: :class:`pytodoist.todoist.User`
>>> from pytodoist im... | python | {
"resource": ""
} |
q235182 | _login | train | def _login(login_func, *args):
"""A helper function for logging in. It's purpose is to avoid duplicate
code in the login functions.
"""
response = login_func(*args)
_fail_if_contains_errors(response)
user_json = response.json()
return User(user_json) | python | {
"resource": ""
} |
q235183 | register | train | def register(full_name, email, password, lang=None, timezone=None):
"""Register a new Todoist account.
:param full_name: The user's full name.
:type full_name: str
:param email: The user's email address.
:type email: str
:param password: The user's password.
:type password: str
:param l... | python | {
"resource": ""
} |
q235184 | register_with_google | train | def register_with_google(full_name, email, oauth2_token,
lang=None, timezone=None):
"""Register a new Todoist account by linking a Google account.
:param full_name: The user's full name.
:type full_name: str
:param email: The user's email address.
:type email: str
:para... | python | {
"resource": ""
} |
q235185 | _fail_if_contains_errors | train | def _fail_if_contains_errors(response, sync_uuid=None):
"""Raise a RequestError Exception if a given response
does not denote a successful request.
"""
if response.status_code != _HTTP_OK:
raise RequestError(response)
response_json = response.json()
if sync_uuid and 'sync_status' in resp... | python | {
"resource": ""
} |
q235186 | _perform_command | train | def _perform_command(user, command_type, command_args):
"""Perform an operation on Todoist using the API sync end-point."""
command_uuid = _gen_uuid()
command = {
'type': command_type,
'args': command_args,
'uuid': command_uuid,
'temp_id': _gen_uuid()
}
commands = jso... | python | {
"resource": ""
} |
q235187 | User.update | train | def update(self):
"""Update the user's details on Todoist.
This method must be called to register any local attribute changes
with Todoist.
>>> from pytodoist import todoist
>>> user = todoist.login('john.doe@gmail.com', 'password')
>>> user.full_name = 'John Smith'
... | python | {
"resource": ""
} |
q235188 | User.sync | train | def sync(self, resource_types='["all"]'):
"""Synchronize the user's data with the Todoist server.
This function will pull data from the Todoist server and update the
state of the user object such that they match. It does not *push* data
to Todoist. If you want to do that use
:fu... | python | {
"resource": ""
} |
q235189 | User._sync_projects | train | def _sync_projects(self, projects_json):
""""Populate the user's projects from a JSON encoded list."""
for project_json in projects_json:
project_id = project_json['id']
self.projects[project_id] = Project(project_json, self) | python | {
"resource": ""
} |
q235190 | User._sync_tasks | train | def _sync_tasks(self, tasks_json):
""""Populate the user's tasks from a JSON encoded list."""
for task_json in tasks_json:
task_id = task_json['id']
project_id = task_json['project_id']
if project_id not in self.projects:
# ignore orphan tasks
... | python | {
"resource": ""
} |
q235191 | User._sync_notes | train | def _sync_notes(self, notes_json):
""""Populate the user's notes from a JSON encoded list."""
for note_json in notes_json:
note_id = note_json['id']
task_id = note_json['item_id']
if task_id not in self.tasks:
# ignore orphan notes
cont... | python | {
"resource": ""
} |
q235192 | User._sync_labels | train | def _sync_labels(self, labels_json):
""""Populate the user's labels from a JSON encoded list."""
for label_json in labels_json:
label_id = label_json['id']
self.labels[label_id] = Label(label_json, self) | python | {
"resource": ""
} |
q235193 | User._sync_filters | train | def _sync_filters(self, filters_json):
""""Populate the user's filters from a JSON encoded list."""
for filter_json in filters_json:
filter_id = filter_json['id']
self.filters[filter_id] = Filter(filter_json, self) | python | {
"resource": ""
} |
q235194 | User._sync_reminders | train | def _sync_reminders(self, reminders_json):
""""Populate the user's reminders from a JSON encoded list."""
for reminder_json in reminders_json:
reminder_id = reminder_json['id']
task_id = reminder_json['item_id']
if task_id not in self.tasks:
# ignore o... | python | {
"resource": ""
} |
q235195 | User.quick_add | train | def quick_add(self, text, note=None, reminder=None):
"""Add a task using the 'Quick Add Task' syntax.
:param text: The text of the task that is parsed. A project
name starts with the `#` character, a label starts with a `@`
and an assignee starts with a `+`.
:type text: ... | python | {
"resource": ""
} |
q235196 | User.add_project | train | def add_project(self, name, color=None, indent=None, order=None):
"""Add a project to the user's account.
:param name: The project name.
:type name: str
:return: The project that was added.
:rtype: :class:`pytodoist.todoist.Project`
>>> from pytodoist import todoist
... | python | {
"resource": ""
} |
q235197 | User.get_project | train | def get_project(self, project_name):
"""Return the project with a given name.
:param project_name: The name to search for.
:type project_name: str
:return: The project that has the name ``project_name`` or ``None``
if no project is found.
:rtype: :class:`pytodoist.to... | python | {
"resource": ""
} |
q235198 | User.get_uncompleted_tasks | train | def get_uncompleted_tasks(self):
"""Return all of a user's uncompleted tasks.
.. warning:: Requires Todoist premium.
:return: A list of uncompleted tasks.
:rtype: list of :class:`pytodoist.todoist.Task`
>>> from pytodoist import todoist
>>> user = todoist.login('john.d... | python | {
"resource": ""
} |
q235199 | User.search_tasks | train | def search_tasks(self, *queries):
"""Return a list of tasks that match some search criteria.
.. note:: Example queries can be found
`here <https://todoist.com/Help/timeQuery>`_.
.. note:: A standard set of queries are available
in the :class:`pytodoist.todoist.Query` cl... | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.