id int32 0 252k | repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 51 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 |
|---|---|---|---|---|---|---|---|---|---|---|---|
20,000 | Hrabal/TemPy | tempy/elements.py | Tag.remove_attr | def remove_attr(self, attr):
"""Removes an attribute."""
self._stable = False
self.attrs.pop(attr, None)
return self | python | def remove_attr(self, attr):
self._stable = False
self.attrs.pop(attr, None)
return self | [
"def",
"remove_attr",
"(",
"self",
",",
"attr",
")",
":",
"self",
".",
"_stable",
"=",
"False",
"self",
".",
"attrs",
".",
"pop",
"(",
"attr",
",",
"None",
")",
"return",
"self"
] | Removes an attribute. | [
"Removes",
"an",
"attribute",
"."
] | 7d229b73e2ce3ccbb8254deae05c1f758f626ed6 | https://github.com/Hrabal/TemPy/blob/7d229b73e2ce3ccbb8254deae05c1f758f626ed6/tempy/elements.py#L88-L92 |
20,001 | Hrabal/TemPy | tempy/elements.py | Tag.render_attrs | 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))
else:
fnc = self._FORMAT_ATTRS.get(k, None)
val = fnc(v) if fnc else v
ret.append(' %s="%s"' % (self._SPECIAL_ATTRS.get(k, k), val))
return "".join(ret) | python | def render_attrs(self):
ret = []
for k, v in self.attrs.items():
if v:
if v is bool:
ret.append(" %s" % self._SPECIAL_ATTRS.get(k, k))
else:
fnc = self._FORMAT_ATTRS.get(k, None)
val = fnc(v) if fnc else v
ret.append(' %s="%s"' % (self._SPECIAL_ATTRS.get(k, k), val))
return "".join(ret) | [
"def",
"render_attrs",
"(",
"self",
")",
":",
"ret",
"=",
"[",
"]",
"for",
"k",
",",
"v",
"in",
"self",
".",
"attrs",
".",
"items",
"(",
")",
":",
"if",
"v",
":",
"if",
"v",
"is",
"bool",
":",
"ret",
".",
"append",
"(",
"\" %s\"",
"%",
"self"... | Renders the tag's attributes using the formats and performing special attributes name substitution. | [
"Renders",
"the",
"tag",
"s",
"attributes",
"using",
"the",
"formats",
"and",
"performing",
"special",
"attributes",
"name",
"substitution",
"."
] | 7d229b73e2ce3ccbb8254deae05c1f758f626ed6 | https://github.com/Hrabal/TemPy/blob/7d229b73e2ce3ccbb8254deae05c1f758f626ed6/tempy/elements.py#L94-L105 |
20,002 | Hrabal/TemPy | tempy/elements.py | Tag.toggle_class | 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 | def toggle_class(self, csscl):
self._stable = False
action = ("add", "remove")[self.has_class(csscl)]
return getattr(self.attrs["klass"], action)(csscl) | [
"def",
"toggle_class",
"(",
"self",
",",
"csscl",
")",
":",
"self",
".",
"_stable",
"=",
"False",
"action",
"=",
"(",
"\"add\"",
",",
"\"remove\"",
")",
"[",
"self",
".",
"has_class",
"(",
"csscl",
")",
"]",
"return",
"getattr",
"(",
"self",
".",
"at... | Same as jQuery's toggleClass function. It toggles the css class on this element. | [
"Same",
"as",
"jQuery",
"s",
"toggleClass",
"function",
".",
"It",
"toggles",
"the",
"css",
"class",
"on",
"this",
"element",
"."
] | 7d229b73e2ce3ccbb8254deae05c1f758f626ed6 | https://github.com/Hrabal/TemPy/blob/7d229b73e2ce3ccbb8254deae05c1f758f626ed6/tempy/elements.py#L137-L141 |
20,003 | Hrabal/TemPy | tempy/elements.py | Tag.add_class | 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 | def add_class(self, cssclass):
if self.has_class(cssclass):
return self
return self.toggle_class(cssclass) | [
"def",
"add_class",
"(",
"self",
",",
"cssclass",
")",
":",
"if",
"self",
".",
"has_class",
"(",
"cssclass",
")",
":",
"return",
"self",
"return",
"self",
".",
"toggle_class",
"(",
"cssclass",
")"
] | Adds a css class to this element. | [
"Adds",
"a",
"css",
"class",
"to",
"this",
"element",
"."
] | 7d229b73e2ce3ccbb8254deae05c1f758f626ed6 | https://github.com/Hrabal/TemPy/blob/7d229b73e2ce3ccbb8254deae05c1f758f626ed6/tempy/elements.py#L143-L147 |
20,004 | Hrabal/TemPy | tempy/elements.py | Tag.remove_class | 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 | def remove_class(self, cssclass):
if not self.has_class(cssclass):
return self
return self.toggle_class(cssclass) | [
"def",
"remove_class",
"(",
"self",
",",
"cssclass",
")",
":",
"if",
"not",
"self",
".",
"has_class",
"(",
"cssclass",
")",
":",
"return",
"self",
"return",
"self",
".",
"toggle_class",
"(",
"cssclass",
")"
] | Removes the given class from this element. | [
"Removes",
"the",
"given",
"class",
"from",
"this",
"element",
"."
] | 7d229b73e2ce3ccbb8254deae05c1f758f626ed6 | https://github.com/Hrabal/TemPy/blob/7d229b73e2ce3ccbb8254deae05c1f758f626ed6/tempy/elements.py#L149-L153 |
20,005 | Hrabal/TemPy | tempy/elements.py | Tag.css | 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, props, "Arguments not valid")
elif kwprops:
styles = kwprops
else:
raise WrongContentError(self, None, "args OR wkargs are needed")
return self.attr(style=styles) | python | def css(self, *props, **kwprops):
self._stable = False
styles = {}
if props:
if len(props) == 1 and isinstance(props[0], Mapping):
styles = props[0]
else:
raise WrongContentError(self, props, "Arguments not valid")
elif kwprops:
styles = kwprops
else:
raise WrongContentError(self, None, "args OR wkargs are needed")
return self.attr(style=styles) | [
"def",
"css",
"(",
"self",
",",
"*",
"props",
",",
"*",
"*",
"kwprops",
")",
":",
"self",
".",
"_stable",
"=",
"False",
"styles",
"=",
"{",
"}",
"if",
"props",
":",
"if",
"len",
"(",
"props",
")",
"==",
"1",
"and",
"isinstance",
"(",
"props",
"... | Adds css properties to this element. | [
"Adds",
"css",
"properties",
"to",
"this",
"element",
"."
] | 7d229b73e2ce3ccbb8254deae05c1f758f626ed6 | https://github.com/Hrabal/TemPy/blob/7d229b73e2ce3ccbb8254deae05c1f758f626ed6/tempy/elements.py#L155-L168 |
20,006 | Hrabal/TemPy | tempy/elements.py | Tag.show | 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 | def show(self, display=None):
self._stable = False
if not display:
self.attrs["style"].pop("display")
else:
self.attrs["style"]["display"] = display
return self | [
"def",
"show",
"(",
"self",
",",
"display",
"=",
"None",
")",
":",
"self",
".",
"_stable",
"=",
"False",
"if",
"not",
"display",
":",
"self",
".",
"attrs",
"[",
"\"style\"",
"]",
".",
"pop",
"(",
"\"display\"",
")",
"else",
":",
"self",
".",
"attrs... | Removes the display style attribute.
If a display type is provided | [
"Removes",
"the",
"display",
"style",
"attribute",
".",
"If",
"a",
"display",
"type",
"is",
"provided"
] | 7d229b73e2ce3ccbb8254deae05c1f758f626ed6 | https://github.com/Hrabal/TemPy/blob/7d229b73e2ce3ccbb8254deae05c1f758f626ed6/tempy/elements.py#L176-L184 |
20,007 | Hrabal/TemPy | tempy/elements.py | Tag.toggle | 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 | def toggle(self):
self._stable = False
return self.show() if self.attrs["style"]["display"] == "none" else self.hide() | [
"def",
"toggle",
"(",
"self",
")",
":",
"self",
".",
"_stable",
"=",
"False",
"return",
"self",
".",
"show",
"(",
")",
"if",
"self",
".",
"attrs",
"[",
"\"style\"",
"]",
"[",
"\"display\"",
"]",
"==",
"\"none\"",
"else",
"self",
".",
"hide",
"(",
"... | Same as jQuery's toggle, toggles the display attribute of this element. | [
"Same",
"as",
"jQuery",
"s",
"toggle",
"toggles",
"the",
"display",
"attribute",
"of",
"this",
"element",
"."
] | 7d229b73e2ce3ccbb8254deae05c1f758f626ed6 | https://github.com/Hrabal/TemPy/blob/7d229b73e2ce3ccbb8254deae05c1f758f626ed6/tempy/elements.py#L186-L189 |
20,008 | Hrabal/TemPy | tempy/elements.py | Tag.text | 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())
else:
texts.append(child)
return " ".join(texts) | python | def text(self):
texts = []
for child in self.childs:
if isinstance(child, Tag):
texts.append(child.text())
elif isinstance(child, Content):
texts.append(child.render())
else:
texts.append(child)
return " ".join(texts) | [
"def",
"text",
"(",
"self",
")",
":",
"texts",
"=",
"[",
"]",
"for",
"child",
"in",
"self",
".",
"childs",
":",
"if",
"isinstance",
"(",
"child",
",",
"Tag",
")",
":",
"texts",
".",
"append",
"(",
"child",
".",
"text",
"(",
")",
")",
"elif",
"i... | Renders the contents inside this element, without html tags. | [
"Renders",
"the",
"contents",
"inside",
"this",
"element",
"without",
"html",
"tags",
"."
] | 7d229b73e2ce3ccbb8254deae05c1f758f626ed6 | https://github.com/Hrabal/TemPy/blob/7d229b73e2ce3ccbb8254deae05c1f758f626ed6/tempy/elements.py#L195-L205 |
20,009 | Hrabal/TemPy | tempy/elements.py | Tag.render | 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._stable = False
for arg in args:
self._stable = False
if isinstance(arg, dict):
self.inject(arg)
if kwargs:
self._stable = False
self.inject(kwargs)
# If the tag or his contents are not changed and we already have rendered it
# with the same attrs we skip all the work
if self._stable and self._render:
return self._render
pretty_pre = pretty_inner = ""
if pretty:
pretty_pre = "\n" + ("\t" * self._depth) if pretty else ""
pretty_inner = "\n" + ("\t" * self._depth) if len(self.childs) > 1 else ""
inner = self.render_childs(pretty) if not self._void else ""
# We declare the tag is stable and have an official render:
tag_data = (
pretty_pre,
self._get__tag(),
self.render_attrs(),
inner,
pretty_inner,
self._get__tag()
)[: 6 - [0, 3][self._void]]
self._render = self._template % tag_data
self._stable = "pretty" if pretty else True
return self._render | python | def render(self, *args, **kwargs):
# 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._stable = False
for arg in args:
self._stable = False
if isinstance(arg, dict):
self.inject(arg)
if kwargs:
self._stable = False
self.inject(kwargs)
# If the tag or his contents are not changed and we already have rendered it
# with the same attrs we skip all the work
if self._stable and self._render:
return self._render
pretty_pre = pretty_inner = ""
if pretty:
pretty_pre = "\n" + ("\t" * self._depth) if pretty else ""
pretty_inner = "\n" + ("\t" * self._depth) if len(self.childs) > 1 else ""
inner = self.render_childs(pretty) if not self._void else ""
# We declare the tag is stable and have an official render:
tag_data = (
pretty_pre,
self._get__tag(),
self.render_attrs(),
inner,
pretty_inner,
self._get__tag()
)[: 6 - [0, 3][self._void]]
self._render = self._template % tag_data
self._stable = "pretty" if pretty else True
return self._render | [
"def",
"render",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# args kwargs API provided for last minute content injection",
"# self._reverse_mro_func('pre_render')",
"pretty",
"=",
"kwargs",
".",
"pop",
"(",
"\"pretty\"",
",",
"False",
")",
"i... | Renders the element and all his childrens. | [
"Renders",
"the",
"element",
"and",
"all",
"his",
"childrens",
"."
] | 7d229b73e2ce3ccbb8254deae05c1f758f626ed6 | https://github.com/Hrabal/TemPy/blob/7d229b73e2ce3ccbb8254deae05c1f758f626ed6/tempy/elements.py#L207-L245 |
20,010 | Hrabal/TemPy | tempy/t.py | TempyParser._make_tempy_tag | 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.unknown_tag_maker, self.unknown_tag_maker.Void][void]
tempy_tag_cls = unknow_maker[tag]
attrs = {Tag._TO_SPECIALS.get(k, k): v or True for k, v in attrs}
tempy_tag = tempy_tag_cls(**attrs)
if not self.current_tag:
self.result.append(tempy_tag)
if not void:
self.current_tag = tempy_tag
else:
if not tempy_tag._void:
self.current_tag(tempy_tag)
self.current_tag = self.current_tag.childs[-1] | python | def _make_tempy_tag(self, tag, attrs, void):
tempy_tag_cls = getattr(self.tempy_tags, tag.title(), None)
if not tempy_tag_cls:
unknow_maker = [self.unknown_tag_maker, self.unknown_tag_maker.Void][void]
tempy_tag_cls = unknow_maker[tag]
attrs = {Tag._TO_SPECIALS.get(k, k): v or True for k, v in attrs}
tempy_tag = tempy_tag_cls(**attrs)
if not self.current_tag:
self.result.append(tempy_tag)
if not void:
self.current_tag = tempy_tag
else:
if not tempy_tag._void:
self.current_tag(tempy_tag)
self.current_tag = self.current_tag.childs[-1] | [
"def",
"_make_tempy_tag",
"(",
"self",
",",
"tag",
",",
"attrs",
",",
"void",
")",
":",
"tempy_tag_cls",
"=",
"getattr",
"(",
"self",
".",
"tempy_tags",
",",
"tag",
".",
"title",
"(",
")",
",",
"None",
")",
"if",
"not",
"tempy_tag_cls",
":",
"unknow_ma... | Searches in tempy.tags for the correct tag to use, if does not exists uses the TempyFactory to
create a custom tag. | [
"Searches",
"in",
"tempy",
".",
"tags",
"for",
"the",
"correct",
"tag",
"to",
"use",
"if",
"does",
"not",
"exists",
"uses",
"the",
"TempyFactory",
"to",
"create",
"a",
"custom",
"tag",
"."
] | 7d229b73e2ce3ccbb8254deae05c1f758f626ed6 | https://github.com/Hrabal/TemPy/blob/7d229b73e2ce3ccbb8254deae05c1f758f626ed6/tempy/t.py#L33-L49 |
20,011 | Hrabal/TemPy | tempy/t.py | TempyGod.from_string | 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 | def from_string(self, html_string):
self._html_parser._reset().feed(html_string)
return self._html_parser.result | [
"def",
"from_string",
"(",
"self",
",",
"html_string",
")",
":",
"self",
".",
"_html_parser",
".",
"_reset",
"(",
")",
".",
"feed",
"(",
"html_string",
")",
"return",
"self",
".",
"_html_parser",
".",
"result"
] | Parses an html string and returns a list of Tempy trees. | [
"Parses",
"an",
"html",
"string",
"and",
"returns",
"a",
"list",
"of",
"Tempy",
"trees",
"."
] | 7d229b73e2ce3ccbb8254deae05c1f758f626ed6 | https://github.com/Hrabal/TemPy/blob/7d229b73e2ce3ccbb8254deae05c1f758f626ed6/tempy/t.py#L104-L107 |
20,012 | Hrabal/TemPy | tempy/t.py | TempyGod.dump | 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(
'"filename" argument should have a .py extension, if given.'
)
if not filename.endswith(".py"):
filename += ".py"
with open(filename, "w") as f:
f.write(
"# -*- coding: utf-8 -*-\nfrom tempy import T\nfrom tempy.tags import *\n"
)
for tempy_tree in tempy_tree_list:
f.write(tempy_tree.to_code(pretty=pretty))
return filename | python | def dump(self, tempy_tree_list, filename, pretty=False):
if not filename:
raise ValueError('"filename" argument should not be none.')
if len(filename.split(".")) > 1 and not filename.endswith(".py"):
raise ValueError(
'"filename" argument should have a .py extension, if given.'
)
if not filename.endswith(".py"):
filename += ".py"
with open(filename, "w") as f:
f.write(
"# -*- coding: utf-8 -*-\nfrom tempy import T\nfrom tempy.tags import *\n"
)
for tempy_tree in tempy_tree_list:
f.write(tempy_tree.to_code(pretty=pretty))
return filename | [
"def",
"dump",
"(",
"self",
",",
"tempy_tree_list",
",",
"filename",
",",
"pretty",
"=",
"False",
")",
":",
"if",
"not",
"filename",
":",
"raise",
"ValueError",
"(",
"'\"filename\" argument should not be none.'",
")",
"if",
"len",
"(",
"filename",
".",
"split"... | Dumps a Tempy object to a python file | [
"Dumps",
"a",
"Tempy",
"object",
"to",
"a",
"python",
"file"
] | 7d229b73e2ce3ccbb8254deae05c1f758f626ed6 | https://github.com/Hrabal/TemPy/blob/7d229b73e2ce3ccbb8254deae05c1f758f626ed6/tempy/t.py#L113-L129 |
20,013 | Hrabal/TemPy | tempy/tempyrepr.py | _filter_classes | 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 cls | python | def _filter_classes(cls_list, cls_type):
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 cls | [
"def",
"_filter_classes",
"(",
"cls_list",
",",
"cls_type",
")",
":",
"for",
"cls",
"in",
"cls_list",
":",
"if",
"isinstance",
"(",
"cls",
",",
"type",
")",
"and",
"issubclass",
"(",
"cls",
",",
"cls_type",
")",
":",
"if",
"cls_type",
"==",
"TempyPlace",... | Filters a list of classes and yields TempyREPR subclasses | [
"Filters",
"a",
"list",
"of",
"classes",
"and",
"yields",
"TempyREPR",
"subclasses"
] | 7d229b73e2ce3ccbb8254deae05c1f758f626ed6 | https://github.com/Hrabal/TemPy/blob/7d229b73e2ce3ccbb8254deae05c1f758f626ed6/tempy/tempyrepr.py#L10-L17 |
20,014 | Hrabal/TemPy | tempy/tempyrepr.py | REPRFinder._evaluate_tempyREPR | 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 have the same name of the container
score += 1
elif repr_cls.__name__ == self.root.__class__.__name__:
# One point if the REPR have the same name of the Tempy tree root
score += 1
# Add points defined in scorers methods of used TempyPlaces
for parent_cls in _filter_classes(repr_cls.__mro__[1:], TempyPlace):
for scorer in (
method for method in dir(parent_cls) if method.startswith("_reprscore")
):
score += getattr(parent_cls, scorer, lambda *args: 0)(
parent_cls, self, child
)
return score | python | def _evaluate_tempyREPR(self, child, repr_cls):
score = 0
if repr_cls.__name__ == self.__class__.__name__:
# One point if the REPR have the same name of the container
score += 1
elif repr_cls.__name__ == self.root.__class__.__name__:
# One point if the REPR have the same name of the Tempy tree root
score += 1
# Add points defined in scorers methods of used TempyPlaces
for parent_cls in _filter_classes(repr_cls.__mro__[1:], TempyPlace):
for scorer in (
method for method in dir(parent_cls) if method.startswith("_reprscore")
):
score += getattr(parent_cls, scorer, lambda *args: 0)(
parent_cls, self, child
)
return score | [
"def",
"_evaluate_tempyREPR",
"(",
"self",
",",
"child",
",",
"repr_cls",
")",
":",
"score",
"=",
"0",
"if",
"repr_cls",
".",
"__name__",
"==",
"self",
".",
"__class__",
".",
"__name__",
":",
"# One point if the REPR have the same name of the container",
"score",
... | 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. | [
"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",
"."
] | 7d229b73e2ce3ccbb8254deae05c1f758f626ed6 | https://github.com/Hrabal/TemPy/blob/7d229b73e2ce3ccbb8254deae05c1f758f626ed6/tempy/tempyrepr.py#L23-L42 |
20,015 | Hrabal/TemPy | tempy/tempyrepr.py | REPRFinder._search_for_view | 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)
sorted_reprs = sorted(
_filter_classes(obj.__class__.__dict__.values(), TempyREPR),
key=evaluator,
reverse=True,
)
if sorted_reprs:
# If we find some TempyREPR, we return the one with the best score.
return sorted_reprs[0]
return None | python | def _search_for_view(self, obj):
evaluator = partial(self._evaluate_tempyREPR, obj)
sorted_reprs = sorted(
_filter_classes(obj.__class__.__dict__.values(), TempyREPR),
key=evaluator,
reverse=True,
)
if sorted_reprs:
# If we find some TempyREPR, we return the one with the best score.
return sorted_reprs[0]
return None | [
"def",
"_search_for_view",
"(",
"self",
",",
"obj",
")",
":",
"evaluator",
"=",
"partial",
"(",
"self",
".",
"_evaluate_tempyREPR",
",",
"obj",
")",
"sorted_reprs",
"=",
"sorted",
"(",
"_filter_classes",
"(",
"obj",
".",
"__class__",
".",
"__dict__",
".",
... | 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. | [
"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",
"... | 7d229b73e2ce3ccbb8254deae05c1f758f626ed6 | https://github.com/Hrabal/TemPy/blob/7d229b73e2ce3ccbb8254deae05c1f758f626ed6/tempy/tempyrepr.py#L44-L58 |
20,016 | Hrabal/TemPy | tempy/widgets.py | TempyTable.add_row | 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 | def add_row(self, row_data, resize_x=True):
if not resize_x:
self._check_row_size(row_data)
self.body(Tr()(Td()(cell) for cell in row_data))
return self | [
"def",
"add_row",
"(",
"self",
",",
"row_data",
",",
"resize_x",
"=",
"True",
")",
":",
"if",
"not",
"resize_x",
":",
"self",
".",
"_check_row_size",
"(",
"row_data",
")",
"self",
".",
"body",
"(",
"Tr",
"(",
")",
"(",
"Td",
"(",
")",
"(",
"cell",
... | Adds a row at the end of the table | [
"Adds",
"a",
"row",
"at",
"the",
"end",
"of",
"the",
"table"
] | 7d229b73e2ce3ccbb8254deae05c1f758f626ed6 | https://github.com/Hrabal/TemPy/blob/7d229b73e2ce3ccbb8254deae05c1f758f626ed6/tempy/widgets.py#L174-L179 |
20,017 | Hrabal/TemPy | tempy/widgets.py | TempyTable.pop_row | 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 | def pop_row(self, idr=None, tags=False):
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] | [
"def",
"pop_row",
"(",
"self",
",",
"idr",
"=",
"None",
",",
"tags",
"=",
"False",
")",
":",
"idr",
"=",
"idr",
"if",
"idr",
"is",
"not",
"None",
"else",
"len",
"(",
"self",
".",
"body",
")",
"-",
"1",
"row",
"=",
"self",
".",
"body",
".",
"p... | Pops a row, default the last | [
"Pops",
"a",
"row",
"default",
"the",
"last"
] | 7d229b73e2ce3ccbb8254deae05c1f758f626ed6 | https://github.com/Hrabal/TemPy/blob/7d229b73e2ce3ccbb8254deae05c1f758f626ed6/tempy/widgets.py#L181-L185 |
20,018 | Hrabal/TemPy | tempy/widgets.py | TempyTable.pop_cell | 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.childs[0] | python | def pop_cell(self, idy=None, idx=None, tags=False):
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.childs[0] | [
"def",
"pop_cell",
"(",
"self",
",",
"idy",
"=",
"None",
",",
"idx",
"=",
"None",
",",
"tags",
"=",
"False",
")",
":",
"idy",
"=",
"idy",
"if",
"idy",
"is",
"not",
"None",
"else",
"len",
"(",
"self",
".",
"body",
")",
"-",
"1",
"idx",
"=",
"i... | Pops a cell, default the last of the last row | [
"Pops",
"a",
"cell",
"default",
"the",
"last",
"of",
"the",
"last",
"row"
] | 7d229b73e2ce3ccbb8254deae05c1f758f626ed6 | https://github.com/Hrabal/TemPy/blob/7d229b73e2ce3ccbb8254deae05c1f758f626ed6/tempy/widgets.py#L187-L192 |
20,019 | Hrabal/TemPy | tempy/tags.py | Html.render | def render(self, *args, **kwargs):
"""Override so each html page served have a doctype"""
return self.doctype.render() + super().render(*args, **kwargs) | python | def render(self, *args, **kwargs):
return self.doctype.render() + super().render(*args, **kwargs) | [
"def",
"render",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"doctype",
".",
"render",
"(",
")",
"+",
"super",
"(",
")",
".",
"render",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | Override so each html page served have a doctype | [
"Override",
"so",
"each",
"html",
"page",
"served",
"have",
"a",
"doctype"
] | 7d229b73e2ce3ccbb8254deae05c1f758f626ed6 | https://github.com/Hrabal/TemPy/blob/7d229b73e2ce3ccbb8254deae05c1f758f626ed6/tempy/tags.py#L71-L73 |
20,020 | Hrabal/TemPy | tempy/tempy.py | DOMNavigator._find_content | 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_name)
else:
# Fallback for no content (Raise NoContent?)
return "" | python | def _find_content(self, cont_name):
try:
a = self.content_data[cont_name]
return a
except KeyError:
if self.parent:
return self.parent._find_content(cont_name)
else:
# Fallback for no content (Raise NoContent?)
return "" | [
"def",
"_find_content",
"(",
"self",
",",
"cont_name",
")",
":",
"try",
":",
"a",
"=",
"self",
".",
"content_data",
"[",
"cont_name",
"]",
"return",
"a",
"except",
"KeyError",
":",
"if",
"self",
".",
"parent",
":",
"return",
"self",
".",
"parent",
".",... | Search for a content_name in the content data, if not found the parent is searched. | [
"Search",
"for",
"a",
"content_name",
"in",
"the",
"content",
"data",
"if",
"not",
"found",
"the",
"parent",
"is",
"searched",
"."
] | 7d229b73e2ce3ccbb8254deae05c1f758f626ed6 | https://github.com/Hrabal/TemPy/blob/7d229b73e2ce3ccbb8254deae05c1f758f626ed6/tempy/tempy.py#L26-L36 |
20,021 | Hrabal/TemPy | tempy/tempy.py | DOMNavigator._get_non_tempy_contents | 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 | def _get_non_tempy_contents(self):
for thing in filter(
lambda x: not issubclass(x.__class__, DOMElement), self.childs
):
yield thing | [
"def",
"_get_non_tempy_contents",
"(",
"self",
")",
":",
"for",
"thing",
"in",
"filter",
"(",
"lambda",
"x",
":",
"not",
"issubclass",
"(",
"x",
".",
"__class__",
",",
"DOMElement",
")",
",",
"self",
".",
"childs",
")",
":",
"yield",
"thing"
] | Returns rendered Contents and non-DOMElement stuff inside this Tag. | [
"Returns",
"rendered",
"Contents",
"and",
"non",
"-",
"DOMElement",
"stuff",
"inside",
"this",
"Tag",
"."
] | 7d229b73e2ce3ccbb8254deae05c1f758f626ed6 | https://github.com/Hrabal/TemPy/blob/7d229b73e2ce3ccbb8254deae05c1f758f626ed6/tempy/tempy.py#L38-L43 |
20,022 | Hrabal/TemPy | tempy/tempy.py | DOMNavigator.siblings | 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 | def siblings(self):
return list(filter(lambda x: id(x) != id(self), self.parent.childs)) | [
"def",
"siblings",
"(",
"self",
")",
":",
"return",
"list",
"(",
"filter",
"(",
"lambda",
"x",
":",
"id",
"(",
"x",
")",
"!=",
"id",
"(",
"self",
")",
",",
"self",
".",
"parent",
".",
"childs",
")",
")"
] | Returns all the siblings of this element as a list. | [
"Returns",
"all",
"the",
"siblings",
"of",
"this",
"element",
"as",
"a",
"list",
"."
] | 7d229b73e2ce3ccbb8254deae05c1f758f626ed6 | https://github.com/Hrabal/TemPy/blob/7d229b73e2ce3ccbb8254deae05c1f758f626ed6/tempy/tempy.py#L129-L131 |
20,023 | Hrabal/TemPy | tempy/tempy.py | DOMNavigator.bft | 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 | def bft(self):
queue = deque([self])
while queue:
node = queue.pop()
yield node
if hasattr(node, "childs"):
queue.extendleft(node.childs) | [
"def",
"bft",
"(",
"self",
")",
":",
"queue",
"=",
"deque",
"(",
"[",
"self",
"]",
")",
"while",
"queue",
":",
"node",
"=",
"queue",
".",
"pop",
"(",
")",
"yield",
"node",
"if",
"hasattr",
"(",
"node",
",",
"\"childs\"",
")",
":",
"queue",
".",
... | Generator that returns each element of the tree in Breadth-first order | [
"Generator",
"that",
"returns",
"each",
"element",
"of",
"the",
"tree",
"in",
"Breadth",
"-",
"first",
"order"
] | 7d229b73e2ce3ccbb8254deae05c1f758f626ed6 | https://github.com/Hrabal/TemPy/blob/7d229b73e2ce3ccbb8254deae05c1f758f626ed6/tempy/tempy.py#L141-L148 |
20,024 | Hrabal/TemPy | tempy/tempy.py | DOMModifier._insert | 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 name, an attribute containing the child is created in this instance.
"""
if idx and idx < 0:
idx = 0
if prepend:
idx = 0
else:
idx = idx if idx is not None else len(self.childs)
if dom_group is not None:
if not isinstance(dom_group, Iterable) or isinstance(
dom_group, (DOMElement, str)
):
dom_group = [dom_group]
for i_group, elem in enumerate(dom_group):
if elem is not None:
# Element insertion in this DOMElement childs
self.childs.insert(idx + i_group, elem)
# Managing child attributes if needed
if issubclass(elem.__class__, DOMElement):
elem.parent = self
if name:
setattr(self, name, elem) | python | def _insert(self, dom_group, idx=None, prepend=False, name=None):
if idx and idx < 0:
idx = 0
if prepend:
idx = 0
else:
idx = idx if idx is not None else len(self.childs)
if dom_group is not None:
if not isinstance(dom_group, Iterable) or isinstance(
dom_group, (DOMElement, str)
):
dom_group = [dom_group]
for i_group, elem in enumerate(dom_group):
if elem is not None:
# Element insertion in this DOMElement childs
self.childs.insert(idx + i_group, elem)
# Managing child attributes if needed
if issubclass(elem.__class__, DOMElement):
elem.parent = self
if name:
setattr(self, name, elem) | [
"def",
"_insert",
"(",
"self",
",",
"dom_group",
",",
"idx",
"=",
"None",
",",
"prepend",
"=",
"False",
",",
"name",
"=",
"None",
")",
":",
"if",
"idx",
"and",
"idx",
"<",
"0",
":",
"idx",
"=",
"0",
"if",
"prepend",
":",
"idx",
"=",
"0",
"else"... | 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 name, an attribute containing the child is created in this instance. | [
"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",
"... | 7d229b73e2ce3ccbb8254deae05c1f758f626ed6 | https://github.com/Hrabal/TemPy/blob/7d229b73e2ce3ccbb8254deae05c1f758f626ed6/tempy/tempy.py#L245-L270 |
20,025 | Hrabal/TemPy | tempy/tempy.py | DOMModifier.after | 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 | def after(self, i, sibling, name=None):
self.parent._insert(sibling, idx=self._own_index + 1 + i, name=name)
return self | [
"def",
"after",
"(",
"self",
",",
"i",
",",
"sibling",
",",
"name",
"=",
"None",
")",
":",
"self",
".",
"parent",
".",
"_insert",
"(",
"sibling",
",",
"idx",
"=",
"self",
".",
"_own_index",
"+",
"1",
"+",
"i",
",",
"name",
"=",
"name",
")",
"re... | Adds siblings after the current tag. | [
"Adds",
"siblings",
"after",
"the",
"current",
"tag",
"."
] | 7d229b73e2ce3ccbb8254deae05c1f758f626ed6 | https://github.com/Hrabal/TemPy/blob/7d229b73e2ce3ccbb8254deae05c1f758f626ed6/tempy/tempy.py#L317-L320 |
20,026 | Hrabal/TemPy | tempy/tempy.py | DOMModifier.prepend | 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 | def prepend(self, _, child, name=None):
self._insert(child, prepend=True, name=name)
return self | [
"def",
"prepend",
"(",
"self",
",",
"_",
",",
"child",
",",
"name",
"=",
"None",
")",
":",
"self",
".",
"_insert",
"(",
"child",
",",
"prepend",
"=",
"True",
",",
"name",
"=",
"name",
")",
"return",
"self"
] | Adds childs to this tag, starting from the first position. | [
"Adds",
"childs",
"to",
"this",
"tag",
"starting",
"from",
"the",
"first",
"position",
"."
] | 7d229b73e2ce3ccbb8254deae05c1f758f626ed6 | https://github.com/Hrabal/TemPy/blob/7d229b73e2ce3ccbb8254deae05c1f758f626ed6/tempy/tempy.py#L329-L332 |
20,027 | Hrabal/TemPy | tempy/tempy.py | DOMModifier.append | def append(self, _, child, name=None):
"""Adds childs to this tag, after the current existing childs."""
self._insert(child, name=name)
return self | python | def append(self, _, child, name=None):
self._insert(child, name=name)
return self | [
"def",
"append",
"(",
"self",
",",
"_",
",",
"child",
",",
"name",
"=",
"None",
")",
":",
"self",
".",
"_insert",
"(",
"child",
",",
"name",
"=",
"name",
")",
"return",
"self"
] | Adds childs to this tag, after the current existing childs. | [
"Adds",
"childs",
"to",
"this",
"tag",
"after",
"the",
"current",
"existing",
"childs",
"."
] | 7d229b73e2ce3ccbb8254deae05c1f758f626ed6 | https://github.com/Hrabal/TemPy/blob/7d229b73e2ce3ccbb8254deae05c1f758f626ed6/tempy/tempy.py#L340-L343 |
20,028 | Hrabal/TemPy | tempy/tempy.py | DOMModifier.wrap | 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)
return self | python | def wrap(self, other):
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)
return self | [
"def",
"wrap",
"(",
"self",
",",
"other",
")",
":",
"if",
"other",
".",
"childs",
":",
"raise",
"TagError",
"(",
"self",
",",
"\"Wrapping in a non empty Tag is forbidden.\"",
")",
"if",
"self",
".",
"parent",
":",
"self",
".",
"before",
"(",
"other",
")",
... | Wraps this element inside another empty tag. | [
"Wraps",
"this",
"element",
"inside",
"another",
"empty",
"tag",
"."
] | 7d229b73e2ce3ccbb8254deae05c1f758f626ed6 | https://github.com/Hrabal/TemPy/blob/7d229b73e2ce3ccbb8254deae05c1f758f626ed6/tempy/tempy.py#L350-L358 |
20,029 | Hrabal/TemPy | tempy/tempy.py | DOMModifier.replace_with | def replace_with(self, other):
"""Replace this element with the given DOMElement."""
self.after(other)
self.parent.pop(self._own_index)
return other | python | def replace_with(self, other):
self.after(other)
self.parent.pop(self._own_index)
return other | [
"def",
"replace_with",
"(",
"self",
",",
"other",
")",
":",
"self",
".",
"after",
"(",
"other",
")",
"self",
".",
"parent",
".",
"pop",
"(",
"self",
".",
"_own_index",
")",
"return",
"other"
] | Replace this element with the given DOMElement. | [
"Replace",
"this",
"element",
"with",
"the",
"given",
"DOMElement",
"."
] | 7d229b73e2ce3ccbb8254deae05c1f758f626ed6 | https://github.com/Hrabal/TemPy/blob/7d229b73e2ce3ccbb8254deae05c1f758f626ed6/tempy/tempy.py#L427-L431 |
20,030 | Hrabal/TemPy | tempy/tempy.py | DOMModifier.remove | 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 | def remove(self):
if self._own_index is not None and self.parent:
self.parent.pop(self._own_index)
return self | [
"def",
"remove",
"(",
"self",
")",
":",
"if",
"self",
".",
"_own_index",
"is",
"not",
"None",
"and",
"self",
".",
"parent",
":",
"self",
".",
"parent",
".",
"pop",
"(",
"self",
".",
"_own_index",
")",
"return",
"self"
] | Detach this element from his father. | [
"Detach",
"this",
"element",
"from",
"his",
"father",
"."
] | 7d229b73e2ce3ccbb8254deae05c1f758f626ed6 | https://github.com/Hrabal/TemPy/blob/7d229b73e2ce3ccbb8254deae05c1f758f626ed6/tempy/tempy.py#L433-L437 |
20,031 | Hrabal/TemPy | tempy/tempy.py | DOMModifier._detach_childs | 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):
child.parent = None
self.childs[idx_from:idx_to] = []
return removed | python | def _detach_childs(self, idx_from=None, idx_to=None):
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):
child.parent = None
self.childs[idx_from:idx_to] = []
return removed | [
"def",
"_detach_childs",
"(",
"self",
",",
"idx_from",
"=",
"None",
",",
"idx_to",
"=",
"None",
")",
":",
"idx_from",
"=",
"idx_from",
"or",
"0",
"idx_to",
"=",
"idx_to",
"or",
"len",
"(",
"self",
".",
"childs",
")",
"removed",
"=",
"self",
".",
"chi... | Moves all the childs to a new father | [
"Moves",
"all",
"the",
"childs",
"to",
"a",
"new",
"father"
] | 7d229b73e2ce3ccbb8254deae05c1f758f626ed6 | https://github.com/Hrabal/TemPy/blob/7d229b73e2ce3ccbb8254deae05c1f758f626ed6/tempy/tempy.py#L439-L448 |
20,032 | Hrabal/TemPy | tempy/tempy.py | DOMModifier.move | 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 | def move(self, new_father, idx=None, prepend=None, name=None):
self.parent.pop(self._own_index)
new_father._insert(self, idx=idx, prepend=prepend, name=name)
new_father._stable = False
return self | [
"def",
"move",
"(",
"self",
",",
"new_father",
",",
"idx",
"=",
"None",
",",
"prepend",
"=",
"None",
",",
"name",
"=",
"None",
")",
":",
"self",
".",
"parent",
".",
"pop",
"(",
"self",
".",
"_own_index",
")",
"new_father",
".",
"_insert",
"(",
"sel... | Moves this element from his father to the given one. | [
"Moves",
"this",
"element",
"from",
"his",
"father",
"to",
"the",
"given",
"one",
"."
] | 7d229b73e2ce3ccbb8254deae05c1f758f626ed6 | https://github.com/Hrabal/TemPy/blob/7d229b73e2ce3ccbb8254deae05c1f758f626ed6/tempy/tempy.py#L455-L460 |
20,033 | user-cont/colin | colin/core/colin.py | run | 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: timeout per-check (in seconds)
:param skips: name of checks to skip
:param target: str (image name, ostree or dockertar)
or ImageTarget
or path/file-like object for dockerfile
:param target_type: string, either image, dockerfile, dockertar
:param tags: list of str (if not None, the checks will be filtered by tags.)
:param ruleset_name: str (e.g. fedora; if None, default would be used)
:param ruleset_file: fileobj instance holding ruleset configuration
:param ruleset: dict, content of a ruleset file
:param logging_level: logging level (default logging.WARNING)
:param checks_paths: list of str, directories where the checks are present
:param pull: bool, pull the image from registry
:param insecure: bool, pull from an insecure registry (HTTP/invalid TLS)
:return: Results instance
"""
_set_logging(level=logging_level)
logger.debug("Checking started.")
target = Target.get_instance(
target=target,
logging_level=logging_level,
pull=pull,
target_type=target_type,
insecure=insecure,
)
checks_to_run = _get_checks(
target_type=target.__class__,
tags=tags,
ruleset_name=ruleset_name,
ruleset_file=ruleset_file,
ruleset=ruleset,
checks_paths=checks_paths,
skips=skips,
)
result = go_through_checks(target=target, checks=checks_to_run, timeout=timeout)
return result | python | 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,
):
_set_logging(level=logging_level)
logger.debug("Checking started.")
target = Target.get_instance(
target=target,
logging_level=logging_level,
pull=pull,
target_type=target_type,
insecure=insecure,
)
checks_to_run = _get_checks(
target_type=target.__class__,
tags=tags,
ruleset_name=ruleset_name,
ruleset_file=ruleset_file,
ruleset=ruleset,
checks_paths=checks_paths,
skips=skips,
)
result = go_through_checks(target=target, checks=checks_to_run, timeout=timeout)
return result | [
"def",
"run",
"(",
"target",
",",
"target_type",
",",
"tags",
"=",
"None",
",",
"ruleset_name",
"=",
"None",
",",
"ruleset_file",
"=",
"None",
",",
"ruleset",
"=",
"None",
",",
"logging_level",
"=",
"logging",
".",
"WARNING",
",",
"checks_paths",
"=",
"N... | Runs the sanity checks for the target.
:param timeout: timeout per-check (in seconds)
:param skips: name of checks to skip
:param target: str (image name, ostree or dockertar)
or ImageTarget
or path/file-like object for dockerfile
:param target_type: string, either image, dockerfile, dockertar
:param tags: list of str (if not None, the checks will be filtered by tags.)
:param ruleset_name: str (e.g. fedora; if None, default would be used)
:param ruleset_file: fileobj instance holding ruleset configuration
:param ruleset: dict, content of a ruleset file
:param logging_level: logging level (default logging.WARNING)
:param checks_paths: list of str, directories where the checks are present
:param pull: bool, pull the image from registry
:param insecure: bool, pull from an insecure registry (HTTP/invalid TLS)
:return: Results instance | [
"Runs",
"the",
"sanity",
"checks",
"for",
"the",
"target",
"."
] | 00bb80e6e91522e15361935f813e8cf13d7e76dc | https://github.com/user-cont/colin/blob/00bb80e6e91522e15361935f813e8cf13d7e76dc/colin/core/colin.py#L26-L78 |
20,034 | user-cont/colin | colin/core/colin.py | get_checks | 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 enum
:param tags: list of str (if not None, the checks will be filtered by tags.)
:param ruleset_name: str (e.g. fedora; if None, default would be used)
:param ruleset_file: fileobj instance holding ruleset configuration
:param ruleset: dict, content of a ruleset file
:param logging_level: logging level (default logging.WARNING)
:param checks_paths: list of str, directories where the checks are present
:return: list of check instances
"""
_set_logging(level=logging_level)
logger.debug("Finding checks started.")
return _get_checks(
target_type=target_type,
tags=tags,
ruleset_name=ruleset_name,
ruleset_file=ruleset_file,
ruleset=ruleset,
checks_paths=checks_paths,
skips=skips,
) | python | 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,
):
_set_logging(level=logging_level)
logger.debug("Finding checks started.")
return _get_checks(
target_type=target_type,
tags=tags,
ruleset_name=ruleset_name,
ruleset_file=ruleset_file,
ruleset=ruleset,
checks_paths=checks_paths,
skips=skips,
) | [
"def",
"get_checks",
"(",
"target_type",
"=",
"None",
",",
"tags",
"=",
"None",
",",
"ruleset_name",
"=",
"None",
",",
"ruleset_file",
"=",
"None",
",",
"ruleset",
"=",
"None",
",",
"logging_level",
"=",
"logging",
".",
"WARNING",
",",
"checks_paths",
"=",... | Get the sanity checks for the target.
:param skips: name of checks to skip
:param target_type: TargetType enum
:param tags: list of str (if not None, the checks will be filtered by tags.)
:param ruleset_name: str (e.g. fedora; if None, default would be used)
:param ruleset_file: fileobj instance holding ruleset configuration
:param ruleset: dict, content of a ruleset file
:param logging_level: logging level (default logging.WARNING)
:param checks_paths: list of str, directories where the checks are present
:return: list of check instances | [
"Get",
"the",
"sanity",
"checks",
"for",
"the",
"target",
"."
] | 00bb80e6e91522e15361935f813e8cf13d7e76dc | https://github.com/user-cont/colin/blob/00bb80e6e91522e15361935f813e8cf13d7e76dc/colin/core/colin.py#L81-L114 |
20,035 | user-cont/colin | colin/core/colin.py | _set_logging | 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.
:param logger_name: str, name of the logger
:param level: int, see logging.{DEBUG,INFO,ERROR,...}: level of logger and handler
:param handler_class: logging.Handler instance, default is StreamHandler (/dev/stderr)
:param handler_kwargs: dict, keyword arguments to handler's constructor
:param format: str, formatting style
:param date_format: str, date style in the logs
"""
if level != logging.NOTSET:
logger = logging.getLogger(logger_name)
logger.setLevel(level)
# do not readd handlers if they are already present
if not [x for x in logger.handlers if isinstance(x, handler_class)]:
handler_kwargs = handler_kwargs or {}
handler = handler_class(**handler_kwargs)
handler.setLevel(level)
formatter = logging.Formatter(format, date_format)
handler.setFormatter(formatter)
logger.addHandler(handler) | python | 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'):
if level != logging.NOTSET:
logger = logging.getLogger(logger_name)
logger.setLevel(level)
# do not readd handlers if they are already present
if not [x for x in logger.handlers if isinstance(x, handler_class)]:
handler_kwargs = handler_kwargs or {}
handler = handler_class(**handler_kwargs)
handler.setLevel(level)
formatter = logging.Formatter(format, date_format)
handler.setFormatter(formatter)
logger.addHandler(handler) | [
"def",
"_set_logging",
"(",
"logger_name",
"=",
"\"colin\"",
",",
"level",
"=",
"logging",
".",
"INFO",
",",
"handler_class",
"=",
"logging",
".",
"StreamHandler",
",",
"handler_kwargs",
"=",
"None",
",",
"format",
"=",
"'%(asctime)s.%(msecs).03d %(filename)-17s %(l... | Set personal logger for this library.
:param logger_name: str, name of the logger
:param level: int, see logging.{DEBUG,INFO,ERROR,...}: level of logger and handler
:param handler_class: logging.Handler instance, default is StreamHandler (/dev/stderr)
:param handler_kwargs: dict, keyword arguments to handler's constructor
:param format: str, formatting style
:param date_format: str, date style in the logs | [
"Set",
"personal",
"logger",
"for",
"this",
"library",
"."
] | 00bb80e6e91522e15361935f813e8cf13d7e76dc | https://github.com/user-cont/colin/blob/00bb80e6e91522e15361935f813e8cf13d7e76dc/colin/core/colin.py#L135-L164 |
20,036 | user-cont/colin | colin/core/checks/check_utils.py | check_label | 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 (required==True: True if the label is present and match the regex if specified)
(required==False: True if the label is not present)
"""
present = target_labels is not None and not set(labels).isdisjoint(set(target_labels))
if present:
if required and not value_regex:
return True
elif value_regex:
pattern = re.compile(value_regex)
present_labels = set(labels) & set(target_labels)
for l in present_labels:
if not bool(pattern.search(target_labels[l])):
return False
return True
else:
return False
else:
return not required | python | def check_label(labels, required, value_regex, target_labels):
present = target_labels is not None and not set(labels).isdisjoint(set(target_labels))
if present:
if required and not value_regex:
return True
elif value_regex:
pattern = re.compile(value_regex)
present_labels = set(labels) & set(target_labels)
for l in present_labels:
if not bool(pattern.search(target_labels[l])):
return False
return True
else:
return False
else:
return not required | [
"def",
"check_label",
"(",
"labels",
",",
"required",
",",
"value_regex",
",",
"target_labels",
")",
":",
"present",
"=",
"target_labels",
"is",
"not",
"None",
"and",
"not",
"set",
"(",
"labels",
")",
".",
"isdisjoint",
"(",
"set",
"(",
"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 (required==True: True if the label is present and match the regex if specified)
(required==False: True if the label is not present) | [
"Check",
"if",
"the",
"label",
"is",
"required",
"and",
"match",
"the",
"regex"
] | 00bb80e6e91522e15361935f813e8cf13d7e76dc | https://github.com/user-cont/colin/blob/00bb80e6e91522e15361935f813e8cf13d7e76dc/colin/core/checks/check_utils.py#L7-L34 |
20,037 | user-cont/colin | colin/core/checks/abstract_check.py | AbstractCheck.json | 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': self.tags,
} | python | def json(self):
return {
'name': self.name,
'message': self.message,
'description': self.description,
'reference_url': self.reference_url,
'tags': self.tags,
} | [
"def",
"json",
"(",
"self",
")",
":",
"return",
"{",
"'name'",
":",
"self",
".",
"name",
",",
"'message'",
":",
"self",
".",
"message",
",",
"'description'",
":",
"self",
".",
"description",
",",
"'reference_url'",
":",
"self",
".",
"reference_url",
",",... | Get json representation of the check
:return: dict (str -> obj) | [
"Get",
"json",
"representation",
"of",
"the",
"check"
] | 00bb80e6e91522e15361935f813e8cf13d7e76dc | https://github.com/user-cont/colin/blob/00bb80e6e91522e15361935f813e8cf13d7e76dc/colin/core/checks/abstract_check.py#L47-L59 |
20,038 | user-cont/colin | colin/core/ruleset/ruleset.py | get_checks_paths | 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.abspath(p)
# let's utilize the default upstream checks always
if checks_paths:
p += [os.path.abspath(x) for x in checks_paths]
return [p] | python | def get_checks_paths(checks_paths=None):
p = os.path.join(__file__, os.pardir, os.pardir, os.pardir, "checks")
p = os.path.abspath(p)
# let's utilize the default upstream checks always
if checks_paths:
p += [os.path.abspath(x) for x in checks_paths]
return [p] | [
"def",
"get_checks_paths",
"(",
"checks_paths",
"=",
"None",
")",
":",
"p",
"=",
"os",
".",
"path",
".",
"join",
"(",
"__file__",
",",
"os",
".",
"pardir",
",",
"os",
".",
"pardir",
",",
"os",
".",
"pardir",
",",
"\"checks\"",
")",
"p",
"=",
"os",
... | 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) | [
"Get",
"path",
"to",
"checks",
"."
] | 00bb80e6e91522e15361935f813e8cf13d7e76dc | https://github.com/user-cont/colin/blob/00bb80e6e91522e15361935f813e8cf13d7e76dc/colin/core/ruleset/ruleset.py#L124-L136 |
20,039 | user-cont/colin | colin/core/ruleset/ruleset.py | get_ruleset_file | 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 + ext) for ext in EXTS]
for ruleset_file in possible_ruleset_files:
if os.path.isfile(ruleset_file):
logger.debug("Ruleset file '{}' found.".format(ruleset_file))
return ruleset_file
logger.warning("Ruleset with the name '{}' cannot be found at '{}'."
.format(ruleset, ruleset_dirs))
raise ColinRulesetException("Ruleset with the name '{}' cannot be found.".format(ruleset)) | python | def get_ruleset_file(ruleset=None):
ruleset = ruleset or "default"
ruleset_dirs = get_ruleset_dirs()
for ruleset_directory in ruleset_dirs:
possible_ruleset_files = [os.path.join(ruleset_directory, ruleset + ext) for ext in EXTS]
for ruleset_file in possible_ruleset_files:
if os.path.isfile(ruleset_file):
logger.debug("Ruleset file '{}' found.".format(ruleset_file))
return ruleset_file
logger.warning("Ruleset with the name '{}' cannot be found at '{}'."
.format(ruleset, ruleset_dirs))
raise ColinRulesetException("Ruleset with the name '{}' cannot be found.".format(ruleset)) | [
"def",
"get_ruleset_file",
"(",
"ruleset",
"=",
"None",
")",
":",
"ruleset",
"=",
"ruleset",
"or",
"\"default\"",
"ruleset_dirs",
"=",
"get_ruleset_dirs",
"(",
")",
"for",
"ruleset_directory",
"in",
"ruleset_dirs",
":",
"possible_ruleset_files",
"=",
"[",
"os",
... | Get the ruleset file from name
:param ruleset: str
:return: str | [
"Get",
"the",
"ruleset",
"file",
"from",
"name"
] | 00bb80e6e91522e15361935f813e8cf13d7e76dc | https://github.com/user-cont/colin/blob/00bb80e6e91522e15361935f813e8cf13d7e76dc/colin/core/ruleset/ruleset.py#L139-L159 |
20,040 | user-cont/colin | colin/core/ruleset/ruleset.py | get_rulesets | 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.path.isfile(file_path) and f.lower().endswith(ext):
ruleset_files.append((f[:-len(ext)], file_path))
return ruleset_files | python | def get_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.path.isfile(file_path) and f.lower().endswith(ext):
ruleset_files.append((f[:-len(ext)], file_path))
return ruleset_files | [
"def",
"get_rulesets",
"(",
")",
":",
"rulesets_dirs",
"=",
"get_ruleset_dirs",
"(",
")",
"ruleset_files",
"=",
"[",
"]",
"for",
"rulesets_dir",
"in",
"rulesets_dirs",
":",
"for",
"f",
"in",
"os",
".",
"listdir",
"(",
"rulesets_dir",
")",
":",
"for",
"ext"... | Get available rulesets. | [
"Get",
"available",
"rulesets",
"."
] | 00bb80e6e91522e15361935f813e8cf13d7e76dc | https://github.com/user-cont/colin/blob/00bb80e6e91522e15361935f813e8cf13d7e76dc/colin/core/ruleset/ruleset.py#L205-L217 |
20,041 | user-cont/colin | colin/utils/cmd_tools.py | get_rpm_version | 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:
return version_result.stdout.decode().rstrip()
else:
return None | python | def get_rpm_version(package_name):
version_result = subprocess.run(["rpm", "-q", package_name],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
if version_result.returncode == 0:
return version_result.stdout.decode().rstrip()
else:
return None | [
"def",
"get_rpm_version",
"(",
"package_name",
")",
":",
"version_result",
"=",
"subprocess",
".",
"run",
"(",
"[",
"\"rpm\"",
",",
"\"-q\"",
",",
"package_name",
"]",
",",
"stdout",
"=",
"subprocess",
".",
"PIPE",
",",
"stderr",
"=",
"subprocess",
".",
"P... | Get a version of the package with 'rpm -q' command. | [
"Get",
"a",
"version",
"of",
"the",
"package",
"with",
"rpm",
"-",
"q",
"command",
"."
] | 00bb80e6e91522e15361935f813e8cf13d7e76dc | https://github.com/user-cont/colin/blob/00bb80e6e91522e15361935f813e8cf13d7e76dc/colin/utils/cmd_tools.py#L77-L85 |
20,042 | user-cont/colin | colin/utils/cmd_tools.py | is_rpm_installed | 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.returncode
except FileNotFoundError:
rpm_installed = False
return rpm_installed | python | def is_rpm_installed():
try:
version_result = subprocess.run(["rpm", "--usage"],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
rpm_installed = not version_result.returncode
except FileNotFoundError:
rpm_installed = False
return rpm_installed | [
"def",
"is_rpm_installed",
"(",
")",
":",
"try",
":",
"version_result",
"=",
"subprocess",
".",
"run",
"(",
"[",
"\"rpm\"",
",",
"\"--usage\"",
"]",
",",
"stdout",
"=",
"subprocess",
".",
"PIPE",
",",
"stderr",
"=",
"subprocess",
".",
"PIPE",
")",
"rpm_i... | Tests if the rpm command is present. | [
"Tests",
"if",
"the",
"rpm",
"command",
"is",
"present",
"."
] | 00bb80e6e91522e15361935f813e8cf13d7e76dc | https://github.com/user-cont/colin/blob/00bb80e6e91522e15361935f813e8cf13d7e76dc/colin/utils/cmd_tools.py#L88-L97 |
20,043 | user-cont/colin | colin/utils/cmd_tools.py | exit_after | 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 = threading.Timer(s, thread.interrupt_main)
timer.start()
try:
result = fn(*args, **kwargs)
except KeyboardInterrupt:
raise TimeoutError("Function '{}' hit the timeout ({}s).".format(fn.__name__, s))
finally:
timer.cancel()
return result
return inner
return outer | python | def exit_after(s):
def outer(fn):
def inner(*args, **kwargs):
timer = threading.Timer(s, thread.interrupt_main)
timer.start()
try:
result = fn(*args, **kwargs)
except KeyboardInterrupt:
raise TimeoutError("Function '{}' hit the timeout ({}s).".format(fn.__name__, s))
finally:
timer.cancel()
return result
return inner
return outer | [
"def",
"exit_after",
"(",
"s",
")",
":",
"def",
"outer",
"(",
"fn",
")",
":",
"def",
"inner",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"timer",
"=",
"threading",
".",
"Timer",
"(",
"s",
",",
"thread",
".",
"interrupt_main",
")",
"time... | 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 | [
"Use",
"as",
"decorator",
"to",
"exit",
"process",
"if",
"function",
"takes",
"longer",
"than",
"s",
"seconds",
"."
] | 00bb80e6e91522e15361935f813e8cf13d7e76dc | https://github.com/user-cont/colin/blob/00bb80e6e91522e15361935f813e8cf13d7e76dc/colin/utils/cmd_tools.py#L100-L124 |
20,044 | user-cont/colin | colin/utils/cmd_tools.py | retry | 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
"""
if retry_count <= 0:
raise ValueError("retry_count have to be positive")
def decorator(f):
@functools.wraps(f)
def wrapper(*args, **kwargs):
for i in range(retry_count, 0, -1):
try:
return f(*args, **kwargs)
except Exception:
if i <= 1:
raise
time.sleep(delay)
return wrapper
return decorator | python | def retry(retry_count=5, delay=2):
if retry_count <= 0:
raise ValueError("retry_count have to be positive")
def decorator(f):
@functools.wraps(f)
def wrapper(*args, **kwargs):
for i in range(retry_count, 0, -1):
try:
return f(*args, **kwargs)
except Exception:
if i <= 1:
raise
time.sleep(delay)
return wrapper
return decorator | [
"def",
"retry",
"(",
"retry_count",
"=",
"5",
",",
"delay",
"=",
"2",
")",
":",
"if",
"retry_count",
"<=",
"0",
":",
"raise",
"ValueError",
"(",
"\"retry_count have to be positive\"",
")",
"def",
"decorator",
"(",
"f",
")",
":",
"@",
"functools",
".",
"w... | 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 | [
"Use",
"as",
"decorator",
"to",
"retry",
"functions",
"few",
"times",
"with",
"delays"
] | 00bb80e6e91522e15361935f813e8cf13d7e76dc | https://github.com/user-cont/colin/blob/00bb80e6e91522e15361935f813e8cf13d7e76dc/colin/utils/cmd_tools.py#L127-L151 |
20,045 | user-cont/colin | colin/utils/cont.py | ImageName.parse | 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('/', 2)
if len(s) == 2:
if '.' in s[0] or ':' in s[0]:
result.registry = s[0]
else:
result.namespace = s[0]
elif len(s) == 3:
result.registry = s[0]
result.namespace = s[1]
result.repository = s[-1]
try:
result.repository, result.digest = result.repository.rsplit("@", 1)
except ValueError:
try:
result.repository, result.tag = result.repository.rsplit(":", 1)
except ValueError:
result.tag = "latest"
return result | python | def parse(cls, image_name):
result = cls()
# registry.org/namespace/repo:tag
s = image_name.split('/', 2)
if len(s) == 2:
if '.' in s[0] or ':' in s[0]:
result.registry = s[0]
else:
result.namespace = s[0]
elif len(s) == 3:
result.registry = s[0]
result.namespace = s[1]
result.repository = s[-1]
try:
result.repository, result.digest = result.repository.rsplit("@", 1)
except ValueError:
try:
result.repository, result.tag = result.repository.rsplit(":", 1)
except ValueError:
result.tag = "latest"
return result | [
"def",
"parse",
"(",
"cls",
",",
"image_name",
")",
":",
"result",
"=",
"cls",
"(",
")",
"# registry.org/namespace/repo:tag",
"s",
"=",
"image_name",
".",
"split",
"(",
"'/'",
",",
"2",
")",
"if",
"len",
"(",
"s",
")",
"==",
"2",
":",
"if",
"'.'",
... | Get the instance of ImageName from the string representation.
:param image_name: str (any possible form of image name)
:return: ImageName instance | [
"Get",
"the",
"instance",
"of",
"ImageName",
"from",
"the",
"string",
"representation",
"."
] | 00bb80e6e91522e15361935f813e8cf13d7e76dc | https://github.com/user-cont/colin/blob/00bb80e6e91522e15361935f813e8cf13d7e76dc/colin/utils/cont.py#L22-L52 |
20,046 | user-cont/colin | colin/core/ruleset/loader.py | CheckStruct.other_attributes | 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 | def other_attributes(self):
return {k: v for k, v in self.c.items() if
k not in ["name", "names", "tags", "additional_tags", "usable_targets"]} | [
"def",
"other_attributes",
"(",
"self",
")",
":",
"return",
"{",
"k",
":",
"v",
"for",
"k",
",",
"v",
"in",
"self",
".",
"c",
".",
"items",
"(",
")",
"if",
"k",
"not",
"in",
"[",
"\"name\"",
",",
"\"names\"",
",",
"\"tags\"",
",",
"\"additional_tag... | return dict with all other data except for the described above | [
"return",
"dict",
"with",
"all",
"other",
"data",
"except",
"for",
"the",
"described",
"above"
] | 00bb80e6e91522e15361935f813e8cf13d7e76dc | https://github.com/user-cont/colin/blob/00bb80e6e91522e15361935f813e8cf13d7e76dc/colin/core/ruleset/loader.py#L118-L121 |
20,047 | user-cont/colin | colin/core/loader.py | should_we_load | 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 needs to be a child of AbstractCheck
for m in mro:
if m.__name__ == "AbstractCheck":
return True
return False | python | def should_we_load(kls):
# 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 needs to be a child of AbstractCheck
for m in mro:
if m.__name__ == "AbstractCheck":
return True
return False | [
"def",
"should_we_load",
"(",
"kls",
")",
":",
"# we don't load abstract classes",
"if",
"kls",
".",
"__name__",
".",
"endswith",
"(",
"\"AbstractCheck\"",
")",
":",
"return",
"False",
"# and we only load checks",
"if",
"not",
"kls",
".",
"__name__",
".",
"endswit... | should we load this class as a check? | [
"should",
"we",
"load",
"this",
"class",
"as",
"a",
"check?"
] | 00bb80e6e91522e15361935f813e8cf13d7e76dc | https://github.com/user-cont/colin/blob/00bb80e6e91522e15361935f813e8cf13d7e76dc/colin/core/loader.py#L54-L67 |
20,048 | user-cont/colin | colin/core/loader.py | CheckLoader.obtain_check_classes | 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"):
continue
path = os.path.join(root, fi)
check_classes = check_classes.union(set(
load_check_classes_from_file(path)))
return list(check_classes) | python | def obtain_check_classes(self):
check_classes = set()
for path in self.paths:
for root, _, files in os.walk(path):
for fi in files:
if not fi.endswith(".py"):
continue
path = os.path.join(root, fi)
check_classes = check_classes.union(set(
load_check_classes_from_file(path)))
return list(check_classes) | [
"def",
"obtain_check_classes",
"(",
"self",
")",
":",
"check_classes",
"=",
"set",
"(",
")",
"for",
"path",
"in",
"self",
".",
"paths",
":",
"for",
"root",
",",
"_",
",",
"files",
"in",
"os",
".",
"walk",
"(",
"path",
")",
":",
"for",
"fi",
"in",
... | find children of AbstractCheck class and return them as a list | [
"find",
"children",
"of",
"AbstractCheck",
"class",
"and",
"return",
"them",
"as",
"a",
"list"
] | 00bb80e6e91522e15361935f813e8cf13d7e76dc | https://github.com/user-cont/colin/blob/00bb80e6e91522e15361935f813e8cf13d7e76dc/colin/core/loader.py#L103-L114 |
20,049 | user-cont/colin | colin/core/loader.py | CheckLoader.import_class | 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_name)
self.mapping[check_class.name] = check_class
logger.info("successfully loaded class %s", check_class)
return check_class | python | def import_class(self, import_name):
module_name, class_name = import_name.rsplit(".", 1)
mod = import_module(module_name)
check_class = getattr(mod, class_name)
self.mapping[check_class.name] = check_class
logger.info("successfully loaded class %s", check_class)
return check_class | [
"def",
"import_class",
"(",
"self",
",",
"import_name",
")",
":",
"module_name",
",",
"class_name",
"=",
"import_name",
".",
"rsplit",
"(",
"\".\"",
",",
"1",
")",
"mod",
"=",
"import_module",
"(",
"module_name",
")",
"check_class",
"=",
"getattr",
"(",
"m... | import selected class
:param import_name, str, e.g. some.module.MyClass
:return the class | [
"import",
"selected",
"class"
] | 00bb80e6e91522e15361935f813e8cf13d7e76dc | https://github.com/user-cont/colin/blob/00bb80e6e91522e15361935f813e8cf13d7e76dc/colin/core/loader.py#L116-L128 |
20,050 | user-cont/colin | colin/core/result.py | CheckResults._dict_of_results | 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,
'ok': r.ok,
'status': r.status,
'description': r.description,
'message': r.message,
'reference_url': r.reference_url,
'logs': r.logs,
})
result_json["checks"] = result_list
return result_json | python | def _dict_of_results(self):
result_json = {}
result_list = []
for r in self.results:
result_list.append({
'name': r.check_name,
'ok': r.ok,
'status': r.status,
'description': r.description,
'message': r.message,
'reference_url': r.reference_url,
'logs': r.logs,
})
result_json["checks"] = result_list
return result_json | [
"def",
"_dict_of_results",
"(",
"self",
")",
":",
"result_json",
"=",
"{",
"}",
"result_list",
"=",
"[",
"]",
"for",
"r",
"in",
"self",
".",
"results",
":",
"result_list",
".",
"append",
"(",
"{",
"'name'",
":",
"r",
".",
"check_name",
",",
"'ok'",
"... | Get the dictionary representation of results
:return: dict (str -> dict (str -> str)) | [
"Get",
"the",
"dictionary",
"representation",
"of",
"results"
] | 00bb80e6e91522e15361935f813e8cf13d7e76dc | https://github.com/user-cont/colin/blob/00bb80e6e91522e15361935f813e8cf13d7e76dc/colin/core/result.py#L64-L84 |
20,051 | user-cont/colin | colin/core/result.py | CheckResults.statistics | 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 | def statistics(self):
result = {}
for r in self.results:
result.setdefault(r.status, 0)
result[r.status] += 1
return result | [
"def",
"statistics",
"(",
"self",
")",
":",
"result",
"=",
"{",
"}",
"for",
"r",
"in",
"self",
".",
"results",
":",
"result",
".",
"setdefault",
"(",
"r",
".",
"status",
",",
"0",
")",
"result",
"[",
"r",
".",
"status",
"]",
"+=",
"1",
"return",
... | Get the dictionary with the count of the check-statuses
:return: dict(str -> int) | [
"Get",
"the",
"dictionary",
"with",
"the",
"count",
"of",
"the",
"check",
"-",
"statuses"
] | 00bb80e6e91522e15361935f813e8cf13d7e76dc | https://github.com/user-cont/colin/blob/00bb80e6e91522e15361935f813e8cf13d7e76dc/colin/core/result.py#L101-L111 |
20,052 | user-cont/colin | colin/core/result.py | CheckResults.generate_pretty_output | 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_check = False
for r in self.results:
has_check = True
if stat:
output_function(OUTPUT_CHARS[r.status],
fg=COLOURS[r.status],
nl=False)
else:
output_function(str(r), fg=COLOURS[r.status])
if verbose:
output_function(" -> {}\n"
" -> {}".format(r.description,
r.reference_url),
fg=COLOURS[r.status])
if logs and r.logs:
output_function(" -> logs:",
fg=COLOURS[r.status])
for l in r.logs:
output_function(" -> {}".format(l),
fg=COLOURS[r.status])
if not has_check:
output_function("No check found.")
elif stat and not verbose:
output_function("")
else:
output_function("")
for status, count in six.iteritems(self.statistics):
output_function("{}:{} ".format(status, count), nl=False)
output_function("") | python | def generate_pretty_output(self, stat, verbose, output_function, logs=True):
has_check = False
for r in self.results:
has_check = True
if stat:
output_function(OUTPUT_CHARS[r.status],
fg=COLOURS[r.status],
nl=False)
else:
output_function(str(r), fg=COLOURS[r.status])
if verbose:
output_function(" -> {}\n"
" -> {}".format(r.description,
r.reference_url),
fg=COLOURS[r.status])
if logs and r.logs:
output_function(" -> logs:",
fg=COLOURS[r.status])
for l in r.logs:
output_function(" -> {}".format(l),
fg=COLOURS[r.status])
if not has_check:
output_function("No check found.")
elif stat and not verbose:
output_function("")
else:
output_function("")
for status, count in six.iteritems(self.statistics):
output_function("{}:{} ".format(status, count), nl=False)
output_function("") | [
"def",
"generate_pretty_output",
"(",
"self",
",",
"stat",
",",
"verbose",
",",
"output_function",
",",
"logs",
"=",
"True",
")",
":",
"has_check",
"=",
"False",
"for",
"r",
"in",
"self",
".",
"results",
":",
"has_check",
"=",
"True",
"if",
"stat",
":",
... | 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 | [
"Send",
"the",
"formated",
"to",
"the",
"provided",
"function"
] | 00bb80e6e91522e15361935f813e8cf13d7e76dc | https://github.com/user-cont/colin/blob/00bb80e6e91522e15361935f813e8cf13d7e76dc/colin/core/result.py#L133-L171 |
20,053 | user-cont/colin | colin/core/result.py | CheckResults.get_pretty_string | 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,
verbose=verbose,
output_function=pretty_output.save_output)
return pretty_output.result | python | def get_pretty_string(self, stat, verbose):
pretty_output = _PrettyOutputToStr()
self.generate_pretty_output(stat=stat,
verbose=verbose,
output_function=pretty_output.save_output)
return pretty_output.result | [
"def",
"get_pretty_string",
"(",
"self",
",",
"stat",
",",
"verbose",
")",
":",
"pretty_output",
"=",
"_PrettyOutputToStr",
"(",
")",
"self",
".",
"generate_pretty_output",
"(",
"stat",
"=",
"stat",
",",
"verbose",
"=",
"verbose",
",",
"output_function",
"=",
... | Pretty string representation of the results
:param stat: bool
:param verbose: bool
:return: str | [
"Pretty",
"string",
"representation",
"of",
"the",
"results"
] | 00bb80e6e91522e15361935f813e8cf13d7e76dc | https://github.com/user-cont/colin/blob/00bb80e6e91522e15361935f813e8cf13d7e76dc/colin/core/result.py#L173-L185 |
20,054 | user-cont/colin | colin/core/checks/fmf_check.py | receive_fmf_metadata | 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 Object or list
"""
output = {}
fmf_tree = ExtendedTree(path)
logger.debug("get FMF metadata for test (path:%s name=%s)", path, name)
# ignore items with @ in names, to avoid using unreferenced items
items = [x for x in fmf_tree.climb() if x.name.endswith("/" + name) and "@" not in x.name]
if object_list:
return items
if len(items) == 1:
output = items[0]
elif len(items) > 1:
raise Exception("There is more FMF test metadata for item by name:{}({}) {}".format(
name, len(items), [x.name for x in items]))
elif not items:
raise Exception("Unable to get FMF metadata for: {}".format(name))
return output | python | def receive_fmf_metadata(name, path, object_list=False):
output = {}
fmf_tree = ExtendedTree(path)
logger.debug("get FMF metadata for test (path:%s name=%s)", path, name)
# ignore items with @ in names, to avoid using unreferenced items
items = [x for x in fmf_tree.climb() if x.name.endswith("/" + name) and "@" not in x.name]
if object_list:
return items
if len(items) == 1:
output = items[0]
elif len(items) > 1:
raise Exception("There is more FMF test metadata for item by name:{}({}) {}".format(
name, len(items), [x.name for x in items]))
elif not items:
raise Exception("Unable to get FMF metadata for: {}".format(name))
return output | [
"def",
"receive_fmf_metadata",
"(",
"name",
",",
"path",
",",
"object_list",
"=",
"False",
")",
":",
"output",
"=",
"{",
"}",
"fmf_tree",
"=",
"ExtendedTree",
"(",
"path",
")",
"logger",
".",
"debug",
"(",
"\"get FMF metadata for test (path:%s name=%s)\"",
",",
... | 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 Object or list | [
"search",
"node",
"identified",
"by",
"name",
"fmfpath"
] | 00bb80e6e91522e15361935f813e8cf13d7e76dc | https://github.com/user-cont/colin/blob/00bb80e6e91522e15361935f813e8cf13d7e76dc/colin/core/checks/fmf_check.py#L15-L38 |
20,055 | user-cont/colin | colin/cli/colin.py | list_checks | 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:
logging.basicConfig(stream=six.StringIO())
log_level = _get_log_level(debug=debug,
verbose=verbose)
checks = get_checks(ruleset_name=ruleset,
ruleset_file=ruleset_file,
logging_level=log_level,
tags=tag,
checks_paths=checks_paths,
skips=skip)
_print_checks(checks=checks)
if json:
AbstractCheck.save_checks_to_json(file=json, checks=checks)
except ColinException as ex:
logger.error("An error occurred: %r", ex)
if debug:
raise
else:
raise click.ClickException(str(ex))
except Exception as ex:
logger.error("An error occurred: %r", ex)
if debug:
raise
else:
raise click.ClickException(str(ex)) | python | def list_checks(ruleset, ruleset_file, debug, json, skip, tag, verbose, checks_paths):
if ruleset and ruleset_file:
raise click.BadOptionUsage(
"Options '--ruleset' and '--file-ruleset' cannot be used together.")
try:
if not debug:
logging.basicConfig(stream=six.StringIO())
log_level = _get_log_level(debug=debug,
verbose=verbose)
checks = get_checks(ruleset_name=ruleset,
ruleset_file=ruleset_file,
logging_level=log_level,
tags=tag,
checks_paths=checks_paths,
skips=skip)
_print_checks(checks=checks)
if json:
AbstractCheck.save_checks_to_json(file=json, checks=checks)
except ColinException as ex:
logger.error("An error occurred: %r", ex)
if debug:
raise
else:
raise click.ClickException(str(ex))
except Exception as ex:
logger.error("An error occurred: %r", ex)
if debug:
raise
else:
raise click.ClickException(str(ex)) | [
"def",
"list_checks",
"(",
"ruleset",
",",
"ruleset_file",
",",
"debug",
",",
"json",
",",
"skip",
",",
"tag",
",",
"verbose",
",",
"checks_paths",
")",
":",
"if",
"ruleset",
"and",
"ruleset_file",
":",
"raise",
"click",
".",
"BadOptionUsage",
"(",
"\"Opti... | Print the checks. | [
"Print",
"the",
"checks",
"."
] | 00bb80e6e91522e15361935f813e8cf13d7e76dc | https://github.com/user-cont/colin/blob/00bb80e6e91522e15361935f813e8cf13d7e76dc/colin/cli/colin.py#L158-L193 |
20,056 | user-cont/colin | colin/cli/colin.py | list_rulesets | 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 error occurred: %r", ex)
if debug:
raise
else:
raise click.ClickException(str(ex)) | python | def list_rulesets(debug):
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 error occurred: %r", ex)
if debug:
raise
else:
raise click.ClickException(str(ex)) | [
"def",
"list_rulesets",
"(",
"debug",
")",
":",
"try",
":",
"rulesets",
"=",
"get_rulesets",
"(",
")",
"max_len",
"=",
"max",
"(",
"[",
"len",
"(",
"r",
"[",
"0",
"]",
")",
"for",
"r",
"in",
"rulesets",
"]",
")",
"for",
"r",
"in",
"rulesets",
":"... | List available rulesets. | [
"List",
"available",
"rulesets",
"."
] | 00bb80e6e91522e15361935f813e8cf13d7e76dc | https://github.com/user-cont/colin/blob/00bb80e6e91522e15361935f813e8cf13d7e76dc/colin/cli/colin.py#L200-L214 |
20,057 | user-cont/colin | colin/cli/colin.py | info | 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__)))
# click.echo(get_version_of_the_python_package(module=conu))
rpm_installed = is_rpm_installed()
click.echo(get_version_msg_from_the_cmd(package_name="podman", use_rpm=rpm_installed))
click.echo(get_version_msg_from_the_cmd(package_name="skopeo", use_rpm=rpm_installed))
click.echo(get_version_msg_from_the_cmd(package_name="ostree",
use_rpm=rpm_installed,
max_lines_of_the_output=3)) | python | def info():
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__)))
# click.echo(get_version_of_the_python_package(module=conu))
rpm_installed = is_rpm_installed()
click.echo(get_version_msg_from_the_cmd(package_name="podman", use_rpm=rpm_installed))
click.echo(get_version_msg_from_the_cmd(package_name="skopeo", use_rpm=rpm_installed))
click.echo(get_version_msg_from_the_cmd(package_name="ostree",
use_rpm=rpm_installed,
max_lines_of_the_output=3)) | [
"def",
"info",
"(",
")",
":",
"installation_path",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"__file__",
")",
",",
"os",
".",
"path",
".",
"pardir",
")",
")",
"click"... | Show info about colin and its dependencies. | [
"Show",
"info",
"about",
"colin",
"and",
"its",
"dependencies",
"."
] | 00bb80e6e91522e15361935f813e8cf13d7e76dc | https://github.com/user-cont/colin/blob/00bb80e6e91522e15361935f813e8cf13d7e76dc/colin/cli/colin.py#L219-L235 |
20,058 | user-cont/colin | colin/cli/colin.py | _print_results | 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,
verbose=verbose,
output_function=click.secho) | python | def _print_results(results, stat=False, verbose=False):
results.generate_pretty_output(stat=stat,
verbose=verbose,
output_function=click.secho) | [
"def",
"_print_results",
"(",
"results",
",",
"stat",
"=",
"False",
",",
"verbose",
"=",
"False",
")",
":",
"results",
".",
"generate_pretty_output",
"(",
"stat",
"=",
"stat",
",",
"verbose",
"=",
"verbose",
",",
"output_function",
"=",
"click",
".",
"sech... | Prints the results to the stdout
:type verbose: bool
:param results: generator of results
:param stat: if True print stat instead of full output | [
"Prints",
"the",
"results",
"to",
"the",
"stdout"
] | 00bb80e6e91522e15361935f813e8cf13d7e76dc | https://github.com/user-cont/colin/blob/00bb80e6e91522e15361935f813e8cf13d7e76dc/colin/cli/colin.py#L245-L255 |
20,059 | user-cont/colin | colin/core/target.py | DockerfileTarget.labels | 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 | def labels(self):
if self._labels is None:
self._labels = self.instance.labels
return self._labels | [
"def",
"labels",
"(",
"self",
")",
":",
"if",
"self",
".",
"_labels",
"is",
"None",
":",
"self",
".",
"_labels",
"=",
"self",
".",
"instance",
".",
"labels",
"return",
"self",
".",
"_labels"
] | Get list of labels from the target instance.
:return: [str] | [
"Get",
"list",
"of",
"labels",
"from",
"the",
"target",
"instance",
"."
] | 00bb80e6e91522e15361935f813e8cf13d7e76dc | https://github.com/user-cont/colin/blob/00bb80e6e91522e15361935f813e8cf13d7e76dc/colin/core/target.py#L131-L139 |
20,060 | user-cont/colin | colin/core/target.py | OstreeTarget.labels | 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"]
return self._labels | python | def labels(self):
if self._labels is None:
cmd = ["skopeo", "inspect", self.skopeo_target]
self._labels = json.loads(subprocess.check_output(cmd))["Labels"]
return self._labels | [
"def",
"labels",
"(",
"self",
")",
":",
"if",
"self",
".",
"_labels",
"is",
"None",
":",
"cmd",
"=",
"[",
"\"skopeo\"",
",",
"\"inspect\"",
",",
"self",
".",
"skopeo_target",
"]",
"self",
".",
"_labels",
"=",
"json",
".",
"loads",
"(",
"subprocess",
... | Provide labels without the need of dockerd. Instead skopeo is being used.
:return: dict | [
"Provide",
"labels",
"without",
"the",
"need",
"of",
"dockerd",
".",
"Instead",
"skopeo",
"is",
"being",
"used",
"."
] | 00bb80e6e91522e15361935f813e8cf13d7e76dc | https://github.com/user-cont/colin/blob/00bb80e6e91522e15361935f813e8cf13d7e76dc/colin/core/target.py#L341-L350 |
20,061 | user-cont/colin | colin/core/target.py | OstreeTarget.tmpdir | 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 | def tmpdir(self):
if self._tmpdir is None:
self._tmpdir = mkdtemp(prefix="colin-", dir="/var/tmp")
return self._tmpdir | [
"def",
"tmpdir",
"(",
"self",
")",
":",
"if",
"self",
".",
"_tmpdir",
"is",
"None",
":",
"self",
".",
"_tmpdir",
"=",
"mkdtemp",
"(",
"prefix",
"=",
"\"colin-\"",
",",
"dir",
"=",
"\"/var/tmp\"",
")",
"return",
"self",
".",
"_tmpdir"
] | Temporary directory holding all the runtime data. | [
"Temporary",
"directory",
"holding",
"all",
"the",
"runtime",
"data",
"."
] | 00bb80e6e91522e15361935f813e8cf13d7e76dc | https://github.com/user-cont/colin/blob/00bb80e6e91522e15361935f813e8cf13d7e76dc/colin/core/target.py#L383-L387 |
20,062 | user-cont/colin | colin/core/target.py | OstreeTarget._checkout | 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 mount selected image as an ostree repo.") | python | def _checkout(self):
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 mount selected image as an ostree repo.") | [
"def",
"_checkout",
"(",
"self",
")",
":",
"cmd",
"=",
"[",
"\"atomic\"",
",",
"\"mount\"",
",",
"\"--storage\"",
",",
"\"ostree\"",
",",
"self",
".",
"ref_image_name",
",",
"self",
".",
"mount_point",
"]",
"# self.mount_point has to be created by us",
"self",
"... | check out the image filesystem on self.mount_point | [
"check",
"out",
"the",
"image",
"filesystem",
"on",
"self",
".",
"mount_point"
] | 00bb80e6e91522e15361935f813e8cf13d7e76dc | https://github.com/user-cont/colin/blob/00bb80e6e91522e15361935f813e8cf13d7e76dc/colin/core/target.py#L394-L399 |
20,063 | user-cont/colin | colin/core/target.py | OstreeTarget._run_and_log | 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 ostree_repo_path:
# must not exist, ostree will create it
kwargs["env"]["ATOMIC_OSTREE_REPO"] = ostree_repo_path
if wd:
kwargs["cwd"] = wd
try:
out = subprocess.check_output(cmd, **kwargs)
except subprocess.CalledProcessError as ex:
logger.error(ex.output)
logger.error(error_msg)
raise
logger.debug("%s", out) | python | def _run_and_log(cmd, ostree_repo_path, error_msg, wd=None):
logger.debug("running command %s", cmd)
kwargs = {
"stderr": subprocess.STDOUT,
"env": os.environ.copy(),
}
if ostree_repo_path:
# must not exist, ostree will create it
kwargs["env"]["ATOMIC_OSTREE_REPO"] = ostree_repo_path
if wd:
kwargs["cwd"] = wd
try:
out = subprocess.check_output(cmd, **kwargs)
except subprocess.CalledProcessError as ex:
logger.error(ex.output)
logger.error(error_msg)
raise
logger.debug("%s", out) | [
"def",
"_run_and_log",
"(",
"cmd",
",",
"ostree_repo_path",
",",
"error_msg",
",",
"wd",
"=",
"None",
")",
":",
"logger",
".",
"debug",
"(",
"\"running command %s\"",
",",
"cmd",
")",
"kwargs",
"=",
"{",
"\"stderr\"",
":",
"subprocess",
".",
"STDOUT",
",",... | run provided command and log all of its output; set path to ostree repo | [
"run",
"provided",
"command",
"and",
"log",
"all",
"of",
"its",
"output",
";",
"set",
"path",
"to",
"ostree",
"repo"
] | 00bb80e6e91522e15361935f813e8cf13d7e76dc | https://github.com/user-cont/colin/blob/00bb80e6e91522e15361935f813e8cf13d7e76dc/colin/core/target.py#L402-L420 |
20,064 | Garee/pytodoist | pytodoist/api.py | TodoistAPI.login_with_google | 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_signup: If ``1`` register an account automatically.
:type auto_signup: int
:param full_name: The full name to use if the account is registered
automatically. If no name is given an email based nickname is used.
:type full_name: str
:param timezone: The timezone to use if the account is registered
automatically. If no timezone is given one is chosen based on the
user's IP address.
:type timezone: str
:param lang: The user's language.
:type lang: str
:return: The HTTP response to the request.
:rtype: :class:`requests.Response`
>>> from pytodoist.api import TodoistAPI
>>> api = TodoistAPI()
>>> oauth2_token = 'oauth2_token' # Get this from Google.
>>> response = api.login_with_google('john.doe@gmail.com',
... oauth2_token)
>>> user_info = response.json()
>>> full_name = user_info['full_name']
>>> print(full_name)
John Doe
"""
params = {
'email': email,
'oauth2_token': oauth2_token
}
req_func = self._get
if kwargs.get('auto_signup', 0) == 1: # POST if we're creating a user.
req_func = self._post
return req_func('login_with_google', params, **kwargs) | python | def login_with_google(self, email, oauth2_token, **kwargs):
params = {
'email': email,
'oauth2_token': oauth2_token
}
req_func = self._get
if kwargs.get('auto_signup', 0) == 1: # POST if we're creating a user.
req_func = self._post
return req_func('login_with_google', params, **kwargs) | [
"def",
"login_with_google",
"(",
"self",
",",
"email",
",",
"oauth2_token",
",",
"*",
"*",
"kwargs",
")",
":",
"params",
"=",
"{",
"'email'",
":",
"email",
",",
"'oauth2_token'",
":",
"oauth2_token",
"}",
"req_func",
"=",
"self",
".",
"_get",
"if",
"kwar... | 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_signup: If ``1`` register an account automatically.
:type auto_signup: int
:param full_name: The full name to use if the account is registered
automatically. If no name is given an email based nickname is used.
:type full_name: str
:param timezone: The timezone to use if the account is registered
automatically. If no timezone is given one is chosen based on the
user's IP address.
:type timezone: str
:param lang: The user's language.
:type lang: str
:return: The HTTP response to the request.
:rtype: :class:`requests.Response`
>>> from pytodoist.api import TodoistAPI
>>> api = TodoistAPI()
>>> oauth2_token = 'oauth2_token' # Get this from Google.
>>> response = api.login_with_google('john.doe@gmail.com',
... oauth2_token)
>>> user_info = response.json()
>>> full_name = user_info['full_name']
>>> print(full_name)
John Doe | [
"Login",
"to",
"Todoist",
"using",
"Google",
"s",
"oauth2",
"authentication",
"."
] | 3359cbff485ebdbbb4ffbd58d71e21a817874dd7 | https://github.com/Garee/pytodoist/blob/3359cbff485ebdbbb4ffbd58d71e21a817874dd7/pytodoist/api.py#L60-L98 |
20,065 | Garee/pytodoist | pytodoist/api.py | TodoistAPI.register | 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
:param lang: The user's language.
:type lang: str
:param timezone: The user's timezone.
:type timezone: str
:return: The HTTP response to the request.
:rtype: :class:`requests.Response`
>>> from pytodoist.api import TodoistAPI
>>> api = TodoistAPI()
>>> response = api.register('john.doe@gmail.com', 'John Doe',
... 'password')
>>> user_info = response.json()
>>> full_name = user_info['full_name']
>>> print(full_name)
John Doe
"""
params = {
'email': email,
'full_name': full_name,
'password': password
}
return self._post('register', params, **kwargs) | python | def register(self, email, full_name, password, **kwargs):
params = {
'email': email,
'full_name': full_name,
'password': password
}
return self._post('register', params, **kwargs) | [
"def",
"register",
"(",
"self",
",",
"email",
",",
"full_name",
",",
"password",
",",
"*",
"*",
"kwargs",
")",
":",
"params",
"=",
"{",
"'email'",
":",
"email",
",",
"'full_name'",
":",
"full_name",
",",
"'password'",
":",
"password",
"}",
"return",
"s... | 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
:param lang: The user's language.
:type lang: str
:param timezone: The user's timezone.
:type timezone: str
:return: The HTTP response to the request.
:rtype: :class:`requests.Response`
>>> from pytodoist.api import TodoistAPI
>>> api = TodoistAPI()
>>> response = api.register('john.doe@gmail.com', 'John Doe',
... 'password')
>>> user_info = response.json()
>>> full_name = user_info['full_name']
>>> print(full_name)
John Doe | [
"Register",
"a",
"new",
"Todoist",
"user",
"."
] | 3359cbff485ebdbbb4ffbd58d71e21a817874dd7 | https://github.com/Garee/pytodoist/blob/3359cbff485ebdbbb4ffbd58d71e21a817874dd7/pytodoist/api.py#L100-L130 |
20,066 | Garee/pytodoist | pytodoist/api.py | TodoistAPI.delete_user | 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 deletion.
:type reason_for_delete: str
:param in_background: If ``0``, delete the user instantly.
:type in_background: int
:return: The HTTP response to the request.
:rtype: :class:`requests.Response`
"""
params = {
'token': api_token,
'current_password': password
}
return self._post('delete_user', params, **kwargs) | python | def delete_user(self, api_token, password, **kwargs):
params = {
'token': api_token,
'current_password': password
}
return self._post('delete_user', params, **kwargs) | [
"def",
"delete_user",
"(",
"self",
",",
"api_token",
",",
"password",
",",
"*",
"*",
"kwargs",
")",
":",
"params",
"=",
"{",
"'token'",
":",
"api_token",
",",
"'current_password'",
":",
"password",
"}",
"return",
"self",
".",
"_post",
"(",
"'delete_user'",... | 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 deletion.
:type reason_for_delete: str
:param in_background: If ``0``, delete the user instantly.
:type in_background: int
:return: The HTTP response to the request.
:rtype: :class:`requests.Response` | [
"Delete",
"a",
"registered",
"Todoist",
"user",
"s",
"account",
"."
] | 3359cbff485ebdbbb4ffbd58d71e21a817874dd7 | https://github.com/Garee/pytodoist/blob/3359cbff485ebdbbb4ffbd58d71e21a817874dd7/pytodoist/api.py#L132-L150 |
20,067 | Garee/pytodoist | pytodoist/api.py | TodoistAPI.sync | 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 the last seq_no you received.
:type seq_no: int
:param seq_no_global: The request sequence number. On initial request
pass ``0``. On all others pass the last seq_no you received.
:type seq_no_global: int
:param resource_types: Specifies which subset of data you want to
receive e.g. only projects. Defaults to all data.
:type resources_types: str
:param commands: A list of JSON commands to perform.
:type commands: list (str)
:return: The HTTP response to the request.
:rtype: :class:`requests.Response`
>>> from pytodoist.api import TodoistAPI
>>> api = TodoistAPI()
>>> response = api.register('john.doe@gmail.com', 'John Doe',
... 'password')
>>> user_info = response.json()
>>> api_token = user_info['api_token']
>>> response = api.sync(api_token, 0, 0, '["projects"]')
>>> print(response.json())
{'seq_no_global': 3848029654, 'seq_no': 3848029654, 'Projects': ...}
"""
params = {
'token': api_token,
'sync_token': sync_token,
}
req_func = self._post
if 'commands' not in kwargs: # GET if we're not changing data.
req_func = self._get
params['resource_types'] = resource_types
return req_func('sync', params, **kwargs) | python | def sync(self, api_token, sync_token, resource_types='["all"]', **kwargs):
params = {
'token': api_token,
'sync_token': sync_token,
}
req_func = self._post
if 'commands' not in kwargs: # GET if we're not changing data.
req_func = self._get
params['resource_types'] = resource_types
return req_func('sync', params, **kwargs) | [
"def",
"sync",
"(",
"self",
",",
"api_token",
",",
"sync_token",
",",
"resource_types",
"=",
"'[\"all\"]'",
",",
"*",
"*",
"kwargs",
")",
":",
"params",
"=",
"{",
"'token'",
":",
"api_token",
",",
"'sync_token'",
":",
"sync_token",
",",
"}",
"req_func",
... | 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 the last seq_no you received.
:type seq_no: int
:param seq_no_global: The request sequence number. On initial request
pass ``0``. On all others pass the last seq_no you received.
:type seq_no_global: int
:param resource_types: Specifies which subset of data you want to
receive e.g. only projects. Defaults to all data.
:type resources_types: str
:param commands: A list of JSON commands to perform.
:type commands: list (str)
:return: The HTTP response to the request.
:rtype: :class:`requests.Response`
>>> from pytodoist.api import TodoistAPI
>>> api = TodoistAPI()
>>> response = api.register('john.doe@gmail.com', 'John Doe',
... 'password')
>>> user_info = response.json()
>>> api_token = user_info['api_token']
>>> response = api.sync(api_token, 0, 0, '["projects"]')
>>> print(response.json())
{'seq_no_global': 3848029654, 'seq_no': 3848029654, 'Projects': ...} | [
"Update",
"and",
"retrieve",
"Todoist",
"data",
"."
] | 3359cbff485ebdbbb4ffbd58d71e21a817874dd7 | https://github.com/Garee/pytodoist/blob/3359cbff485ebdbbb4ffbd58d71e21a817874dd7/pytodoist/api.py#L152-L189 |
20,068 | Garee/pytodoist | pytodoist/api.py | TodoistAPI.query | 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/Help/timeQuery>`_.
:type queries: list (str)
:param as_count: If ``1`` then return the count of matching tasks.
:type as_count: int
:return: The HTTP response to the request.
:rtype: :class:`requests.Response`
"""
params = {
'token': api_token,
'queries': queries
}
return self._get('query', params, **kwargs) | python | def query(self, api_token, queries, **kwargs):
params = {
'token': api_token,
'queries': queries
}
return self._get('query', params, **kwargs) | [
"def",
"query",
"(",
"self",
",",
"api_token",
",",
"queries",
",",
"*",
"*",
"kwargs",
")",
":",
"params",
"=",
"{",
"'token'",
":",
"api_token",
",",
"'queries'",
":",
"queries",
"}",
"return",
"self",
".",
"_get",
"(",
"'query'",
",",
"params",
",... | 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/Help/timeQuery>`_.
:type queries: list (str)
:param as_count: If ``1`` then return the count of matching tasks.
:type as_count: int
:return: The HTTP response to the request.
:rtype: :class:`requests.Response` | [
"Search",
"all",
"of",
"a",
"user",
"s",
"tasks",
"using",
"date",
"priority",
"and",
"label",
"queries",
"."
] | 3359cbff485ebdbbb4ffbd58d71e21a817874dd7 | https://github.com/Garee/pytodoist/blob/3359cbff485ebdbbb4ffbd58d71e21a817874dd7/pytodoist/api.py#L191-L208 |
20,069 | Garee/pytodoist | pytodoist/api.py | TodoistAPI.add_item | 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``
:type project_id: str
:param date_string: The deadline date for the task.
:type date_string: str
:param priority: The task priority ``(1-4)``.
:type priority: int
:param indent: The task indentation ``(1-4)``.
:type indent: int
:param item_order: The task order.
:type item_order: int
:param children: A list of child tasks IDs.
:type children: str
:param labels: A list of label IDs.
:type labels: str
:param assigned_by_uid: The ID of the user who assigns current task.
Accepts 0 or any user id from the list of project collaborators.
If value is unset or invalid it will automatically be set up by
your uid.
:type assigned_by_uid: str
:param responsible_uid: The id of user who is responsible for
accomplishing the current task. Accepts 0 or any user id from
the list of project collaborators. If the value is unset or
invalid it will automatically be set to null.
:type responsible_uid: str
:param note: Content of a note to add.
:type note: str
:return: The HTTP response to the request.
:rtype: :class:`requests.Response`
>>> from pytodoist.api import TodoistAPI
>>> api = TodoistAPI()
>>> response = api.login('john.doe@gmail.com', 'password')
>>> user_info = response.json()
>>> user_api_token = user_info['token']
>>> response = api.add_item(user_api_token, 'Install PyTodoist')
>>> task = response.json()
>>> print(task['content'])
Install PyTodoist
"""
params = {
'token': api_token,
'content': content
}
return self._post('add_item', params, **kwargs) | python | def add_item(self, api_token, content, **kwargs):
params = {
'token': api_token,
'content': content
}
return self._post('add_item', params, **kwargs) | [
"def",
"add_item",
"(",
"self",
",",
"api_token",
",",
"content",
",",
"*",
"*",
"kwargs",
")",
":",
"params",
"=",
"{",
"'token'",
":",
"api_token",
",",
"'content'",
":",
"content",
"}",
"return",
"self",
".",
"_post",
"(",
"'add_item'",
",",
"params... | 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``
:type project_id: str
:param date_string: The deadline date for the task.
:type date_string: str
:param priority: The task priority ``(1-4)``.
:type priority: int
:param indent: The task indentation ``(1-4)``.
:type indent: int
:param item_order: The task order.
:type item_order: int
:param children: A list of child tasks IDs.
:type children: str
:param labels: A list of label IDs.
:type labels: str
:param assigned_by_uid: The ID of the user who assigns current task.
Accepts 0 or any user id from the list of project collaborators.
If value is unset or invalid it will automatically be set up by
your uid.
:type assigned_by_uid: str
:param responsible_uid: The id of user who is responsible for
accomplishing the current task. Accepts 0 or any user id from
the list of project collaborators. If the value is unset or
invalid it will automatically be set to null.
:type responsible_uid: str
:param note: Content of a note to add.
:type note: str
:return: The HTTP response to the request.
:rtype: :class:`requests.Response`
>>> from pytodoist.api import TodoistAPI
>>> api = TodoistAPI()
>>> response = api.login('john.doe@gmail.com', 'password')
>>> user_info = response.json()
>>> user_api_token = user_info['token']
>>> response = api.add_item(user_api_token, 'Install PyTodoist')
>>> task = response.json()
>>> print(task['content'])
Install PyTodoist | [
"Add",
"a",
"task",
"to",
"a",
"project",
"."
] | 3359cbff485ebdbbb4ffbd58d71e21a817874dd7 | https://github.com/Garee/pytodoist/blob/3359cbff485ebdbbb4ffbd58d71e21a817874dd7/pytodoist/api.py#L210-L260 |
20,070 | Garee/pytodoist | pytodoist/api.py | TodoistAPI.quick_add | 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 starts with a `@`
and an assignee starts with a `+`.
:type text: str
:param note: The content of the note.
:type note: str
:param reminder: The date of the reminder, added in free form text.
:type reminder: str
:return: The HTTP response to the request.
:rtype: :class:`requests.Response`
"""
params = {
'token': api_token,
'text': text
}
return self._post('quick/add', params, **kwargs) | python | def quick_add(self, api_token, text, **kwargs):
params = {
'token': api_token,
'text': text
}
return self._post('quick/add', params, **kwargs) | [
"def",
"quick_add",
"(",
"self",
",",
"api_token",
",",
"text",
",",
"*",
"*",
"kwargs",
")",
":",
"params",
"=",
"{",
"'token'",
":",
"api_token",
",",
"'text'",
":",
"text",
"}",
"return",
"self",
".",
"_post",
"(",
"'quick/add'",
",",
"params",
",... | 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 starts with a `@`
and an assignee starts with a `+`.
:type text: str
:param note: The content of the note.
:type note: str
:param reminder: The date of the reminder, added in free form text.
:type reminder: str
:return: The HTTP response to the request.
:rtype: :class:`requests.Response` | [
"Add",
"a",
"task",
"using",
"the",
"Todoist",
"Quick",
"Add",
"Task",
"syntax",
"."
] | 3359cbff485ebdbbb4ffbd58d71e21a817874dd7 | https://github.com/Garee/pytodoist/blob/3359cbff485ebdbbb4ffbd58d71e21a817874dd7/pytodoist/api.py#L262-L282 |
20,071 | Garee/pytodoist | pytodoist/api.py | TodoistAPI.get_all_completed_tasks | 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_id: str
:param limit: The maximum number of tasks to return
(default ``30``, max ``50``).
:type limit: int
:param offset: Used for pagination if there are more tasks than limit.
:type offset: int
:param from_date: Return tasks with a completion date on or older than
from_date. Formatted as ``2007-4-29T10:13``.
:type from_date: str
:param to: Return tasks with a completion date on or less than
to_date. Formatted as ``2007-4-29T10:13``.
:type from_date: str
:return: The HTTP response to the request.
:rtype: :class:`requests.Response`
>>> from pytodoist.api import TodoistAPI
>>> api = TodoistAPI()
>>> response = api.login('john.doe@gmail.com', 'password')
>>> user_info = response.json()
>>> user_api_token = user_info['api_token']
>>> response = api.get_all_completed_tasks(user_api_token)
>>> completed_tasks = response.json()
"""
params = {
'token': api_token
}
return self._get('get_all_completed_items', params, **kwargs) | python | def get_all_completed_tasks(self, api_token, **kwargs):
params = {
'token': api_token
}
return self._get('get_all_completed_items', params, **kwargs) | [
"def",
"get_all_completed_tasks",
"(",
"self",
",",
"api_token",
",",
"*",
"*",
"kwargs",
")",
":",
"params",
"=",
"{",
"'token'",
":",
"api_token",
"}",
"return",
"self",
".",
"_get",
"(",
"'get_all_completed_items'",
",",
"params",
",",
"*",
"*",
"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_id: str
:param limit: The maximum number of tasks to return
(default ``30``, max ``50``).
:type limit: int
:param offset: Used for pagination if there are more tasks than limit.
:type offset: int
:param from_date: Return tasks with a completion date on or older than
from_date. Formatted as ``2007-4-29T10:13``.
:type from_date: str
:param to: Return tasks with a completion date on or less than
to_date. Formatted as ``2007-4-29T10:13``.
:type from_date: str
:return: The HTTP response to the request.
:rtype: :class:`requests.Response`
>>> from pytodoist.api import TodoistAPI
>>> api = TodoistAPI()
>>> response = api.login('john.doe@gmail.com', 'password')
>>> user_info = response.json()
>>> user_api_token = user_info['api_token']
>>> response = api.get_all_completed_tasks(user_api_token)
>>> completed_tasks = response.json() | [
"Return",
"a",
"list",
"of",
"a",
"user",
"s",
"completed",
"tasks",
"."
] | 3359cbff485ebdbbb4ffbd58d71e21a817874dd7 | https://github.com/Garee/pytodoist/blob/3359cbff485ebdbbb4ffbd58d71e21a817874dd7/pytodoist/api.py#L284-L318 |
20,072 | Garee/pytodoist | pytodoist/api.py | TodoistAPI.upload_file | 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 HTTP response to the request.
:rtype: :class:`requests.Response`
"""
params = {
'token': api_token,
'file_name': os.path.basename(file_path)
}
with open(file_path, 'rb') as f:
files = {'file': f}
return self._post('upload_file', params, files, **kwargs) | python | def upload_file(self, api_token, file_path, **kwargs):
params = {
'token': api_token,
'file_name': os.path.basename(file_path)
}
with open(file_path, 'rb') as f:
files = {'file': f}
return self._post('upload_file', params, files, **kwargs) | [
"def",
"upload_file",
"(",
"self",
",",
"api_token",
",",
"file_path",
",",
"*",
"*",
"kwargs",
")",
":",
"params",
"=",
"{",
"'token'",
":",
"api_token",
",",
"'file_name'",
":",
"os",
".",
"path",
".",
"basename",
"(",
"file_path",
")",
"}",
"with",
... | 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 HTTP response to the request.
:rtype: :class:`requests.Response` | [
"Upload",
"a",
"file",
"suitable",
"to",
"be",
"passed",
"as",
"a",
"file_attachment",
"."
] | 3359cbff485ebdbbb4ffbd58d71e21a817874dd7 | https://github.com/Garee/pytodoist/blob/3359cbff485ebdbbb4ffbd58d71e21a817874dd7/pytodoist/api.py#L320-L336 |
20,073 | Garee/pytodoist | pytodoist/api.py | TodoistAPI.get_productivity_stats | 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 = {
'token': api_token
}
return self._get('get_productivity_stats', params, **kwargs) | python | def get_productivity_stats(self, api_token, **kwargs):
params = {
'token': api_token
}
return self._get('get_productivity_stats', params, **kwargs) | [
"def",
"get_productivity_stats",
"(",
"self",
",",
"api_token",
",",
"*",
"*",
"kwargs",
")",
":",
"params",
"=",
"{",
"'token'",
":",
"api_token",
"}",
"return",
"self",
".",
"_get",
"(",
"'get_productivity_stats'",
",",
"params",
",",
"*",
"*",
"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` | [
"Return",
"a",
"user",
"s",
"productivity",
"stats",
"."
] | 3359cbff485ebdbbb4ffbd58d71e21a817874dd7 | https://github.com/Garee/pytodoist/blob/3359cbff485ebdbbb4ffbd58d71e21a817874dd7/pytodoist/api.py#L338-L349 |
20,074 | Garee/pytodoist | pytodoist/api.py | TodoistAPI.update_notification_settings | 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 event.
:type event: str
:param service: ``email`` or ``push``
:type service: str
:param should_notify: If ``0`` notify, otherwise do not.
:type should_notify: int
:return: The HTTP response to the request.
:rtype: :class:`requests.Response`
>>> from pytodoist.api import TodoistAPI
>>> api = TodoistAPI()
>>> response = api.login('john.doe@gmail.com', 'password')
>>> user_info = response.json()
>>> user_api_token = user_info['api_token']
>>> response = api.update_notification_settings(user_api_token,
... 'user_left_project',
... 'email', 0)
...
"""
params = {
'token': api_token,
'notification_type': event,
'service': service,
'dont_notify': should_notify
}
return self._post('update_notification_setting', params) | python | def update_notification_settings(self, api_token, event,
service, should_notify):
params = {
'token': api_token,
'notification_type': event,
'service': service,
'dont_notify': should_notify
}
return self._post('update_notification_setting', params) | [
"def",
"update_notification_settings",
"(",
"self",
",",
"api_token",
",",
"event",
",",
"service",
",",
"should_notify",
")",
":",
"params",
"=",
"{",
"'token'",
":",
"api_token",
",",
"'notification_type'",
":",
"event",
",",
"'service'",
":",
"service",
","... | 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 event.
:type event: str
:param service: ``email`` or ``push``
:type service: str
:param should_notify: If ``0`` notify, otherwise do not.
:type should_notify: int
:return: The HTTP response to the request.
:rtype: :class:`requests.Response`
>>> from pytodoist.api import TodoistAPI
>>> api = TodoistAPI()
>>> response = api.login('john.doe@gmail.com', 'password')
>>> user_info = response.json()
>>> user_api_token = user_info['api_token']
>>> response = api.update_notification_settings(user_api_token,
... 'user_left_project',
... 'email', 0)
... | [
"Update",
"a",
"user",
"s",
"notification",
"settings",
"."
] | 3359cbff485ebdbbb4ffbd58d71e21a817874dd7 | https://github.com/Garee/pytodoist/blob/3359cbff485ebdbbb4ffbd58d71e21a817874dd7/pytodoist/api.py#L351-L382 |
20,075 | Garee/pytodoist | pytodoist/api.py | TodoistAPI._get | 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 parameters.
:type kwargs: dict
:return: The HTTP response to the request.
:rtype: :class:`requests.Response`
"""
return self._request(requests.get, end_point, params, **kwargs) | python | def _get(self, end_point, params=None, **kwargs):
return self._request(requests.get, end_point, params, **kwargs) | [
"def",
"_get",
"(",
"self",
",",
"end_point",
",",
"params",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"_request",
"(",
"requests",
".",
"get",
",",
"end_point",
",",
"params",
",",
"*",
"*",
"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 parameters.
:type kwargs: dict
:return: The HTTP response to the request.
:rtype: :class:`requests.Response` | [
"Send",
"a",
"HTTP",
"GET",
"request",
"to",
"a",
"Todoist",
"API",
"end",
"-",
"point",
"."
] | 3359cbff485ebdbbb4ffbd58d71e21a817874dd7 | https://github.com/Garee/pytodoist/blob/3359cbff485ebdbbb4ffbd58d71e21a817874dd7/pytodoist/api.py#L415-L427 |
20,076 | Garee/pytodoist | pytodoist/api.py | TodoistAPI._post | 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 files that are being sent as multipart/form-data.
:type files: dict
:param kwargs: Any optional parameters.
:type kwargs: dict
:return: The HTTP response to the request.
:rtype: :class:`requests.Response`
"""
return self._request(requests.post, end_point, params, files, **kwargs) | python | def _post(self, end_point, params=None, files=None, **kwargs):
return self._request(requests.post, end_point, params, files, **kwargs) | [
"def",
"_post",
"(",
"self",
",",
"end_point",
",",
"params",
"=",
"None",
",",
"files",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"_request",
"(",
"requests",
".",
"post",
",",
"end_point",
",",
"params",
",",
"files",
... | 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 files that are being sent as multipart/form-data.
:type files: dict
:param kwargs: Any optional parameters.
:type kwargs: dict
:return: The HTTP response to the request.
:rtype: :class:`requests.Response` | [
"Send",
"a",
"HTTP",
"POST",
"request",
"to",
"a",
"Todoist",
"API",
"end",
"-",
"point",
"."
] | 3359cbff485ebdbbb4ffbd58d71e21a817874dd7 | https://github.com/Garee/pytodoist/blob/3359cbff485ebdbbb4ffbd58d71e21a817874dd7/pytodoist/api.py#L429-L443 |
20,077 | Garee/pytodoist | pytodoist/api.py | TodoistAPI._request | 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 Todoist API end-point.
:type end_point: str
:param params: The required request parameters.
:type params: dict
:param files: Any files that are being sent as multipart/form-data.
:type files: dict
:param kwargs: Any optional parameters.
:type kwargs: dict
:return: The HTTP response to the request.
:rtype: :class:`requests.Response`
"""
url = self.URL + end_point
if params and kwargs:
params.update(kwargs)
return req_func(url, params=params, files=files) | python | def _request(self, req_func, end_point, params=None, files=None, **kwargs):
url = self.URL + end_point
if params and kwargs:
params.update(kwargs)
return req_func(url, params=params, files=files) | [
"def",
"_request",
"(",
"self",
",",
"req_func",
",",
"end_point",
",",
"params",
"=",
"None",
",",
"files",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"url",
"=",
"self",
".",
"URL",
"+",
"end_point",
"if",
"params",
"and",
"kwargs",
":",
"pa... | 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 Todoist API end-point.
:type end_point: str
:param params: The required request parameters.
:type params: dict
:param files: Any files that are being sent as multipart/form-data.
:type files: dict
:param kwargs: Any optional parameters.
:type kwargs: dict
:return: The HTTP response to the request.
:rtype: :class:`requests.Response` | [
"Send",
"a",
"HTTP",
"request",
"to",
"a",
"Todoist",
"API",
"end",
"-",
"point",
"."
] | 3359cbff485ebdbbb4ffbd58d71e21a817874dd7 | https://github.com/Garee/pytodoist/blob/3359cbff485ebdbbb4ffbd58d71e21a817874dd7/pytodoist/api.py#L445-L464 |
20,078 | Garee/pytodoist | pytodoist/todoist.py | login_with_api_token | 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 import todoist
>>> api_token = 'api_token'
>>> user = todoist.login_with_api_token(api_token)
>>> print(user.full_name)
John Doe
"""
response = API.sync(api_token, '*', '["user"]')
_fail_if_contains_errors(response)
user_json = response.json()['user']
# Required as sync doesn't return the api_token.
user_json['api_token'] = user_json['token']
return User(user_json) | python | def login_with_api_token(api_token):
response = API.sync(api_token, '*', '["user"]')
_fail_if_contains_errors(response)
user_json = response.json()['user']
# Required as sync doesn't return the api_token.
user_json['api_token'] = user_json['token']
return User(user_json) | [
"def",
"login_with_api_token",
"(",
"api_token",
")",
":",
"response",
"=",
"API",
".",
"sync",
"(",
"api_token",
",",
"'*'",
",",
"'[\"user\"]'",
")",
"_fail_if_contains_errors",
"(",
"response",
")",
"user_json",
"=",
"response",
".",
"json",
"(",
")",
"["... | 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 import todoist
>>> api_token = 'api_token'
>>> user = todoist.login_with_api_token(api_token)
>>> print(user.full_name)
John Doe | [
"Login",
"to",
"Todoist",
"using",
"a",
"user",
"s",
"api",
"token",
"."
] | 3359cbff485ebdbbb4ffbd58d71e21a817874dd7 | https://github.com/Garee/pytodoist/blob/3359cbff485ebdbbb4ffbd58d71e21a817874dd7/pytodoist/todoist.py#L71-L92 |
20,079 | Garee/pytodoist | pytodoist/todoist.py | _login | 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 | def _login(login_func, *args):
response = login_func(*args)
_fail_if_contains_errors(response)
user_json = response.json()
return User(user_json) | [
"def",
"_login",
"(",
"login_func",
",",
"*",
"args",
")",
":",
"response",
"=",
"login_func",
"(",
"*",
"args",
")",
"_fail_if_contains_errors",
"(",
"response",
")",
"user_json",
"=",
"response",
".",
"json",
"(",
")",
"return",
"User",
"(",
"user_json",... | A helper function for logging in. It's purpose is to avoid duplicate
code in the login functions. | [
"A",
"helper",
"function",
"for",
"logging",
"in",
".",
"It",
"s",
"purpose",
"is",
"to",
"avoid",
"duplicate",
"code",
"in",
"the",
"login",
"functions",
"."
] | 3359cbff485ebdbbb4ffbd58d71e21a817874dd7 | https://github.com/Garee/pytodoist/blob/3359cbff485ebdbbb4ffbd58d71e21a817874dd7/pytodoist/todoist.py#L95-L102 |
20,080 | Garee/pytodoist | pytodoist/todoist.py | register | 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 lang: The user's language.
:type lang: str
:param timezone: The user's timezone.
:type timezone: str
:return: The Todoist user.
:rtype: :class:`pytodoist.todoist.User`
>>> from pytodoist import todoist
>>> user = todoist.register('John Doe', 'john.doe@gmail.com', 'password')
>>> print(user.full_name)
John Doe
"""
response = API.register(email, full_name, password,
lang=lang, timezone=timezone)
_fail_if_contains_errors(response)
user_json = response.json()
user = User(user_json)
user.password = password
return user | python | def register(full_name, email, password, lang=None, timezone=None):
response = API.register(email, full_name, password,
lang=lang, timezone=timezone)
_fail_if_contains_errors(response)
user_json = response.json()
user = User(user_json)
user.password = password
return user | [
"def",
"register",
"(",
"full_name",
",",
"email",
",",
"password",
",",
"lang",
"=",
"None",
",",
"timezone",
"=",
"None",
")",
":",
"response",
"=",
"API",
".",
"register",
"(",
"email",
",",
"full_name",
",",
"password",
",",
"lang",
"=",
"lang",
... | 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 lang: The user's language.
:type lang: str
:param timezone: The user's timezone.
:type timezone: str
:return: The Todoist user.
:rtype: :class:`pytodoist.todoist.User`
>>> from pytodoist import todoist
>>> user = todoist.register('John Doe', 'john.doe@gmail.com', 'password')
>>> print(user.full_name)
John Doe | [
"Register",
"a",
"new",
"Todoist",
"account",
"."
] | 3359cbff485ebdbbb4ffbd58d71e21a817874dd7 | https://github.com/Garee/pytodoist/blob/3359cbff485ebdbbb4ffbd58d71e21a817874dd7/pytodoist/todoist.py#L105-L132 |
20,081 | Garee/pytodoist | pytodoist/todoist.py | register_with_google | 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
:param oauth2_token: The oauth2 token associated with the email.
:type oauth2_token: str
:param lang: The user's language.
:type lang: str
:param timezone: The user's timezone.
:type timezone: str
:return: The Todoist user.
:rtype: :class:`pytodoist.todoist.User`
.. note:: It is up to you to obtain the valid oauth2 token.
>>> from pytodoist import todoist
>>> oauth2_token = 'oauth2_token'
>>> user = todoist.register_with_google('John Doe', 'john.doe@gmail.com',
... oauth2_token)
>>> print(user.full_name)
John Doe
"""
response = API.login_with_google(email, oauth2_token, auto_signup=1,
full_name=full_name, lang=lang,
timezone=timezone)
_fail_if_contains_errors(response)
user_json = response.json()
user = User(user_json)
return user | python | def register_with_google(full_name, email, oauth2_token,
lang=None, timezone=None):
response = API.login_with_google(email, oauth2_token, auto_signup=1,
full_name=full_name, lang=lang,
timezone=timezone)
_fail_if_contains_errors(response)
user_json = response.json()
user = User(user_json)
return user | [
"def",
"register_with_google",
"(",
"full_name",
",",
"email",
",",
"oauth2_token",
",",
"lang",
"=",
"None",
",",
"timezone",
"=",
"None",
")",
":",
"response",
"=",
"API",
".",
"login_with_google",
"(",
"email",
",",
"oauth2_token",
",",
"auto_signup",
"="... | 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
:param oauth2_token: The oauth2 token associated with the email.
:type oauth2_token: str
:param lang: The user's language.
:type lang: str
:param timezone: The user's timezone.
:type timezone: str
:return: The Todoist user.
:rtype: :class:`pytodoist.todoist.User`
.. note:: It is up to you to obtain the valid oauth2 token.
>>> from pytodoist import todoist
>>> oauth2_token = 'oauth2_token'
>>> user = todoist.register_with_google('John Doe', 'john.doe@gmail.com',
... oauth2_token)
>>> print(user.full_name)
John Doe | [
"Register",
"a",
"new",
"Todoist",
"account",
"by",
"linking",
"a",
"Google",
"account",
"."
] | 3359cbff485ebdbbb4ffbd58d71e21a817874dd7 | https://github.com/Garee/pytodoist/blob/3359cbff485ebdbbb4ffbd58d71e21a817874dd7/pytodoist/todoist.py#L135-L167 |
20,082 | Garee/pytodoist | pytodoist/todoist.py | _fail_if_contains_errors | 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 response_json:
status = response_json['sync_status']
if sync_uuid in status and 'error' in status[sync_uuid]:
raise RequestError(response) | python | def _fail_if_contains_errors(response, sync_uuid=None):
if response.status_code != _HTTP_OK:
raise RequestError(response)
response_json = response.json()
if sync_uuid and 'sync_status' in response_json:
status = response_json['sync_status']
if sync_uuid in status and 'error' in status[sync_uuid]:
raise RequestError(response) | [
"def",
"_fail_if_contains_errors",
"(",
"response",
",",
"sync_uuid",
"=",
"None",
")",
":",
"if",
"response",
".",
"status_code",
"!=",
"_HTTP_OK",
":",
"raise",
"RequestError",
"(",
"response",
")",
"response_json",
"=",
"response",
".",
"json",
"(",
")",
... | Raise a RequestError Exception if a given response
does not denote a successful request. | [
"Raise",
"a",
"RequestError",
"Exception",
"if",
"a",
"given",
"response",
"does",
"not",
"denote",
"a",
"successful",
"request",
"."
] | 3359cbff485ebdbbb4ffbd58d71e21a817874dd7 | https://github.com/Garee/pytodoist/blob/3359cbff485ebdbbb4ffbd58d71e21a817874dd7/pytodoist/todoist.py#L170-L180 |
20,083 | Garee/pytodoist | pytodoist/todoist.py | _perform_command | 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 = json.dumps([command])
response = API.sync(user.api_token, user.sync_token, commands=commands)
_fail_if_contains_errors(response, command_uuid)
response_json = response.json()
user.sync_token = response_json['sync_token'] | python | def _perform_command(user, command_type, command_args):
command_uuid = _gen_uuid()
command = {
'type': command_type,
'args': command_args,
'uuid': command_uuid,
'temp_id': _gen_uuid()
}
commands = json.dumps([command])
response = API.sync(user.api_token, user.sync_token, commands=commands)
_fail_if_contains_errors(response, command_uuid)
response_json = response.json()
user.sync_token = response_json['sync_token'] | [
"def",
"_perform_command",
"(",
"user",
",",
"command_type",
",",
"command_args",
")",
":",
"command_uuid",
"=",
"_gen_uuid",
"(",
")",
"command",
"=",
"{",
"'type'",
":",
"command_type",
",",
"'args'",
":",
"command_args",
",",
"'uuid'",
":",
"command_uuid",
... | Perform an operation on Todoist using the API sync end-point. | [
"Perform",
"an",
"operation",
"on",
"Todoist",
"using",
"the",
"API",
"sync",
"end",
"-",
"point",
"."
] | 3359cbff485ebdbbb4ffbd58d71e21a817874dd7 | https://github.com/Garee/pytodoist/blob/3359cbff485ebdbbb4ffbd58d71e21a817874dd7/pytodoist/todoist.py#L188-L201 |
20,084 | Garee/pytodoist | pytodoist/todoist.py | User.update | 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'
>>> # At this point Todoist still thinks the name is 'John Doe'.
>>> user.update()
>>> # Now the name has been updated on Todoist.
"""
args = {attr: getattr(self, attr) for attr in self.to_update}
_perform_command(self, 'user_update', args) | python | def update(self):
args = {attr: getattr(self, attr) for attr in self.to_update}
_perform_command(self, 'user_update', args) | [
"def",
"update",
"(",
"self",
")",
":",
"args",
"=",
"{",
"attr",
":",
"getattr",
"(",
"self",
",",
"attr",
")",
"for",
"attr",
"in",
"self",
".",
"to_update",
"}",
"_perform_command",
"(",
"self",
",",
"'user_update'",
",",
"args",
")"
] | 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'
>>> # At this point Todoist still thinks the name is 'John Doe'.
>>> user.update()
>>> # Now the name has been updated on Todoist. | [
"Update",
"the",
"user",
"s",
"details",
"on",
"Todoist",
"."
] | 3359cbff485ebdbbb4ffbd58d71e21a817874dd7 | https://github.com/Garee/pytodoist/blob/3359cbff485ebdbbb4ffbd58d71e21a817874dd7/pytodoist/todoist.py#L313-L327 |
20,085 | Garee/pytodoist | pytodoist/todoist.py | User.sync | 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
:func:`pytodoist.todoist.User.update`.
:param resource_types: A JSON-encoded list of Todoist resources which
should be synced. By default this is everything, but you can
choose to sync only selected resources. See
`here <https://developer.todoist.com/#retrieve-data>`_ for a list
of resources.
"""
response = API.sync(self.api_token, '*', resource_types)
_fail_if_contains_errors(response)
response_json = response.json()
self.sync_token = response_json['sync_token']
if 'projects' in response_json:
self._sync_projects(response_json['projects'])
if 'items' in response_json:
self._sync_tasks(response_json['items'])
if 'notes' in response_json:
self._sync_notes(response_json['notes'])
if 'labels' in response_json:
self._sync_labels(response_json['labels'])
if 'filters' in response_json:
self._sync_filters(response_json['filters'])
if 'reminders' in response_json:
self._sync_reminders(response_json['reminders']) | python | def sync(self, resource_types='["all"]'):
response = API.sync(self.api_token, '*', resource_types)
_fail_if_contains_errors(response)
response_json = response.json()
self.sync_token = response_json['sync_token']
if 'projects' in response_json:
self._sync_projects(response_json['projects'])
if 'items' in response_json:
self._sync_tasks(response_json['items'])
if 'notes' in response_json:
self._sync_notes(response_json['notes'])
if 'labels' in response_json:
self._sync_labels(response_json['labels'])
if 'filters' in response_json:
self._sync_filters(response_json['filters'])
if 'reminders' in response_json:
self._sync_reminders(response_json['reminders']) | [
"def",
"sync",
"(",
"self",
",",
"resource_types",
"=",
"'[\"all\"]'",
")",
":",
"response",
"=",
"API",
".",
"sync",
"(",
"self",
".",
"api_token",
",",
"'*'",
",",
"resource_types",
")",
"_fail_if_contains_errors",
"(",
"response",
")",
"response_json",
"=... | 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
:func:`pytodoist.todoist.User.update`.
:param resource_types: A JSON-encoded list of Todoist resources which
should be synced. By default this is everything, but you can
choose to sync only selected resources. See
`here <https://developer.todoist.com/#retrieve-data>`_ for a list
of resources. | [
"Synchronize",
"the",
"user",
"s",
"data",
"with",
"the",
"Todoist",
"server",
"."
] | 3359cbff485ebdbbb4ffbd58d71e21a817874dd7 | https://github.com/Garee/pytodoist/blob/3359cbff485ebdbbb4ffbd58d71e21a817874dd7/pytodoist/todoist.py#L329-L358 |
20,086 | Garee/pytodoist | pytodoist/todoist.py | User._sync_projects | 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 | def _sync_projects(self, projects_json):
"for project_json in projects_json:
project_id = project_json['id']
self.projects[project_id] = Project(project_json, self) | [
"def",
"_sync_projects",
"(",
"self",
",",
"projects_json",
")",
":",
"for",
"project_json",
"in",
"projects_json",
":",
"project_id",
"=",
"project_json",
"[",
"'id'",
"]",
"self",
".",
"projects",
"[",
"project_id",
"]",
"=",
"Project",
"(",
"project_json",
... | Populate the user's projects from a JSON encoded list. | [
"Populate",
"the",
"user",
"s",
"projects",
"from",
"a",
"JSON",
"encoded",
"list",
"."
] | 3359cbff485ebdbbb4ffbd58d71e21a817874dd7 | https://github.com/Garee/pytodoist/blob/3359cbff485ebdbbb4ffbd58d71e21a817874dd7/pytodoist/todoist.py#L360-L364 |
20,087 | Garee/pytodoist | pytodoist/todoist.py | User._sync_tasks | 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
continue
project = self.projects[project_id]
self.tasks[task_id] = Task(task_json, project) | python | def _sync_tasks(self, tasks_json):
"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
continue
project = self.projects[project_id]
self.tasks[task_id] = Task(task_json, project) | [
"def",
"_sync_tasks",
"(",
"self",
",",
"tasks_json",
")",
":",
"for",
"task_json",
"in",
"tasks_json",
":",
"task_id",
"=",
"task_json",
"[",
"'id'",
"]",
"project_id",
"=",
"task_json",
"[",
"'project_id'",
"]",
"if",
"project_id",
"not",
"in",
"self",
"... | Populate the user's tasks from a JSON encoded list. | [
"Populate",
"the",
"user",
"s",
"tasks",
"from",
"a",
"JSON",
"encoded",
"list",
"."
] | 3359cbff485ebdbbb4ffbd58d71e21a817874dd7 | https://github.com/Garee/pytodoist/blob/3359cbff485ebdbbb4ffbd58d71e21a817874dd7/pytodoist/todoist.py#L366-L375 |
20,088 | Garee/pytodoist | pytodoist/todoist.py | User._sync_notes | 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
continue
task = self.tasks[task_id]
self.notes[note_id] = Note(note_json, task) | python | def _sync_notes(self, notes_json):
"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
continue
task = self.tasks[task_id]
self.notes[note_id] = Note(note_json, task) | [
"def",
"_sync_notes",
"(",
"self",
",",
"notes_json",
")",
":",
"for",
"note_json",
"in",
"notes_json",
":",
"note_id",
"=",
"note_json",
"[",
"'id'",
"]",
"task_id",
"=",
"note_json",
"[",
"'item_id'",
"]",
"if",
"task_id",
"not",
"in",
"self",
".",
"ta... | Populate the user's notes from a JSON encoded list. | [
"Populate",
"the",
"user",
"s",
"notes",
"from",
"a",
"JSON",
"encoded",
"list",
"."
] | 3359cbff485ebdbbb4ffbd58d71e21a817874dd7 | https://github.com/Garee/pytodoist/blob/3359cbff485ebdbbb4ffbd58d71e21a817874dd7/pytodoist/todoist.py#L377-L386 |
20,089 | Garee/pytodoist | pytodoist/todoist.py | User._sync_labels | 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 | def _sync_labels(self, labels_json):
"for label_json in labels_json:
label_id = label_json['id']
self.labels[label_id] = Label(label_json, self) | [
"def",
"_sync_labels",
"(",
"self",
",",
"labels_json",
")",
":",
"for",
"label_json",
"in",
"labels_json",
":",
"label_id",
"=",
"label_json",
"[",
"'id'",
"]",
"self",
".",
"labels",
"[",
"label_id",
"]",
"=",
"Label",
"(",
"label_json",
",",
"self",
"... | Populate the user's labels from a JSON encoded list. | [
"Populate",
"the",
"user",
"s",
"labels",
"from",
"a",
"JSON",
"encoded",
"list",
"."
] | 3359cbff485ebdbbb4ffbd58d71e21a817874dd7 | https://github.com/Garee/pytodoist/blob/3359cbff485ebdbbb4ffbd58d71e21a817874dd7/pytodoist/todoist.py#L388-L392 |
20,090 | Garee/pytodoist | pytodoist/todoist.py | User._sync_filters | 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 | def _sync_filters(self, filters_json):
"for filter_json in filters_json:
filter_id = filter_json['id']
self.filters[filter_id] = Filter(filter_json, self) | [
"def",
"_sync_filters",
"(",
"self",
",",
"filters_json",
")",
":",
"for",
"filter_json",
"in",
"filters_json",
":",
"filter_id",
"=",
"filter_json",
"[",
"'id'",
"]",
"self",
".",
"filters",
"[",
"filter_id",
"]",
"=",
"Filter",
"(",
"filter_json",
",",
"... | Populate the user's filters from a JSON encoded list. | [
"Populate",
"the",
"user",
"s",
"filters",
"from",
"a",
"JSON",
"encoded",
"list",
"."
] | 3359cbff485ebdbbb4ffbd58d71e21a817874dd7 | https://github.com/Garee/pytodoist/blob/3359cbff485ebdbbb4ffbd58d71e21a817874dd7/pytodoist/todoist.py#L394-L398 |
20,091 | Garee/pytodoist | pytodoist/todoist.py | User._sync_reminders | 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 orphan reminders
continue
task = self.tasks[task_id]
self.reminders[reminder_id] = Reminder(reminder_json, task) | python | def _sync_reminders(self, reminders_json):
"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 orphan reminders
continue
task = self.tasks[task_id]
self.reminders[reminder_id] = Reminder(reminder_json, task) | [
"def",
"_sync_reminders",
"(",
"self",
",",
"reminders_json",
")",
":",
"for",
"reminder_json",
"in",
"reminders_json",
":",
"reminder_id",
"=",
"reminder_json",
"[",
"'id'",
"]",
"task_id",
"=",
"reminder_json",
"[",
"'item_id'",
"]",
"if",
"task_id",
"not",
... | Populate the user's reminders from a JSON encoded list. | [
"Populate",
"the",
"user",
"s",
"reminders",
"from",
"a",
"JSON",
"encoded",
"list",
"."
] | 3359cbff485ebdbbb4ffbd58d71e21a817874dd7 | https://github.com/Garee/pytodoist/blob/3359cbff485ebdbbb4ffbd58d71e21a817874dd7/pytodoist/todoist.py#L400-L409 |
20,092 | Garee/pytodoist | pytodoist/todoist.py | User.quick_add | 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: str
:param note: The content of the note.
:type note: str
:param reminder: The date of the reminder, added in free form text.
:type reminder: str
:return: The added task.
:rtype: :class:`pytodoist.todoist.Task`
>>> from pytodoist import todoist
>>> user = todoist.login('john.doe@gmail.com', 'password')
>>> task = user.quick_add('Install Pytodoist #personal @app')
>>> print(task.content)
Install PyTodoist
"""
response = API.quick_add(self.api_token, text,
note=note, reminder=reminder)
_fail_if_contains_errors(response)
task_json = response.json()
return Task(task_json, self) | python | def quick_add(self, text, note=None, reminder=None):
response = API.quick_add(self.api_token, text,
note=note, reminder=reminder)
_fail_if_contains_errors(response)
task_json = response.json()
return Task(task_json, self) | [
"def",
"quick_add",
"(",
"self",
",",
"text",
",",
"note",
"=",
"None",
",",
"reminder",
"=",
"None",
")",
":",
"response",
"=",
"API",
".",
"quick_add",
"(",
"self",
".",
"api_token",
",",
"text",
",",
"note",
"=",
"note",
",",
"reminder",
"=",
"r... | 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: str
:param note: The content of the note.
:type note: str
:param reminder: The date of the reminder, added in free form text.
:type reminder: str
:return: The added task.
:rtype: :class:`pytodoist.todoist.Task`
>>> from pytodoist import todoist
>>> user = todoist.login('john.doe@gmail.com', 'password')
>>> task = user.quick_add('Install Pytodoist #personal @app')
>>> print(task.content)
Install PyTodoist | [
"Add",
"a",
"task",
"using",
"the",
"Quick",
"Add",
"Task",
"syntax",
"."
] | 3359cbff485ebdbbb4ffbd58d71e21a817874dd7 | https://github.com/Garee/pytodoist/blob/3359cbff485ebdbbb4ffbd58d71e21a817874dd7/pytodoist/todoist.py#L411-L435 |
20,093 | Garee/pytodoist | pytodoist/todoist.py | User.add_project | 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
>>> user = todoist.login('john.doe@gmail.com', 'password')
>>> project = user.add_project('PyTodoist')
>>> print(project.name)
PyTodoist
"""
args = {
'name': name,
'color': color,
'indent': indent,
'order': order
}
args = {k: args[k] for k in args if args[k] is not None}
_perform_command(self, 'project_add', args)
return self.get_project(name) | python | def add_project(self, name, color=None, indent=None, order=None):
args = {
'name': name,
'color': color,
'indent': indent,
'order': order
}
args = {k: args[k] for k in args if args[k] is not None}
_perform_command(self, 'project_add', args)
return self.get_project(name) | [
"def",
"add_project",
"(",
"self",
",",
"name",
",",
"color",
"=",
"None",
",",
"indent",
"=",
"None",
",",
"order",
"=",
"None",
")",
":",
"args",
"=",
"{",
"'name'",
":",
"name",
",",
"'color'",
":",
"color",
",",
"'indent'",
":",
"indent",
",",
... | 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
>>> user = todoist.login('john.doe@gmail.com', 'password')
>>> project = user.add_project('PyTodoist')
>>> print(project.name)
PyTodoist | [
"Add",
"a",
"project",
"to",
"the",
"user",
"s",
"account",
"."
] | 3359cbff485ebdbbb4ffbd58d71e21a817874dd7 | https://github.com/Garee/pytodoist/blob/3359cbff485ebdbbb4ffbd58d71e21a817874dd7/pytodoist/todoist.py#L437-L459 |
20,094 | Garee/pytodoist | pytodoist/todoist.py | User.get_project | 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.todoist.Project`
>>> from pytodoist import todoist
>>> user = todoist.login('john.doe@gmail.com', 'password')
>>> project = user.get_project('Inbox')
>>> print(project.name)
Inbox
"""
for project in self.get_projects():
if project.name == project_name:
return project | python | def get_project(self, project_name):
for project in self.get_projects():
if project.name == project_name:
return project | [
"def",
"get_project",
"(",
"self",
",",
"project_name",
")",
":",
"for",
"project",
"in",
"self",
".",
"get_projects",
"(",
")",
":",
"if",
"project",
".",
"name",
"==",
"project_name",
":",
"return",
"project"
] | 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.todoist.Project`
>>> from pytodoist import todoist
>>> user = todoist.login('john.doe@gmail.com', 'password')
>>> project = user.get_project('Inbox')
>>> print(project.name)
Inbox | [
"Return",
"the",
"project",
"with",
"a",
"given",
"name",
"."
] | 3359cbff485ebdbbb4ffbd58d71e21a817874dd7 | https://github.com/Garee/pytodoist/blob/3359cbff485ebdbbb4ffbd58d71e21a817874dd7/pytodoist/todoist.py#L461-L478 |
20,095 | Garee/pytodoist | pytodoist/todoist.py | User.get_uncompleted_tasks | 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.doe@gmail.com', 'password')
>>> uncompleted_tasks = user.get_uncompleted_tasks()
>>> for task in uncompleted_tasks:
... task.complete()
"""
tasks = (p.get_uncompleted_tasks() for p in self.get_projects())
return list(itertools.chain.from_iterable(tasks)) | python | def get_uncompleted_tasks(self):
tasks = (p.get_uncompleted_tasks() for p in self.get_projects())
return list(itertools.chain.from_iterable(tasks)) | [
"def",
"get_uncompleted_tasks",
"(",
"self",
")",
":",
"tasks",
"=",
"(",
"p",
".",
"get_uncompleted_tasks",
"(",
")",
"for",
"p",
"in",
"self",
".",
"get_projects",
"(",
")",
")",
"return",
"list",
"(",
"itertools",
".",
"chain",
".",
"from_iterable",
"... | 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.doe@gmail.com', 'password')
>>> uncompleted_tasks = user.get_uncompleted_tasks()
>>> for task in uncompleted_tasks:
... task.complete() | [
"Return",
"all",
"of",
"a",
"user",
"s",
"uncompleted",
"tasks",
"."
] | 3359cbff485ebdbbb4ffbd58d71e21a817874dd7 | https://github.com/Garee/pytodoist/blob/3359cbff485ebdbbb4ffbd58d71e21a817874dd7/pytodoist/todoist.py#L515-L530 |
20,096 | Garee/pytodoist | pytodoist/todoist.py | User.search_tasks | 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` class.
:param queries: Return tasks that match at least one of these queries.
:type queries: list str
:return: A list tasks that match at least one query.
:rtype: list of :class:`pytodoist.todoist.Task`
>>> from pytodoist import todoist
>>> user = todoist.login('john.doe@gmail.com', 'password')
>>> tasks = user.search_tasks(todoist.Query.TOMORROW, '18 Sep')
"""
queries = json.dumps(queries)
response = API.query(self.api_token, queries)
_fail_if_contains_errors(response)
query_results = response.json()
tasks = []
for result in query_results:
if 'data' not in result:
continue
all_tasks = result['data']
if result['type'] == Query.ALL:
all_projects = all_tasks
for project_json in all_projects:
uncompleted_tasks = project_json.get('uncompleted', [])
completed_tasks = project_json.get('completed', [])
all_tasks = uncompleted_tasks + completed_tasks
for task_json in all_tasks:
project_id = task_json['project_id']
project = self.projects[project_id]
task = Task(task_json, project)
tasks.append(task)
return tasks | python | def search_tasks(self, *queries):
queries = json.dumps(queries)
response = API.query(self.api_token, queries)
_fail_if_contains_errors(response)
query_results = response.json()
tasks = []
for result in query_results:
if 'data' not in result:
continue
all_tasks = result['data']
if result['type'] == Query.ALL:
all_projects = all_tasks
for project_json in all_projects:
uncompleted_tasks = project_json.get('uncompleted', [])
completed_tasks = project_json.get('completed', [])
all_tasks = uncompleted_tasks + completed_tasks
for task_json in all_tasks:
project_id = task_json['project_id']
project = self.projects[project_id]
task = Task(task_json, project)
tasks.append(task)
return tasks | [
"def",
"search_tasks",
"(",
"self",
",",
"*",
"queries",
")",
":",
"queries",
"=",
"json",
".",
"dumps",
"(",
"queries",
")",
"response",
"=",
"API",
".",
"query",
"(",
"self",
".",
"api_token",
",",
"queries",
")",
"_fail_if_contains_errors",
"(",
"resp... | 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` class.
:param queries: Return tasks that match at least one of these queries.
:type queries: list str
:return: A list tasks that match at least one query.
:rtype: list of :class:`pytodoist.todoist.Task`
>>> from pytodoist import todoist
>>> user = todoist.login('john.doe@gmail.com', 'password')
>>> tasks = user.search_tasks(todoist.Query.TOMORROW, '18 Sep') | [
"Return",
"a",
"list",
"of",
"tasks",
"that",
"match",
"some",
"search",
"criteria",
"."
] | 3359cbff485ebdbbb4ffbd58d71e21a817874dd7 | https://github.com/Garee/pytodoist/blob/3359cbff485ebdbbb4ffbd58d71e21a817874dd7/pytodoist/todoist.py#L562-L600 |
20,097 | Garee/pytodoist | pytodoist/todoist.py | User.get_label | def get_label(self, label_name):
"""Return the user's label that has a given name.
:param label_name: The name to search for.
:type label_name: str
:return: A label that has a matching name or ``None`` if not found.
:rtype: :class:`pytodoist.todoist.Label`
>>> from pytodoist import todoist
>>> user = todoist.login('john.doe@gmail.com', 'password')
>>> label = user.get_label('family')
"""
for label in self.get_labels():
if label.name == label_name:
return label | python | def get_label(self, label_name):
for label in self.get_labels():
if label.name == label_name:
return label | [
"def",
"get_label",
"(",
"self",
",",
"label_name",
")",
":",
"for",
"label",
"in",
"self",
".",
"get_labels",
"(",
")",
":",
"if",
"label",
".",
"name",
"==",
"label_name",
":",
"return",
"label"
] | Return the user's label that has a given name.
:param label_name: The name to search for.
:type label_name: str
:return: A label that has a matching name or ``None`` if not found.
:rtype: :class:`pytodoist.todoist.Label`
>>> from pytodoist import todoist
>>> user = todoist.login('john.doe@gmail.com', 'password')
>>> label = user.get_label('family') | [
"Return",
"the",
"user",
"s",
"label",
"that",
"has",
"a",
"given",
"name",
"."
] | 3359cbff485ebdbbb4ffbd58d71e21a817874dd7 | https://github.com/Garee/pytodoist/blob/3359cbff485ebdbbb4ffbd58d71e21a817874dd7/pytodoist/todoist.py#L625-L639 |
20,098 | Garee/pytodoist | pytodoist/todoist.py | User.add_filter | def add_filter(self, name, query, color=None, item_order=None):
"""Create a new filter.
.. warning:: Requires Todoist premium.
:param name: The name of the filter.
:param query: The query to search for.
:param color: The color of the filter.
:param item_order: The filter's order in the filter list.
:return: The newly created filter.
:rtype: :class:`pytodoist.todoist.Filter`
>>> from pytodoist import todoist
>>> user = todoist.login('john.doe@gmail.com', 'password')
>>> overdue_filter = user.add_filter('Overdue', todoist.Query.OVERDUE)
"""
args = {
'name': name,
'query': query,
'color': color,
'item_order': item_order
}
_perform_command(self, 'filter_add', args)
return self.get_filter(name) | python | def add_filter(self, name, query, color=None, item_order=None):
args = {
'name': name,
'query': query,
'color': color,
'item_order': item_order
}
_perform_command(self, 'filter_add', args)
return self.get_filter(name) | [
"def",
"add_filter",
"(",
"self",
",",
"name",
",",
"query",
",",
"color",
"=",
"None",
",",
"item_order",
"=",
"None",
")",
":",
"args",
"=",
"{",
"'name'",
":",
"name",
",",
"'query'",
":",
"query",
",",
"'color'",
":",
"color",
",",
"'item_order'"... | Create a new filter.
.. warning:: Requires Todoist premium.
:param name: The name of the filter.
:param query: The query to search for.
:param color: The color of the filter.
:param item_order: The filter's order in the filter list.
:return: The newly created filter.
:rtype: :class:`pytodoist.todoist.Filter`
>>> from pytodoist import todoist
>>> user = todoist.login('john.doe@gmail.com', 'password')
>>> overdue_filter = user.add_filter('Overdue', todoist.Query.OVERDUE) | [
"Create",
"a",
"new",
"filter",
"."
] | 3359cbff485ebdbbb4ffbd58d71e21a817874dd7 | https://github.com/Garee/pytodoist/blob/3359cbff485ebdbbb4ffbd58d71e21a817874dd7/pytodoist/todoist.py#L667-L690 |
20,099 | Garee/pytodoist | pytodoist/todoist.py | User.get_filter | def get_filter(self, name):
"""Return the filter that has the given filter name.
:param name: The name to search for.
:return: The filter with the given name.
:rtype: :class:`pytodoist.todoist.Filter`
>>> from pytodoist import todoist
>>> user = todoist.login('john.doe@gmail.com', 'password')
>>> user.add_filter('Overdue', todoist.Query.OVERDUE)
>>> overdue_filter = user.get_filter('Overdue')
"""
for flter in self.get_filters():
if flter.name == name:
return flter | python | def get_filter(self, name):
for flter in self.get_filters():
if flter.name == name:
return flter | [
"def",
"get_filter",
"(",
"self",
",",
"name",
")",
":",
"for",
"flter",
"in",
"self",
".",
"get_filters",
"(",
")",
":",
"if",
"flter",
".",
"name",
"==",
"name",
":",
"return",
"flter"
] | Return the filter that has the given filter name.
:param name: The name to search for.
:return: The filter with the given name.
:rtype: :class:`pytodoist.todoist.Filter`
>>> from pytodoist import todoist
>>> user = todoist.login('john.doe@gmail.com', 'password')
>>> user.add_filter('Overdue', todoist.Query.OVERDUE)
>>> overdue_filter = user.get_filter('Overdue') | [
"Return",
"the",
"filter",
"that",
"has",
"the",
"given",
"filter",
"name",
"."
] | 3359cbff485ebdbbb4ffbd58d71e21a817874dd7 | https://github.com/Garee/pytodoist/blob/3359cbff485ebdbbb4ffbd58d71e21a817874dd7/pytodoist/todoist.py#L692-L706 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.