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
75
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
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(): """ 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))
[ "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", ")", ")" ]
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
train
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): """ 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)
[ "def", "_print_results", "(", "results", ",", "stat", "=", "False", ",", "verbose", "=", "False", ")", ":", "results", ".", "generate_pretty_output", "(", "stat", "=", "stat", ",", "verbose", "=", "verbose", ",", "output_function", "=", "click", ".", "secho", ")" ]
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
train
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): """ Get list of labels from the target instance. :return: [str] """ 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
train
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): """ 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
[ "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" ]
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
train
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): """ Temporary directory holding all the runtime data. """ 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
train
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): """ 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.")
[ "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.\"", ")" ]
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
train
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): """ 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)
[ "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", ")" ]
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
train
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('[email protected]', ... 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): """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('[email protected]', ... 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)
[ "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", ")" ]
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('[email protected]', ... 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
train
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('[email protected]', '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): """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('[email protected]', '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)
[ "def", "register", "(", "self", ",", "email", ",", "full_name", ",", "password", ",", "*", "*", "kwargs", ")", ":", "params", "=", "{", "'email'", ":", "email", ",", "'full_name'", ":", "full_name", ",", "'password'", ":", "password", "}", "return", "self", ".", "_post", "(", "'register'", ",", "params", ",", "*", "*", "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('[email protected]', '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
train
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): """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)
[ "def", "delete_user", "(", "self", ",", "api_token", ",", "password", ",", "*", "*", "kwargs", ")", ":", "params", "=", "{", "'token'", ":", "api_token", ",", "'current_password'", ":", "password", "}", "return", "self", ".", "_post", "(", "'delete_user'", ",", "params", ",", "*", "*", "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`
[ "Delete", "a", "registered", "Todoist", "user", "s", "account", "." ]
3359cbff485ebdbbb4ffbd58d71e21a817874dd7
https://github.com/Garee/pytodoist/blob/3359cbff485ebdbbb4ffbd58d71e21a817874dd7/pytodoist/api.py#L132-L150
train
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('[email protected]', '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): """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('[email protected]', '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)
[ "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", ")" ]
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('[email protected]', '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
train
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): """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)
[ "def", "query", "(", "self", ",", "api_token", ",", "queries", ",", "*", "*", "kwargs", ")", ":", "params", "=", "{", "'token'", ":", "api_token", ",", "'queries'", ":", "queries", "}", "return", "self", ".", "_get", "(", "'query'", ",", "params", ",", "*", "*", "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`
[ "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
train
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('[email protected]', '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): """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('[email protected]', '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)
[ "def", "add_item", "(", "self", ",", "api_token", ",", "content", ",", "*", "*", "kwargs", ")", ":", "params", "=", "{", "'token'", ":", "api_token", ",", "'content'", ":", "content", "}", "return", "self", ".", "_post", "(", "'add_item'", ",", "params", ",", "*", "*", "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('[email protected]', '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
train
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): """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)
[ "def", "quick_add", "(", "self", ",", "api_token", ",", "text", ",", "*", "*", "kwargs", ")", ":", "params", "=", "{", "'token'", ":", "api_token", ",", "'text'", ":", "text", "}", "return", "self", ".", "_post", "(", "'quick/add'", ",", "params", ",", "*", "*", "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`
[ "Add", "a", "task", "using", "the", "Todoist", "Quick", "Add", "Task", "syntax", "." ]
3359cbff485ebdbbb4ffbd58d71e21a817874dd7
https://github.com/Garee/pytodoist/blob/3359cbff485ebdbbb4ffbd58d71e21a817874dd7/pytodoist/api.py#L262-L282
train
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('[email protected]', '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): """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('[email protected]', '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)
[ "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('[email protected]', '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
train
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): """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)
[ "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", ")" ]
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
train
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): """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)
[ "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
train
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('[email protected]', '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): """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('[email protected]', '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)
[ "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", ")" ]
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('[email protected]', '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
train
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): """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)
[ "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
train
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): """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)
[ "def", "_post", "(", "self", ",", "end_point", ",", "params", "=", "None", ",", "files", "=", "None", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "_request", "(", "requests", ".", "post", ",", "end_point", ",", "params", ",", "files", ",", "*", "*", "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`
[ "Send", "a", "HTTP", "POST", "request", "to", "a", "Todoist", "API", "end", "-", "point", "." ]
3359cbff485ebdbbb4ffbd58d71e21a817874dd7
https://github.com/Garee/pytodoist/blob/3359cbff485ebdbbb4ffbd58d71e21a817874dd7/pytodoist/api.py#L429-L443
train
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): """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)
[ "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", ")" ]
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
train
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): """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)
[ "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", ")" ]
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
train
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): """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)
[ "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
train
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', '[email protected]', '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): """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', '[email protected]', '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
[ "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" ]
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', '[email protected]', '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
train
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', '[email protected]', ... 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): """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', '[email protected]', ... 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
[ "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" ]
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', '[email protected]', ... 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
train
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): """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)
[ "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", ")" ]
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
train
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): """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']
[ "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'", "]" ]
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
train
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('[email protected]', '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): """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('[email protected]', '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)
[ "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('[email protected]', '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
train
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"]'): """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'])
[ "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'", "]", ")" ]
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
train
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): """"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)
[ "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", ")" ]
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
train
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): """"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)
[ "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", ")" ]
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
train
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): """"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)
[ "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", ")" ]
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
train
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): """"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)
[ "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
train
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): """"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)
[ "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", ")" ]
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
train
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): """"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)
[ "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", ")" ]
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
train
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('[email protected]', '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): """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('[email protected]', '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)
[ "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", ")" ]
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('[email protected]', '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
train
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('[email protected]', '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): """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('[email protected]', '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)
[ "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", ")" ]
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('[email protected]', '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
train
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('[email protected]', '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): """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('[email protected]', 'password') >>> project = user.get_project('Inbox') >>> print(project.name) Inbox """ 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('[email protected]', '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
train
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('[email protected]', '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): """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('[email protected]', '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))
[ "def", "get_uncompleted_tasks", "(", "self", ")", ":", "tasks", "=", "(", "p", ".", "get_uncompleted_tasks", "(", ")", "for", "p", "in", "self", ".", "get_projects", "(", ")", ")", "return", "list", "(", "itertools", ".", "chain", ".", "from_iterable", "(", "tasks", ")", ")" ]
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('[email protected]', '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
train
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('[email protected]', '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): """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('[email protected]', '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
[ "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" ]
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('[email protected]', '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
train
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('[email protected]', '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): """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('[email protected]', 'password') >>> label = user.get_label('family') """ 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('[email protected]', '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
train
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('[email protected]', '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): """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('[email protected]', '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)
[ "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", ")" ]
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('[email protected]', '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
train
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('[email protected]', '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): """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('[email protected]', '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
[ "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('[email protected]', '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
train
Garee/pytodoist
pytodoist/todoist.py
User._update_notification_settings
def _update_notification_settings(self, event, service, should_notify): """Update the settings of a an events notifications. :param event: Update the notification settings of this event. :type event: str :param service: The notification service to update. :type service: str :param should_notify: Notify if this is ``1``. :type should_notify: int """ response = API.update_notification_settings(self.api_token, event, service, should_notify) _fail_if_contains_errors(response)
python
def _update_notification_settings(self, event, service, should_notify): """Update the settings of a an events notifications. :param event: Update the notification settings of this event. :type event: str :param service: The notification service to update. :type service: str :param should_notify: Notify if this is ``1``. :type should_notify: int """ response = API.update_notification_settings(self.api_token, event, service, should_notify) _fail_if_contains_errors(response)
[ "def", "_update_notification_settings", "(", "self", ",", "event", ",", "service", ",", "should_notify", ")", ":", "response", "=", "API", ".", "update_notification_settings", "(", "self", ".", "api_token", ",", "event", ",", "service", ",", "should_notify", ")", "_fail_if_contains_errors", "(", "response", ")" ]
Update the settings of a an events notifications. :param event: Update the notification settings of this event. :type event: str :param service: The notification service to update. :type service: str :param should_notify: Notify if this is ``1``. :type should_notify: int
[ "Update", "the", "settings", "of", "a", "an", "events", "notifications", "." ]
3359cbff485ebdbbb4ffbd58d71e21a817874dd7
https://github.com/Garee/pytodoist/blob/3359cbff485ebdbbb4ffbd58d71e21a817874dd7/pytodoist/todoist.py#L743-L756
train
Garee/pytodoist
pytodoist/todoist.py
User.get_productivity_stats
def get_productivity_stats(self): """Return the user's productivity stats. :return: A JSON-encoded representation of the user's productivity stats. :rtype: A JSON-encoded object. >>> from pytodoist import todoist >>> user = todoist.login('[email protected]', 'password') >>> stats = user.get_productivity_stats() >>> print(stats) {"karma_last_update": 50.0, "karma_trend": "up", ... } """ response = API.get_productivity_stats(self.api_token) _fail_if_contains_errors(response) return response.json()
python
def get_productivity_stats(self): """Return the user's productivity stats. :return: A JSON-encoded representation of the user's productivity stats. :rtype: A JSON-encoded object. >>> from pytodoist import todoist >>> user = todoist.login('[email protected]', 'password') >>> stats = user.get_productivity_stats() >>> print(stats) {"karma_last_update": 50.0, "karma_trend": "up", ... } """ response = API.get_productivity_stats(self.api_token) _fail_if_contains_errors(response) return response.json()
[ "def", "get_productivity_stats", "(", "self", ")", ":", "response", "=", "API", ".", "get_productivity_stats", "(", "self", ".", "api_token", ")", "_fail_if_contains_errors", "(", "response", ")", "return", "response", ".", "json", "(", ")" ]
Return the user's productivity stats. :return: A JSON-encoded representation of the user's productivity stats. :rtype: A JSON-encoded object. >>> from pytodoist import todoist >>> user = todoist.login('[email protected]', 'password') >>> stats = user.get_productivity_stats() >>> print(stats) {"karma_last_update": 50.0, "karma_trend": "up", ... }
[ "Return", "the", "user", "s", "productivity", "stats", "." ]
3359cbff485ebdbbb4ffbd58d71e21a817874dd7
https://github.com/Garee/pytodoist/blob/3359cbff485ebdbbb4ffbd58d71e21a817874dd7/pytodoist/todoist.py#L806-L821
train
Garee/pytodoist
pytodoist/todoist.py
User.delete
def delete(self, reason=None): """Delete the user's account from Todoist. .. warning:: You cannot recover the user after deletion! :param reason: The reason for deletion. :type reason: str >>> from pytodoist import todoist >>> user = todoist.login('[email protected]', 'password') >>> user.delete() ... # The user token is now invalid and Todoist operations will fail. """ response = API.delete_user(self.api_token, self.password, reason=reason, in_background=0) _fail_if_contains_errors(response)
python
def delete(self, reason=None): """Delete the user's account from Todoist. .. warning:: You cannot recover the user after deletion! :param reason: The reason for deletion. :type reason: str >>> from pytodoist import todoist >>> user = todoist.login('[email protected]', 'password') >>> user.delete() ... # The user token is now invalid and Todoist operations will fail. """ response = API.delete_user(self.api_token, self.password, reason=reason, in_background=0) _fail_if_contains_errors(response)
[ "def", "delete", "(", "self", ",", "reason", "=", "None", ")", ":", "response", "=", "API", ".", "delete_user", "(", "self", ".", "api_token", ",", "self", ".", "password", ",", "reason", "=", "reason", ",", "in_background", "=", "0", ")", "_fail_if_contains_errors", "(", "response", ")" ]
Delete the user's account from Todoist. .. warning:: You cannot recover the user after deletion! :param reason: The reason for deletion. :type reason: str >>> from pytodoist import todoist >>> user = todoist.login('[email protected]', 'password') >>> user.delete() ... # The user token is now invalid and Todoist operations will fail.
[ "Delete", "the", "user", "s", "account", "from", "Todoist", "." ]
3359cbff485ebdbbb4ffbd58d71e21a817874dd7
https://github.com/Garee/pytodoist/blob/3359cbff485ebdbbb4ffbd58d71e21a817874dd7/pytodoist/todoist.py#L908-L923
train
Garee/pytodoist
pytodoist/todoist.py
Project.archive
def archive(self): """Archive the project. >>> from pytodoist import todoist >>> user = todoist.login('[email protected]', 'password') >>> project = user.get_project('PyTodoist') >>> project.archive() """ args = {'id': self.id} _perform_command(self.owner, 'project_archive', args) self.is_archived = '1'
python
def archive(self): """Archive the project. >>> from pytodoist import todoist >>> user = todoist.login('[email protected]', 'password') >>> project = user.get_project('PyTodoist') >>> project.archive() """ args = {'id': self.id} _perform_command(self.owner, 'project_archive', args) self.is_archived = '1'
[ "def", "archive", "(", "self", ")", ":", "args", "=", "{", "'id'", ":", "self", ".", "id", "}", "_perform_command", "(", "self", ".", "owner", ",", "'project_archive'", ",", "args", ")", "self", ".", "is_archived", "=", "'1'" ]
Archive the project. >>> from pytodoist import todoist >>> user = todoist.login('[email protected]', 'password') >>> project = user.get_project('PyTodoist') >>> project.archive()
[ "Archive", "the", "project", "." ]
3359cbff485ebdbbb4ffbd58d71e21a817874dd7
https://github.com/Garee/pytodoist/blob/3359cbff485ebdbbb4ffbd58d71e21a817874dd7/pytodoist/todoist.py#L982-L992
train
Garee/pytodoist
pytodoist/todoist.py
Project.add_task
def add_task(self, content, date=None, priority=None): """Add a task to the project :param content: The task description. :type content: str :param date: The task deadline. :type date: str :param priority: The priority of the task. :type priority: int :return: The added task. :rtype: :class:`pytodoist.todoist.Task` .. note:: See `here <https://todoist.com/Help/timeInsert>`_ for possible date strings. >>> from pytodoist import todoist >>> user = todoist.login('[email protected]', 'password') >>> project = user.get_project('PyTodoist') >>> task = project.add_task('Install PyTodoist') >>> print(task.content) Install PyTodoist """ response = API.add_item(self.owner.token, content, project_id=self.id, date_string=date, priority=priority) _fail_if_contains_errors(response) task_json = response.json() return Task(task_json, self)
python
def add_task(self, content, date=None, priority=None): """Add a task to the project :param content: The task description. :type content: str :param date: The task deadline. :type date: str :param priority: The priority of the task. :type priority: int :return: The added task. :rtype: :class:`pytodoist.todoist.Task` .. note:: See `here <https://todoist.com/Help/timeInsert>`_ for possible date strings. >>> from pytodoist import todoist >>> user = todoist.login('[email protected]', 'password') >>> project = user.get_project('PyTodoist') >>> task = project.add_task('Install PyTodoist') >>> print(task.content) Install PyTodoist """ response = API.add_item(self.owner.token, content, project_id=self.id, date_string=date, priority=priority) _fail_if_contains_errors(response) task_json = response.json() return Task(task_json, self)
[ "def", "add_task", "(", "self", ",", "content", ",", "date", "=", "None", ",", "priority", "=", "None", ")", ":", "response", "=", "API", ".", "add_item", "(", "self", ".", "owner", ".", "token", ",", "content", ",", "project_id", "=", "self", ".", "id", ",", "date_string", "=", "date", ",", "priority", "=", "priority", ")", "_fail_if_contains_errors", "(", "response", ")", "task_json", "=", "response", ".", "json", "(", ")", "return", "Task", "(", "task_json", ",", "self", ")" ]
Add a task to the project :param content: The task description. :type content: str :param date: The task deadline. :type date: str :param priority: The priority of the task. :type priority: int :return: The added task. :rtype: :class:`pytodoist.todoist.Task` .. note:: See `here <https://todoist.com/Help/timeInsert>`_ for possible date strings. >>> from pytodoist import todoist >>> user = todoist.login('[email protected]', 'password') >>> project = user.get_project('PyTodoist') >>> task = project.add_task('Install PyTodoist') >>> print(task.content) Install PyTodoist
[ "Add", "a", "task", "to", "the", "project" ]
3359cbff485ebdbbb4ffbd58d71e21a817874dd7
https://github.com/Garee/pytodoist/blob/3359cbff485ebdbbb4ffbd58d71e21a817874dd7/pytodoist/todoist.py#L1016-L1042
train
Garee/pytodoist
pytodoist/todoist.py
Project.get_uncompleted_tasks
def get_uncompleted_tasks(self): """Return a list of all uncompleted tasks in this project. .. warning:: Requires Todoist premium. :return: A list of all uncompleted tasks in this project. :rtype: list of :class:`pytodoist.todoist.Task` >>> from pytodoist import todoist >>> user = todoist.login('[email protected]', 'password') >>> project = user.get_project('PyTodoist') >>> project.add_task('Install PyTodoist') >>> uncompleted_tasks = project.get_uncompleted_tasks() >>> for task in uncompleted_tasks: ... task.complete() """ all_tasks = self.get_tasks() completed_tasks = self.get_completed_tasks() return [t for t in all_tasks if t not in completed_tasks]
python
def get_uncompleted_tasks(self): """Return a list of all uncompleted tasks in this project. .. warning:: Requires Todoist premium. :return: A list of all uncompleted tasks in this project. :rtype: list of :class:`pytodoist.todoist.Task` >>> from pytodoist import todoist >>> user = todoist.login('[email protected]', 'password') >>> project = user.get_project('PyTodoist') >>> project.add_task('Install PyTodoist') >>> uncompleted_tasks = project.get_uncompleted_tasks() >>> for task in uncompleted_tasks: ... task.complete() """ all_tasks = self.get_tasks() completed_tasks = self.get_completed_tasks() return [t for t in all_tasks if t not in completed_tasks]
[ "def", "get_uncompleted_tasks", "(", "self", ")", ":", "all_tasks", "=", "self", ".", "get_tasks", "(", ")", "completed_tasks", "=", "self", ".", "get_completed_tasks", "(", ")", "return", "[", "t", "for", "t", "in", "all_tasks", "if", "t", "not", "in", "completed_tasks", "]" ]
Return a list of all uncompleted tasks in this project. .. warning:: Requires Todoist premium. :return: A list of all uncompleted tasks in this project. :rtype: list of :class:`pytodoist.todoist.Task` >>> from pytodoist import todoist >>> user = todoist.login('[email protected]', 'password') >>> project = user.get_project('PyTodoist') >>> project.add_task('Install PyTodoist') >>> uncompleted_tasks = project.get_uncompleted_tasks() >>> for task in uncompleted_tasks: ... task.complete()
[ "Return", "a", "list", "of", "all", "uncompleted", "tasks", "in", "this", "project", "." ]
3359cbff485ebdbbb4ffbd58d71e21a817874dd7
https://github.com/Garee/pytodoist/blob/3359cbff485ebdbbb4ffbd58d71e21a817874dd7/pytodoist/todoist.py#L1044-L1062
train
Garee/pytodoist
pytodoist/todoist.py
Project.get_completed_tasks
def get_completed_tasks(self): """Return a list of all completed tasks in this project. :return: A list of all completed tasks in this project. :rtype: list of :class:`pytodoist.todoist.Task` >>> from pytodoist import todoist >>> user = todoist.login('[email protected]', 'password') >>> project = user.get_project('PyTodoist') >>> task = project.add_task('Install PyTodoist') >>> task.complete() >>> completed_tasks = project.get_completed_tasks() >>> for task in completed_tasks: ... task.uncomplete() """ self.owner.sync() tasks = [] offset = 0 while True: response = API.get_all_completed_tasks(self.owner.api_token, limit=_PAGE_LIMIT, offset=offset, project_id=self.id) _fail_if_contains_errors(response) response_json = response.json() tasks_json = response_json['items'] if len(tasks_json) == 0: break # There are no more completed tasks to retreive. for task_json in tasks_json: project = self.owner.projects[task_json['project_id']] tasks.append(Task(task_json, project)) offset += _PAGE_LIMIT return tasks
python
def get_completed_tasks(self): """Return a list of all completed tasks in this project. :return: A list of all completed tasks in this project. :rtype: list of :class:`pytodoist.todoist.Task` >>> from pytodoist import todoist >>> user = todoist.login('[email protected]', 'password') >>> project = user.get_project('PyTodoist') >>> task = project.add_task('Install PyTodoist') >>> task.complete() >>> completed_tasks = project.get_completed_tasks() >>> for task in completed_tasks: ... task.uncomplete() """ self.owner.sync() tasks = [] offset = 0 while True: response = API.get_all_completed_tasks(self.owner.api_token, limit=_PAGE_LIMIT, offset=offset, project_id=self.id) _fail_if_contains_errors(response) response_json = response.json() tasks_json = response_json['items'] if len(tasks_json) == 0: break # There are no more completed tasks to retreive. for task_json in tasks_json: project = self.owner.projects[task_json['project_id']] tasks.append(Task(task_json, project)) offset += _PAGE_LIMIT return tasks
[ "def", "get_completed_tasks", "(", "self", ")", ":", "self", ".", "owner", ".", "sync", "(", ")", "tasks", "=", "[", "]", "offset", "=", "0", "while", "True", ":", "response", "=", "API", ".", "get_all_completed_tasks", "(", "self", ".", "owner", ".", "api_token", ",", "limit", "=", "_PAGE_LIMIT", ",", "offset", "=", "offset", ",", "project_id", "=", "self", ".", "id", ")", "_fail_if_contains_errors", "(", "response", ")", "response_json", "=", "response", ".", "json", "(", ")", "tasks_json", "=", "response_json", "[", "'items'", "]", "if", "len", "(", "tasks_json", ")", "==", "0", ":", "break", "# There are no more completed tasks to retreive.", "for", "task_json", "in", "tasks_json", ":", "project", "=", "self", ".", "owner", ".", "projects", "[", "task_json", "[", "'project_id'", "]", "]", "tasks", ".", "append", "(", "Task", "(", "task_json", ",", "project", ")", ")", "offset", "+=", "_PAGE_LIMIT", "return", "tasks" ]
Return a list of all completed tasks in this project. :return: A list of all completed tasks in this project. :rtype: list of :class:`pytodoist.todoist.Task` >>> from pytodoist import todoist >>> user = todoist.login('[email protected]', 'password') >>> project = user.get_project('PyTodoist') >>> task = project.add_task('Install PyTodoist') >>> task.complete() >>> completed_tasks = project.get_completed_tasks() >>> for task in completed_tasks: ... task.uncomplete()
[ "Return", "a", "list", "of", "all", "completed", "tasks", "in", "this", "project", "." ]
3359cbff485ebdbbb4ffbd58d71e21a817874dd7
https://github.com/Garee/pytodoist/blob/3359cbff485ebdbbb4ffbd58d71e21a817874dd7/pytodoist/todoist.py#L1064-L1096
train
Garee/pytodoist
pytodoist/todoist.py
Project.get_tasks
def get_tasks(self): """Return all tasks in this project. :return: A list of all tasks in this project.class :rtype: list of :class:`pytodoist.todoist.Task` >>> from pytodoist import todoist >>> user = todoist.login('[email protected]', 'password') >>> project = user.get_project('PyTodoist') >>> project.add_task('Install PyTodoist') >>> project.add_task('Have fun!') >>> tasks = project.get_tasks() >>> for task in tasks: ... print(task.content) Install PyTodoist Have fun! """ self.owner.sync() return [t for t in self.owner.tasks.values() if t.project_id == self.id]
python
def get_tasks(self): """Return all tasks in this project. :return: A list of all tasks in this project.class :rtype: list of :class:`pytodoist.todoist.Task` >>> from pytodoist import todoist >>> user = todoist.login('[email protected]', 'password') >>> project = user.get_project('PyTodoist') >>> project.add_task('Install PyTodoist') >>> project.add_task('Have fun!') >>> tasks = project.get_tasks() >>> for task in tasks: ... print(task.content) Install PyTodoist Have fun! """ self.owner.sync() return [t for t in self.owner.tasks.values() if t.project_id == self.id]
[ "def", "get_tasks", "(", "self", ")", ":", "self", ".", "owner", ".", "sync", "(", ")", "return", "[", "t", "for", "t", "in", "self", ".", "owner", ".", "tasks", ".", "values", "(", ")", "if", "t", ".", "project_id", "==", "self", ".", "id", "]" ]
Return all tasks in this project. :return: A list of all tasks in this project.class :rtype: list of :class:`pytodoist.todoist.Task` >>> from pytodoist import todoist >>> user = todoist.login('[email protected]', 'password') >>> project = user.get_project('PyTodoist') >>> project.add_task('Install PyTodoist') >>> project.add_task('Have fun!') >>> tasks = project.get_tasks() >>> for task in tasks: ... print(task.content) Install PyTodoist Have fun!
[ "Return", "all", "tasks", "in", "this", "project", "." ]
3359cbff485ebdbbb4ffbd58d71e21a817874dd7
https://github.com/Garee/pytodoist/blob/3359cbff485ebdbbb4ffbd58d71e21a817874dd7/pytodoist/todoist.py#L1098-L1117
train
Garee/pytodoist
pytodoist/todoist.py
Project.add_note
def add_note(self, content): """Add a note to the project. .. warning:: Requires Todoist premium. :param content: The note content. :type content: str >>> from pytodoist import todoist >>> user = todoist.login('[email protected]', 'password') >>> project = user.get_project('PyTodoist') >>> project.add_note('Remember to update to the latest version.') """ args = { 'project_id': self.id, 'content': content } _perform_command(self.owner, 'note_add', args)
python
def add_note(self, content): """Add a note to the project. .. warning:: Requires Todoist premium. :param content: The note content. :type content: str >>> from pytodoist import todoist >>> user = todoist.login('[email protected]', 'password') >>> project = user.get_project('PyTodoist') >>> project.add_note('Remember to update to the latest version.') """ args = { 'project_id': self.id, 'content': content } _perform_command(self.owner, 'note_add', args)
[ "def", "add_note", "(", "self", ",", "content", ")", ":", "args", "=", "{", "'project_id'", ":", "self", ".", "id", ",", "'content'", ":", "content", "}", "_perform_command", "(", "self", ".", "owner", ",", "'note_add'", ",", "args", ")" ]
Add a note to the project. .. warning:: Requires Todoist premium. :param content: The note content. :type content: str >>> from pytodoist import todoist >>> user = todoist.login('[email protected]', 'password') >>> project = user.get_project('PyTodoist') >>> project.add_note('Remember to update to the latest version.')
[ "Add", "a", "note", "to", "the", "project", "." ]
3359cbff485ebdbbb4ffbd58d71e21a817874dd7
https://github.com/Garee/pytodoist/blob/3359cbff485ebdbbb4ffbd58d71e21a817874dd7/pytodoist/todoist.py#L1119-L1136
train
Garee/pytodoist
pytodoist/todoist.py
Project.get_notes
def get_notes(self): """Return a list of all of the project's notes. :return: A list of notes. :rtype: list of :class:`pytodoist.todoist.Note` >>> from pytodoist import todoist >>> user = todoist.login('[email protected]', 'password') >>> project = user.get_project('PyTodoist') >>> notes = project.get_notes() """ self.owner.sync() notes = self.owner.notes.values() return [n for n in notes if n.project_id == self.id]
python
def get_notes(self): """Return a list of all of the project's notes. :return: A list of notes. :rtype: list of :class:`pytodoist.todoist.Note` >>> from pytodoist import todoist >>> user = todoist.login('[email protected]', 'password') >>> project = user.get_project('PyTodoist') >>> notes = project.get_notes() """ self.owner.sync() notes = self.owner.notes.values() return [n for n in notes if n.project_id == self.id]
[ "def", "get_notes", "(", "self", ")", ":", "self", ".", "owner", ".", "sync", "(", ")", "notes", "=", "self", ".", "owner", ".", "notes", ".", "values", "(", ")", "return", "[", "n", "for", "n", "in", "notes", "if", "n", ".", "project_id", "==", "self", ".", "id", "]" ]
Return a list of all of the project's notes. :return: A list of notes. :rtype: list of :class:`pytodoist.todoist.Note` >>> from pytodoist import todoist >>> user = todoist.login('[email protected]', 'password') >>> project = user.get_project('PyTodoist') >>> notes = project.get_notes()
[ "Return", "a", "list", "of", "all", "of", "the", "project", "s", "notes", "." ]
3359cbff485ebdbbb4ffbd58d71e21a817874dd7
https://github.com/Garee/pytodoist/blob/3359cbff485ebdbbb4ffbd58d71e21a817874dd7/pytodoist/todoist.py#L1138-L1151
train
Garee/pytodoist
pytodoist/todoist.py
Project.share
def share(self, email, message=None): """Share the project with another Todoist user. :param email: The other user's email address. :type email: str :param message: Optional message to send with the invitation. :type message: str >>> from pytodoist import todoist >>> user = todoist.login('[email protected]', 'password') >>> project = user.get_project('PyTodoist') >>> project.share('[email protected]') """ args = { 'project_id': self.id, 'email': email, 'message': message } _perform_command(self.owner, 'share_project', args)
python
def share(self, email, message=None): """Share the project with another Todoist user. :param email: The other user's email address. :type email: str :param message: Optional message to send with the invitation. :type message: str >>> from pytodoist import todoist >>> user = todoist.login('[email protected]', 'password') >>> project = user.get_project('PyTodoist') >>> project.share('[email protected]') """ args = { 'project_id': self.id, 'email': email, 'message': message } _perform_command(self.owner, 'share_project', args)
[ "def", "share", "(", "self", ",", "email", ",", "message", "=", "None", ")", ":", "args", "=", "{", "'project_id'", ":", "self", ".", "id", ",", "'email'", ":", "email", ",", "'message'", ":", "message", "}", "_perform_command", "(", "self", ".", "owner", ",", "'share_project'", ",", "args", ")" ]
Share the project with another Todoist user. :param email: The other user's email address. :type email: str :param message: Optional message to send with the invitation. :type message: str >>> from pytodoist import todoist >>> user = todoist.login('[email protected]', 'password') >>> project = user.get_project('PyTodoist') >>> project.share('[email protected]')
[ "Share", "the", "project", "with", "another", "Todoist", "user", "." ]
3359cbff485ebdbbb4ffbd58d71e21a817874dd7
https://github.com/Garee/pytodoist/blob/3359cbff485ebdbbb4ffbd58d71e21a817874dd7/pytodoist/todoist.py#L1153-L1171
train
Garee/pytodoist
pytodoist/todoist.py
Project.delete_collaborator
def delete_collaborator(self, email): """Remove a collaborating user from the shared project. :param email: The collaborator's email address. :type email: str >>> from pytodoist import todoist >>> user = todoist.login('[email protected]', 'password') >>> project = user.get_project('PyTodoist') >>> project.delete_collaborator('[email protected]') """ args = { 'project_id': self.id, 'email': email, } _perform_command(self.owner, 'delete_collaborator', args)
python
def delete_collaborator(self, email): """Remove a collaborating user from the shared project. :param email: The collaborator's email address. :type email: str >>> from pytodoist import todoist >>> user = todoist.login('[email protected]', 'password') >>> project = user.get_project('PyTodoist') >>> project.delete_collaborator('[email protected]') """ args = { 'project_id': self.id, 'email': email, } _perform_command(self.owner, 'delete_collaborator', args)
[ "def", "delete_collaborator", "(", "self", ",", "email", ")", ":", "args", "=", "{", "'project_id'", ":", "self", ".", "id", ",", "'email'", ":", "email", ",", "}", "_perform_command", "(", "self", ".", "owner", ",", "'delete_collaborator'", ",", "args", ")" ]
Remove a collaborating user from the shared project. :param email: The collaborator's email address. :type email: str >>> from pytodoist import todoist >>> user = todoist.login('[email protected]', 'password') >>> project = user.get_project('PyTodoist') >>> project.delete_collaborator('[email protected]')
[ "Remove", "a", "collaborating", "user", "from", "the", "shared", "project", "." ]
3359cbff485ebdbbb4ffbd58d71e21a817874dd7
https://github.com/Garee/pytodoist/blob/3359cbff485ebdbbb4ffbd58d71e21a817874dd7/pytodoist/todoist.py#L1173-L1188
train
Garee/pytodoist
pytodoist/todoist.py
Task.complete
def complete(self): """Mark the task complete. >>> from pytodoist import todoist >>> user = todoist.login('[email protected]', 'password') >>> project = user.get_project('PyTodoist') >>> task = project.add_task('Install PyTodoist') >>> task.complete() """ args = { 'id': self.id } _perform_command(self.project.owner, 'item_close', args)
python
def complete(self): """Mark the task complete. >>> from pytodoist import todoist >>> user = todoist.login('[email protected]', 'password') >>> project = user.get_project('PyTodoist') >>> task = project.add_task('Install PyTodoist') >>> task.complete() """ args = { 'id': self.id } _perform_command(self.project.owner, 'item_close', args)
[ "def", "complete", "(", "self", ")", ":", "args", "=", "{", "'id'", ":", "self", ".", "id", "}", "_perform_command", "(", "self", ".", "project", ".", "owner", ",", "'item_close'", ",", "args", ")" ]
Mark the task complete. >>> from pytodoist import todoist >>> user = todoist.login('[email protected]', 'password') >>> project = user.get_project('PyTodoist') >>> task = project.add_task('Install PyTodoist') >>> task.complete()
[ "Mark", "the", "task", "complete", "." ]
3359cbff485ebdbbb4ffbd58d71e21a817874dd7
https://github.com/Garee/pytodoist/blob/3359cbff485ebdbbb4ffbd58d71e21a817874dd7/pytodoist/todoist.py#L1296-L1308
train
Garee/pytodoist
pytodoist/todoist.py
Task.uncomplete
def uncomplete(self): """Mark the task uncomplete. >>> from pytodoist import todoist >>> user = todoist.login('[email protected]', 'password') >>> project = user.get_project('PyTodoist') >>> task = project.add_task('Install PyTodoist') >>> task.uncomplete() """ args = { 'project_id': self.project.id, 'ids': [self.id] } owner = self.project.owner _perform_command(owner, 'item_uncomplete', args)
python
def uncomplete(self): """Mark the task uncomplete. >>> from pytodoist import todoist >>> user = todoist.login('[email protected]', 'password') >>> project = user.get_project('PyTodoist') >>> task = project.add_task('Install PyTodoist') >>> task.uncomplete() """ args = { 'project_id': self.project.id, 'ids': [self.id] } owner = self.project.owner _perform_command(owner, 'item_uncomplete', args)
[ "def", "uncomplete", "(", "self", ")", ":", "args", "=", "{", "'project_id'", ":", "self", ".", "project", ".", "id", ",", "'ids'", ":", "[", "self", ".", "id", "]", "}", "owner", "=", "self", ".", "project", ".", "owner", "_perform_command", "(", "owner", ",", "'item_uncomplete'", ",", "args", ")" ]
Mark the task uncomplete. >>> from pytodoist import todoist >>> user = todoist.login('[email protected]', 'password') >>> project = user.get_project('PyTodoist') >>> task = project.add_task('Install PyTodoist') >>> task.uncomplete()
[ "Mark", "the", "task", "uncomplete", "." ]
3359cbff485ebdbbb4ffbd58d71e21a817874dd7
https://github.com/Garee/pytodoist/blob/3359cbff485ebdbbb4ffbd58d71e21a817874dd7/pytodoist/todoist.py#L1310-L1324
train
Garee/pytodoist
pytodoist/todoist.py
Task.get_notes
def get_notes(self): """Return all notes attached to this Task. :return: A list of all notes attached to this Task. :rtype: list of :class:`pytodoist.todoist.Note` >>> from pytodoist import todoist >>> user = todoist.login('[email protected]', 'password') >>> project = user.get_project('PyTodoist') >>> task = project.add_task('Install PyTodoist.') >>> task.add_note('https://pypi.python.org/pypi') >>> notes = task.get_notes() >>> print(len(notes)) 1 """ owner = self.project.owner owner.sync() return [n for n in owner.notes.values() if n.item_id == self.id]
python
def get_notes(self): """Return all notes attached to this Task. :return: A list of all notes attached to this Task. :rtype: list of :class:`pytodoist.todoist.Note` >>> from pytodoist import todoist >>> user = todoist.login('[email protected]', 'password') >>> project = user.get_project('PyTodoist') >>> task = project.add_task('Install PyTodoist.') >>> task.add_note('https://pypi.python.org/pypi') >>> notes = task.get_notes() >>> print(len(notes)) 1 """ owner = self.project.owner owner.sync() return [n for n in owner.notes.values() if n.item_id == self.id]
[ "def", "get_notes", "(", "self", ")", ":", "owner", "=", "self", ".", "project", ".", "owner", "owner", ".", "sync", "(", ")", "return", "[", "n", "for", "n", "in", "owner", ".", "notes", ".", "values", "(", ")", "if", "n", ".", "item_id", "==", "self", ".", "id", "]" ]
Return all notes attached to this Task. :return: A list of all notes attached to this Task. :rtype: list of :class:`pytodoist.todoist.Note` >>> from pytodoist import todoist >>> user = todoist.login('[email protected]', 'password') >>> project = user.get_project('PyTodoist') >>> task = project.add_task('Install PyTodoist.') >>> task.add_note('https://pypi.python.org/pypi') >>> notes = task.get_notes() >>> print(len(notes)) 1
[ "Return", "all", "notes", "attached", "to", "this", "Task", "." ]
3359cbff485ebdbbb4ffbd58d71e21a817874dd7
https://github.com/Garee/pytodoist/blob/3359cbff485ebdbbb4ffbd58d71e21a817874dd7/pytodoist/todoist.py#L1350-L1367
train
Garee/pytodoist
pytodoist/todoist.py
Task.move
def move(self, project): """Move this task to another project. :param project: The project to move the task to. :type project: :class:`pytodoist.todoist.Project` >>> from pytodoist import todoist >>> user = todoist.login('[email protected]', 'password') >>> project = user.get_project('PyTodoist') >>> task = project.add_task('Install PyTodoist') >>> print(task.project.name) PyTodoist >>> inbox = user.get_project('Inbox') >>> task.move(inbox) >>> print(task.project.name) Inbox """ args = { 'project_items': {self.project.id: [self.id]}, 'to_project': project.id } _perform_command(self.project.owner, 'item_move', args) self.project = project
python
def move(self, project): """Move this task to another project. :param project: The project to move the task to. :type project: :class:`pytodoist.todoist.Project` >>> from pytodoist import todoist >>> user = todoist.login('[email protected]', 'password') >>> project = user.get_project('PyTodoist') >>> task = project.add_task('Install PyTodoist') >>> print(task.project.name) PyTodoist >>> inbox = user.get_project('Inbox') >>> task.move(inbox) >>> print(task.project.name) Inbox """ args = { 'project_items': {self.project.id: [self.id]}, 'to_project': project.id } _perform_command(self.project.owner, 'item_move', args) self.project = project
[ "def", "move", "(", "self", ",", "project", ")", ":", "args", "=", "{", "'project_items'", ":", "{", "self", ".", "project", ".", "id", ":", "[", "self", ".", "id", "]", "}", ",", "'to_project'", ":", "project", ".", "id", "}", "_perform_command", "(", "self", ".", "project", ".", "owner", ",", "'item_move'", ",", "args", ")", "self", ".", "project", "=", "project" ]
Move this task to another project. :param project: The project to move the task to. :type project: :class:`pytodoist.todoist.Project` >>> from pytodoist import todoist >>> user = todoist.login('[email protected]', 'password') >>> project = user.get_project('PyTodoist') >>> task = project.add_task('Install PyTodoist') >>> print(task.project.name) PyTodoist >>> inbox = user.get_project('Inbox') >>> task.move(inbox) >>> print(task.project.name) Inbox
[ "Move", "this", "task", "to", "another", "project", "." ]
3359cbff485ebdbbb4ffbd58d71e21a817874dd7
https://github.com/Garee/pytodoist/blob/3359cbff485ebdbbb4ffbd58d71e21a817874dd7/pytodoist/todoist.py#L1369-L1391
train
Garee/pytodoist
pytodoist/todoist.py
Task.add_date_reminder
def add_date_reminder(self, service, due_date): """Add a reminder to the task which activates on a given date. .. warning:: Requires Todoist premium. :param service: ```email```, ```sms``` or ```push``` for mobile. :type service: str :param due_date: The due date in UTC, formatted as ```YYYY-MM-DDTHH:MM``` :type due_date: str >>> from pytodoist import todoist >>> user = todoist.login('[email protected]', 'password') >>> project = user.get_project('PyTodoist') >>> task = project.add_task('Install PyTodoist') >>> task.add_date_reminder('email', '2015-12-01T09:00') """ args = { 'item_id': self.id, 'service': service, 'type': 'absolute', 'due_date_utc': due_date } _perform_command(self.project.owner, 'reminder_add', args)
python
def add_date_reminder(self, service, due_date): """Add a reminder to the task which activates on a given date. .. warning:: Requires Todoist premium. :param service: ```email```, ```sms``` or ```push``` for mobile. :type service: str :param due_date: The due date in UTC, formatted as ```YYYY-MM-DDTHH:MM``` :type due_date: str >>> from pytodoist import todoist >>> user = todoist.login('[email protected]', 'password') >>> project = user.get_project('PyTodoist') >>> task = project.add_task('Install PyTodoist') >>> task.add_date_reminder('email', '2015-12-01T09:00') """ args = { 'item_id': self.id, 'service': service, 'type': 'absolute', 'due_date_utc': due_date } _perform_command(self.project.owner, 'reminder_add', args)
[ "def", "add_date_reminder", "(", "self", ",", "service", ",", "due_date", ")", ":", "args", "=", "{", "'item_id'", ":", "self", ".", "id", ",", "'service'", ":", "service", ",", "'type'", ":", "'absolute'", ",", "'due_date_utc'", ":", "due_date", "}", "_perform_command", "(", "self", ".", "project", ".", "owner", ",", "'reminder_add'", ",", "args", ")" ]
Add a reminder to the task which activates on a given date. .. warning:: Requires Todoist premium. :param service: ```email```, ```sms``` or ```push``` for mobile. :type service: str :param due_date: The due date in UTC, formatted as ```YYYY-MM-DDTHH:MM``` :type due_date: str >>> from pytodoist import todoist >>> user = todoist.login('[email protected]', 'password') >>> project = user.get_project('PyTodoist') >>> task = project.add_task('Install PyTodoist') >>> task.add_date_reminder('email', '2015-12-01T09:00')
[ "Add", "a", "reminder", "to", "the", "task", "which", "activates", "on", "a", "given", "date", "." ]
3359cbff485ebdbbb4ffbd58d71e21a817874dd7
https://github.com/Garee/pytodoist/blob/3359cbff485ebdbbb4ffbd58d71e21a817874dd7/pytodoist/todoist.py#L1393-L1416
train
Garee/pytodoist
pytodoist/todoist.py
Task.add_location_reminder
def add_location_reminder(self, service, name, lat, long, trigger, radius): """Add a reminder to the task which activates on at a given location. .. warning:: Requires Todoist premium. :param service: ```email```, ```sms``` or ```push``` for mobile. :type service: str :param name: An alias for the location. :type name: str :param lat: The location latitude. :type lat: float :param long: The location longitude. :type long: float :param trigger: ```on_enter``` or ```on_leave```. :type trigger: str :param radius: The radius around the location that is still considered the location. :type radius: float >>> from pytodoist import todoist >>> user = todoist.login('[email protected]', 'password') >>> project = user.get_project('PyTodoist') >>> task = project.add_task('Install PyTodoist') >>> task.add_location_reminder('email', 'Leave Glasgow', ... 55.8580, 4.2590, 'on_leave', 100) """ args = { 'item_id': self.id, 'service': service, 'type': 'location', 'name': name, 'loc_lat': str(lat), 'loc_long': str(long), 'loc_trigger': trigger, 'radius': radius } _perform_command(self.project.owner, 'reminder_add', args)
python
def add_location_reminder(self, service, name, lat, long, trigger, radius): """Add a reminder to the task which activates on at a given location. .. warning:: Requires Todoist premium. :param service: ```email```, ```sms``` or ```push``` for mobile. :type service: str :param name: An alias for the location. :type name: str :param lat: The location latitude. :type lat: float :param long: The location longitude. :type long: float :param trigger: ```on_enter``` or ```on_leave```. :type trigger: str :param radius: The radius around the location that is still considered the location. :type radius: float >>> from pytodoist import todoist >>> user = todoist.login('[email protected]', 'password') >>> project = user.get_project('PyTodoist') >>> task = project.add_task('Install PyTodoist') >>> task.add_location_reminder('email', 'Leave Glasgow', ... 55.8580, 4.2590, 'on_leave', 100) """ args = { 'item_id': self.id, 'service': service, 'type': 'location', 'name': name, 'loc_lat': str(lat), 'loc_long': str(long), 'loc_trigger': trigger, 'radius': radius } _perform_command(self.project.owner, 'reminder_add', args)
[ "def", "add_location_reminder", "(", "self", ",", "service", ",", "name", ",", "lat", ",", "long", ",", "trigger", ",", "radius", ")", ":", "args", "=", "{", "'item_id'", ":", "self", ".", "id", ",", "'service'", ":", "service", ",", "'type'", ":", "'location'", ",", "'name'", ":", "name", ",", "'loc_lat'", ":", "str", "(", "lat", ")", ",", "'loc_long'", ":", "str", "(", "long", ")", ",", "'loc_trigger'", ":", "trigger", ",", "'radius'", ":", "radius", "}", "_perform_command", "(", "self", ".", "project", ".", "owner", ",", "'reminder_add'", ",", "args", ")" ]
Add a reminder to the task which activates on at a given location. .. warning:: Requires Todoist premium. :param service: ```email```, ```sms``` or ```push``` for mobile. :type service: str :param name: An alias for the location. :type name: str :param lat: The location latitude. :type lat: float :param long: The location longitude. :type long: float :param trigger: ```on_enter``` or ```on_leave```. :type trigger: str :param radius: The radius around the location that is still considered the location. :type radius: float >>> from pytodoist import todoist >>> user = todoist.login('[email protected]', 'password') >>> project = user.get_project('PyTodoist') >>> task = project.add_task('Install PyTodoist') >>> task.add_location_reminder('email', 'Leave Glasgow', ... 55.8580, 4.2590, 'on_leave', 100)
[ "Add", "a", "reminder", "to", "the", "task", "which", "activates", "on", "at", "a", "given", "location", "." ]
3359cbff485ebdbbb4ffbd58d71e21a817874dd7
https://github.com/Garee/pytodoist/blob/3359cbff485ebdbbb4ffbd58d71e21a817874dd7/pytodoist/todoist.py#L1418-L1454
train
Garee/pytodoist
pytodoist/todoist.py
Task.get_reminders
def get_reminders(self): """Return a list of the task's reminders. >>> from pytodoist import todoist >>> user = todoist.login('[email protected]', 'password') >>> project = user.get_project('PyTodoist') >>> task = project.add_task('Install PyTodoist') >>> task.add_date_reminder('email', '2015-12-01T09:00') >>> reminders = task.get_reminders() """ owner = self.project.owner return [r for r in owner.get_reminders() if r.task.id == self.id]
python
def get_reminders(self): """Return a list of the task's reminders. >>> from pytodoist import todoist >>> user = todoist.login('[email protected]', 'password') >>> project = user.get_project('PyTodoist') >>> task = project.add_task('Install PyTodoist') >>> task.add_date_reminder('email', '2015-12-01T09:00') >>> reminders = task.get_reminders() """ owner = self.project.owner return [r for r in owner.get_reminders() if r.task.id == self.id]
[ "def", "get_reminders", "(", "self", ")", ":", "owner", "=", "self", ".", "project", ".", "owner", "return", "[", "r", "for", "r", "in", "owner", ".", "get_reminders", "(", ")", "if", "r", ".", "task", ".", "id", "==", "self", ".", "id", "]" ]
Return a list of the task's reminders. >>> from pytodoist import todoist >>> user = todoist.login('[email protected]', 'password') >>> project = user.get_project('PyTodoist') >>> task = project.add_task('Install PyTodoist') >>> task.add_date_reminder('email', '2015-12-01T09:00') >>> reminders = task.get_reminders()
[ "Return", "a", "list", "of", "the", "task", "s", "reminders", "." ]
3359cbff485ebdbbb4ffbd58d71e21a817874dd7
https://github.com/Garee/pytodoist/blob/3359cbff485ebdbbb4ffbd58d71e21a817874dd7/pytodoist/todoist.py#L1456-L1467
train
Garee/pytodoist
pytodoist/todoist.py
Task.delete
def delete(self): """Delete the task. >>> from pytodoist import todoist >>> user = todoist.login('[email protected]', 'password') >>> project = user.get_project('Homework') >>> task = project.add_task('Read Chapter 4') >>> task.delete() """ args = {'ids': [self.id]} _perform_command(self.project.owner, 'item_delete', args) del self.project.owner.tasks[self.id]
python
def delete(self): """Delete the task. >>> from pytodoist import todoist >>> user = todoist.login('[email protected]', 'password') >>> project = user.get_project('Homework') >>> task = project.add_task('Read Chapter 4') >>> task.delete() """ args = {'ids': [self.id]} _perform_command(self.project.owner, 'item_delete', args) del self.project.owner.tasks[self.id]
[ "def", "delete", "(", "self", ")", ":", "args", "=", "{", "'ids'", ":", "[", "self", ".", "id", "]", "}", "_perform_command", "(", "self", ".", "project", ".", "owner", ",", "'item_delete'", ",", "args", ")", "del", "self", ".", "project", ".", "owner", ".", "tasks", "[", "self", ".", "id", "]" ]
Delete the task. >>> from pytodoist import todoist >>> user = todoist.login('[email protected]', 'password') >>> project = user.get_project('Homework') >>> task = project.add_task('Read Chapter 4') >>> task.delete()
[ "Delete", "the", "task", "." ]
3359cbff485ebdbbb4ffbd58d71e21a817874dd7
https://github.com/Garee/pytodoist/blob/3359cbff485ebdbbb4ffbd58d71e21a817874dd7/pytodoist/todoist.py#L1469-L1480
train
Garee/pytodoist
pytodoist/todoist.py
Note.delete
def delete(self): """Delete the note, removing it from it's task. >>> from pytodoist import todoist >>> user = todoist.login('[email protected]', 'password') >>> project = user.get_project('PyTodoist') >>> task = project.add_task('Install PyTodoist.') >>> note = task.add_note('https://pypi.python.org/pypi') >>> note.delete() >>> notes = task.get_notes() >>> print(len(notes)) 0 """ args = {'id': self.id} owner = self.task.project.owner _perform_command(owner, 'note_delete', args)
python
def delete(self): """Delete the note, removing it from it's task. >>> from pytodoist import todoist >>> user = todoist.login('[email protected]', 'password') >>> project = user.get_project('PyTodoist') >>> task = project.add_task('Install PyTodoist.') >>> note = task.add_note('https://pypi.python.org/pypi') >>> note.delete() >>> notes = task.get_notes() >>> print(len(notes)) 0 """ args = {'id': self.id} owner = self.task.project.owner _perform_command(owner, 'note_delete', args)
[ "def", "delete", "(", "self", ")", ":", "args", "=", "{", "'id'", ":", "self", ".", "id", "}", "owner", "=", "self", ".", "task", ".", "project", ".", "owner", "_perform_command", "(", "owner", ",", "'note_delete'", ",", "args", ")" ]
Delete the note, removing it from it's task. >>> from pytodoist import todoist >>> user = todoist.login('[email protected]', 'password') >>> project = user.get_project('PyTodoist') >>> task = project.add_task('Install PyTodoist.') >>> note = task.add_note('https://pypi.python.org/pypi') >>> note.delete() >>> notes = task.get_notes() >>> print(len(notes)) 0
[ "Delete", "the", "note", "removing", "it", "from", "it", "s", "task", "." ]
3359cbff485ebdbbb4ffbd58d71e21a817874dd7
https://github.com/Garee/pytodoist/blob/3359cbff485ebdbbb4ffbd58d71e21a817874dd7/pytodoist/todoist.py#L1535-L1550
train
Garee/pytodoist
pytodoist/todoist.py
Filter.update
def update(self): """Update the filter's details on Todoist. You must call this method to register any local attribute changes with Todoist. >>> from pytodoist import todoist >>> user = todoist.login('[email protected]', 'password') >>> overdue_filter = user.add_filter('Overdue', todoist.Query.OVERDUE) >>> overdue_filter.name = 'OVERDUE!' ... # At this point Todoist still thinks the name is 'Overdue'. >>> overdue_filter.update() ... # Now the name has been updated on Todoist. """ args = {attr: getattr(self, attr) for attr in self.to_update} args['id'] = self.id _perform_command(self.owner, 'filter_update', args)
python
def update(self): """Update the filter's details on Todoist. You must call this method to register any local attribute changes with Todoist. >>> from pytodoist import todoist >>> user = todoist.login('[email protected]', 'password') >>> overdue_filter = user.add_filter('Overdue', todoist.Query.OVERDUE) >>> overdue_filter.name = 'OVERDUE!' ... # At this point Todoist still thinks the name is 'Overdue'. >>> overdue_filter.update() ... # Now the name has been updated on Todoist. """ args = {attr: getattr(self, attr) for attr in self.to_update} args['id'] = self.id _perform_command(self.owner, 'filter_update', args)
[ "def", "update", "(", "self", ")", ":", "args", "=", "{", "attr", ":", "getattr", "(", "self", ",", "attr", ")", "for", "attr", "in", "self", ".", "to_update", "}", "args", "[", "'id'", "]", "=", "self", ".", "id", "_perform_command", "(", "self", ".", "owner", ",", "'filter_update'", ",", "args", ")" ]
Update the filter's details on Todoist. You must call this method to register any local attribute changes with Todoist. >>> from pytodoist import todoist >>> user = todoist.login('[email protected]', 'password') >>> overdue_filter = user.add_filter('Overdue', todoist.Query.OVERDUE) >>> overdue_filter.name = 'OVERDUE!' ... # At this point Todoist still thinks the name is 'Overdue'. >>> overdue_filter.update() ... # Now the name has been updated on Todoist.
[ "Update", "the", "filter", "s", "details", "on", "Todoist", "." ]
3359cbff485ebdbbb4ffbd58d71e21a817874dd7
https://github.com/Garee/pytodoist/blob/3359cbff485ebdbbb4ffbd58d71e21a817874dd7/pytodoist/todoist.py#L1634-L1650
train
Robpol86/colorclass
colorclass/core.py
apply_text
def apply_text(incoming, func): """Call `func` on text portions of incoming color string. :param iter incoming: Incoming string/ColorStr/string-like object to iterate. :param func: Function to call with string portion as first and only parameter. :return: Modified string, same class type as incoming string. """ split = RE_SPLIT.split(incoming) for i, item in enumerate(split): if not item or RE_SPLIT.match(item): continue split[i] = func(item) return incoming.__class__().join(split)
python
def apply_text(incoming, func): """Call `func` on text portions of incoming color string. :param iter incoming: Incoming string/ColorStr/string-like object to iterate. :param func: Function to call with string portion as first and only parameter. :return: Modified string, same class type as incoming string. """ split = RE_SPLIT.split(incoming) for i, item in enumerate(split): if not item or RE_SPLIT.match(item): continue split[i] = func(item) return incoming.__class__().join(split)
[ "def", "apply_text", "(", "incoming", ",", "func", ")", ":", "split", "=", "RE_SPLIT", ".", "split", "(", "incoming", ")", "for", "i", ",", "item", "in", "enumerate", "(", "split", ")", ":", "if", "not", "item", "or", "RE_SPLIT", ".", "match", "(", "item", ")", ":", "continue", "split", "[", "i", "]", "=", "func", "(", "item", ")", "return", "incoming", ".", "__class__", "(", ")", ".", "join", "(", "split", ")" ]
Call `func` on text portions of incoming color string. :param iter incoming: Incoming string/ColorStr/string-like object to iterate. :param func: Function to call with string portion as first and only parameter. :return: Modified string, same class type as incoming string.
[ "Call", "func", "on", "text", "portions", "of", "incoming", "color", "string", "." ]
692e2d6f5ad470b6221c8cb9641970dc5563a572
https://github.com/Robpol86/colorclass/blob/692e2d6f5ad470b6221c8cb9641970dc5563a572/colorclass/core.py#L10-L23
train
Robpol86/colorclass
colorclass/core.py
ColorBytes.decode
def decode(self, encoding='utf-8', errors='strict'): """Decode using the codec registered for encoding. Default encoding is 'utf-8'. errors may be given to set a different error handling scheme. Default is 'strict' meaning that encoding errors raise a UnicodeDecodeError. Other possible values are 'ignore' and 'replace' as well as any other name registered with codecs.register_error that is able to handle UnicodeDecodeErrors. :param str encoding: Codec. :param str errors: Error handling scheme. """ original_class = getattr(self, 'original_class') return original_class(super(ColorBytes, self).decode(encoding, errors))
python
def decode(self, encoding='utf-8', errors='strict'): """Decode using the codec registered for encoding. Default encoding is 'utf-8'. errors may be given to set a different error handling scheme. Default is 'strict' meaning that encoding errors raise a UnicodeDecodeError. Other possible values are 'ignore' and 'replace' as well as any other name registered with codecs.register_error that is able to handle UnicodeDecodeErrors. :param str encoding: Codec. :param str errors: Error handling scheme. """ original_class = getattr(self, 'original_class') return original_class(super(ColorBytes, self).decode(encoding, errors))
[ "def", "decode", "(", "self", ",", "encoding", "=", "'utf-8'", ",", "errors", "=", "'strict'", ")", ":", "original_class", "=", "getattr", "(", "self", ",", "'original_class'", ")", "return", "original_class", "(", "super", "(", "ColorBytes", ",", "self", ")", ".", "decode", "(", "encoding", ",", "errors", ")", ")" ]
Decode using the codec registered for encoding. Default encoding is 'utf-8'. errors may be given to set a different error handling scheme. Default is 'strict' meaning that encoding errors raise a UnicodeDecodeError. Other possible values are 'ignore' and 'replace' as well as any other name registered with codecs.register_error that is able to handle UnicodeDecodeErrors. :param str encoding: Codec. :param str errors: Error handling scheme.
[ "Decode", "using", "the", "codec", "registered", "for", "encoding", ".", "Default", "encoding", "is", "utf", "-", "8", "." ]
692e2d6f5ad470b6221c8cb9641970dc5563a572
https://github.com/Robpol86/colorclass/blob/692e2d6f5ad470b6221c8cb9641970dc5563a572/colorclass/core.py#L37-L48
train
Robpol86/colorclass
colorclass/core.py
ColorStr.center
def center(self, width, fillchar=None): """Return centered in a string of length width. Padding is done using the specified fill character or space. :param int width: Length of output string. :param str fillchar: Use this character instead of spaces. """ if fillchar is not None: result = self.value_no_colors.center(width, fillchar) else: result = self.value_no_colors.center(width) return self.__class__(result.replace(self.value_no_colors, self.value_colors), keep_tags=True)
python
def center(self, width, fillchar=None): """Return centered in a string of length width. Padding is done using the specified fill character or space. :param int width: Length of output string. :param str fillchar: Use this character instead of spaces. """ if fillchar is not None: result = self.value_no_colors.center(width, fillchar) else: result = self.value_no_colors.center(width) return self.__class__(result.replace(self.value_no_colors, self.value_colors), keep_tags=True)
[ "def", "center", "(", "self", ",", "width", ",", "fillchar", "=", "None", ")", ":", "if", "fillchar", "is", "not", "None", ":", "result", "=", "self", ".", "value_no_colors", ".", "center", "(", "width", ",", "fillchar", ")", "else", ":", "result", "=", "self", ".", "value_no_colors", ".", "center", "(", "width", ")", "return", "self", ".", "__class__", "(", "result", ".", "replace", "(", "self", ".", "value_no_colors", ",", "self", ".", "value_colors", ")", ",", "keep_tags", "=", "True", ")" ]
Return centered in a string of length width. Padding is done using the specified fill character or space. :param int width: Length of output string. :param str fillchar: Use this character instead of spaces.
[ "Return", "centered", "in", "a", "string", "of", "length", "width", ".", "Padding", "is", "done", "using", "the", "specified", "fill", "character", "or", "space", "." ]
692e2d6f5ad470b6221c8cb9641970dc5563a572
https://github.com/Robpol86/colorclass/blob/692e2d6f5ad470b6221c8cb9641970dc5563a572/colorclass/core.py#L111-L121
train
Robpol86/colorclass
colorclass/core.py
ColorStr.endswith
def endswith(self, suffix, start=0, end=None): """Return True if ends with the specified suffix, False otherwise. With optional start, test beginning at that position. With optional end, stop comparing at that position. suffix can also be a tuple of strings to try. :param str suffix: Suffix to search. :param int start: Beginning position. :param int end: Stop comparison at this position. """ args = [suffix, start] + ([] if end is None else [end]) return self.value_no_colors.endswith(*args)
python
def endswith(self, suffix, start=0, end=None): """Return True if ends with the specified suffix, False otherwise. With optional start, test beginning at that position. With optional end, stop comparing at that position. suffix can also be a tuple of strings to try. :param str suffix: Suffix to search. :param int start: Beginning position. :param int end: Stop comparison at this position. """ args = [suffix, start] + ([] if end is None else [end]) return self.value_no_colors.endswith(*args)
[ "def", "endswith", "(", "self", ",", "suffix", ",", "start", "=", "0", ",", "end", "=", "None", ")", ":", "args", "=", "[", "suffix", ",", "start", "]", "+", "(", "[", "]", "if", "end", "is", "None", "else", "[", "end", "]", ")", "return", "self", ".", "value_no_colors", ".", "endswith", "(", "*", "args", ")" ]
Return True if ends with the specified suffix, False otherwise. With optional start, test beginning at that position. With optional end, stop comparing at that position. suffix can also be a tuple of strings to try. :param str suffix: Suffix to search. :param int start: Beginning position. :param int end: Stop comparison at this position.
[ "Return", "True", "if", "ends", "with", "the", "specified", "suffix", "False", "otherwise", "." ]
692e2d6f5ad470b6221c8cb9641970dc5563a572
https://github.com/Robpol86/colorclass/blob/692e2d6f5ad470b6221c8cb9641970dc5563a572/colorclass/core.py#L134-L145
train
Robpol86/colorclass
colorclass/core.py
ColorStr.encode
def encode(self, encoding=None, errors='strict'): """Encode using the codec registered for encoding. encoding defaults to the default encoding. errors may be given to set a different error handling scheme. Default is 'strict' meaning that encoding errors raise a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and 'xmlcharrefreplace' as well as any other name registered with codecs.register_error that is able to handle UnicodeEncodeErrors. :param str encoding: Codec. :param str errors: Error handling scheme. """ return ColorBytes(super(ColorStr, self).encode(encoding, errors), original_class=self.__class__)
python
def encode(self, encoding=None, errors='strict'): """Encode using the codec registered for encoding. encoding defaults to the default encoding. errors may be given to set a different error handling scheme. Default is 'strict' meaning that encoding errors raise a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and 'xmlcharrefreplace' as well as any other name registered with codecs.register_error that is able to handle UnicodeEncodeErrors. :param str encoding: Codec. :param str errors: Error handling scheme. """ return ColorBytes(super(ColorStr, self).encode(encoding, errors), original_class=self.__class__)
[ "def", "encode", "(", "self", ",", "encoding", "=", "None", ",", "errors", "=", "'strict'", ")", ":", "return", "ColorBytes", "(", "super", "(", "ColorStr", ",", "self", ")", ".", "encode", "(", "encoding", ",", "errors", ")", ",", "original_class", "=", "self", ".", "__class__", ")" ]
Encode using the codec registered for encoding. encoding defaults to the default encoding. errors may be given to set a different error handling scheme. Default is 'strict' meaning that encoding errors raise a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and 'xmlcharrefreplace' as well as any other name registered with codecs.register_error that is able to handle UnicodeEncodeErrors. :param str encoding: Codec. :param str errors: Error handling scheme.
[ "Encode", "using", "the", "codec", "registered", "for", "encoding", ".", "encoding", "defaults", "to", "the", "default", "encoding", "." ]
692e2d6f5ad470b6221c8cb9641970dc5563a572
https://github.com/Robpol86/colorclass/blob/692e2d6f5ad470b6221c8cb9641970dc5563a572/colorclass/core.py#L147-L157
train
Robpol86/colorclass
colorclass/core.py
ColorStr.decode
def decode(self, encoding=None, errors='strict'): """Decode using the codec registered for encoding. encoding defaults to the default encoding. errors may be given to set a different error handling scheme. Default is 'strict' meaning that encoding errors raise a UnicodeDecodeError. Other possible values are 'ignore' and 'replace' as well as any other name registered with codecs.register_error that is able to handle UnicodeDecodeErrors. :param str encoding: Codec. :param str errors: Error handling scheme. """ return self.__class__(super(ColorStr, self).decode(encoding, errors), keep_tags=True)
python
def decode(self, encoding=None, errors='strict'): """Decode using the codec registered for encoding. encoding defaults to the default encoding. errors may be given to set a different error handling scheme. Default is 'strict' meaning that encoding errors raise a UnicodeDecodeError. Other possible values are 'ignore' and 'replace' as well as any other name registered with codecs.register_error that is able to handle UnicodeDecodeErrors. :param str encoding: Codec. :param str errors: Error handling scheme. """ return self.__class__(super(ColorStr, self).decode(encoding, errors), keep_tags=True)
[ "def", "decode", "(", "self", ",", "encoding", "=", "None", ",", "errors", "=", "'strict'", ")", ":", "return", "self", ".", "__class__", "(", "super", "(", "ColorStr", ",", "self", ")", ".", "decode", "(", "encoding", ",", "errors", ")", ",", "keep_tags", "=", "True", ")" ]
Decode using the codec registered for encoding. encoding defaults to the default encoding. errors may be given to set a different error handling scheme. Default is 'strict' meaning that encoding errors raise a UnicodeDecodeError. Other possible values are 'ignore' and 'replace' as well as any other name registered with codecs.register_error that is able to handle UnicodeDecodeErrors. :param str encoding: Codec. :param str errors: Error handling scheme.
[ "Decode", "using", "the", "codec", "registered", "for", "encoding", ".", "encoding", "defaults", "to", "the", "default", "encoding", "." ]
692e2d6f5ad470b6221c8cb9641970dc5563a572
https://github.com/Robpol86/colorclass/blob/692e2d6f5ad470b6221c8cb9641970dc5563a572/colorclass/core.py#L159-L169
train
Robpol86/colorclass
colorclass/core.py
ColorStr.format
def format(self, *args, **kwargs): """Return a formatted version, using substitutions from args and kwargs. The substitutions are identified by braces ('{' and '}'). """ return self.__class__(super(ColorStr, self).format(*args, **kwargs), keep_tags=True)
python
def format(self, *args, **kwargs): """Return a formatted version, using substitutions from args and kwargs. The substitutions are identified by braces ('{' and '}'). """ return self.__class__(super(ColorStr, self).format(*args, **kwargs), keep_tags=True)
[ "def", "format", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "__class__", "(", "super", "(", "ColorStr", ",", "self", ")", ".", "format", "(", "*", "args", ",", "*", "*", "kwargs", ")", ",", "keep_tags", "=", "True", ")" ]
Return a formatted version, using substitutions from args and kwargs. The substitutions are identified by braces ('{' and '}').
[ "Return", "a", "formatted", "version", "using", "substitutions", "from", "args", "and", "kwargs", "." ]
692e2d6f5ad470b6221c8cb9641970dc5563a572
https://github.com/Robpol86/colorclass/blob/692e2d6f5ad470b6221c8cb9641970dc5563a572/colorclass/core.py#L182-L187
train
Robpol86/colorclass
colorclass/core.py
ColorStr.join
def join(self, iterable): """Return a string which is the concatenation of the strings in the iterable. :param iterable: Join items in this iterable. """ return self.__class__(super(ColorStr, self).join(iterable), keep_tags=True)
python
def join(self, iterable): """Return a string which is the concatenation of the strings in the iterable. :param iterable: Join items in this iterable. """ return self.__class__(super(ColorStr, self).join(iterable), keep_tags=True)
[ "def", "join", "(", "self", ",", "iterable", ")", ":", "return", "self", ".", "__class__", "(", "super", "(", "ColorStr", ",", "self", ")", ".", "join", "(", "iterable", ")", ",", "keep_tags", "=", "True", ")" ]
Return a string which is the concatenation of the strings in the iterable. :param iterable: Join items in this iterable.
[ "Return", "a", "string", "which", "is", "the", "concatenation", "of", "the", "strings", "in", "the", "iterable", "." ]
692e2d6f5ad470b6221c8cb9641970dc5563a572
https://github.com/Robpol86/colorclass/blob/692e2d6f5ad470b6221c8cb9641970dc5563a572/colorclass/core.py#L234-L239
train
Robpol86/colorclass
colorclass/core.py
ColorStr.splitlines
def splitlines(self, keepends=False): """Return a list of the lines in the string, breaking at line boundaries. Line breaks are not included in the resulting list unless keepends is given and True. :param bool keepends: Include linebreaks. """ return [self.__class__(l) for l in self.value_colors.splitlines(keepends)]
python
def splitlines(self, keepends=False): """Return a list of the lines in the string, breaking at line boundaries. Line breaks are not included in the resulting list unless keepends is given and True. :param bool keepends: Include linebreaks. """ return [self.__class__(l) for l in self.value_colors.splitlines(keepends)]
[ "def", "splitlines", "(", "self", ",", "keepends", "=", "False", ")", ":", "return", "[", "self", ".", "__class__", "(", "l", ")", "for", "l", "in", "self", ".", "value_colors", ".", "splitlines", "(", "keepends", ")", "]" ]
Return a list of the lines in the string, breaking at line boundaries. Line breaks are not included in the resulting list unless keepends is given and True. :param bool keepends: Include linebreaks.
[ "Return", "a", "list", "of", "the", "lines", "in", "the", "string", "breaking", "at", "line", "boundaries", "." ]
692e2d6f5ad470b6221c8cb9641970dc5563a572
https://github.com/Robpol86/colorclass/blob/692e2d6f5ad470b6221c8cb9641970dc5563a572/colorclass/core.py#L285-L292
train
Robpol86/colorclass
colorclass/core.py
ColorStr.startswith
def startswith(self, prefix, start=0, end=-1): """Return True if string starts with the specified prefix, False otherwise. With optional start, test beginning at that position. With optional end, stop comparing at that position. prefix can also be a tuple of strings to try. :param str prefix: Prefix to search. :param int start: Beginning position. :param int end: Stop comparison at this position. """ return self.value_no_colors.startswith(prefix, start, end)
python
def startswith(self, prefix, start=0, end=-1): """Return True if string starts with the specified prefix, False otherwise. With optional start, test beginning at that position. With optional end, stop comparing at that position. prefix can also be a tuple of strings to try. :param str prefix: Prefix to search. :param int start: Beginning position. :param int end: Stop comparison at this position. """ return self.value_no_colors.startswith(prefix, start, end)
[ "def", "startswith", "(", "self", ",", "prefix", ",", "start", "=", "0", ",", "end", "=", "-", "1", ")", ":", "return", "self", ".", "value_no_colors", ".", "startswith", "(", "prefix", ",", "start", ",", "end", ")" ]
Return True if string starts with the specified prefix, False otherwise. With optional start, test beginning at that position. With optional end, stop comparing at that position. prefix can also be a tuple of strings to try. :param str prefix: Prefix to search. :param int start: Beginning position. :param int end: Stop comparison at this position.
[ "Return", "True", "if", "string", "starts", "with", "the", "specified", "prefix", "False", "otherwise", "." ]
692e2d6f5ad470b6221c8cb9641970dc5563a572
https://github.com/Robpol86/colorclass/blob/692e2d6f5ad470b6221c8cb9641970dc5563a572/colorclass/core.py#L294-L304
train
Robpol86/colorclass
colorclass/core.py
ColorStr.zfill
def zfill(self, width): """Pad a numeric string with zeros on the left, to fill a field of the specified width. The string is never truncated. :param int width: Length of output string. """ if not self.value_no_colors: result = self.value_no_colors.zfill(width) else: result = self.value_colors.replace(self.value_no_colors, self.value_no_colors.zfill(width)) return self.__class__(result, keep_tags=True)
python
def zfill(self, width): """Pad a numeric string with zeros on the left, to fill a field of the specified width. The string is never truncated. :param int width: Length of output string. """ if not self.value_no_colors: result = self.value_no_colors.zfill(width) else: result = self.value_colors.replace(self.value_no_colors, self.value_no_colors.zfill(width)) return self.__class__(result, keep_tags=True)
[ "def", "zfill", "(", "self", ",", "width", ")", ":", "if", "not", "self", ".", "value_no_colors", ":", "result", "=", "self", ".", "value_no_colors", ".", "zfill", "(", "width", ")", "else", ":", "result", "=", "self", ".", "value_colors", ".", "replace", "(", "self", ".", "value_no_colors", ",", "self", ".", "value_no_colors", ".", "zfill", "(", "width", ")", ")", "return", "self", ".", "__class__", "(", "result", ",", "keep_tags", "=", "True", ")" ]
Pad a numeric string with zeros on the left, to fill a field of the specified width. The string is never truncated. :param int width: Length of output string.
[ "Pad", "a", "numeric", "string", "with", "zeros", "on", "the", "left", "to", "fill", "a", "field", "of", "the", "specified", "width", "." ]
692e2d6f5ad470b6221c8cb9641970dc5563a572
https://github.com/Robpol86/colorclass/blob/692e2d6f5ad470b6221c8cb9641970dc5563a572/colorclass/core.py#L331-L342
train
Robpol86/colorclass
colorclass/color.py
Color.colorize
def colorize(cls, color, string, auto=False): """Color-code entire string using specified color. :param str color: Color of string. :param str string: String to colorize. :param bool auto: Enable auto-color (dark/light terminal). :return: Class instance for colorized string. :rtype: Color """ tag = '{0}{1}'.format('auto' if auto else '', color) return cls('{%s}%s{/%s}' % (tag, string, tag))
python
def colorize(cls, color, string, auto=False): """Color-code entire string using specified color. :param str color: Color of string. :param str string: String to colorize. :param bool auto: Enable auto-color (dark/light terminal). :return: Class instance for colorized string. :rtype: Color """ tag = '{0}{1}'.format('auto' if auto else '', color) return cls('{%s}%s{/%s}' % (tag, string, tag))
[ "def", "colorize", "(", "cls", ",", "color", ",", "string", ",", "auto", "=", "False", ")", ":", "tag", "=", "'{0}{1}'", ".", "format", "(", "'auto'", "if", "auto", "else", "''", ",", "color", ")", "return", "cls", "(", "'{%s}%s{/%s}'", "%", "(", "tag", ",", "string", ",", "tag", ")", ")" ]
Color-code entire string using specified color. :param str color: Color of string. :param str string: String to colorize. :param bool auto: Enable auto-color (dark/light terminal). :return: Class instance for colorized string. :rtype: Color
[ "Color", "-", "code", "entire", "string", "using", "specified", "color", "." ]
692e2d6f5ad470b6221c8cb9641970dc5563a572
https://github.com/Robpol86/colorclass/blob/692e2d6f5ad470b6221c8cb9641970dc5563a572/colorclass/color.py#L17-L28
train
Robpol86/colorclass
colorclass/codes.py
list_tags
def list_tags(): """List the available tags. :return: List of 4-item tuples: opening tag, closing tag, main ansi value, closing ansi value. :rtype: list """ # Build reverse dictionary. Keys are closing tags, values are [closing ansi, opening tag, opening ansi]. reverse_dict = dict() for tag, ansi in sorted(BASE_CODES.items()): if tag.startswith('/'): reverse_dict[tag] = [ansi, None, None] else: reverse_dict['/' + tag][1:] = [tag, ansi] # Collapse four_item_tuples = [(v[1], k, v[2], v[0]) for k, v in reverse_dict.items()] # Sort. def sorter(four_item): """Sort /all /fg /bg first, then b i u flash, then auto colors, then dark colors, finally light colors. :param iter four_item: [opening tag, closing tag, main ansi value, closing ansi value] :return Sorting weight. :rtype: int """ if not four_item[2]: # /all /fg /bg return four_item[3] - 200 if four_item[2] < 10 or four_item[0].startswith('auto'): # b f i u or auto colors return four_item[2] - 100 return four_item[2] four_item_tuples.sort(key=sorter) return four_item_tuples
python
def list_tags(): """List the available tags. :return: List of 4-item tuples: opening tag, closing tag, main ansi value, closing ansi value. :rtype: list """ # Build reverse dictionary. Keys are closing tags, values are [closing ansi, opening tag, opening ansi]. reverse_dict = dict() for tag, ansi in sorted(BASE_CODES.items()): if tag.startswith('/'): reverse_dict[tag] = [ansi, None, None] else: reverse_dict['/' + tag][1:] = [tag, ansi] # Collapse four_item_tuples = [(v[1], k, v[2], v[0]) for k, v in reverse_dict.items()] # Sort. def sorter(four_item): """Sort /all /fg /bg first, then b i u flash, then auto colors, then dark colors, finally light colors. :param iter four_item: [opening tag, closing tag, main ansi value, closing ansi value] :return Sorting weight. :rtype: int """ if not four_item[2]: # /all /fg /bg return four_item[3] - 200 if four_item[2] < 10 or four_item[0].startswith('auto'): # b f i u or auto colors return four_item[2] - 100 return four_item[2] four_item_tuples.sort(key=sorter) return four_item_tuples
[ "def", "list_tags", "(", ")", ":", "# Build reverse dictionary. Keys are closing tags, values are [closing ansi, opening tag, opening ansi].", "reverse_dict", "=", "dict", "(", ")", "for", "tag", ",", "ansi", "in", "sorted", "(", "BASE_CODES", ".", "items", "(", ")", ")", ":", "if", "tag", ".", "startswith", "(", "'/'", ")", ":", "reverse_dict", "[", "tag", "]", "=", "[", "ansi", ",", "None", ",", "None", "]", "else", ":", "reverse_dict", "[", "'/'", "+", "tag", "]", "[", "1", ":", "]", "=", "[", "tag", ",", "ansi", "]", "# Collapse", "four_item_tuples", "=", "[", "(", "v", "[", "1", "]", ",", "k", ",", "v", "[", "2", "]", ",", "v", "[", "0", "]", ")", "for", "k", ",", "v", "in", "reverse_dict", ".", "items", "(", ")", "]", "# Sort.", "def", "sorter", "(", "four_item", ")", ":", "\"\"\"Sort /all /fg /bg first, then b i u flash, then auto colors, then dark colors, finally light colors.\n\n :param iter four_item: [opening tag, closing tag, main ansi value, closing ansi value]\n\n :return Sorting weight.\n :rtype: int\n \"\"\"", "if", "not", "four_item", "[", "2", "]", ":", "# /all /fg /bg", "return", "four_item", "[", "3", "]", "-", "200", "if", "four_item", "[", "2", "]", "<", "10", "or", "four_item", "[", "0", "]", ".", "startswith", "(", "'auto'", ")", ":", "# b f i u or auto colors", "return", "four_item", "[", "2", "]", "-", "100", "return", "four_item", "[", "2", "]", "four_item_tuples", ".", "sort", "(", "key", "=", "sorter", ")", "return", "four_item_tuples" ]
List the available tags. :return: List of 4-item tuples: opening tag, closing tag, main ansi value, closing ansi value. :rtype: list
[ "List", "the", "available", "tags", "." ]
692e2d6f5ad470b6221c8cb9641970dc5563a572
https://github.com/Robpol86/colorclass/blob/692e2d6f5ad470b6221c8cb9641970dc5563a572/colorclass/codes.py#L196-L229
train
Robpol86/colorclass
colorclass/codes.py
ANSICodeMapping.disable_if_no_tty
def disable_if_no_tty(cls): """Disable all colors only if there is no TTY available. :return: True if colors are disabled, False if stderr or stdout is a TTY. :rtype: bool """ if sys.stdout.isatty() or sys.stderr.isatty(): return False cls.disable_all_colors() return True
python
def disable_if_no_tty(cls): """Disable all colors only if there is no TTY available. :return: True if colors are disabled, False if stderr or stdout is a TTY. :rtype: bool """ if sys.stdout.isatty() or sys.stderr.isatty(): return False cls.disable_all_colors() return True
[ "def", "disable_if_no_tty", "(", "cls", ")", ":", "if", "sys", ".", "stdout", ".", "isatty", "(", ")", "or", "sys", ".", "stderr", ".", "isatty", "(", ")", ":", "return", "False", "cls", ".", "disable_all_colors", "(", ")", "return", "True" ]
Disable all colors only if there is no TTY available. :return: True if colors are disabled, False if stderr or stdout is a TTY. :rtype: bool
[ "Disable", "all", "colors", "only", "if", "there", "is", "no", "TTY", "available", "." ]
692e2d6f5ad470b6221c8cb9641970dc5563a572
https://github.com/Robpol86/colorclass/blob/692e2d6f5ad470b6221c8cb9641970dc5563a572/colorclass/codes.py#L94-L103
train
Robpol86/colorclass
colorclass/windows.py
get_console_info
def get_console_info(kernel32, handle): """Get information about this current console window. http://msdn.microsoft.com/en-us/library/windows/desktop/ms683231 https://code.google.com/p/colorama/issues/detail?id=47 https://bitbucket.org/pytest-dev/py/src/4617fe46/py/_io/terminalwriter.py Windows 10 Insider since around February 2016 finally introduced support for ANSI colors. No need to replace stdout and stderr streams to intercept colors and issue multiple SetConsoleTextAttribute() calls for these consoles. :raise OSError: When GetConsoleScreenBufferInfo or GetConsoleMode API calls fail. :param ctypes.windll.kernel32 kernel32: Loaded kernel32 instance. :param int handle: stderr or stdout handle. :return: Foreground and background colors (integers) as well as native ANSI support (bool). :rtype: tuple """ # Query Win32 API. csbi = ConsoleScreenBufferInfo() # Populated by GetConsoleScreenBufferInfo. lpcsbi = ctypes.byref(csbi) dword = ctypes.c_ulong() # Populated by GetConsoleMode. lpdword = ctypes.byref(dword) if not kernel32.GetConsoleScreenBufferInfo(handle, lpcsbi) or not kernel32.GetConsoleMode(handle, lpdword): raise ctypes.WinError() # Parse data. # buffer_width = int(csbi.dwSize.X - 1) # buffer_height = int(csbi.dwSize.Y) # terminal_width = int(csbi.srWindow.Right - csbi.srWindow.Left) # terminal_height = int(csbi.srWindow.Bottom - csbi.srWindow.Top) fg_color = csbi.wAttributes % 16 bg_color = csbi.wAttributes & 240 native_ansi = bool(dword.value & ENABLE_VIRTUAL_TERMINAL_PROCESSING) return fg_color, bg_color, native_ansi
python
def get_console_info(kernel32, handle): """Get information about this current console window. http://msdn.microsoft.com/en-us/library/windows/desktop/ms683231 https://code.google.com/p/colorama/issues/detail?id=47 https://bitbucket.org/pytest-dev/py/src/4617fe46/py/_io/terminalwriter.py Windows 10 Insider since around February 2016 finally introduced support for ANSI colors. No need to replace stdout and stderr streams to intercept colors and issue multiple SetConsoleTextAttribute() calls for these consoles. :raise OSError: When GetConsoleScreenBufferInfo or GetConsoleMode API calls fail. :param ctypes.windll.kernel32 kernel32: Loaded kernel32 instance. :param int handle: stderr or stdout handle. :return: Foreground and background colors (integers) as well as native ANSI support (bool). :rtype: tuple """ # Query Win32 API. csbi = ConsoleScreenBufferInfo() # Populated by GetConsoleScreenBufferInfo. lpcsbi = ctypes.byref(csbi) dword = ctypes.c_ulong() # Populated by GetConsoleMode. lpdword = ctypes.byref(dword) if not kernel32.GetConsoleScreenBufferInfo(handle, lpcsbi) or not kernel32.GetConsoleMode(handle, lpdword): raise ctypes.WinError() # Parse data. # buffer_width = int(csbi.dwSize.X - 1) # buffer_height = int(csbi.dwSize.Y) # terminal_width = int(csbi.srWindow.Right - csbi.srWindow.Left) # terminal_height = int(csbi.srWindow.Bottom - csbi.srWindow.Top) fg_color = csbi.wAttributes % 16 bg_color = csbi.wAttributes & 240 native_ansi = bool(dword.value & ENABLE_VIRTUAL_TERMINAL_PROCESSING) return fg_color, bg_color, native_ansi
[ "def", "get_console_info", "(", "kernel32", ",", "handle", ")", ":", "# Query Win32 API.", "csbi", "=", "ConsoleScreenBufferInfo", "(", ")", "# Populated by GetConsoleScreenBufferInfo.", "lpcsbi", "=", "ctypes", ".", "byref", "(", "csbi", ")", "dword", "=", "ctypes", ".", "c_ulong", "(", ")", "# Populated by GetConsoleMode.", "lpdword", "=", "ctypes", ".", "byref", "(", "dword", ")", "if", "not", "kernel32", ".", "GetConsoleScreenBufferInfo", "(", "handle", ",", "lpcsbi", ")", "or", "not", "kernel32", ".", "GetConsoleMode", "(", "handle", ",", "lpdword", ")", ":", "raise", "ctypes", ".", "WinError", "(", ")", "# Parse data.", "# buffer_width = int(csbi.dwSize.X - 1)", "# buffer_height = int(csbi.dwSize.Y)", "# terminal_width = int(csbi.srWindow.Right - csbi.srWindow.Left)", "# terminal_height = int(csbi.srWindow.Bottom - csbi.srWindow.Top)", "fg_color", "=", "csbi", ".", "wAttributes", "%", "16", "bg_color", "=", "csbi", ".", "wAttributes", "&", "240", "native_ansi", "=", "bool", "(", "dword", ".", "value", "&", "ENABLE_VIRTUAL_TERMINAL_PROCESSING", ")", "return", "fg_color", ",", "bg_color", ",", "native_ansi" ]
Get information about this current console window. http://msdn.microsoft.com/en-us/library/windows/desktop/ms683231 https://code.google.com/p/colorama/issues/detail?id=47 https://bitbucket.org/pytest-dev/py/src/4617fe46/py/_io/terminalwriter.py Windows 10 Insider since around February 2016 finally introduced support for ANSI colors. No need to replace stdout and stderr streams to intercept colors and issue multiple SetConsoleTextAttribute() calls for these consoles. :raise OSError: When GetConsoleScreenBufferInfo or GetConsoleMode API calls fail. :param ctypes.windll.kernel32 kernel32: Loaded kernel32 instance. :param int handle: stderr or stdout handle. :return: Foreground and background colors (integers) as well as native ANSI support (bool). :rtype: tuple
[ "Get", "information", "about", "this", "current", "console", "window", "." ]
692e2d6f5ad470b6221c8cb9641970dc5563a572
https://github.com/Robpol86/colorclass/blob/692e2d6f5ad470b6221c8cb9641970dc5563a572/colorclass/windows.py#L113-L148
train
Robpol86/colorclass
colorclass/windows.py
bg_color_native_ansi
def bg_color_native_ansi(kernel32, stderr, stdout): """Get background color and if console supports ANSI colors natively for both streams. :param ctypes.windll.kernel32 kernel32: Loaded kernel32 instance. :param int stderr: stderr handle. :param int stdout: stdout handle. :return: Background color (int) and native ANSI support (bool). :rtype: tuple """ try: if stderr == INVALID_HANDLE_VALUE: raise OSError bg_color, native_ansi = get_console_info(kernel32, stderr)[1:] except OSError: try: if stdout == INVALID_HANDLE_VALUE: raise OSError bg_color, native_ansi = get_console_info(kernel32, stdout)[1:] except OSError: bg_color, native_ansi = WINDOWS_CODES['black'], False return bg_color, native_ansi
python
def bg_color_native_ansi(kernel32, stderr, stdout): """Get background color and if console supports ANSI colors natively for both streams. :param ctypes.windll.kernel32 kernel32: Loaded kernel32 instance. :param int stderr: stderr handle. :param int stdout: stdout handle. :return: Background color (int) and native ANSI support (bool). :rtype: tuple """ try: if stderr == INVALID_HANDLE_VALUE: raise OSError bg_color, native_ansi = get_console_info(kernel32, stderr)[1:] except OSError: try: if stdout == INVALID_HANDLE_VALUE: raise OSError bg_color, native_ansi = get_console_info(kernel32, stdout)[1:] except OSError: bg_color, native_ansi = WINDOWS_CODES['black'], False return bg_color, native_ansi
[ "def", "bg_color_native_ansi", "(", "kernel32", ",", "stderr", ",", "stdout", ")", ":", "try", ":", "if", "stderr", "==", "INVALID_HANDLE_VALUE", ":", "raise", "OSError", "bg_color", ",", "native_ansi", "=", "get_console_info", "(", "kernel32", ",", "stderr", ")", "[", "1", ":", "]", "except", "OSError", ":", "try", ":", "if", "stdout", "==", "INVALID_HANDLE_VALUE", ":", "raise", "OSError", "bg_color", ",", "native_ansi", "=", "get_console_info", "(", "kernel32", ",", "stdout", ")", "[", "1", ":", "]", "except", "OSError", ":", "bg_color", ",", "native_ansi", "=", "WINDOWS_CODES", "[", "'black'", "]", ",", "False", "return", "bg_color", ",", "native_ansi" ]
Get background color and if console supports ANSI colors natively for both streams. :param ctypes.windll.kernel32 kernel32: Loaded kernel32 instance. :param int stderr: stderr handle. :param int stdout: stdout handle. :return: Background color (int) and native ANSI support (bool). :rtype: tuple
[ "Get", "background", "color", "and", "if", "console", "supports", "ANSI", "colors", "natively", "for", "both", "streams", "." ]
692e2d6f5ad470b6221c8cb9641970dc5563a572
https://github.com/Robpol86/colorclass/blob/692e2d6f5ad470b6221c8cb9641970dc5563a572/colorclass/windows.py#L151-L172
train
Robpol86/colorclass
colorclass/windows.py
WindowsStream.colors
def colors(self): """Return the current foreground and background colors.""" try: return get_console_info(self._kernel32, self._stream_handle)[:2] except OSError: return WINDOWS_CODES['white'], WINDOWS_CODES['black']
python
def colors(self): """Return the current foreground and background colors.""" try: return get_console_info(self._kernel32, self._stream_handle)[:2] except OSError: return WINDOWS_CODES['white'], WINDOWS_CODES['black']
[ "def", "colors", "(", "self", ")", ":", "try", ":", "return", "get_console_info", "(", "self", ".", "_kernel32", ",", "self", ".", "_stream_handle", ")", "[", ":", "2", "]", "except", "OSError", ":", "return", "WINDOWS_CODES", "[", "'white'", "]", ",", "WINDOWS_CODES", "[", "'black'", "]" ]
Return the current foreground and background colors.
[ "Return", "the", "current", "foreground", "and", "background", "colors", "." ]
692e2d6f5ad470b6221c8cb9641970dc5563a572
https://github.com/Robpol86/colorclass/blob/692e2d6f5ad470b6221c8cb9641970dc5563a572/colorclass/windows.py#L217-L222
train
Robpol86/colorclass
colorclass/windows.py
WindowsStream.colors
def colors(self, color_code): """Change the foreground and background colors for subsequently printed characters. None resets colors to their original values (when class was instantiated). Since setting a color requires including both foreground and background codes (merged), setting just the foreground color resets the background color to black, and vice versa. This function first gets the current background and foreground colors, merges in the requested color code, and sets the result. However if we need to remove just the foreground color but leave the background color the same (or vice versa) such as when {/red} is used, we must merge the default foreground color with the current background color. This is the reason for those negative values. :param int color_code: Color code from WINDOWS_CODES. """ if color_code is None: color_code = WINDOWS_CODES['/all'] # Get current color code. current_fg, current_bg = self.colors # Handle special negative codes. Also determine the final color code. if color_code == WINDOWS_CODES['/fg']: final_color_code = self.default_fg | current_bg # Reset the foreground only. elif color_code == WINDOWS_CODES['/bg']: final_color_code = current_fg | self.default_bg # Reset the background only. elif color_code == WINDOWS_CODES['/all']: final_color_code = self.default_fg | self.default_bg # Reset both. elif color_code == WINDOWS_CODES['bgblack']: final_color_code = current_fg # Black background. else: new_is_bg = color_code in self.ALL_BG_CODES final_color_code = color_code | (current_fg if new_is_bg else current_bg) # Set new code. self._kernel32.SetConsoleTextAttribute(self._stream_handle, final_color_code)
python
def colors(self, color_code): """Change the foreground and background colors for subsequently printed characters. None resets colors to their original values (when class was instantiated). Since setting a color requires including both foreground and background codes (merged), setting just the foreground color resets the background color to black, and vice versa. This function first gets the current background and foreground colors, merges in the requested color code, and sets the result. However if we need to remove just the foreground color but leave the background color the same (or vice versa) such as when {/red} is used, we must merge the default foreground color with the current background color. This is the reason for those negative values. :param int color_code: Color code from WINDOWS_CODES. """ if color_code is None: color_code = WINDOWS_CODES['/all'] # Get current color code. current_fg, current_bg = self.colors # Handle special negative codes. Also determine the final color code. if color_code == WINDOWS_CODES['/fg']: final_color_code = self.default_fg | current_bg # Reset the foreground only. elif color_code == WINDOWS_CODES['/bg']: final_color_code = current_fg | self.default_bg # Reset the background only. elif color_code == WINDOWS_CODES['/all']: final_color_code = self.default_fg | self.default_bg # Reset both. elif color_code == WINDOWS_CODES['bgblack']: final_color_code = current_fg # Black background. else: new_is_bg = color_code in self.ALL_BG_CODES final_color_code = color_code | (current_fg if new_is_bg else current_bg) # Set new code. self._kernel32.SetConsoleTextAttribute(self._stream_handle, final_color_code)
[ "def", "colors", "(", "self", ",", "color_code", ")", ":", "if", "color_code", "is", "None", ":", "color_code", "=", "WINDOWS_CODES", "[", "'/all'", "]", "# Get current color code.", "current_fg", ",", "current_bg", "=", "self", ".", "colors", "# Handle special negative codes. Also determine the final color code.", "if", "color_code", "==", "WINDOWS_CODES", "[", "'/fg'", "]", ":", "final_color_code", "=", "self", ".", "default_fg", "|", "current_bg", "# Reset the foreground only.", "elif", "color_code", "==", "WINDOWS_CODES", "[", "'/bg'", "]", ":", "final_color_code", "=", "current_fg", "|", "self", ".", "default_bg", "# Reset the background only.", "elif", "color_code", "==", "WINDOWS_CODES", "[", "'/all'", "]", ":", "final_color_code", "=", "self", ".", "default_fg", "|", "self", ".", "default_bg", "# Reset both.", "elif", "color_code", "==", "WINDOWS_CODES", "[", "'bgblack'", "]", ":", "final_color_code", "=", "current_fg", "# Black background.", "else", ":", "new_is_bg", "=", "color_code", "in", "self", ".", "ALL_BG_CODES", "final_color_code", "=", "color_code", "|", "(", "current_fg", "if", "new_is_bg", "else", "current_bg", ")", "# Set new code.", "self", ".", "_kernel32", ".", "SetConsoleTextAttribute", "(", "self", ".", "_stream_handle", ",", "final_color_code", ")" ]
Change the foreground and background colors for subsequently printed characters. None resets colors to their original values (when class was instantiated). Since setting a color requires including both foreground and background codes (merged), setting just the foreground color resets the background color to black, and vice versa. This function first gets the current background and foreground colors, merges in the requested color code, and sets the result. However if we need to remove just the foreground color but leave the background color the same (or vice versa) such as when {/red} is used, we must merge the default foreground color with the current background color. This is the reason for those negative values. :param int color_code: Color code from WINDOWS_CODES.
[ "Change", "the", "foreground", "and", "background", "colors", "for", "subsequently", "printed", "characters", "." ]
692e2d6f5ad470b6221c8cb9641970dc5563a572
https://github.com/Robpol86/colorclass/blob/692e2d6f5ad470b6221c8cb9641970dc5563a572/colorclass/windows.py#L225-L262
train
Robpol86/colorclass
colorclass/windows.py
WindowsStream.write
def write(self, p_str): """Write to stream. :param str p_str: string to print. """ for segment in RE_SPLIT.split(p_str): if not segment: # Empty string. p_str probably starts with colors so the first item is always ''. continue if not RE_SPLIT.match(segment): # No color codes, print regular text. print(segment, file=self._original_stream, end='') self._original_stream.flush() continue for color_code in (int(c) for c in RE_NUMBER_SEARCH.findall(segment)[0].split(';')): if color_code in self.COMPILED_CODES: self.colors = self.COMPILED_CODES[color_code]
python
def write(self, p_str): """Write to stream. :param str p_str: string to print. """ for segment in RE_SPLIT.split(p_str): if not segment: # Empty string. p_str probably starts with colors so the first item is always ''. continue if not RE_SPLIT.match(segment): # No color codes, print regular text. print(segment, file=self._original_stream, end='') self._original_stream.flush() continue for color_code in (int(c) for c in RE_NUMBER_SEARCH.findall(segment)[0].split(';')): if color_code in self.COMPILED_CODES: self.colors = self.COMPILED_CODES[color_code]
[ "def", "write", "(", "self", ",", "p_str", ")", ":", "for", "segment", "in", "RE_SPLIT", ".", "split", "(", "p_str", ")", ":", "if", "not", "segment", ":", "# Empty string. p_str probably starts with colors so the first item is always ''.", "continue", "if", "not", "RE_SPLIT", ".", "match", "(", "segment", ")", ":", "# No color codes, print regular text.", "print", "(", "segment", ",", "file", "=", "self", ".", "_original_stream", ",", "end", "=", "''", ")", "self", ".", "_original_stream", ".", "flush", "(", ")", "continue", "for", "color_code", "in", "(", "int", "(", "c", ")", "for", "c", "in", "RE_NUMBER_SEARCH", ".", "findall", "(", "segment", ")", "[", "0", "]", ".", "split", "(", "';'", ")", ")", ":", "if", "color_code", "in", "self", ".", "COMPILED_CODES", ":", "self", ".", "colors", "=", "self", ".", "COMPILED_CODES", "[", "color_code", "]" ]
Write to stream. :param str p_str: string to print.
[ "Write", "to", "stream", "." ]
692e2d6f5ad470b6221c8cb9641970dc5563a572
https://github.com/Robpol86/colorclass/blob/692e2d6f5ad470b6221c8cb9641970dc5563a572/colorclass/windows.py#L264-L280
train
Robpol86/colorclass
colorclass/parse.py
prune_overridden
def prune_overridden(ansi_string): """Remove color codes that are rendered ineffective by subsequent codes in one escape sequence then sort codes. :param str ansi_string: Incoming ansi_string with ANSI color codes. :return: Color string with pruned color sequences. :rtype: str """ multi_seqs = set(p for p in RE_ANSI.findall(ansi_string) if ';' in p[1]) # Sequences with multiple color codes. for escape, codes in multi_seqs: r_codes = list(reversed(codes.split(';'))) # Nuke everything before {/all}. try: r_codes = r_codes[:r_codes.index('0') + 1] except ValueError: pass # Thin out groups. for group in CODE_GROUPS: for pos in reversed([i for i, n in enumerate(r_codes) if n in group][1:]): r_codes.pop(pos) # Done. reduced_codes = ';'.join(sorted(r_codes, key=int)) if codes != reduced_codes: ansi_string = ansi_string.replace(escape, '\033[' + reduced_codes + 'm') return ansi_string
python
def prune_overridden(ansi_string): """Remove color codes that are rendered ineffective by subsequent codes in one escape sequence then sort codes. :param str ansi_string: Incoming ansi_string with ANSI color codes. :return: Color string with pruned color sequences. :rtype: str """ multi_seqs = set(p for p in RE_ANSI.findall(ansi_string) if ';' in p[1]) # Sequences with multiple color codes. for escape, codes in multi_seqs: r_codes = list(reversed(codes.split(';'))) # Nuke everything before {/all}. try: r_codes = r_codes[:r_codes.index('0') + 1] except ValueError: pass # Thin out groups. for group in CODE_GROUPS: for pos in reversed([i for i, n in enumerate(r_codes) if n in group][1:]): r_codes.pop(pos) # Done. reduced_codes = ';'.join(sorted(r_codes, key=int)) if codes != reduced_codes: ansi_string = ansi_string.replace(escape, '\033[' + reduced_codes + 'm') return ansi_string
[ "def", "prune_overridden", "(", "ansi_string", ")", ":", "multi_seqs", "=", "set", "(", "p", "for", "p", "in", "RE_ANSI", ".", "findall", "(", "ansi_string", ")", "if", "';'", "in", "p", "[", "1", "]", ")", "# Sequences with multiple color codes.", "for", "escape", ",", "codes", "in", "multi_seqs", ":", "r_codes", "=", "list", "(", "reversed", "(", "codes", ".", "split", "(", "';'", ")", ")", ")", "# Nuke everything before {/all}.", "try", ":", "r_codes", "=", "r_codes", "[", ":", "r_codes", ".", "index", "(", "'0'", ")", "+", "1", "]", "except", "ValueError", ":", "pass", "# Thin out groups.", "for", "group", "in", "CODE_GROUPS", ":", "for", "pos", "in", "reversed", "(", "[", "i", "for", "i", ",", "n", "in", "enumerate", "(", "r_codes", ")", "if", "n", "in", "group", "]", "[", "1", ":", "]", ")", ":", "r_codes", ".", "pop", "(", "pos", ")", "# Done.", "reduced_codes", "=", "';'", ".", "join", "(", "sorted", "(", "r_codes", ",", "key", "=", "int", ")", ")", "if", "codes", "!=", "reduced_codes", ":", "ansi_string", "=", "ansi_string", ".", "replace", "(", "escape", ",", "'\\033['", "+", "reduced_codes", "+", "'m'", ")", "return", "ansi_string" ]
Remove color codes that are rendered ineffective by subsequent codes in one escape sequence then sort codes. :param str ansi_string: Incoming ansi_string with ANSI color codes. :return: Color string with pruned color sequences. :rtype: str
[ "Remove", "color", "codes", "that", "are", "rendered", "ineffective", "by", "subsequent", "codes", "in", "one", "escape", "sequence", "then", "sort", "codes", "." ]
692e2d6f5ad470b6221c8cb9641970dc5563a572
https://github.com/Robpol86/colorclass/blob/692e2d6f5ad470b6221c8cb9641970dc5563a572/colorclass/parse.py#L17-L46
train
Robpol86/colorclass
colorclass/parse.py
parse_input
def parse_input(tagged_string, disable_colors, keep_tags): """Perform the actual conversion of tags to ANSI escaped codes. Provides a version of the input without any colors for len() and other methods. :param str tagged_string: The input unicode value. :param bool disable_colors: Strip all colors in both outputs. :param bool keep_tags: Skip parsing curly bracket tags into ANSI escape sequences. :return: 2-item tuple. First item is the parsed output. Second item is a version of the input without any colors. :rtype: tuple """ codes = ANSICodeMapping(tagged_string) output_colors = getattr(tagged_string, 'value_colors', tagged_string) # Convert: '{b}{red}' -> '\033[1m\033[31m' if not keep_tags: for tag, replacement in (('{' + k + '}', '' if v is None else '\033[%dm' % v) for k, v in codes.items()): output_colors = output_colors.replace(tag, replacement) # Strip colors. output_no_colors = RE_ANSI.sub('', output_colors) if disable_colors: return output_no_colors, output_no_colors # Combine: '\033[1m\033[31m' -> '\033[1;31m' while True: simplified = RE_COMBINE.sub(r'\033[\1;\2m', output_colors) if simplified == output_colors: break output_colors = simplified # Prune: '\033[31;32;33;34;35m' -> '\033[35m' output_colors = prune_overridden(output_colors) # Deduplicate: '\033[1;mT\033[1;mE\033[1;mS\033[1;mT' -> '\033[1;mTEST' previous_escape = None segments = list() for item in (i for i in RE_SPLIT.split(output_colors) if i): if RE_SPLIT.match(item): if item != previous_escape: segments.append(item) previous_escape = item else: segments.append(item) output_colors = ''.join(segments) return output_colors, output_no_colors
python
def parse_input(tagged_string, disable_colors, keep_tags): """Perform the actual conversion of tags to ANSI escaped codes. Provides a version of the input without any colors for len() and other methods. :param str tagged_string: The input unicode value. :param bool disable_colors: Strip all colors in both outputs. :param bool keep_tags: Skip parsing curly bracket tags into ANSI escape sequences. :return: 2-item tuple. First item is the parsed output. Second item is a version of the input without any colors. :rtype: tuple """ codes = ANSICodeMapping(tagged_string) output_colors = getattr(tagged_string, 'value_colors', tagged_string) # Convert: '{b}{red}' -> '\033[1m\033[31m' if not keep_tags: for tag, replacement in (('{' + k + '}', '' if v is None else '\033[%dm' % v) for k, v in codes.items()): output_colors = output_colors.replace(tag, replacement) # Strip colors. output_no_colors = RE_ANSI.sub('', output_colors) if disable_colors: return output_no_colors, output_no_colors # Combine: '\033[1m\033[31m' -> '\033[1;31m' while True: simplified = RE_COMBINE.sub(r'\033[\1;\2m', output_colors) if simplified == output_colors: break output_colors = simplified # Prune: '\033[31;32;33;34;35m' -> '\033[35m' output_colors = prune_overridden(output_colors) # Deduplicate: '\033[1;mT\033[1;mE\033[1;mS\033[1;mT' -> '\033[1;mTEST' previous_escape = None segments = list() for item in (i for i in RE_SPLIT.split(output_colors) if i): if RE_SPLIT.match(item): if item != previous_escape: segments.append(item) previous_escape = item else: segments.append(item) output_colors = ''.join(segments) return output_colors, output_no_colors
[ "def", "parse_input", "(", "tagged_string", ",", "disable_colors", ",", "keep_tags", ")", ":", "codes", "=", "ANSICodeMapping", "(", "tagged_string", ")", "output_colors", "=", "getattr", "(", "tagged_string", ",", "'value_colors'", ",", "tagged_string", ")", "# Convert: '{b}{red}' -> '\\033[1m\\033[31m'", "if", "not", "keep_tags", ":", "for", "tag", ",", "replacement", "in", "(", "(", "'{'", "+", "k", "+", "'}'", ",", "''", "if", "v", "is", "None", "else", "'\\033[%dm'", "%", "v", ")", "for", "k", ",", "v", "in", "codes", ".", "items", "(", ")", ")", ":", "output_colors", "=", "output_colors", ".", "replace", "(", "tag", ",", "replacement", ")", "# Strip colors.", "output_no_colors", "=", "RE_ANSI", ".", "sub", "(", "''", ",", "output_colors", ")", "if", "disable_colors", ":", "return", "output_no_colors", ",", "output_no_colors", "# Combine: '\\033[1m\\033[31m' -> '\\033[1;31m'", "while", "True", ":", "simplified", "=", "RE_COMBINE", ".", "sub", "(", "r'\\033[\\1;\\2m'", ",", "output_colors", ")", "if", "simplified", "==", "output_colors", ":", "break", "output_colors", "=", "simplified", "# Prune: '\\033[31;32;33;34;35m' -> '\\033[35m'", "output_colors", "=", "prune_overridden", "(", "output_colors", ")", "# Deduplicate: '\\033[1;mT\\033[1;mE\\033[1;mS\\033[1;mT' -> '\\033[1;mTEST'", "previous_escape", "=", "None", "segments", "=", "list", "(", ")", "for", "item", "in", "(", "i", "for", "i", "in", "RE_SPLIT", ".", "split", "(", "output_colors", ")", "if", "i", ")", ":", "if", "RE_SPLIT", ".", "match", "(", "item", ")", ":", "if", "item", "!=", "previous_escape", ":", "segments", ".", "append", "(", "item", ")", "previous_escape", "=", "item", "else", ":", "segments", ".", "append", "(", "item", ")", "output_colors", "=", "''", ".", "join", "(", "segments", ")", "return", "output_colors", ",", "output_no_colors" ]
Perform the actual conversion of tags to ANSI escaped codes. Provides a version of the input without any colors for len() and other methods. :param str tagged_string: The input unicode value. :param bool disable_colors: Strip all colors in both outputs. :param bool keep_tags: Skip parsing curly bracket tags into ANSI escape sequences. :return: 2-item tuple. First item is the parsed output. Second item is a version of the input without any colors. :rtype: tuple
[ "Perform", "the", "actual", "conversion", "of", "tags", "to", "ANSI", "escaped", "codes", "." ]
692e2d6f5ad470b6221c8cb9641970dc5563a572
https://github.com/Robpol86/colorclass/blob/692e2d6f5ad470b6221c8cb9641970dc5563a572/colorclass/parse.py#L49-L96
train
Robpol86/colorclass
colorclass/search.py
build_color_index
def build_color_index(ansi_string): """Build an index between visible characters and a string with invisible color codes. :param str ansi_string: String with color codes (ANSI escape sequences). :return: Position of visible characters in color string (indexes match non-color string). :rtype: tuple """ mapping = list() color_offset = 0 for item in (i for i in RE_SPLIT.split(ansi_string) if i): if RE_SPLIT.match(item): color_offset += len(item) else: for _ in range(len(item)): mapping.append(color_offset) color_offset += 1 return tuple(mapping)
python
def build_color_index(ansi_string): """Build an index between visible characters and a string with invisible color codes. :param str ansi_string: String with color codes (ANSI escape sequences). :return: Position of visible characters in color string (indexes match non-color string). :rtype: tuple """ mapping = list() color_offset = 0 for item in (i for i in RE_SPLIT.split(ansi_string) if i): if RE_SPLIT.match(item): color_offset += len(item) else: for _ in range(len(item)): mapping.append(color_offset) color_offset += 1 return tuple(mapping)
[ "def", "build_color_index", "(", "ansi_string", ")", ":", "mapping", "=", "list", "(", ")", "color_offset", "=", "0", "for", "item", "in", "(", "i", "for", "i", "in", "RE_SPLIT", ".", "split", "(", "ansi_string", ")", "if", "i", ")", ":", "if", "RE_SPLIT", ".", "match", "(", "item", ")", ":", "color_offset", "+=", "len", "(", "item", ")", "else", ":", "for", "_", "in", "range", "(", "len", "(", "item", ")", ")", ":", "mapping", ".", "append", "(", "color_offset", ")", "color_offset", "+=", "1", "return", "tuple", "(", "mapping", ")" ]
Build an index between visible characters and a string with invisible color codes. :param str ansi_string: String with color codes (ANSI escape sequences). :return: Position of visible characters in color string (indexes match non-color string). :rtype: tuple
[ "Build", "an", "index", "between", "visible", "characters", "and", "a", "string", "with", "invisible", "color", "codes", "." ]
692e2d6f5ad470b6221c8cb9641970dc5563a572
https://github.com/Robpol86/colorclass/blob/692e2d6f5ad470b6221c8cb9641970dc5563a572/colorclass/search.py#L6-L23
train
Robpol86/colorclass
colorclass/search.py
find_char_color
def find_char_color(ansi_string, pos): """Determine what color a character is in the string. :param str ansi_string: String with color codes (ANSI escape sequences). :param int pos: Position of the character in the ansi_string. :return: Character along with all surrounding color codes. :rtype: str """ result = list() position = 0 # Set to None when character is found. for item in (i for i in RE_SPLIT.split(ansi_string) if i): if RE_SPLIT.match(item): result.append(item) if position is not None: position += len(item) elif position is not None: for char in item: if position == pos: result.append(char) position = None break position += 1 return ''.join(result)
python
def find_char_color(ansi_string, pos): """Determine what color a character is in the string. :param str ansi_string: String with color codes (ANSI escape sequences). :param int pos: Position of the character in the ansi_string. :return: Character along with all surrounding color codes. :rtype: str """ result = list() position = 0 # Set to None when character is found. for item in (i for i in RE_SPLIT.split(ansi_string) if i): if RE_SPLIT.match(item): result.append(item) if position is not None: position += len(item) elif position is not None: for char in item: if position == pos: result.append(char) position = None break position += 1 return ''.join(result)
[ "def", "find_char_color", "(", "ansi_string", ",", "pos", ")", ":", "result", "=", "list", "(", ")", "position", "=", "0", "# Set to None when character is found.", "for", "item", "in", "(", "i", "for", "i", "in", "RE_SPLIT", ".", "split", "(", "ansi_string", ")", "if", "i", ")", ":", "if", "RE_SPLIT", ".", "match", "(", "item", ")", ":", "result", ".", "append", "(", "item", ")", "if", "position", "is", "not", "None", ":", "position", "+=", "len", "(", "item", ")", "elif", "position", "is", "not", "None", ":", "for", "char", "in", "item", ":", "if", "position", "==", "pos", ":", "result", ".", "append", "(", "char", ")", "position", "=", "None", "break", "position", "+=", "1", "return", "''", ".", "join", "(", "result", ")" ]
Determine what color a character is in the string. :param str ansi_string: String with color codes (ANSI escape sequences). :param int pos: Position of the character in the ansi_string. :return: Character along with all surrounding color codes. :rtype: str
[ "Determine", "what", "color", "a", "character", "is", "in", "the", "string", "." ]
692e2d6f5ad470b6221c8cb9641970dc5563a572
https://github.com/Robpol86/colorclass/blob/692e2d6f5ad470b6221c8cb9641970dc5563a572/colorclass/search.py#L26-L49
train
threeML/astromodels
astromodels/utils/angular_distance.py
angular_distance_fast
def angular_distance_fast(ra1, dec1, ra2, dec2): """ Compute angular distance using the Haversine formula. Use this one when you know you will never ask for points at their antipodes. If this is not the case, use the angular_distance function which is slower, but works also for antipodes. :param lon1: :param lat1: :param lon2: :param lat2: :return: """ lon1 = np.deg2rad(ra1) lat1 = np.deg2rad(dec1) lon2 = np.deg2rad(ra2) lat2 = np.deg2rad(dec2) dlon = lon2 - lon1 dlat = lat2 - lat1 a = np.sin(dlat/2.0)**2 + np.cos(lat1) * np.cos(lat2) * np.sin(dlon /2.0)**2 c = 2 * np.arcsin(np.sqrt(a)) return np.rad2deg(c)
python
def angular_distance_fast(ra1, dec1, ra2, dec2): """ Compute angular distance using the Haversine formula. Use this one when you know you will never ask for points at their antipodes. If this is not the case, use the angular_distance function which is slower, but works also for antipodes. :param lon1: :param lat1: :param lon2: :param lat2: :return: """ lon1 = np.deg2rad(ra1) lat1 = np.deg2rad(dec1) lon2 = np.deg2rad(ra2) lat2 = np.deg2rad(dec2) dlon = lon2 - lon1 dlat = lat2 - lat1 a = np.sin(dlat/2.0)**2 + np.cos(lat1) * np.cos(lat2) * np.sin(dlon /2.0)**2 c = 2 * np.arcsin(np.sqrt(a)) return np.rad2deg(c)
[ "def", "angular_distance_fast", "(", "ra1", ",", "dec1", ",", "ra2", ",", "dec2", ")", ":", "lon1", "=", "np", ".", "deg2rad", "(", "ra1", ")", "lat1", "=", "np", ".", "deg2rad", "(", "dec1", ")", "lon2", "=", "np", ".", "deg2rad", "(", "ra2", ")", "lat2", "=", "np", ".", "deg2rad", "(", "dec2", ")", "dlon", "=", "lon2", "-", "lon1", "dlat", "=", "lat2", "-", "lat1", "a", "=", "np", ".", "sin", "(", "dlat", "/", "2.0", ")", "**", "2", "+", "np", ".", "cos", "(", "lat1", ")", "*", "np", ".", "cos", "(", "lat2", ")", "*", "np", ".", "sin", "(", "dlon", "/", "2.0", ")", "**", "2", "c", "=", "2", "*", "np", ".", "arcsin", "(", "np", ".", "sqrt", "(", "a", ")", ")", "return", "np", ".", "rad2deg", "(", "c", ")" ]
Compute angular distance using the Haversine formula. Use this one when you know you will never ask for points at their antipodes. If this is not the case, use the angular_distance function which is slower, but works also for antipodes. :param lon1: :param lat1: :param lon2: :param lat2: :return:
[ "Compute", "angular", "distance", "using", "the", "Haversine", "formula", ".", "Use", "this", "one", "when", "you", "know", "you", "will", "never", "ask", "for", "points", "at", "their", "antipodes", ".", "If", "this", "is", "not", "the", "case", "use", "the", "angular_distance", "function", "which", "is", "slower", "but", "works", "also", "for", "antipodes", "." ]
9aac365a372f77603039533df9a6b694c1e360d5
https://github.com/threeML/astromodels/blob/9aac365a372f77603039533df9a6b694c1e360d5/astromodels/utils/angular_distance.py#L4-L26
train
threeML/astromodels
astromodels/utils/angular_distance.py
angular_distance
def angular_distance(ra1, dec1, ra2, dec2): """ Returns the angular distance between two points, two sets of points, or a set of points and one point. :param ra1: array or float, longitude of first point(s) :param dec1: array or float, latitude of first point(s) :param ra2: array or float, longitude of second point(s) :param dec2: array or float, latitude of second point(s) :return: angular distance(s) in degrees """ # Vincenty formula, slower than the Haversine formula in some cases, but stable also at antipodes lon1 = np.deg2rad(ra1) lat1 = np.deg2rad(dec1) lon2 = np.deg2rad(ra2) lat2 = np.deg2rad(dec2) sdlon = np.sin(lon2 - lon1) cdlon = np.cos(lon2 - lon1) slat1 = np.sin(lat1) slat2 = np.sin(lat2) clat1 = np.cos(lat1) clat2 = np.cos(lat2) num1 = clat2 * sdlon num2 = clat1 * slat2 - slat1 * clat2 * cdlon denominator = slat1 * slat2 + clat1 * clat2 * cdlon return np.rad2deg(np.arctan2(np.sqrt(num1 ** 2 + num2 ** 2), denominator))
python
def angular_distance(ra1, dec1, ra2, dec2): """ Returns the angular distance between two points, two sets of points, or a set of points and one point. :param ra1: array or float, longitude of first point(s) :param dec1: array or float, latitude of first point(s) :param ra2: array or float, longitude of second point(s) :param dec2: array or float, latitude of second point(s) :return: angular distance(s) in degrees """ # Vincenty formula, slower than the Haversine formula in some cases, but stable also at antipodes lon1 = np.deg2rad(ra1) lat1 = np.deg2rad(dec1) lon2 = np.deg2rad(ra2) lat2 = np.deg2rad(dec2) sdlon = np.sin(lon2 - lon1) cdlon = np.cos(lon2 - lon1) slat1 = np.sin(lat1) slat2 = np.sin(lat2) clat1 = np.cos(lat1) clat2 = np.cos(lat2) num1 = clat2 * sdlon num2 = clat1 * slat2 - slat1 * clat2 * cdlon denominator = slat1 * slat2 + clat1 * clat2 * cdlon return np.rad2deg(np.arctan2(np.sqrt(num1 ** 2 + num2 ** 2), denominator))
[ "def", "angular_distance", "(", "ra1", ",", "dec1", ",", "ra2", ",", "dec2", ")", ":", "# Vincenty formula, slower than the Haversine formula in some cases, but stable also at antipodes", "lon1", "=", "np", ".", "deg2rad", "(", "ra1", ")", "lat1", "=", "np", ".", "deg2rad", "(", "dec1", ")", "lon2", "=", "np", ".", "deg2rad", "(", "ra2", ")", "lat2", "=", "np", ".", "deg2rad", "(", "dec2", ")", "sdlon", "=", "np", ".", "sin", "(", "lon2", "-", "lon1", ")", "cdlon", "=", "np", ".", "cos", "(", "lon2", "-", "lon1", ")", "slat1", "=", "np", ".", "sin", "(", "lat1", ")", "slat2", "=", "np", ".", "sin", "(", "lat2", ")", "clat1", "=", "np", ".", "cos", "(", "lat1", ")", "clat2", "=", "np", ".", "cos", "(", "lat2", ")", "num1", "=", "clat2", "*", "sdlon", "num2", "=", "clat1", "*", "slat2", "-", "slat1", "*", "clat2", "*", "cdlon", "denominator", "=", "slat1", "*", "slat2", "+", "clat1", "*", "clat2", "*", "cdlon", "return", "np", ".", "rad2deg", "(", "np", ".", "arctan2", "(", "np", ".", "sqrt", "(", "num1", "**", "2", "+", "num2", "**", "2", ")", ",", "denominator", ")", ")" ]
Returns the angular distance between two points, two sets of points, or a set of points and one point. :param ra1: array or float, longitude of first point(s) :param dec1: array or float, latitude of first point(s) :param ra2: array or float, longitude of second point(s) :param dec2: array or float, latitude of second point(s) :return: angular distance(s) in degrees
[ "Returns", "the", "angular", "distance", "between", "two", "points", "two", "sets", "of", "points", "or", "a", "set", "of", "points", "and", "one", "point", "." ]
9aac365a372f77603039533df9a6b694c1e360d5
https://github.com/threeML/astromodels/blob/9aac365a372f77603039533df9a6b694c1e360d5/astromodels/utils/angular_distance.py#L29-L58
train
threeML/astromodels
astromodels/core/memoization.py
memoize
def memoize(method): """ A decorator for functions of sources which memoize the results of the last _CACHE_SIZE calls, :param method: method to be memoized :return: the decorated method """ cache = method.cache = collections.OrderedDict() # Put these two methods in the local space (faster) _get = cache.get _popitem = cache.popitem @functools.wraps(method) def memoizer(instance, x, *args, **kwargs): if not _WITH_MEMOIZATION or isinstance(x, u.Quantity): # Memoization is not active or using units, do not use memoization return method(instance, x, *args, **kwargs) # Create a tuple because a tuple is hashable unique_id = tuple(float(yy.value) for yy in instance.parameters.values()) + (x.size, x.min(), x.max()) # Create a unique identifier for this combination of inputs key = hash(unique_id) # Let's do it this way so we only look into the dictionary once result = _get(key) if result is not None: return result else: result = method(instance, x, *args, **kwargs) cache[key] = result if len(cache) > _CACHE_SIZE: # Remove half of the element (but at least 1, even if _CACHE_SIZE=1, which would be pretty idiotic ;-) ) [_popitem(False) for i in range(max(_CACHE_SIZE // 2, 1))] return result # Add the function as a "attribute" so we can access it memoizer.input_object = method return memoizer
python
def memoize(method): """ A decorator for functions of sources which memoize the results of the last _CACHE_SIZE calls, :param method: method to be memoized :return: the decorated method """ cache = method.cache = collections.OrderedDict() # Put these two methods in the local space (faster) _get = cache.get _popitem = cache.popitem @functools.wraps(method) def memoizer(instance, x, *args, **kwargs): if not _WITH_MEMOIZATION or isinstance(x, u.Quantity): # Memoization is not active or using units, do not use memoization return method(instance, x, *args, **kwargs) # Create a tuple because a tuple is hashable unique_id = tuple(float(yy.value) for yy in instance.parameters.values()) + (x.size, x.min(), x.max()) # Create a unique identifier for this combination of inputs key = hash(unique_id) # Let's do it this way so we only look into the dictionary once result = _get(key) if result is not None: return result else: result = method(instance, x, *args, **kwargs) cache[key] = result if len(cache) > _CACHE_SIZE: # Remove half of the element (but at least 1, even if _CACHE_SIZE=1, which would be pretty idiotic ;-) ) [_popitem(False) for i in range(max(_CACHE_SIZE // 2, 1))] return result # Add the function as a "attribute" so we can access it memoizer.input_object = method return memoizer
[ "def", "memoize", "(", "method", ")", ":", "cache", "=", "method", ".", "cache", "=", "collections", ".", "OrderedDict", "(", ")", "# Put these two methods in the local space (faster)", "_get", "=", "cache", ".", "get", "_popitem", "=", "cache", ".", "popitem", "@", "functools", ".", "wraps", "(", "method", ")", "def", "memoizer", "(", "instance", ",", "x", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "not", "_WITH_MEMOIZATION", "or", "isinstance", "(", "x", ",", "u", ".", "Quantity", ")", ":", "# Memoization is not active or using units, do not use memoization", "return", "method", "(", "instance", ",", "x", ",", "*", "args", ",", "*", "*", "kwargs", ")", "# Create a tuple because a tuple is hashable", "unique_id", "=", "tuple", "(", "float", "(", "yy", ".", "value", ")", "for", "yy", "in", "instance", ".", "parameters", ".", "values", "(", ")", ")", "+", "(", "x", ".", "size", ",", "x", ".", "min", "(", ")", ",", "x", ".", "max", "(", ")", ")", "# Create a unique identifier for this combination of inputs", "key", "=", "hash", "(", "unique_id", ")", "# Let's do it this way so we only look into the dictionary once", "result", "=", "_get", "(", "key", ")", "if", "result", "is", "not", "None", ":", "return", "result", "else", ":", "result", "=", "method", "(", "instance", ",", "x", ",", "*", "args", ",", "*", "*", "kwargs", ")", "cache", "[", "key", "]", "=", "result", "if", "len", "(", "cache", ")", ">", "_CACHE_SIZE", ":", "# Remove half of the element (but at least 1, even if _CACHE_SIZE=1, which would be pretty idiotic ;-) )", "[", "_popitem", "(", "False", ")", "for", "i", "in", "range", "(", "max", "(", "_CACHE_SIZE", "//", "2", ",", "1", ")", ")", "]", "return", "result", "# Add the function as a \"attribute\" so we can access it", "memoizer", ".", "input_object", "=", "method", "return", "memoizer" ]
A decorator for functions of sources which memoize the results of the last _CACHE_SIZE calls, :param method: method to be memoized :return: the decorated method
[ "A", "decorator", "for", "functions", "of", "sources", "which", "memoize", "the", "results", "of", "the", "last", "_CACHE_SIZE", "calls" ]
9aac365a372f77603039533df9a6b694c1e360d5
https://github.com/threeML/astromodels/blob/9aac365a372f77603039533df9a6b694c1e360d5/astromodels/core/memoization.py#L36-L90
train
threeML/astromodels
astromodels/core/model.py
Model.free_parameters
def free_parameters(self): """ Get a dictionary with all the free parameters in this model :return: dictionary of free parameters """ # Refresh the list self._update_parameters() # Filter selecting only free parameters free_parameters_dictionary = collections.OrderedDict() for parameter_name, parameter in self._parameters.iteritems(): if parameter.free: free_parameters_dictionary[parameter_name] = parameter return free_parameters_dictionary
python
def free_parameters(self): """ Get a dictionary with all the free parameters in this model :return: dictionary of free parameters """ # Refresh the list self._update_parameters() # Filter selecting only free parameters free_parameters_dictionary = collections.OrderedDict() for parameter_name, parameter in self._parameters.iteritems(): if parameter.free: free_parameters_dictionary[parameter_name] = parameter return free_parameters_dictionary
[ "def", "free_parameters", "(", "self", ")", ":", "# Refresh the list", "self", ".", "_update_parameters", "(", ")", "# Filter selecting only free parameters", "free_parameters_dictionary", "=", "collections", ".", "OrderedDict", "(", ")", "for", "parameter_name", ",", "parameter", "in", "self", ".", "_parameters", ".", "iteritems", "(", ")", ":", "if", "parameter", ".", "free", ":", "free_parameters_dictionary", "[", "parameter_name", "]", "=", "parameter", "return", "free_parameters_dictionary" ]
Get a dictionary with all the free parameters in this model :return: dictionary of free parameters
[ "Get", "a", "dictionary", "with", "all", "the", "free", "parameters", "in", "this", "model" ]
9aac365a372f77603039533df9a6b694c1e360d5
https://github.com/threeML/astromodels/blob/9aac365a372f77603039533df9a6b694c1e360d5/astromodels/core/model.py#L186-L207
train
threeML/astromodels
astromodels/core/model.py
Model.set_free_parameters
def set_free_parameters(self, values): """ Set the free parameters in the model to the provided values. NOTE: of course, order matters :param values: a list of new values :return: None """ assert len(values) == len(self.free_parameters) for parameter, this_value in zip(self.free_parameters.values(), values): parameter.value = this_value
python
def set_free_parameters(self, values): """ Set the free parameters in the model to the provided values. NOTE: of course, order matters :param values: a list of new values :return: None """ assert len(values) == len(self.free_parameters) for parameter, this_value in zip(self.free_parameters.values(), values): parameter.value = this_value
[ "def", "set_free_parameters", "(", "self", ",", "values", ")", ":", "assert", "len", "(", "values", ")", "==", "len", "(", "self", ".", "free_parameters", ")", "for", "parameter", ",", "this_value", "in", "zip", "(", "self", ".", "free_parameters", ".", "values", "(", ")", ",", "values", ")", ":", "parameter", ".", "value", "=", "this_value" ]
Set the free parameters in the model to the provided values. NOTE: of course, order matters :param values: a list of new values :return: None
[ "Set", "the", "free", "parameters", "in", "the", "model", "to", "the", "provided", "values", "." ]
9aac365a372f77603039533df9a6b694c1e360d5
https://github.com/threeML/astromodels/blob/9aac365a372f77603039533df9a6b694c1e360d5/astromodels/core/model.py#L235-L249
train
threeML/astromodels
astromodels/core/model.py
Model.add_independent_variable
def add_independent_variable(self, variable): """ Add a global independent variable to this model, such as time. :param variable: an IndependentVariable instance :return: none """ assert isinstance(variable, IndependentVariable), "Variable must be an instance of IndependentVariable" if self._has_child(variable.name): self._remove_child(variable.name) self._add_child(variable) # Add also to the list of independent variables self._independent_variables[variable.name] = variable
python
def add_independent_variable(self, variable): """ Add a global independent variable to this model, such as time. :param variable: an IndependentVariable instance :return: none """ assert isinstance(variable, IndependentVariable), "Variable must be an instance of IndependentVariable" if self._has_child(variable.name): self._remove_child(variable.name) self._add_child(variable) # Add also to the list of independent variables self._independent_variables[variable.name] = variable
[ "def", "add_independent_variable", "(", "self", ",", "variable", ")", ":", "assert", "isinstance", "(", "variable", ",", "IndependentVariable", ")", ",", "\"Variable must be an instance of IndependentVariable\"", "if", "self", ".", "_has_child", "(", "variable", ".", "name", ")", ":", "self", ".", "_remove_child", "(", "variable", ".", "name", ")", "self", ".", "_add_child", "(", "variable", ")", "# Add also to the list of independent variables", "self", ".", "_independent_variables", "[", "variable", ".", "name", "]", "=", "variable" ]
Add a global independent variable to this model, such as time. :param variable: an IndependentVariable instance :return: none
[ "Add", "a", "global", "independent", "variable", "to", "this", "model", "such", "as", "time", "." ]
9aac365a372f77603039533df9a6b694c1e360d5
https://github.com/threeML/astromodels/blob/9aac365a372f77603039533df9a6b694c1e360d5/astromodels/core/model.py#L373-L390
train
threeML/astromodels
astromodels/core/model.py
Model.remove_independent_variable
def remove_independent_variable(self, variable_name): """ Remove an independent variable which was added with add_independent_variable :param variable_name: name of variable to remove :return: """ self._remove_child(variable_name) # Remove also from the list of independent variables self._independent_variables.pop(variable_name)
python
def remove_independent_variable(self, variable_name): """ Remove an independent variable which was added with add_independent_variable :param variable_name: name of variable to remove :return: """ self._remove_child(variable_name) # Remove also from the list of independent variables self._independent_variables.pop(variable_name)
[ "def", "remove_independent_variable", "(", "self", ",", "variable_name", ")", ":", "self", ".", "_remove_child", "(", "variable_name", ")", "# Remove also from the list of independent variables", "self", ".", "_independent_variables", ".", "pop", "(", "variable_name", ")" ]
Remove an independent variable which was added with add_independent_variable :param variable_name: name of variable to remove :return:
[ "Remove", "an", "independent", "variable", "which", "was", "added", "with", "add_independent_variable" ]
9aac365a372f77603039533df9a6b694c1e360d5
https://github.com/threeML/astromodels/blob/9aac365a372f77603039533df9a6b694c1e360d5/astromodels/core/model.py#L392-L403
train
threeML/astromodels
astromodels/core/model.py
Model.add_external_parameter
def add_external_parameter(self, parameter): """ Add a parameter that comes from something other than a function, to the model. :param parameter: a Parameter instance :return: none """ assert isinstance(parameter, Parameter), "Variable must be an instance of IndependentVariable" if self._has_child(parameter.name): # Remove it from the children only if it is a Parameter instance, otherwise don't, which will # make the _add_child call fail (which is the expected behaviour! You shouldn't call two children # with the same name) if isinstance(self._get_child(parameter.name), Parameter): warnings.warn("External parameter %s already exist in the model. Overwriting it..." % parameter.name, RuntimeWarning) self._remove_child(parameter.name) # This will fail if another node with the same name is already in the model self._add_child(parameter)
python
def add_external_parameter(self, parameter): """ Add a parameter that comes from something other than a function, to the model. :param parameter: a Parameter instance :return: none """ assert isinstance(parameter, Parameter), "Variable must be an instance of IndependentVariable" if self._has_child(parameter.name): # Remove it from the children only if it is a Parameter instance, otherwise don't, which will # make the _add_child call fail (which is the expected behaviour! You shouldn't call two children # with the same name) if isinstance(self._get_child(parameter.name), Parameter): warnings.warn("External parameter %s already exist in the model. Overwriting it..." % parameter.name, RuntimeWarning) self._remove_child(parameter.name) # This will fail if another node with the same name is already in the model self._add_child(parameter)
[ "def", "add_external_parameter", "(", "self", ",", "parameter", ")", ":", "assert", "isinstance", "(", "parameter", ",", "Parameter", ")", ",", "\"Variable must be an instance of IndependentVariable\"", "if", "self", ".", "_has_child", "(", "parameter", ".", "name", ")", ":", "# Remove it from the children only if it is a Parameter instance, otherwise don't, which will", "# make the _add_child call fail (which is the expected behaviour! You shouldn't call two children", "# with the same name)", "if", "isinstance", "(", "self", ".", "_get_child", "(", "parameter", ".", "name", ")", ",", "Parameter", ")", ":", "warnings", ".", "warn", "(", "\"External parameter %s already exist in the model. Overwriting it...\"", "%", "parameter", ".", "name", ",", "RuntimeWarning", ")", "self", ".", "_remove_child", "(", "parameter", ".", "name", ")", "# This will fail if another node with the same name is already in the model", "self", ".", "_add_child", "(", "parameter", ")" ]
Add a parameter that comes from something other than a function, to the model. :param parameter: a Parameter instance :return: none
[ "Add", "a", "parameter", "that", "comes", "from", "something", "other", "than", "a", "function", "to", "the", "model", "." ]
9aac365a372f77603039533df9a6b694c1e360d5
https://github.com/threeML/astromodels/blob/9aac365a372f77603039533df9a6b694c1e360d5/astromodels/core/model.py#L405-L430
train
threeML/astromodels
astromodels/core/model.py
Model.unlink
def unlink(self, parameter): """ Sets free one or more parameters which have been linked previously :param parameter: the parameter to be set free, can also be a list of parameters :return: (none) """ if not isinstance(parameter,list): # Make a list of one element parameter_list = [parameter] else: # Make a copy to avoid tampering with the input parameter_list = list(parameter) for param in parameter_list: if param.has_auxiliary_variable(): param.remove_auxiliary_variable() else: with warnings.catch_warnings(): warnings.simplefilter("always", RuntimeWarning) warnings.warn("Parameter %s has no link to be removed." % param.path, RuntimeWarning)
python
def unlink(self, parameter): """ Sets free one or more parameters which have been linked previously :param parameter: the parameter to be set free, can also be a list of parameters :return: (none) """ if not isinstance(parameter,list): # Make a list of one element parameter_list = [parameter] else: # Make a copy to avoid tampering with the input parameter_list = list(parameter) for param in parameter_list: if param.has_auxiliary_variable(): param.remove_auxiliary_variable() else: with warnings.catch_warnings(): warnings.simplefilter("always", RuntimeWarning) warnings.warn("Parameter %s has no link to be removed." % param.path, RuntimeWarning)
[ "def", "unlink", "(", "self", ",", "parameter", ")", ":", "if", "not", "isinstance", "(", "parameter", ",", "list", ")", ":", "# Make a list of one element", "parameter_list", "=", "[", "parameter", "]", "else", ":", "# Make a copy to avoid tampering with the input", "parameter_list", "=", "list", "(", "parameter", ")", "for", "param", "in", "parameter_list", ":", "if", "param", ".", "has_auxiliary_variable", "(", ")", ":", "param", ".", "remove_auxiliary_variable", "(", ")", "else", ":", "with", "warnings", ".", "catch_warnings", "(", ")", ":", "warnings", ".", "simplefilter", "(", "\"always\"", ",", "RuntimeWarning", ")", "warnings", ".", "warn", "(", "\"Parameter %s has no link to be removed.\"", "%", "param", ".", "path", ",", "RuntimeWarning", ")" ]
Sets free one or more parameters which have been linked previously :param parameter: the parameter to be set free, can also be a list of parameters :return: (none)
[ "Sets", "free", "one", "or", "more", "parameters", "which", "have", "been", "linked", "previously" ]
9aac365a372f77603039533df9a6b694c1e360d5
https://github.com/threeML/astromodels/blob/9aac365a372f77603039533df9a6b694c1e360d5/astromodels/core/model.py#L488-L513
train
threeML/astromodels
astromodels/core/model.py
Model.display
def display(self, complete=False): """ Display information about the point source. :param complete : if True, displays also information on fixed parameters :return: (none) """ # Switch on the complete display flag self._complete_display = bool(complete) # This will automatically choose the best representation among repr and repr_html super(Model, self).display() # Go back to default self._complete_display = False
python
def display(self, complete=False): """ Display information about the point source. :param complete : if True, displays also information on fixed parameters :return: (none) """ # Switch on the complete display flag self._complete_display = bool(complete) # This will automatically choose the best representation among repr and repr_html super(Model, self).display() # Go back to default self._complete_display = False
[ "def", "display", "(", "self", ",", "complete", "=", "False", ")", ":", "# Switch on the complete display flag", "self", ".", "_complete_display", "=", "bool", "(", "complete", ")", "# This will automatically choose the best representation among repr and repr_html", "super", "(", "Model", ",", "self", ")", ".", "display", "(", ")", "# Go back to default", "self", ".", "_complete_display", "=", "False" ]
Display information about the point source. :param complete : if True, displays also information on fixed parameters :return: (none)
[ "Display", "information", "about", "the", "point", "source", "." ]
9aac365a372f77603039533df9a6b694c1e360d5
https://github.com/threeML/astromodels/blob/9aac365a372f77603039533df9a6b694c1e360d5/astromodels/core/model.py#L515-L532
train
threeML/astromodels
astromodels/core/model.py
Model.save
def save(self, output_file, overwrite=False): """Save the model to disk""" if os.path.exists(output_file) and overwrite is False: raise ModelFileExists("The file %s exists already. If you want to overwrite it, use the 'overwrite=True' " "options as 'model.save(\"%s\", overwrite=True)'. " % (output_file, output_file)) else: data = self.to_dict_with_types() # Write it to disk try: # Get the YAML representation of the data representation = my_yaml.dump(data, default_flow_style=False) with open(output_file, "w+") as f: # Add a new line at the end of each voice (just for clarity) f.write(representation.replace("\n", "\n\n")) except IOError: raise CannotWriteModel(os.path.dirname(os.path.abspath(output_file)), "Could not write model file %s. Check your permissions to write or the " "report on the free space which follows: " % output_file)
python
def save(self, output_file, overwrite=False): """Save the model to disk""" if os.path.exists(output_file) and overwrite is False: raise ModelFileExists("The file %s exists already. If you want to overwrite it, use the 'overwrite=True' " "options as 'model.save(\"%s\", overwrite=True)'. " % (output_file, output_file)) else: data = self.to_dict_with_types() # Write it to disk try: # Get the YAML representation of the data representation = my_yaml.dump(data, default_flow_style=False) with open(output_file, "w+") as f: # Add a new line at the end of each voice (just for clarity) f.write(representation.replace("\n", "\n\n")) except IOError: raise CannotWriteModel(os.path.dirname(os.path.abspath(output_file)), "Could not write model file %s. Check your permissions to write or the " "report on the free space which follows: " % output_file)
[ "def", "save", "(", "self", ",", "output_file", ",", "overwrite", "=", "False", ")", ":", "if", "os", ".", "path", ".", "exists", "(", "output_file", ")", "and", "overwrite", "is", "False", ":", "raise", "ModelFileExists", "(", "\"The file %s exists already. If you want to overwrite it, use the 'overwrite=True' \"", "\"options as 'model.save(\\\"%s\\\", overwrite=True)'. \"", "%", "(", "output_file", ",", "output_file", ")", ")", "else", ":", "data", "=", "self", ".", "to_dict_with_types", "(", ")", "# Write it to disk", "try", ":", "# Get the YAML representation of the data", "representation", "=", "my_yaml", ".", "dump", "(", "data", ",", "default_flow_style", "=", "False", ")", "with", "open", "(", "output_file", ",", "\"w+\"", ")", "as", "f", ":", "# Add a new line at the end of each voice (just for clarity)", "f", ".", "write", "(", "representation", ".", "replace", "(", "\"\\n\"", ",", "\"\\n\\n\"", ")", ")", "except", "IOError", ":", "raise", "CannotWriteModel", "(", "os", ".", "path", ".", "dirname", "(", "os", ".", "path", ".", "abspath", "(", "output_file", ")", ")", ",", "\"Could not write model file %s. Check your permissions to write or the \"", "\"report on the free space which follows: \"", "%", "output_file", ")" ]
Save the model to disk
[ "Save", "the", "model", "to", "disk" ]
9aac365a372f77603039533df9a6b694c1e360d5
https://github.com/threeML/astromodels/blob/9aac365a372f77603039533df9a6b694c1e360d5/astromodels/core/model.py#L915-L946
train
threeML/astromodels
astromodels/core/model.py
Model.get_point_source_fluxes
def get_point_source_fluxes(self, id, energies, tag=None): """ Get the fluxes from the id-th point source :param id: id of the source :param energies: energies at which you need the flux :param tag: a tuple (integration variable, a, b) specifying the integration to perform. If this parameter is specified then the returned value will be the average flux for the source computed as the integral between a and b over the integration variable divided by (b-a). The integration variable must be an independent variable contained in the model. If b is None, then instead of integrating the integration variable will be set to a and the model evaluated in a. :return: fluxes """ return self._point_sources.values()[id](energies, tag=tag)
python
def get_point_source_fluxes(self, id, energies, tag=None): """ Get the fluxes from the id-th point source :param id: id of the source :param energies: energies at which you need the flux :param tag: a tuple (integration variable, a, b) specifying the integration to perform. If this parameter is specified then the returned value will be the average flux for the source computed as the integral between a and b over the integration variable divided by (b-a). The integration variable must be an independent variable contained in the model. If b is None, then instead of integrating the integration variable will be set to a and the model evaluated in a. :return: fluxes """ return self._point_sources.values()[id](energies, tag=tag)
[ "def", "get_point_source_fluxes", "(", "self", ",", "id", ",", "energies", ",", "tag", "=", "None", ")", ":", "return", "self", ".", "_point_sources", ".", "values", "(", ")", "[", "id", "]", "(", "energies", ",", "tag", "=", "tag", ")" ]
Get the fluxes from the id-th point source :param id: id of the source :param energies: energies at which you need the flux :param tag: a tuple (integration variable, a, b) specifying the integration to perform. If this parameter is specified then the returned value will be the average flux for the source computed as the integral between a and b over the integration variable divided by (b-a). The integration variable must be an independent variable contained in the model. If b is None, then instead of integrating the integration variable will be set to a and the model evaluated in a. :return: fluxes
[ "Get", "the", "fluxes", "from", "the", "id", "-", "th", "point", "source" ]
9aac365a372f77603039533df9a6b694c1e360d5
https://github.com/threeML/astromodels/blob/9aac365a372f77603039533df9a6b694c1e360d5/astromodels/core/model.py#L968-L982
train