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('[email protected]', 'password')\n >>> project = user.get_project('PyTodoist')\n >>> project.add_task('Install PyTodoist')\n >>> uncompleted_tasks = project.get_uncompleted_tasks()\n >>> for task in uncompleted_tasks:\n ... task.complete()\n "
] |
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,
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.\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('[email protected]', 'password')\n >>> project = user.get_project('PyTodoist')\n >>> task = project.add_task('Install PyTodoist')\n >>> task.complete()\n >>> completed_tasks = project.get_completed_tasks()\n >>> for task in completed_tasks:\n ... task.uncomplete()\n "
] |
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('[email protected]', 'password')\n >>> project = user.get_project('PyTodoist')\n >>> project.add_task('Install PyTodoist')\n >>> project.add_task('Have fun!')\n >>> tasks = project.get_tasks()\n >>> for task in tasks:\n ... print(task.content)\n Install PyTodoist\n Have fun!\n "
] |
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('[email protected]', 'password')\n >>> project = user.get_project('PyTodoist')\n >>> project.add_note('Remember to update to the latest version.')\n "
] |
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('[email protected]', 'password')\n >>> project = user.get_project('PyTodoist')\n >>> notes = project.get_notes()\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('[email protected]', 'password')\n >>> project = user.get_project('PyTodoist')\n >>> project.share('[email protected]')\n "
] |
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('[email protected]', 'password')\n >>> project = user.get_project('PyTodoist')\n >>> project.delete_collaborator('[email protected]')\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('[email protected]', '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('[email protected]', '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('[email protected]', '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('[email protected]', 'password')\n >>> project = user.get_project('PyTodoist')\n >>> task = project.add_task('Install PyTodoist.')\n >>> task.add_note('https://pypi.python.org/pypi')\n >>> notes = task.get_notes()\n >>> print(len(notes))\n 1\n "
] |
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('[email protected]', 'password')\n >>> project = user.get_project('PyTodoist')\n >>> task = project.add_task('Install PyTodoist')\n >>> print(task.project.name)\n PyTodoist\n >>> inbox = user.get_project('Inbox')\n >>> task.move(inbox)\n >>> print(task.project.name)\n Inbox\n "
] |
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', args) | [
"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 :type due_date: str\n\n >>> from pytodoist import todoist\n >>> user = todoist.login('[email protected]', 'password')\n >>> project = user.get_project('PyTodoist')\n >>> task = project.add_task('Install PyTodoist')\n >>> task.add_date_reminder('email', '2015-12-01T09:00')\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_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.\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: The location latitude.\n :type lat: float\n :param long: The location longitude.\n :type long: float\n :param trigger: ```on_enter``` or ```on_leave```.\n :type trigger: str\n :param radius: The radius around the location that is still considered\n the location.\n :type radius: float\n\n >>> from pytodoist import todoist\n >>> user = todoist.login('[email protected]', 'password')\n >>> project = user.get_project('PyTodoist')\n >>> task = project.add_task('Install PyTodoist')\n >>> task.add_location_reminder('email', 'Leave Glasgow',\n ... 55.8580, 4.2590, 'on_leave', 100)\n "
] |
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('[email protected]', 'password')\n >>> project = user.get_project('PyTodoist')\n >>> task = project.add_task('Install PyTodoist')\n >>> task.add_date_reminder('email', '2015-12-01T09:00')\n >>> reminders = task.get_reminders()\n "
] |
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('[email protected]', '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('[email protected]', 'password')\n >>> project = user.get_project('PyTodoist')\n >>> task = project.add_task('Install PyTodoist.')\n >>> note = task.add_note('https://pypi.python.org/pypi')\n >>> note.delete()\n >>> notes = task.get_notes()\n >>> print(len(notes))\n 0\n "
] |
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('[email protected]', 'password')\n >>> overdue_filter = user.add_filter('Overdue', todoist.Query.OVERDUE)\n >>> overdue_filter.name = 'OVERDUE!'\n ... # At this point Todoist still thinks the name is 'Overdue'.\n >>> overdue_filter.update()\n ... # Now the name has been updated on Todoist.\n "
] |
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 funcarg not in kwargs]
funcargs_required = funcargs[:-len(defaults)] \
if defaults is not None \
else funcargs
params_required = [
funcarg for funcarg in funcargs_required
if funcarg not in kwargs
]
return not (len(params_required) <= len(args) <= len(params)) | [
" 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 = [
parameter for name, parameter in parameters.items()
if name not in kwargs
]
params_required = [
param for param in params
if param.default is param.empty
]
return not (len(params_required) <= len(args) <= len(params)) | [
"\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.version_info >= (3, 3):
return is_invalid_params_py3(func, *args, **kwargs)
else:
# NOTE: use Python2 method for Python 3.2 as well. Starting from Python
# 3.3 it is recommended to use inspect.signature instead.
# In Python 3.0 - 3.2 inspect.getfullargspec is preferred but these
# versions are almost not supported. Users should consider upgrading.
return is_invalid_params_py2(func, *args, **kwargs) | [
"\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. number of args should be >= remaining func.parameters less default\n "
] |
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 object unmodified.\n\n Examples\n --------\n\n Use as method\n\n >>> d = Dispatcher()\n >>> d.add_method(lambda a, b: a + b, name=\"sum\")\n <function __main__.<lambda>>\n\n Or use as decorator\n\n >>> d = Dispatcher()\n >>> @d.add_method\n def mymethod(*args, **kwargs):\n print(args, kwargs)\n\n Or use as a decorator with a different function name\n >>> d = Dispatcher()\n >>> @d.add_method(name=\"my.method\")\n def mymethod(*args, **kwargs):\n print(args, kwargs)\n\n "
] |
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:
getattr(handle, 'close', lambda: None)() | [
"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 registered with codecs.register_error that is able to handle UnicodeDecodeErrors.\n\n :param str encoding: Codec.\n :param str errors: Error handling scheme.\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_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.\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 position.\n "
] |
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: Beginning position.\n :param int end: Stop comparison at this position.\n "
] |
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 'xmlcharrefreplace' as well as any\n other name registered with codecs.register_error that is able to handle UnicodeEncodeErrors.\n\n :param str encoding: Codec.\n :param str errors: Error handling scheme.\n "
] |
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 other name\n registered with codecs.register_error that is able to handle UnicodeDecodeErrors.\n\n :param str encoding: Codec.\n :param str errors: Error handling scheme.\n "
] |
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 comparison at this position.\n "
] |
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 comparison at this position.\n "
] |
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 start: Beginning position.\n :param int end: Stop comparison at this position.\n "
] |
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__(result, keep_tags=True) | [
"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, 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):
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.\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 tag, main ansi value, closing ansi value]\n\n :return Sorting weight.\n :rtype: int\n "
] |
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 = ctypes.c_void_p
kernel32.GetConsoleScreenBufferInfo.argtypes = [
ctypes.c_void_p,
ctypes.POINTER(ConsoleScreenBufferInfo),
]
kernel32.GetConsoleScreenBufferInfo.restype = ctypes.c_long
# Get handles.
if hasattr(sys.stderr, '_original_stream'):
stderr = INVALID_HANDLE_VALUE
else:
stderr = kernel32.GetStdHandle(STD_ERROR_HANDLE)
if hasattr(sys.stdout, '_original_stream'):
stdout = INVALID_HANDLE_VALUE
else:
stdout = kernel32.GetStdHandle(STD_OUTPUT_HANDLE)
return kernel32, stderr, stdout | [
"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.kernel32.\n 2. While we're doing all this we might as well get the handles to STDOUT and STDERR streams.\n 3. If either stream has already been replaced set return value to INVALID_HANDLE_VALUE to indicate it shouldn't be\n replaced.\n\n :raise AttributeError: When called on a non-Windows platform.\n\n :param kernel32: Optional mock kernel32 object. For testing.\n\n :return: Loaded kernel32 instance, stderr handle (int), stdout handle (int).\n :rtype: tuple\n "
] |
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)
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.\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 finally introduced support for ANSI colors. No need to replace stdout\n and stderr streams to intercept colors and issue multiple SetConsoleTextAttribute() calls for these consoles.\n\n :raise OSError: When GetConsoleScreenBufferInfo or GetConsoleMode API calls fail.\n\n :param ctypes.windll.kernel32 kernel32: Loaded kernel32 instance.\n :param int handle: stderr or stdout handle.\n\n :return: Foreground and background colors (integers) as well as native ANSI support (bool).\n :rtype: tuple\n "
] |
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_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.\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 :rtype: tuple\n "
] |
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.
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.\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 the background color to black, and vice versa.\n\n This function first gets the current background and foreground colors, merges in the requested color code, and\n sets the result.\n\n However if we need to remove just the foreground color but leave the background color the same (or vice versa)\n such as when {/red} is used, we must merge the default foreground color with the current background color. This\n is the reason for those negative values.\n\n :param int color_code: Color code from WINDOWS_CODES.\n "
] |
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):
# 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.\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.stdout, '_original_stream'):
getattr(sys, 'stdout').color = None
# Restore original streams.
changed = False
if hasattr(sys.stderr, '_original_stream'):
changed = True
sys.stderr = getattr(sys.stderr, '_original_stream')
if hasattr(sys.stdout, '_original_stream'):
changed = True
sys.stdout = getattr(sys.stdout, '_original_stream')
return changed | [
"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 stdout == INVALID_HANDLE_VALUE:
return False # No valid handles, nothing to do.
# Get console info.
bg_color, native_ansi = bg_color_native_ansi(kernel32, stderr, stdout)
# Set auto colors:
if auto_colors:
if bg_color in (112, 96, 240, 176, 224, 208, 160):
ANSICodeMapping.set_light_background()
else:
ANSICodeMapping.set_dark_background()
# Don't replace streams if ANSI codes are natively supported.
if native_ansi:
return False
# Reset on exit if requested.
if reset_atexit:
atexit.register(cls.disable)
# Overwrite stream references.
if stderr != INVALID_HANDLE_VALUE:
sys.stderr.flush()
sys.stderr = WindowsStream(kernel32, stderr, sys.stderr)
if stdout != INVALID_HANDLE_VALUE:
sys.stdout.flush()
sys.stdout = WindowsStream(kernel32, stdout, sys.stdout)
return True | [
"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 Python exit (in case you forget to reset it yourself with\n a closing tag). Does nothing on native ANSI consoles.\n\n :return: If streams replaced successfully.\n :rtype: bool\n "
] |
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 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.\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, 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.\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 curly bracket tags into ANSI escape sequences.\n\n :return: 2-item tuple. First item is the parsed output. Second item is a version of the input without any colors.\n :rtype: tuple\n "
] |
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)):
mapping.append(color_offset)
color_offset += 1
return tuple(mapping) | [
"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 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.\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-bg'):
set_light_background()
elif OPTIONS.get('--dark-bg'):
set_dark_background()
# Light or dark colors.
print('Autocolors for all backgrounds:')
print(Color(' {autoblack}Black{/black} {autored}Red{/red} {autogreen}Green{/green} '), end='')
print(Color('{autoyellow}Yellow{/yellow} {autoblue}Blue{/blue} {automagenta}Magenta{/magenta} '), end='')
print(Color('{autocyan}Cyan{/cyan} {autowhite}White{/white}'))
print(Color(' {autobgblack}{autoblack}Black{/black}{/bgblack} '), end='')
print(Color('{autobgblack}{autored}Red{/red}{/bgblack} {autobgblack}{autogreen}Green{/green}{/bgblack} '), end='')
print(Color('{autobgblack}{autoyellow}Yellow{/yellow}{/bgblack} '), end='')
print(Color('{autobgblack}{autoblue}Blue{/blue}{/bgblack} '), end='')
print(Color('{autobgblack}{automagenta}Magenta{/magenta}{/bgblack} '), end='')
print(Color('{autobgblack}{autocyan}Cyan{/cyan}{/bgblack} {autobgblack}{autowhite}White{/white}{/bgblack}'))
print(Color(' {autobgred}{autoblack}Black{/black}{/bgred} {autobgred}{autored}Red{/red}{/bgred} '), end='')
print(Color('{autobgred}{autogreen}Green{/green}{/bgred} {autobgred}{autoyellow}Yellow{/yellow}{/bgred} '), end='')
print(Color('{autobgred}{autoblue}Blue{/blue}{/bgred} {autobgred}{automagenta}Magenta{/magenta}{/bgred} '), end='')
print(Color('{autobgred}{autocyan}Cyan{/cyan}{/bgred} {autobgred}{autowhite}White{/white}{/bgred}'))
print(Color(' {autobggreen}{autoblack}Black{/black}{/bggreen} '), end='')
print(Color('{autobggreen}{autored}Red{/red}{/bggreen} {autobggreen}{autogreen}Green{/green}{/bggreen} '), end='')
print(Color('{autobggreen}{autoyellow}Yellow{/yellow}{/bggreen} '), end='')
print(Color('{autobggreen}{autoblue}Blue{/blue}{/bggreen} '), end='')
print(Color('{autobggreen}{automagenta}Magenta{/magenta}{/bggreen} '), end='')
print(Color('{autobggreen}{autocyan}Cyan{/cyan}{/bggreen} {autobggreen}{autowhite}White{/white}{/bggreen}'))
print(Color(' {autobgyellow}{autoblack}Black{/black}{/bgyellow} '), end='')
print(Color('{autobgyellow}{autored}Red{/red}{/bgyellow} '), end='')
print(Color('{autobgyellow}{autogreen}Green{/green}{/bgyellow} '), end='')
print(Color('{autobgyellow}{autoyellow}Yellow{/yellow}{/bgyellow} '), end='')
print(Color('{autobgyellow}{autoblue}Blue{/blue}{/bgyellow} '), end='')
print(Color('{autobgyellow}{automagenta}Magenta{/magenta}{/bgyellow} '), end='')
print(Color('{autobgyellow}{autocyan}Cyan{/cyan}{/bgyellow} {autobgyellow}{autowhite}White{/white}{/bgyellow}'))
print(Color(' {autobgblue}{autoblack}Black{/black}{/bgblue} {autobgblue}{autored}Red{/red}{/bgblue} '), end='')
print(Color('{autobgblue}{autogreen}Green{/green}{/bgblue} '), end='')
print(Color('{autobgblue}{autoyellow}Yellow{/yellow}{/bgblue} {autobgblue}{autoblue}Blue{/blue}{/bgblue} '), end='')
print(Color('{autobgblue}{automagenta}Magenta{/magenta}{/bgblue} '), end='')
print(Color('{autobgblue}{autocyan}Cyan{/cyan}{/bgblue} {autobgblue}{autowhite}White{/white}{/bgblue}'))
print(Color(' {autobgmagenta}{autoblack}Black{/black}{/bgmagenta} '), end='')
print(Color('{autobgmagenta}{autored}Red{/red}{/bgmagenta} '), end='')
print(Color('{autobgmagenta}{autogreen}Green{/green}{/bgmagenta} '), end='')
print(Color('{autobgmagenta}{autoyellow}Yellow{/yellow}{/bgmagenta} '), end='')
print(Color('{autobgmagenta}{autoblue}Blue{/blue}{/bgmagenta} '), end='')
print(Color('{autobgmagenta}{automagenta}Magenta{/magenta}{/bgmagenta} '), end='')
print(Color('{autobgmagenta}{autocyan}Cyan{/cyan}{/bgmagenta} '), end='')
print(Color('{autobgmagenta}{autowhite}White{/white}{/bgmagenta}'))
print(Color(' {autobgcyan}{autoblack}Black{/black}{/bgcyan} {autobgcyan}{autored}Red{/red}{/bgcyan} '), end='')
print(Color('{autobgcyan}{autogreen}Green{/green}{/bgcyan} '), end='')
print(Color('{autobgcyan}{autoyellow}Yellow{/yellow}{/bgcyan} {autobgcyan}{autoblue}Blue{/blue}{/bgcyan} '), end='')
print(Color('{autobgcyan}{automagenta}Magenta{/magenta}{/bgcyan} '), end='')
print(Color('{autobgcyan}{autocyan}Cyan{/cyan}{/bgcyan} {autobgcyan}{autowhite}White{/white}{/bgcyan}'))
print(Color(' {autobgwhite}{autoblack}Black{/black}{/bgwhite} '), end='')
print(Color('{autobgwhite}{autored}Red{/red}{/bgwhite} {autobgwhite}{autogreen}Green{/green}{/bgwhite} '), end='')
print(Color('{autobgwhite}{autoyellow}Yellow{/yellow}{/bgwhite} '), end='')
print(Color('{autobgwhite}{autoblue}Blue{/blue}{/bgwhite} '), end='')
print(Color('{autobgwhite}{automagenta}Magenta{/magenta}{/bgwhite} '), end='')
print(Color('{autobgwhite}{autocyan}Cyan{/cyan}{/bgwhite} {autobgwhite}{autowhite}White{/white}{/bgwhite}'))
print()
# Light colors.
print('Light colors for dark backgrounds:')
print(Color(' {hiblack}Black{/black} {hired}Red{/red} {higreen}Green{/green} '), end='')
print(Color('{hiyellow}Yellow{/yellow} {hiblue}Blue{/blue} {himagenta}Magenta{/magenta} '), end='')
print(Color('{hicyan}Cyan{/cyan} {hiwhite}White{/white}'))
print(Color(' {hibgblack}{hiblack}Black{/black}{/bgblack} '), end='')
print(Color('{hibgblack}{hired}Red{/red}{/bgblack} {hibgblack}{higreen}Green{/green}{/bgblack} '), end='')
print(Color('{hibgblack}{hiyellow}Yellow{/yellow}{/bgblack} '), end='')
print(Color('{hibgblack}{hiblue}Blue{/blue}{/bgblack} '), end='')
print(Color('{hibgblack}{himagenta}Magenta{/magenta}{/bgblack} '), end='')
print(Color('{hibgblack}{hicyan}Cyan{/cyan}{/bgblack} {hibgblack}{hiwhite}White{/white}{/bgblack}'))
print(Color(' {hibgred}{hiblack}Black{/black}{/bgred} {hibgred}{hired}Red{/red}{/bgred} '), end='')
print(Color('{hibgred}{higreen}Green{/green}{/bgred} {hibgred}{hiyellow}Yellow{/yellow}{/bgred} '), end='')
print(Color('{hibgred}{hiblue}Blue{/blue}{/bgred} {hibgred}{himagenta}Magenta{/magenta}{/bgred} '), end='')
print(Color('{hibgred}{hicyan}Cyan{/cyan}{/bgred} {hibgred}{hiwhite}White{/white}{/bgred}'))
print(Color(' {hibggreen}{hiblack}Black{/black}{/bggreen} '), end='')
print(Color('{hibggreen}{hired}Red{/red}{/bggreen} {hibggreen}{higreen}Green{/green}{/bggreen} '), end='')
print(Color('{hibggreen}{hiyellow}Yellow{/yellow}{/bggreen} '), end='')
print(Color('{hibggreen}{hiblue}Blue{/blue}{/bggreen} '), end='')
print(Color('{hibggreen}{himagenta}Magenta{/magenta}{/bggreen} '), end='')
print(Color('{hibggreen}{hicyan}Cyan{/cyan}{/bggreen} {hibggreen}{hiwhite}White{/white}{/bggreen}'))
print(Color(' {hibgyellow}{hiblack}Black{/black}{/bgyellow} '), end='')
print(Color('{hibgyellow}{hired}Red{/red}{/bgyellow} '), end='')
print(Color('{hibgyellow}{higreen}Green{/green}{/bgyellow} '), end='')
print(Color('{hibgyellow}{hiyellow}Yellow{/yellow}{/bgyellow} '), end='')
print(Color('{hibgyellow}{hiblue}Blue{/blue}{/bgyellow} '), end='')
print(Color('{hibgyellow}{himagenta}Magenta{/magenta}{/bgyellow} '), end='')
print(Color('{hibgyellow}{hicyan}Cyan{/cyan}{/bgyellow} {hibgyellow}{hiwhite}White{/white}{/bgyellow}'))
print(Color(' {hibgblue}{hiblack}Black{/black}{/bgblue} {hibgblue}{hired}Red{/red}{/bgblue} '), end='')
print(Color('{hibgblue}{higreen}Green{/green}{/bgblue} '), end='')
print(Color('{hibgblue}{hiyellow}Yellow{/yellow}{/bgblue} {hibgblue}{hiblue}Blue{/blue}{/bgblue} '), end='')
print(Color('{hibgblue}{himagenta}Magenta{/magenta}{/bgblue} '), end='')
print(Color('{hibgblue}{hicyan}Cyan{/cyan}{/bgblue} {hibgblue}{hiwhite}White{/white}{/bgblue}'))
print(Color(' {hibgmagenta}{hiblack}Black{/black}{/bgmagenta} '), end='')
print(Color('{hibgmagenta}{hired}Red{/red}{/bgmagenta} '), end='')
print(Color('{hibgmagenta}{higreen}Green{/green}{/bgmagenta} '), end='')
print(Color('{hibgmagenta}{hiyellow}Yellow{/yellow}{/bgmagenta} '), end='')
print(Color('{hibgmagenta}{hiblue}Blue{/blue}{/bgmagenta} '), end='')
print(Color('{hibgmagenta}{himagenta}Magenta{/magenta}{/bgmagenta} '), end='')
print(Color('{hibgmagenta}{hicyan}Cyan{/cyan}{/bgmagenta} '), end='')
print(Color('{hibgmagenta}{hiwhite}White{/white}{/bgmagenta}'))
print(Color(' {hibgcyan}{hiblack}Black{/black}{/bgcyan} {hibgcyan}{hired}Red{/red}{/bgcyan} '), end='')
print(Color('{hibgcyan}{higreen}Green{/green}{/bgcyan} '), end='')
print(Color('{hibgcyan}{hiyellow}Yellow{/yellow}{/bgcyan} {hibgcyan}{hiblue}Blue{/blue}{/bgcyan} '), end='')
print(Color('{hibgcyan}{himagenta}Magenta{/magenta}{/bgcyan} '), end='')
print(Color('{hibgcyan}{hicyan}Cyan{/cyan}{/bgcyan} {hibgcyan}{hiwhite}White{/white}{/bgcyan}'))
print(Color(' {hibgwhite}{hiblack}Black{/black}{/bgwhite} '), end='')
print(Color('{hibgwhite}{hired}Red{/red}{/bgwhite} {hibgwhite}{higreen}Green{/green}{/bgwhite} '), end='')
print(Color('{hibgwhite}{hiyellow}Yellow{/yellow}{/bgwhite} '), end='')
print(Color('{hibgwhite}{hiblue}Blue{/blue}{/bgwhite} '), end='')
print(Color('{hibgwhite}{himagenta}Magenta{/magenta}{/bgwhite} '), end='')
print(Color('{hibgwhite}{hicyan}Cyan{/cyan}{/bgwhite} {hibgwhite}{hiwhite}White{/white}{/bgwhite}'))
print()
# Dark colors.
print('Dark colors for light backgrounds:')
print(Color(' {black}Black{/black} {red}Red{/red} {green}Green{/green} {yellow}Yellow{/yellow} '), end='')
print(Color('{blue}Blue{/blue} {magenta}Magenta{/magenta} {cyan}Cyan{/cyan} {white}White{/white}'))
print(Color(' {bgblack}{black}Black{/black}{/bgblack} {bgblack}{red}Red{/red}{/bgblack} '), end='')
print(Color('{bgblack}{green}Green{/green}{/bgblack} {bgblack}{yellow}Yellow{/yellow}{/bgblack} '), end='')
print(Color('{bgblack}{blue}Blue{/blue}{/bgblack} {bgblack}{magenta}Magenta{/magenta}{/bgblack} '), end='')
print(Color('{bgblack}{cyan}Cyan{/cyan}{/bgblack} {bgblack}{white}White{/white}{/bgblack}'))
print(Color(' {bgred}{black}Black{/black}{/bgred} {bgred}{red}Red{/red}{/bgred} '), end='')
print(Color('{bgred}{green}Green{/green}{/bgred} {bgred}{yellow}Yellow{/yellow}{/bgred} '), end='')
print(Color('{bgred}{blue}Blue{/blue}{/bgred} {bgred}{magenta}Magenta{/magenta}{/bgred} '), end='')
print(Color('{bgred}{cyan}Cyan{/cyan}{/bgred} {bgred}{white}White{/white}{/bgred}'))
print(Color(' {bggreen}{black}Black{/black}{/bggreen} {bggreen}{red}Red{/red}{/bggreen} '), end='')
print(Color('{bggreen}{green}Green{/green}{/bggreen} {bggreen}{yellow}Yellow{/yellow}{/bggreen} '), end='')
print(Color('{bggreen}{blue}Blue{/blue}{/bggreen} {bggreen}{magenta}Magenta{/magenta}{/bggreen} '), end='')
print(Color('{bggreen}{cyan}Cyan{/cyan}{/bggreen} {bggreen}{white}White{/white}{/bggreen}'))
print(Color(' {bgyellow}{black}Black{/black}{/bgyellow} {bgyellow}{red}Red{/red}{/bgyellow} '), end='')
print(Color('{bgyellow}{green}Green{/green}{/bgyellow} {bgyellow}{yellow}Yellow{/yellow}{/bgyellow} '), end='')
print(Color('{bgyellow}{blue}Blue{/blue}{/bgyellow} {bgyellow}{magenta}Magenta{/magenta}{/bgyellow} '), end='')
print(Color('{bgyellow}{cyan}Cyan{/cyan}{/bgyellow} {bgyellow}{white}White{/white}{/bgyellow}'))
print(Color(' {bgblue}{black}Black{/black}{/bgblue} {bgblue}{red}Red{/red}{/bgblue} '), end='')
print(Color('{bgblue}{green}Green{/green}{/bgblue} {bgblue}{yellow}Yellow{/yellow}{/bgblue} '), end='')
print(Color('{bgblue}{blue}Blue{/blue}{/bgblue} {bgblue}{magenta}Magenta{/magenta}{/bgblue} '), end='')
print(Color('{bgblue}{cyan}Cyan{/cyan}{/bgblue} {bgblue}{white}White{/white}{/bgblue}'))
print(Color(' {bgmagenta}{black}Black{/black}{/bgmagenta} {bgmagenta}{red}Red{/red}{/bgmagenta} '), end='')
print(Color('{bgmagenta}{green}Green{/green}{/bgmagenta} {bgmagenta}{yellow}Yellow{/yellow}{/bgmagenta} '), end='')
print(Color('{bgmagenta}{blue}Blue{/blue}{/bgmagenta} {bgmagenta}{magenta}Magenta{/magenta}{/bgmagenta} '), end='')
print(Color('{bgmagenta}{cyan}Cyan{/cyan}{/bgmagenta} {bgmagenta}{white}White{/white}{/bgmagenta}'))
print(Color(' {bgcyan}{black}Black{/black}{/bgcyan} {bgcyan}{red}Red{/red}{/bgcyan} '), end='')
print(Color('{bgcyan}{green}Green{/green}{/bgcyan} {bgcyan}{yellow}Yellow{/yellow}{/bgcyan} '), end='')
print(Color('{bgcyan}{blue}Blue{/blue}{/bgcyan} {bgcyan}{magenta}Magenta{/magenta}{/bgcyan} '), end='')
print(Color('{bgcyan}{cyan}Cyan{/cyan}{/bgcyan} {bgcyan}{white}White{/white}{/bgcyan}'))
print(Color(' {bgwhite}{black}Black{/black}{/bgwhite} {bgwhite}{red}Red{/red}{/bgwhite} '), end='')
print(Color('{bgwhite}{green}Green{/green}{/bgwhite} {bgwhite}{yellow}Yellow{/yellow}{/bgwhite} '), end='')
print(Color('{bgwhite}{blue}Blue{/blue}{/bgwhite} {bgwhite}{magenta}Magenta{/magenta}{/bgwhite} '), end='')
print(Color('{bgwhite}{cyan}Cyan{/cyan}{/bgwhite} {bgwhite}{white}White{/white}{/bgwhite}'))
if OPTIONS['--wait']:
print('Waiting for {0} to exist within 10 seconds...'.format(OPTIONS['--wait']), file=sys.stderr, end='')
stop_after = time.time() + 20
while not os.path.exists(OPTIONS['--wait']) and time.time() < stop_after:
print('.', file=sys.stderr, end='')
sys.stderr.flush()
time.sleep(0.5)
print(' done') | [
"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.sin(dlon /2.0)**2
c = 2 * np.arcsin(np.sqrt(a))
return np.rad2deg(c) | [
"\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 :param lat2:\n :return:\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 = 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)) | [
"\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: array or float, latitude of second point(s)\n :return: angular distance(s) in degrees\n "
] |
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 law of cosines: https://en.wikipedia.org/wiki/Spherical_law_of_cosines#Rearrangements
numerator = np.atleast_1d( np.cos(c) - np.cos(a) * np.cos(b) )
denominator = np.atleast_1d( np.sin(a)*np.sin(b) )
return np.where( denominator == 0 , np.zeros( len(denominator)), np.rad2deg( np.arccos( numerator/denominator)) ) | [
"\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, 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: array or float, latitude of second point(s)\n :return: spherical angle in degrees\n "
] |
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)
yield
_WITH_MEMOIZATION = old_status
_CACHE_SIZE = old_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):
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 | [
"\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_inputs = [H0, q0, lambda_0]
for i, current_setting in enumerate(current_settings):
if user_inputs[i] is None:
# the user didn't modify this,
# so lets keep what was already set
user_inputs[i] = current_setting
# pass this to xspec
_xspec.set_xscosmo(*user_inputs) | [
"\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 none or the current setting (H_0, q_0, lambda_0)\n "
] |
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 documentation.")
# Expand all variables and other things like ~
headas_env = os.path.expandvars(os.path.expanduser(headas_env))
# Lazy check that it exists
assert os.path.exists(headas_env), "The HEADAS env. variable point to a non-existent directory: %s" % (headas_env)
# Get one directory above HEADAS (i.e., $HEADAS/..)
inferred_path = os.path.dirname(headas_env)
# Now model.dat should be in $HEADAS/../spectral/manager
final_path = os.path.join(inferred_path, 'spectral', 'manager', 'model.dat')
# Check that model.dat exists
assert os.path.exists(final_path), "Cannot find Xspec model definition file %s" % (final_path)
return os.path.abspath(final_path) | [
"\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 \r or \r\n with \n (the former two might be in the file if
# it originates from Windows)
if "\n" in model_dat:
model_dat = model_dat.replace("\r", "")
else:
model_dat = model_dat.replace("\r", "\n")
# Loop through the file and build the model definition
# dictionary
lines = model_dat.split("\n")
model_definitions = collections.OrderedDict()
for line in lines:
match = re.match('''(.+(add|mul|con|acn).+)''', line)
if match is not None:
# This is a model definition
tokens = line.split()
if len(tokens) == 7:
(model_name, n_parameters,
min_energy, max_energy,
library_function,
model_type,
flag) = line.split()
else:
(model_name, n_parameters,
min_energy, max_energy,
library_function,
model_type,
flag,
flag_2) = line.split()
this_model = collections.OrderedDict()
this_model['description'] = 'The %s model from XSpec (https://heasarc.gsfc.nasa.gov/xanadu/' \
'xspec/manual/XspecModels.html)' % model_name
this_model['parameters'] = collections.OrderedDict()
model_definitions[(model_name, library_function, model_type)] = this_model
else:
# This is a parameter definition
if len(line.split()) == 0:
# Empty line
continue
# Parameters are free by default, unless they have delta < 0
# they are switch parameters or scale parameters
free = True
if line[0] == '$':
# Probably a switch parameter
free = False
tokens = line.split()
if len(tokens) == 2:
par_name = tokens[0][1:]
default_value = tokens[1]
par_unit = ""
hard_minimum, soft_minimum, soft_maximum, hard_maximum = (0, 0, 1e9, 1e9)
elif len(tokens) == 3:
par_name = tokens[0][1:]
default_value = tokens[2]
par_unit = ""
hard_minimum, soft_minimum, soft_maximum, hard_maximum = (0, 0, 1e9, 1e9)
else:
match = re.match('(\S+)\s+(\".+\"|[a-zA-Z]+)?(.+)*', line[1:])
par_name, par_unit, par_spec = match.groups()
tokens = par_spec.split()
if len(tokens) == 1:
default_value = tokens[0]
par_unit = ""
hard_minimum, soft_minimum, soft_maximum, hard_maximum = (0, 0, 1e9, 1e9)
else:
par_unit = ""
(default_value,
hard_minimum, soft_minimum,
soft_maximum, hard_maximum,
delta) = par_spec.split()
else:
# A normal parameter
match = re.match('(\S+)\s+(\".+\"|\S+)(.+)', line)
if match is None:
raise RuntimeError("Cannot parse parameter %s" % line)
par_name, par_unit, par_spec = match.groups()
if par_name[0] == '*':
# Scale parameter (always frozen)
par_name = par_name[1:]
free = False
tokens = par_spec.split()
if len(tokens) == 1:
default_value = tokens[0]
(hard_minimum, soft_minimum,
soft_maximum, hard_maximum,
delta) = (None, None, None, None, 0.1)
else:
(default_value,
hard_minimum, soft_minimum,
soft_maximum, hard_maximum,
delta) = par_spec.split()
delta = abs(float(delta))
else:
(default_value,
hard_minimum, soft_minimum,
soft_maximum, hard_maximum,
delta) = par_spec.split()
delta = float(delta)
if delta <= 0:
free = False
delta = abs(delta)
# Now fix the parameter name removing illegal characters
# (for example 'log(A)' is not a legal name)
par_name = re.sub('[\(,\)]', '_', par_name)
par_name = re.sub('<', '_less_', par_name)
par_name = re.sub('>', '_more_', par_name)
par_name = re.sub('/', '_div_', par_name)
par_name = re.sub('\-', '_minus_', par_name)
par_name = re.sub('\+', '_plus_', par_name)
par_name = re.sub('\.', '_dot_', par_name)
par_name = re.sub('@', '_at_', par_name)
# Parameter names must be lower case
par_name = par_name.lower()
# Some parameters are enclosed between ", like "z"
par_name = par_name.replace('"', '')
# "z" is a protected name in astromodels.
if par_name == "z":
par_name = "redshift"
# Check that the parameter name is not an illegal Python name
if par_name in illegal_variable_names:
par_name = "xs_%s" % par_name
# Sometimes the unit is " " which is not recognized by astropy
if par_unit:
par_unit = par_unit.replace("\"",'')
# There are some errors in model.dat , like KeV instead of keV, and ergcm/s instead of erg cm /s
# Let's correct them
if par_unit == "KeV":
par_unit = "keV"
elif par_unit == "ergcm/s":
par_unit = "erg cm / s"
elif par_unit == "days":
par_unit = "day"
elif par_unit == "z" and par_name.lower() == "redshift":
par_unit = ""
# There are funny units in model.dat, like "Rs" (which means Schwarzschild radius) or other things
# so let's try to convert the par_unit into an astropy.Unit instance. If that fails, use a unitless unit
try:
_ = u.Unit(par_unit)
except ValueError:
# Unit not recognized
#warnings.warn("Unit %s is not recognized by astropy." % par_unit)
par_unit = ''
# Make sure that this is a valid python identifier
# by matching it with the relative regexp
if re.match('([a-zA-Z_][a-zA-Z0-9_]*)$', par_name) is None:
raise ValueError("Illegal identifier name %s" % (par_name))
this_model['parameters'][par_name] = {'initial value': float(default_value),
'desc': '(see https://heasarc.gsfc.nasa.gov/xanadu/xspec/manual/'
'XspecModels.html)',
'min': hard_minimum,
'max': hard_maximum,
'delta': float(delta),
'unit': par_unit,
'free': free}
return model_definitions | [
"\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 for multiple "
"sources" % source.name)
else: # pragma: no cover
raise
# Now see if this is a point or extended source, and add them to the
# appropriate dictionary
if source.source_type == POINT_SOURCE:
self._point_sources[source.name] = source
elif source.source_type == EXTENDED_SOURCE:
self._extended_sources[source.name] = source
elif source.source_type == PARTICLE_SOURCE:
self._particle_sources[source.name] = source
else: # pragma: no cover
raise InvalidInput("Input sources must be either a point source or an extended source") | [
"\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_sources.pop(source.name)
elif source.source_type == EXTENDED_SOURCE:
self._extended_sources.pop(source.name)
elif source.source_type == PARTICLE_SOURCE:
self._particle_sources.pop(source.name)
self._remove_child(source_name) | [
"\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.iteritems():
if parameter.free:
free_parameters_dictionary[parameter_name] = parameter
return free_parameters_dictionary | [
"\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.iteritems():
if parameter.has_auxiliary_variable():
linked_parameter_dictionary[parameter_name] = parameter
return linked_parameter_dictionary | [
"\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 law.\n\n :return: dictionary of linked parameters\n "
] |
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._add_child(variable)
# Add also to the list of independent variables
self._independent_variables[variable.name] = variable | [
"\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 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) | [
"\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
parameter_1_list = list(parameter_1)
for param_1 in parameter_1_list:
assert param_1.path in self, "Parameter %s is not contained in this model" % param_1.path
assert parameter_2.path in self, "Parameter %s is not contained in this model" % parameter_2.path
if link_function is None:
# Use the Line function by default, with both parameters fixed so that the two
# parameters to be linked will vary together
link_function = get_function('Line')
link_function.a.value = 1
link_function.a.fix = True
link_function.b.value = 0
link_function.b.fix = True
for param_1 in parameter_1_list:
param_1.add_auxiliary_variable(parameter_2, link_function)
# Now set the units of the link function
link_function.set_units(parameter_2.unit, param_1.unit) | [
"\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 :param link_function: a function instance. If not provided, the identity function will be used by default.\n Otherwise, this link will be set: parameter_1 = link_function(parameter_2)\n :return: (none)\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)
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) | [
"\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()
# Go back to default
self._complete_display = False | [
"\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' "
"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"
] |
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 will be the average flux for the source computed as the integral\n between a and b over the integration variable divided by (b-a). The integration variable must be an independent\n variable contained in the model. If b is None, then instead of integrating the integration variable will be\n set to a and the model evaluated in a.\n :return: fluxes\n "
] |
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\n :return: flux array\n "
] |
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:-(max_width-3)])
else:
return trial1
else:
return line | [
"\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():
if par.free:
return True
return False | [
"\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.path] = par
for par in self.position.parameters.values():
if par.free:
free_parameters[par.path] = par
return free_parameters | [
"\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.position.parameters.values():
all_parameters[par.path] = par
return all_parameters | [
"\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.