Code stringlengths 103 85.9k | Summary listlengths 0 94 |
|---|---|
Please provide a description of the function: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.\n\n .. warning:: Requires Todoist premium.\n\n :return: A list of all uncompleted tasks in this project.\n :rtype: list of :class:`pytodoist.todoist.Task`\n\n >>> from pytodoist import todoist\n >>> user = todoist.login('joh... |
Please provide a description of the function: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,
... | [
"Return a list of all completed tasks in this project.\n\n :return: A list of all completed tasks in this project.\n :rtype: list of :class:`pytodoist.todoist.Task`\n\n >>> from pytodoist import todoist\n >>> user = todoist.login('john.doe@gmail.com', 'password')\n >>> project = u... |
Please provide a description of the function: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.\n\n :return: A list of all tasks in this project.class\n :rtype: list of :class:`pytodoist.todoist.Task`\n\n >>> from pytodoist import todoist\n >>> user = todoist.login('john.doe@gmail.com', 'password')\n >>> project = user.get_project('PyTodois... |
Please provide a description of the function: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.\n\n .. warning:: Requires Todoist premium.\n\n :param content: The note content.\n :type content: str\n\n >>> from pytodoist import todoist\n >>> user = todoist.login('john.doe@gmail.com', 'password')\n >>> project = user.get_project('PyTodoist')... |
Please provide a description of the function: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.\n\n :return: A list of notes.\n :rtype: list of :class:`pytodoist.todoist.Note`\n\n >>> from pytodoist import todoist\n >>> user = todoist.login('john.doe@gmail.com', 'password')\n >>> project = user.get_project('PyTodoist')\n >... |
Please provide a description of the function: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.\n\n :param email: The other user's email address.\n :type email: str\n :param message: Optional message to send with the invitation.\n :type message: str\n\n >>> from pytodoist import todoist\n >>> user = todoist.login('john.doe... |
Please provide a description of the function: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.\n\n :param email: The collaborator's email address.\n :type email: str\n\n >>> from pytodoist import todoist\n >>> user = todoist.login('john.doe@gmail.com', 'password')\n >>> project = user.get_project('PyTodoist')\n >>... |
Please provide a description of the function:def delete(self):
args = {'ids': [self.id]}
_perform_command(self.owner, 'project_delete', args)
del self.owner.projects[self.id] | [
"Delete the project.\n\n >>> from pytodoist import todoist\n >>> user = todoist.login('john.doe@gmail.com', 'password')\n >>> project = user.get_project('PyTodoist')\n >>> project.delete()\n "
] |
Please provide a description of the function:def complete(self):
args = {
'id': self.id
}
_perform_command(self.project.owner, 'item_close', args) | [
"Mark the task complete.\n\n >>> from pytodoist import todoist\n >>> user = todoist.login('john.doe@gmail.com', 'password')\n >>> project = user.get_project('PyTodoist')\n >>> task = project.add_task('Install PyTodoist')\n >>> task.complete()\n "
] |
Please provide a description of the function: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.\n\n >>> from pytodoist import todoist\n >>> user = todoist.login('john.doe@gmail.com', 'password')\n >>> project = user.get_project('PyTodoist')\n >>> task = project.add_task('Install PyTodoist')\n >>> task.uncomplete()\n "
] |
Please provide a description of the function: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.\n\n :return: A list of all notes attached to this Task.\n :rtype: list of :class:`pytodoist.todoist.Note`\n\n >>> from pytodoist import todoist\n >>> user = todoist.login('john.doe@gmail.com', 'password')\n >>> project = user.get_project('P... |
Please provide a description of the function: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.\n\n :param project: The project to move the task to.\n :type project: :class:`pytodoist.todoist.Project`\n\n >>> from pytodoist import todoist\n >>> user = todoist.login('john.doe@gmail.com', 'password')\n >>> project = user.get_project('PyTodoi... |
Please provide a description of the function: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... | [
"Add a reminder to the task which activates on a given date.\n\n .. warning:: Requires Todoist premium.\n\n :param service: ```email```, ```sms``` or ```push``` for mobile.\n :type service: str\n :param due_date: The due date in UTC, formatted as\n ```YYYY-MM-DDTHH:MM```\n ... |
Please provide a description of the function: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_l... | [
"Add a reminder to the task which activates on at a given location.\n\n .. warning:: Requires Todoist premium.\n\n :param service: ```email```, ```sms``` or ```push``` for mobile.\n :type service: str\n :param name: An alias for the location.\n :type name: str\n :param lat:... |
Please provide a description of the function: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.\n\n >>> from pytodoist import todoist\n >>> user = todoist.login('john.doe@gmail.com', 'password')\n >>> project = user.get_project('PyTodoist')\n >>> task = project.add_task('Install PyTodoist')\n >>> task.add_date_reminder('email', '2015-1... |
Please provide a description of the function: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.\n\n >>> from pytodoist import todoist\n >>> user = todoist.login('john.doe@gmail.com', 'password')\n >>> project = user.get_project('Homework')\n >>> task = project.add_task('Read Chapter 4')\n >>> task.delete()\n "
] |
Please provide a description of the function: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.\n\n >>> from pytodoist import todoist\n >>> user = todoist.login('john.doe@gmail.com', 'password')\n >>> project = user.get_project('PyTodoist')\n >>> task = project.add_task('Install PyTodoist.')\n >>> note = task.add_note('https://py... |
Please provide a description of the function: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.\n\n You must call this method to register any local attribute changes with\n Todoist.\n\n >>> from pytodoist import todoist\n >>> user = todoist.login('john.doe@gmail.com', 'password')\n >>> overdue_filter = user.add_filter('Overdue', todoi... |
Please provide a description of the function:def is_invalid_params_py2(func, *args, **kwargs):
funcargs, varargs, varkwargs, defaults = inspect.getargspec(func)
unexpected = set(kwargs.keys()) - set(funcargs)
if len(unexpected) > 0:
return True
params = [funcarg for funcarg in funcargs if... | [
" Check, whether function 'func' accepts parameters 'args', 'kwargs'.\n\n NOTE: Method is called after funct(*args, **kwargs) generated TypeError,\n it is aimed to destinguish TypeError because of invalid parameters from\n TypeError from inside the function.\n\n .. versionadded: 1.9.0\n\n "
] |
Please provide a description of the function:def is_invalid_params_py3(func, *args, **kwargs):
signature = inspect.signature(func)
parameters = signature.parameters
unexpected = set(kwargs.keys()) - set(parameters.keys())
if len(unexpected) > 0:
return True
params = [
paramete... | [
"\n Use inspect.signature instead of inspect.getargspec or\n inspect.getfullargspec (based on inspect.signature itself) as it provides\n more information about function parameters.\n\n .. versionadded: 1.11.2\n\n "
] |
Please provide a description of the function:def is_invalid_params(func, *args, **kwargs):
# For builtin functions inspect.getargspec(funct) return error. If builtin
# function generates TypeError, it is because of wrong parameters.
if not inspect.isfunction(func):
return True
if sys.versi... | [
"\n Method:\n Validate pre-defined criteria, if any is True - function is invalid\n 0. func should be callable\n 1. kwargs should not have unexpected keywords\n 2. remove kwargs.keys from func.parameters\n 3. number of args should be <= remaining func.parameters\n 4. num... |
Please provide a description of the function:def add_method(self, f=None, name=None):
if name and not f:
return functools.partial(self.add_method, name=name)
self.method_map[name or f.__name__] = f
return f | [
" Add a method to the dispatcher.\n\n Parameters\n ----------\n f : callable\n Callable to be added.\n name : str, optional\n Name to register (the default is function **f** name)\n\n Notes\n -----\n When used as a decorator keeps callable objec... |
Please provide a description of the function:def readme():
path = os.path.realpath(os.path.join(os.path.dirname(__file__), 'README.rst'))
handle = None
try:
handle = codecs.open(path, encoding='utf-8')
return handle.read(131072)
except IOError:
return ''
finally:
... | [
"Try to read README.rst or return empty string if failed.\n\n :return: File contents.\n :rtype: str\n "
] |
Please provide a description of the function: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.\n\n :param iter incoming: Incoming string/ColorStr/string-like object to iterate.\n :param func: Function to call with string portion as first and only parameter.\n\n :return: Modified string, same class type as incoming string.\n "
] |
Please provide a description of the function: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'.\n\n errors may be given to set a different error handling scheme. Default is 'strict' meaning that encoding errors\n raise a UnicodeDecodeError. Other possible values are 'ignore' and 'replace' as well as any other name\n ... |
Please provide a description of the function: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_n... | [
"Return centered in a string of length width. Padding is done using the specified fill character or space.\n\n :param int width: Length of output string.\n :param str fillchar: Use this character instead of spaces.\n "
] |
Please provide a description of the function:def count(self, sub, start=0, end=-1):
return self.value_no_colors.count(sub, start, end) | [
"Return the number of non-overlapping occurrences of substring sub in string[start:end].\n\n Optional arguments start and end are interpreted as in slice notation.\n\n :param str sub: Substring to search.\n :param int start: Beginning position.\n :param int end: Stop comparison at this p... |
Please provide a description of the function: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.\n\n With optional start, test beginning at that position. With optional end, stop comparing at that position.\n suffix can also be a tuple of strings to try.\n\n :param str suffix: Suffix to search.\n :param int start: Begi... |
Please provide a description of the function: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.\n\n errors may be given to set a different error handling scheme. Default is 'strict' meaning that encoding errors\n raise a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and 'xmlcharrefrepl... |
Please provide a description of the function: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.\n\n errors may be given to set a different error handling scheme. Default is 'strict' meaning that encoding errors\n raise a UnicodeDecodeError. Other possible values are 'ignore' and 'replace' as well as any o... |
Please provide a description of the function:def find(self, sub, start=None, end=None):
return self.value_no_colors.find(sub, start, end) | [
"Return the lowest index where substring sub is found, such that sub is contained within string[start:end].\n\n Optional arguments start and end are interpreted as in slice notation.\n\n :param str sub: Substring to search.\n :param int start: Beginning position.\n :param int end: Stop c... |
Please provide a description of the function: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.\n\n The substitutions are identified by braces ('{' and '}').\n "
] |
Please provide a description of the function:def index(self, sub, start=None, end=None):
return self.value_no_colors.index(sub, start, end) | [
"Like S.find() but raise ValueError when the substring is not found.\n\n :param str sub: Substring to search.\n :param int start: Beginning position.\n :param int end: Stop comparison at this position.\n "
] |
Please provide a description of the function: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.\n\n :param iterable: Join items in this iterable.\n "
] |
Please provide a description of the function:def rfind(self, sub, start=None, end=None):
return self.value_no_colors.rfind(sub, start, end) | [
"Return the highest index where substring sub is found, such that sub is contained within string[start:end].\n\n Optional arguments start and end are interpreted as in slice notation.\n\n :param str sub: Substring to search.\n :param int start: Beginning position.\n :param int end: Stop ... |
Please provide a description of the function:def rindex(self, sub, start=None, end=None):
return self.value_no_colors.rindex(sub, start, end) | [
"Like .rfind() but raise ValueError when the substring is not found.\n\n :param str sub: Substring to search.\n :param int start: Beginning position.\n :param int end: Stop comparison at this position.\n "
] |
Please provide a description of the function: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.\n\n Line breaks are not included in the resulting list unless keepends is given and True.\n\n :param bool keepends: Include linebreaks.\n "
] |
Please provide a description of the function: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.\n\n With optional start, test beginning at that position. With optional end, stop comparing at that position. prefix\n can also be a tuple of strings to try.\n\n :param str prefix: Prefix to search.\n :param int st... |
Please provide a description of the function: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__(re... | [
"Pad a numeric string with zeros on the left, to fill a field of the specified width.\n\n The string is never truncated.\n\n :param int width: Length of output string.\n "
] |
Please provide a description of the function: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.\n\n :param str color: Color of string.\n :param str string: String to colorize.\n :param bool auto: Enable auto-color (dark/light terminal).\n\n :return: Class instance for colorized string.\n :rtype: Color\n "
] |
Please provide a description of the function:def black(cls, string, auto=False):
return cls.colorize('black', string, auto=auto) | [
"Color-code entire string.\n\n :param str string: String to colorize.\n :param bool auto: Enable auto-color (dark/light terminal).\n\n :return: Class instance for colorized string.\n :rtype: Color\n "
] |
Please provide a description of the function:def bgblack(cls, string, auto=False):
return cls.colorize('bgblack', string, auto=auto) | [
"Color-code entire string.\n\n :param str string: String to colorize.\n :param bool auto: Enable auto-color (dark/light terminal).\n\n :return: Class instance for colorized string.\n :rtype: Color\n "
] |
Please provide a description of the function:def red(cls, string, auto=False):
return cls.colorize('red', string, auto=auto) | [
"Color-code entire string.\n\n :param str string: String to colorize.\n :param bool auto: Enable auto-color (dark/light terminal).\n\n :return: Class instance for colorized string.\n :rtype: Color\n "
] |
Please provide a description of the function:def bgred(cls, string, auto=False):
return cls.colorize('bgred', string, auto=auto) | [
"Color-code entire string.\n\n :param str string: String to colorize.\n :param bool auto: Enable auto-color (dark/light terminal).\n\n :return: Class instance for colorized string.\n :rtype: Color\n "
] |
Please provide a description of the function:def green(cls, string, auto=False):
return cls.colorize('green', string, auto=auto) | [
"Color-code entire string.\n\n :param str string: String to colorize.\n :param bool auto: Enable auto-color (dark/light terminal).\n\n :return: Class instance for colorized string.\n :rtype: Color\n "
] |
Please provide a description of the function:def bggreen(cls, string, auto=False):
return cls.colorize('bggreen', string, auto=auto) | [
"Color-code entire string.\n\n :param str string: String to colorize.\n :param bool auto: Enable auto-color (dark/light terminal).\n\n :return: Class instance for colorized string.\n :rtype: Color\n "
] |
Please provide a description of the function:def yellow(cls, string, auto=False):
return cls.colorize('yellow', string, auto=auto) | [
"Color-code entire string.\n\n :param str string: String to colorize.\n :param bool auto: Enable auto-color (dark/light terminal).\n\n :return: Class instance for colorized string.\n :rtype: Color\n "
] |
Please provide a description of the function:def bgyellow(cls, string, auto=False):
return cls.colorize('bgyellow', string, auto=auto) | [
"Color-code entire string.\n\n :param str string: String to colorize.\n :param bool auto: Enable auto-color (dark/light terminal).\n\n :return: Class instance for colorized string.\n :rtype: Color\n "
] |
Please provide a description of the function:def blue(cls, string, auto=False):
return cls.colorize('blue', string, auto=auto) | [
"Color-code entire string.\n\n :param str string: String to colorize.\n :param bool auto: Enable auto-color (dark/light terminal).\n\n :return: Class instance for colorized string.\n :rtype: Color\n "
] |
Please provide a description of the function:def bgblue(cls, string, auto=False):
return cls.colorize('bgblue', string, auto=auto) | [
"Color-code entire string.\n\n :param str string: String to colorize.\n :param bool auto: Enable auto-color (dark/light terminal).\n\n :return: Class instance for colorized string.\n :rtype: Color\n "
] |
Please provide a description of the function:def magenta(cls, string, auto=False):
return cls.colorize('magenta', string, auto=auto) | [
"Color-code entire string.\n\n :param str string: String to colorize.\n :param bool auto: Enable auto-color (dark/light terminal).\n\n :return: Class instance for colorized string.\n :rtype: Color\n "
] |
Please provide a description of the function:def bgmagenta(cls, string, auto=False):
return cls.colorize('bgmagenta', string, auto=auto) | [
"Color-code entire string.\n\n :param str string: String to colorize.\n :param bool auto: Enable auto-color (dark/light terminal).\n\n :return: Class instance for colorized string.\n :rtype: Color\n "
] |
Please provide a description of the function:def cyan(cls, string, auto=False):
return cls.colorize('cyan', string, auto=auto) | [
"Color-code entire string.\n\n :param str string: String to colorize.\n :param bool auto: Enable auto-color (dark/light terminal).\n\n :return: Class instance for colorized string.\n :rtype: Color\n "
] |
Please provide a description of the function:def bgcyan(cls, string, auto=False):
return cls.colorize('bgcyan', string, auto=auto) | [
"Color-code entire string.\n\n :param str string: String to colorize.\n :param bool auto: Enable auto-color (dark/light terminal).\n\n :return: Class instance for colorized string.\n :rtype: Color\n "
] |
Please provide a description of the function:def white(cls, string, auto=False):
return cls.colorize('white', string, auto=auto) | [
"Color-code entire string.\n\n :param str string: String to colorize.\n :param bool auto: Enable auto-color (dark/light terminal).\n\n :return: Class instance for colorized string.\n :rtype: Color\n "
] |
Please provide a description of the function:def bgwhite(cls, string, auto=False):
return cls.colorize('bgwhite', string, auto=auto) | [
"Color-code entire string.\n\n :param str string: String to colorize.\n :param bool auto: Enable auto-color (dark/light terminal).\n\n :return: Class instance for colorized string.\n :rtype: Color\n "
] |
Please provide a description of the function: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... | [
"List the available tags.\n\n :return: List of 4-item tuples: opening tag, closing tag, main ansi value, closing ansi value.\n :rtype: list\n ",
"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 ta... |
Please provide a description of the function: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.\n\n :return: True if colors are disabled, False if stderr or stdout is a TTY.\n :rtype: bool\n "
] |
Please provide a description of the function:def init_kernel32(kernel32=None):
if not kernel32:
kernel32 = ctypes.LibraryLoader(ctypes.WinDLL).kernel32 # Load our own instance. Unique memory address.
kernel32.GetStdHandle.argtypes = [ctypes.c_ulong]
kernel32.GetStdHandle.restype = ctyp... | [
"Load a unique instance of WinDLL into memory, set arg/return types, and get stdout/err handles.\n\n 1. Since we are setting DLL function argument types and return types, we need to maintain our own instance of\n kernel32 to prevent overriding (or being overwritten by) user's own changes to ctypes.windll.k... |
Please provide a description of the function: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)... | [
"Get information about this current console window.\n\n http://msdn.microsoft.com/en-us/library/windows/desktop/ms683231\n https://code.google.com/p/colorama/issues/detail?id=47\n https://bitbucket.org/pytest-dev/py/src/4617fe46/py/_io/terminalwriter.py\n\n Windows 10 Insider since around February 2016 ... |
Please provide a description of the function: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_HAN... | [
"Get background color and if console supports ANSI colors natively for both streams.\n\n :param ctypes.windll.kernel32 kernel32: Loaded kernel32 instance.\n :param int stderr: stderr handle.\n :param int stdout: stdout handle.\n\n :return: Background color (int) and native ANSI support (bool).\n :rty... |
Please provide a description of the function: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."
] |
Please provide a description of the function: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.... | [
"Change the foreground and background colors for subsequently printed characters.\n\n None resets colors to their original values (when class was instantiated).\n\n Since setting a color requires including both foreground and background codes (merged), setting just the\n foreground color resets... |
Please provide a description of the function: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):
... | [
"Write to stream.\n\n :param str p_str: string to print.\n "
] |
Please provide a description of the function:def disable(cls):
# Skip if not on Windows.
if not IS_WINDOWS:
return False
# Restore default colors.
if hasattr(sys.stderr, '_original_stream'):
getattr(sys, 'stderr').color = None
if hasattr(sys.stdo... | [
"Restore sys.stderr and sys.stdout to their original objects. Resets colors to their original values.\n\n :return: If streams restored successfully.\n :rtype: bool\n "
] |
Please provide a description of the function:def enable(cls, auto_colors=False, reset_atexit=False):
if not IS_WINDOWS:
return False # Windows only.
# Get values from init_kernel32().
kernel32, stderr, stdout = init_kernel32()
if stderr == INVALID_HANDLE_VALUE and ... | [
"Enable color text with print() or sys.stdout.write() (stderr too).\n\n :param bool auto_colors: Automatically selects dark or light colors based on current terminal's background\n color. Only works with {autored} and related tags.\n :param bool reset_atexit: Resets original colors upon Pyt... |
Please provide a description of the function: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 be... | [
"Remove color codes that are rendered ineffective by subsequent codes in one escape sequence then sort codes.\n\n :param str ansi_string: Incoming ansi_string with ANSI color codes.\n\n :return: Color string with pruned color sequences.\n :rtype: str\n "
] |
Please provide a description of the function: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, replace... | [
"Perform the actual conversion of tags to ANSI escaped codes.\n\n Provides a version of the input without any colors for len() and other methods.\n\n :param str tagged_string: The input unicode value.\n :param bool disable_colors: Strip all colors in both outputs.\n :param bool keep_tags: Skip parsing c... |
Please provide a description of the function: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)):
... | [
"Build an index between visible characters and a string with invisible color codes.\n\n :param str ansi_string: String with color codes (ANSI escape sequences).\n\n :return: Position of visible characters in color string (indexes match non-color string).\n :rtype: tuple\n "
] |
Please provide a description of the function: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... | [
"Determine what color a character is in the string.\n\n :param str ansi_string: String with color codes (ANSI escape sequences).\n :param int pos: Position of the character in the ansi_string.\n\n :return: Character along with all surrounding color codes.\n :rtype: str\n "
] |
Please provide a description of the function:def main():
if OPTIONS.get('--no-colors'):
disable_all_colors()
elif OPTIONS.get('--colors'):
enable_all_colors()
if is_enabled() and os.name == 'nt':
Windows.enable(auto_colors=True, reset_atexit=True)
elif OPTIONS.get('--light-... | [
"Main function called upon script execution."
] |
Please provide a description of the function: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.... | [
"\n Compute angular distance using the Haversine formula. Use this one when you know you will never ask for points at\n their antipodes. If this is not the case, use the angular_distance function which is slower, but works also for\n antipodes.\n\n :param lon1:\n :param lat1:\n :param lon2:\n :... |
Please provide a description of the function: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 =... | [
"\n Returns the angular distance between two points, two sets of points, or a set of points and one point.\n\n :param ra1: array or float, longitude of first point(s)\n :param dec1: array or float, latitude of first point(s)\n :param ra2: array or float, longitude of second point(s)\n :param dec2: ar... |
Please provide a description of the function:def spherical_angle( ra0, dec0, ra1, dec1, ra2, dec2 ):
a = np.deg2rad( angular_distance(ra0, dec0, ra1, dec1))
b = np.deg2rad( angular_distance(ra0, dec0, ra2, dec2))
c = np.deg2rad( angular_distance(ra2, dec2, ra1, dec1))
#use the spherical l... | [
"\n Returns the spherical angle distance between two sets of great circles defined by (ra0, dec0), (ra1, dec1) and (ra0, dec0), (ra2, dec2)\n\n :param ra0: array or float, longitude of intersection point(s)\n :param dec0: array or float, latitude of intersection point(s)\n :param ra1: array or float, lo... |
Please provide a description of the function:def use_astromodels_memoization(switch, cache_size=_CACHE_SIZE):
global _WITH_MEMOIZATION
global _CACHE_SIZE
old_status = bool(_WITH_MEMOIZATION)
old_cache_size = int(_CACHE_SIZE)
_WITH_MEMOIZATION = bool(switch)
_CACHE_SIZE = int(cache_size)
... | [
"\n Activate/deactivate memoization temporarily\n\n :param switch: True (memoization on) or False (memoization off)\n :param cache_size: number of previous evaluation of functions to keep in memory. Default: 100\n :return:\n "
] |
Please provide a description of the function: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):
i... | [
"\n A decorator for functions of sources which memoize the results of the last _CACHE_SIZE calls,\n\n :param method: method to be memoized\n :return: the decorated method\n "
] |
Please provide a description of the function:def xspec_cosmo(H0=None,q0=None,lambda_0=None):
current_settings = _xspec.get_xscosmo()
if (H0 is None) and (q0 is None) and (lambda_0 is None):
return current_settings
else:
# ok, we will see what was changed by the used
user_... | [
"\n Define the Cosmology in use within the XSpec models. See Xspec manual for help:\n\n http://heasarc.nasa.gov/xanadu/xspec/manual/XScosmo.html\n \n All parameters can be modified or just a single parameter\n\n :param H0: the hubble constant\n :param q0:\n :param lambda_0:\n :return: Either... |
Please provide a description of the function:def find_model_dat():
# model.dat is in $HEADAS/../spectral
headas_env = os.environ.get("HEADAS")
assert headas_env is not None, ("You need to setup the HEADAS variable before importing this module."
" See Heasoft docum... | [
"\n Find the file containing the definition of all the models in Xspec\n (model.dat) and return its path\n "
] |
Please provide a description of the function:def get_models(model_dat_path):
# Check first if we already have a model data file in the data directory
with open(model_dat_path) as f:
# model.dat is a text file, no size issues here (will fit in memory)
model_dat = f.read()
# Replace... | [
"\n Parse the model.dat file from Xspec and returns a dictionary containing the definition of all the models\n\n :param model_dat_path: the path to the model.dat file\n :return: dictionary containing the definition of all XSpec models\n "
] |
Please provide a description of the function:def _add_source(self, source):
try:
self._add_child(source)
except AttributeError:
if isinstance(source, Source):
raise DuplicatedNode("More than one source with the name '%s'. You cannot use the same name... | [
"\n Remember to call _update_parameters after this!\n :param source:\n :return:\n "
] |
Please provide a description of the function:def _remove_source(self, source_name):
assert source_name in self.sources, "Source %s is not part of the current model" % source_name
source = self.sources.pop(source_name)
if source.source_type == POINT_SOURCE:
self._point_so... | [
"\n Remember to call _update_parameters after this\n :param source_name:\n :return:\n "
] |
Please provide a description of the function: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.iter... | [
"\n Get a dictionary with all the free parameters in this model\n\n :return: dictionary of free parameters\n "
] |
Please provide a description of the function:def linked_parameters(self):
# Refresh the list
self._update_parameters()
# Filter selecting only free parameters
linked_parameter_dictionary = collections.OrderedDict()
for parameter_name, parameter in self._parameters.i... | [
"\n Get a dictionary with all parameters in this model in a linked status. A parameter is in a linked status\n if it is linked to another parameter (i.e. it is forced to have the same value of the other parameter), or\n if it is linked with another parameter or an independent variable through a... |
Please provide a description of the function: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 | [
"\n Set the free parameters in the model to the provided values.\n\n NOTE: of course, order matters\n\n :param values: a list of new values\n :return: None\n "
] |
Please provide a description of the function:def sources(self):
sources = collections.OrderedDict()
for d in (self.point_sources, self.extended_sources, self.particle_sources):
sources.update(d)
return sources | [
"\n Returns a dictionary containing all defined sources (of any kind)\n\n :return: collections.OrderedDict()\n\n "
] |
Please provide a description of the function: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._a... | [
"\n Add a global independent variable to this model, such as time.\n\n :param variable: an IndependentVariable instance\n :return: none\n "
] |
Please provide a description of the function: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) | [
"\n Remove an independent variable which was added with add_independent_variable\n\n :param variable_name: name of variable to remove\n :return:\n "
] |
Please provide a description of the function: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 ins... | [
"\n Add a parameter that comes from something other than a function, to the model.\n\n :param parameter: a Parameter instance\n :return: none\n "
] |
Please provide a description of the function:def link(self, parameter_1, parameter_2, link_function=None):
if not isinstance(parameter_1,list):
# Make a list of one element
parameter_1_list = [parameter_1]
else:
# Make a copy to avoid tampering with the input
... | [
"\n Link the value of the provided parameters through the provided function (identity is the default, i.e.,\n parameter_1 = parameter_2).\n\n :param parameter_1: the first parameter;can be either a single parameter or a list of prarameters\n :param parameter_2: the second parameter\n ... |
Please provide a description of the function: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)... | [
"\n Sets free one or more parameters which have been linked previously\n\n :param parameter: the parameter to be set free, can also be a list of parameters\n :return: (none)\n "
] |
Please provide a description of the function: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()
... | [
"\n Display information about the point source.\n\n :param complete : if True, displays also information on fixed parameters\n :return: (none)\n "
] |
Please provide a description of the function: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' "
"... | [
"Save the model to disk"
] |
Please provide a description of the function:def get_point_source_position(self, id):
pts = self._point_sources.values()[id]
return pts.position.get_ra(), pts.position.get_dec() | [
"\n Get the point source position (R.A., Dec)\n\n :param id: id of the source\n :return: a tuple with R.A. and Dec.\n "
] |
Please provide a description of the function:def get_point_source_fluxes(self, id, energies, tag=None):
return self._point_sources.values()[id](energies, tag=tag) | [
"\n Get the fluxes from the id-th point source\n\n :param id: id of the source\n :param energies: energies at which you need the flux\n :param tag: a tuple (integration variable, a, b) specifying the integration to perform. If this\n parameter is specified then the returned value ... |
Please provide a description of the function:def get_extended_source_fluxes(self, id, j2000_ra, j2000_dec, energies):
return self._extended_sources.values()[id](j2000_ra, j2000_dec, energies) | [
"\n Get the flux of the id-th extended sources at the given position at the given energies\n\n :param id: id of the source\n :param j2000_ra: R.A. where the flux is desired\n :param j2000_dec: Dec. where the flux is desired\n :param energies: energies at which the flux is desired\... |
Please provide a description of the function:def get_total_flux(self, energies):
fluxes = []
for src in self._point_sources:
fluxes.append(self._point_sources[src](energies))
return np.sum(fluxes, axis=0) | [
"\n Returns the total differential flux at the provided energies from all *point* sources\n\n :return:\n "
] |
Please provide a description of the function:def long_path_formatter(line, max_width=pd.get_option('max_colwidth')):
if len(line) > max_width:
tokens = line.split(".")
trial1 = "%s...%s" % (tokens[0], tokens[-1])
if len(trial1) > max_width:
return "...%s" %(tokens[-1][-1... | [
"\n If a path is longer than max_width, it substitute it with the first and last element,\n joined by \"...\". For example 'this.is.a.long.path.which.we.want.to.shorten' becomes\n 'this...shorten'\n\n :param line:\n :param max_width:\n :return:\n "
] |
Please provide a description of the function:def has_free_parameters(self):
for component in self._components.values():
for par in component.shape.parameters.values():
if par.free:
return True
for par in self.position.parameters.values():
... | [
"\n Returns True or False whether there is any parameter in this source\n\n :return:\n "
] |
Please provide a description of the function:def free_parameters(self):
free_parameters = collections.OrderedDict()
for component in self._components.values():
for par in component.shape.parameters.values():
if par.free:
free_parameters[par.pa... | [
"\n Returns a dictionary of free parameters for this source.\n We use the parameter path as the key because it's \n guaranteed to be unique, unlike the parameter name.\n\n :return:\n "
] |
Please provide a description of the function:def parameters(self):
all_parameters = collections.OrderedDict()
for component in self._components.values():
for par in component.shape.parameters.values():
all_parameters[par.path] = par
for par in self.positi... | [
"\n Returns a dictionary of all parameters for this source.\n We use the parameter path as the key because it's \n guaranteed to be unique, unlike the parameter name.\n\n :return:\n "
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.