id int32 0 252k | repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 51 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 |
|---|---|---|---|---|---|---|---|---|---|---|---|
20,100 | Garee/pytodoist | pytodoist/todoist.py | User._update_notification_settings | def _update_notification_settings(self, event, service,
should_notify):
"""Update the settings of a an events notifications.
:param event: Update the notification settings of this event.
:type event: str
:param service: The notification service to update.
:type service: str
:param should_notify: Notify if this is ``1``.
:type should_notify: int
"""
response = API.update_notification_settings(self.api_token, event,
service, should_notify)
_fail_if_contains_errors(response) | python | def _update_notification_settings(self, event, service,
should_notify):
response = API.update_notification_settings(self.api_token, event,
service, should_notify)
_fail_if_contains_errors(response) | [
"def",
"_update_notification_settings",
"(",
"self",
",",
"event",
",",
"service",
",",
"should_notify",
")",
":",
"response",
"=",
"API",
".",
"update_notification_settings",
"(",
"self",
".",
"api_token",
",",
"event",
",",
"service",
",",
"should_notify",
")"... | Update the settings of a an events notifications.
:param event: Update the notification settings of this event.
:type event: str
:param service: The notification service to update.
:type service: str
:param should_notify: Notify if this is ``1``.
:type should_notify: int | [
"Update",
"the",
"settings",
"of",
"a",
"an",
"events",
"notifications",
"."
] | 3359cbff485ebdbbb4ffbd58d71e21a817874dd7 | https://github.com/Garee/pytodoist/blob/3359cbff485ebdbbb4ffbd58d71e21a817874dd7/pytodoist/todoist.py#L743-L756 |
20,101 | Garee/pytodoist | pytodoist/todoist.py | User.get_productivity_stats | def get_productivity_stats(self):
"""Return the user's productivity stats.
:return: A JSON-encoded representation of the user's productivity
stats.
:rtype: A JSON-encoded object.
>>> from pytodoist import todoist
>>> user = todoist.login('john.doe@gmail.com', 'password')
>>> stats = user.get_productivity_stats()
>>> print(stats)
{"karma_last_update": 50.0, "karma_trend": "up", ... }
"""
response = API.get_productivity_stats(self.api_token)
_fail_if_contains_errors(response)
return response.json() | python | def get_productivity_stats(self):
response = API.get_productivity_stats(self.api_token)
_fail_if_contains_errors(response)
return response.json() | [
"def",
"get_productivity_stats",
"(",
"self",
")",
":",
"response",
"=",
"API",
".",
"get_productivity_stats",
"(",
"self",
".",
"api_token",
")",
"_fail_if_contains_errors",
"(",
"response",
")",
"return",
"response",
".",
"json",
"(",
")"
] | Return the user's productivity stats.
:return: A JSON-encoded representation of the user's productivity
stats.
:rtype: A JSON-encoded object.
>>> from pytodoist import todoist
>>> user = todoist.login('john.doe@gmail.com', 'password')
>>> stats = user.get_productivity_stats()
>>> print(stats)
{"karma_last_update": 50.0, "karma_trend": "up", ... } | [
"Return",
"the",
"user",
"s",
"productivity",
"stats",
"."
] | 3359cbff485ebdbbb4ffbd58d71e21a817874dd7 | https://github.com/Garee/pytodoist/blob/3359cbff485ebdbbb4ffbd58d71e21a817874dd7/pytodoist/todoist.py#L806-L821 |
20,102 | Garee/pytodoist | pytodoist/todoist.py | User.delete | def delete(self, reason=None):
"""Delete the user's account from Todoist.
.. warning:: You cannot recover the user after deletion!
:param reason: The reason for deletion.
:type reason: str
>>> from pytodoist import todoist
>>> user = todoist.login('john.doe@gmail.com', 'password')
>>> user.delete()
... # The user token is now invalid and Todoist operations will fail.
"""
response = API.delete_user(self.api_token, self.password,
reason=reason, in_background=0)
_fail_if_contains_errors(response) | python | def delete(self, reason=None):
response = API.delete_user(self.api_token, self.password,
reason=reason, in_background=0)
_fail_if_contains_errors(response) | [
"def",
"delete",
"(",
"self",
",",
"reason",
"=",
"None",
")",
":",
"response",
"=",
"API",
".",
"delete_user",
"(",
"self",
".",
"api_token",
",",
"self",
".",
"password",
",",
"reason",
"=",
"reason",
",",
"in_background",
"=",
"0",
")",
"_fail_if_co... | Delete the user's account from Todoist.
.. warning:: You cannot recover the user after deletion!
:param reason: The reason for deletion.
:type reason: str
>>> from pytodoist import todoist
>>> user = todoist.login('john.doe@gmail.com', 'password')
>>> user.delete()
... # The user token is now invalid and Todoist operations will fail. | [
"Delete",
"the",
"user",
"s",
"account",
"from",
"Todoist",
"."
] | 3359cbff485ebdbbb4ffbd58d71e21a817874dd7 | https://github.com/Garee/pytodoist/blob/3359cbff485ebdbbb4ffbd58d71e21a817874dd7/pytodoist/todoist.py#L908-L923 |
20,103 | Garee/pytodoist | pytodoist/todoist.py | Project.archive | def archive(self):
"""Archive the project.
>>> from pytodoist import todoist
>>> user = todoist.login('john.doe@gmail.com', 'password')
>>> project = user.get_project('PyTodoist')
>>> project.archive()
"""
args = {'id': self.id}
_perform_command(self.owner, 'project_archive', args)
self.is_archived = '1' | python | def archive(self):
args = {'id': self.id}
_perform_command(self.owner, 'project_archive', args)
self.is_archived = '1' | [
"def",
"archive",
"(",
"self",
")",
":",
"args",
"=",
"{",
"'id'",
":",
"self",
".",
"id",
"}",
"_perform_command",
"(",
"self",
".",
"owner",
",",
"'project_archive'",
",",
"args",
")",
"self",
".",
"is_archived",
"=",
"'1'"
] | Archive the project.
>>> from pytodoist import todoist
>>> user = todoist.login('john.doe@gmail.com', 'password')
>>> project = user.get_project('PyTodoist')
>>> project.archive() | [
"Archive",
"the",
"project",
"."
] | 3359cbff485ebdbbb4ffbd58d71e21a817874dd7 | https://github.com/Garee/pytodoist/blob/3359cbff485ebdbbb4ffbd58d71e21a817874dd7/pytodoist/todoist.py#L982-L992 |
20,104 | Garee/pytodoist | pytodoist/todoist.py | Project.add_task | def add_task(self, content, date=None, priority=None):
"""Add a task to the project
:param content: The task description.
:type content: str
:param date: The task deadline.
:type date: str
:param priority: The priority of the task.
:type priority: int
:return: The added task.
:rtype: :class:`pytodoist.todoist.Task`
.. note:: See `here <https://todoist.com/Help/timeInsert>`_
for possible date strings.
>>> from pytodoist import todoist
>>> user = todoist.login('john.doe@gmail.com', 'password')
>>> project = user.get_project('PyTodoist')
>>> task = project.add_task('Install PyTodoist')
>>> print(task.content)
Install PyTodoist
"""
response = API.add_item(self.owner.token, content, project_id=self.id,
date_string=date, priority=priority)
_fail_if_contains_errors(response)
task_json = response.json()
return Task(task_json, self) | python | def add_task(self, content, date=None, priority=None):
response = API.add_item(self.owner.token, content, project_id=self.id,
date_string=date, priority=priority)
_fail_if_contains_errors(response)
task_json = response.json()
return Task(task_json, self) | [
"def",
"add_task",
"(",
"self",
",",
"content",
",",
"date",
"=",
"None",
",",
"priority",
"=",
"None",
")",
":",
"response",
"=",
"API",
".",
"add_item",
"(",
"self",
".",
"owner",
".",
"token",
",",
"content",
",",
"project_id",
"=",
"self",
".",
... | Add a task to the project
:param content: The task description.
:type content: str
:param date: The task deadline.
:type date: str
:param priority: The priority of the task.
:type priority: int
:return: The added task.
:rtype: :class:`pytodoist.todoist.Task`
.. note:: See `here <https://todoist.com/Help/timeInsert>`_
for possible date strings.
>>> from pytodoist import todoist
>>> user = todoist.login('john.doe@gmail.com', 'password')
>>> project = user.get_project('PyTodoist')
>>> task = project.add_task('Install PyTodoist')
>>> print(task.content)
Install PyTodoist | [
"Add",
"a",
"task",
"to",
"the",
"project"
] | 3359cbff485ebdbbb4ffbd58d71e21a817874dd7 | https://github.com/Garee/pytodoist/blob/3359cbff485ebdbbb4ffbd58d71e21a817874dd7/pytodoist/todoist.py#L1016-L1042 |
20,105 | Garee/pytodoist | pytodoist/todoist.py | Project.get_uncompleted_tasks | def get_uncompleted_tasks(self):
"""Return a list of all uncompleted tasks in this project.
.. warning:: Requires Todoist premium.
:return: A list of all uncompleted tasks in this project.
:rtype: list of :class:`pytodoist.todoist.Task`
>>> from pytodoist import todoist
>>> user = todoist.login('john.doe@gmail.com', 'password')
>>> project = user.get_project('PyTodoist')
>>> project.add_task('Install PyTodoist')
>>> uncompleted_tasks = project.get_uncompleted_tasks()
>>> for task in uncompleted_tasks:
... task.complete()
"""
all_tasks = self.get_tasks()
completed_tasks = self.get_completed_tasks()
return [t for t in all_tasks if t not in completed_tasks] | python | def get_uncompleted_tasks(self):
all_tasks = self.get_tasks()
completed_tasks = self.get_completed_tasks()
return [t for t in all_tasks if t not in completed_tasks] | [
"def",
"get_uncompleted_tasks",
"(",
"self",
")",
":",
"all_tasks",
"=",
"self",
".",
"get_tasks",
"(",
")",
"completed_tasks",
"=",
"self",
".",
"get_completed_tasks",
"(",
")",
"return",
"[",
"t",
"for",
"t",
"in",
"all_tasks",
"if",
"t",
"not",
"in",
... | Return a list of all uncompleted tasks in this project.
.. warning:: Requires Todoist premium.
:return: A list of all uncompleted tasks in this project.
:rtype: list of :class:`pytodoist.todoist.Task`
>>> from pytodoist import todoist
>>> user = todoist.login('john.doe@gmail.com', 'password')
>>> project = user.get_project('PyTodoist')
>>> project.add_task('Install PyTodoist')
>>> uncompleted_tasks = project.get_uncompleted_tasks()
>>> for task in uncompleted_tasks:
... task.complete() | [
"Return",
"a",
"list",
"of",
"all",
"uncompleted",
"tasks",
"in",
"this",
"project",
"."
] | 3359cbff485ebdbbb4ffbd58d71e21a817874dd7 | https://github.com/Garee/pytodoist/blob/3359cbff485ebdbbb4ffbd58d71e21a817874dd7/pytodoist/todoist.py#L1044-L1062 |
20,106 | Garee/pytodoist | pytodoist/todoist.py | Project.get_completed_tasks | def get_completed_tasks(self):
"""Return a list of all completed tasks in this project.
:return: A list of all completed tasks in this project.
:rtype: list of :class:`pytodoist.todoist.Task`
>>> from pytodoist import todoist
>>> user = todoist.login('john.doe@gmail.com', 'password')
>>> project = user.get_project('PyTodoist')
>>> task = project.add_task('Install PyTodoist')
>>> task.complete()
>>> completed_tasks = project.get_completed_tasks()
>>> for task in completed_tasks:
... task.uncomplete()
"""
self.owner.sync()
tasks = []
offset = 0
while True:
response = API.get_all_completed_tasks(self.owner.api_token,
limit=_PAGE_LIMIT,
offset=offset,
project_id=self.id)
_fail_if_contains_errors(response)
response_json = response.json()
tasks_json = response_json['items']
if len(tasks_json) == 0:
break # There are no more completed tasks to retreive.
for task_json in tasks_json:
project = self.owner.projects[task_json['project_id']]
tasks.append(Task(task_json, project))
offset += _PAGE_LIMIT
return tasks | python | def get_completed_tasks(self):
self.owner.sync()
tasks = []
offset = 0
while True:
response = API.get_all_completed_tasks(self.owner.api_token,
limit=_PAGE_LIMIT,
offset=offset,
project_id=self.id)
_fail_if_contains_errors(response)
response_json = response.json()
tasks_json = response_json['items']
if len(tasks_json) == 0:
break # There are no more completed tasks to retreive.
for task_json in tasks_json:
project = self.owner.projects[task_json['project_id']]
tasks.append(Task(task_json, project))
offset += _PAGE_LIMIT
return tasks | [
"def",
"get_completed_tasks",
"(",
"self",
")",
":",
"self",
".",
"owner",
".",
"sync",
"(",
")",
"tasks",
"=",
"[",
"]",
"offset",
"=",
"0",
"while",
"True",
":",
"response",
"=",
"API",
".",
"get_all_completed_tasks",
"(",
"self",
".",
"owner",
".",
... | Return a list of all completed tasks in this project.
:return: A list of all completed tasks in this project.
:rtype: list of :class:`pytodoist.todoist.Task`
>>> from pytodoist import todoist
>>> user = todoist.login('john.doe@gmail.com', 'password')
>>> project = user.get_project('PyTodoist')
>>> task = project.add_task('Install PyTodoist')
>>> task.complete()
>>> completed_tasks = project.get_completed_tasks()
>>> for task in completed_tasks:
... task.uncomplete() | [
"Return",
"a",
"list",
"of",
"all",
"completed",
"tasks",
"in",
"this",
"project",
"."
] | 3359cbff485ebdbbb4ffbd58d71e21a817874dd7 | https://github.com/Garee/pytodoist/blob/3359cbff485ebdbbb4ffbd58d71e21a817874dd7/pytodoist/todoist.py#L1064-L1096 |
20,107 | Garee/pytodoist | pytodoist/todoist.py | Project.get_tasks | def get_tasks(self):
"""Return all tasks in this project.
:return: A list of all tasks in this project.class
:rtype: list of :class:`pytodoist.todoist.Task`
>>> from pytodoist import todoist
>>> user = todoist.login('john.doe@gmail.com', 'password')
>>> project = user.get_project('PyTodoist')
>>> project.add_task('Install PyTodoist')
>>> project.add_task('Have fun!')
>>> tasks = project.get_tasks()
>>> for task in tasks:
... print(task.content)
Install PyTodoist
Have fun!
"""
self.owner.sync()
return [t for t in self.owner.tasks.values()
if t.project_id == self.id] | python | def get_tasks(self):
self.owner.sync()
return [t for t in self.owner.tasks.values()
if t.project_id == self.id] | [
"def",
"get_tasks",
"(",
"self",
")",
":",
"self",
".",
"owner",
".",
"sync",
"(",
")",
"return",
"[",
"t",
"for",
"t",
"in",
"self",
".",
"owner",
".",
"tasks",
".",
"values",
"(",
")",
"if",
"t",
".",
"project_id",
"==",
"self",
".",
"id",
"]... | Return all tasks in this project.
:return: A list of all tasks in this project.class
:rtype: list of :class:`pytodoist.todoist.Task`
>>> from pytodoist import todoist
>>> user = todoist.login('john.doe@gmail.com', 'password')
>>> project = user.get_project('PyTodoist')
>>> project.add_task('Install PyTodoist')
>>> project.add_task('Have fun!')
>>> tasks = project.get_tasks()
>>> for task in tasks:
... print(task.content)
Install PyTodoist
Have fun! | [
"Return",
"all",
"tasks",
"in",
"this",
"project",
"."
] | 3359cbff485ebdbbb4ffbd58d71e21a817874dd7 | https://github.com/Garee/pytodoist/blob/3359cbff485ebdbbb4ffbd58d71e21a817874dd7/pytodoist/todoist.py#L1098-L1117 |
20,108 | Garee/pytodoist | pytodoist/todoist.py | Project.add_note | def add_note(self, content):
"""Add a note to the project.
.. warning:: Requires Todoist premium.
:param content: The note content.
:type content: str
>>> from pytodoist import todoist
>>> user = todoist.login('john.doe@gmail.com', 'password')
>>> project = user.get_project('PyTodoist')
>>> project.add_note('Remember to update to the latest version.')
"""
args = {
'project_id': self.id,
'content': content
}
_perform_command(self.owner, 'note_add', args) | python | def add_note(self, content):
args = {
'project_id': self.id,
'content': content
}
_perform_command(self.owner, 'note_add', args) | [
"def",
"add_note",
"(",
"self",
",",
"content",
")",
":",
"args",
"=",
"{",
"'project_id'",
":",
"self",
".",
"id",
",",
"'content'",
":",
"content",
"}",
"_perform_command",
"(",
"self",
".",
"owner",
",",
"'note_add'",
",",
"args",
")"
] | Add a note to the project.
.. warning:: Requires Todoist premium.
:param content: The note content.
:type content: str
>>> from pytodoist import todoist
>>> user = todoist.login('john.doe@gmail.com', 'password')
>>> project = user.get_project('PyTodoist')
>>> project.add_note('Remember to update to the latest version.') | [
"Add",
"a",
"note",
"to",
"the",
"project",
"."
] | 3359cbff485ebdbbb4ffbd58d71e21a817874dd7 | https://github.com/Garee/pytodoist/blob/3359cbff485ebdbbb4ffbd58d71e21a817874dd7/pytodoist/todoist.py#L1119-L1136 |
20,109 | Garee/pytodoist | pytodoist/todoist.py | Project.get_notes | def get_notes(self):
"""Return a list of all of the project's notes.
:return: A list of notes.
:rtype: list of :class:`pytodoist.todoist.Note`
>>> from pytodoist import todoist
>>> user = todoist.login('john.doe@gmail.com', 'password')
>>> project = user.get_project('PyTodoist')
>>> notes = project.get_notes()
"""
self.owner.sync()
notes = self.owner.notes.values()
return [n for n in notes if n.project_id == self.id] | python | def get_notes(self):
self.owner.sync()
notes = self.owner.notes.values()
return [n for n in notes if n.project_id == self.id] | [
"def",
"get_notes",
"(",
"self",
")",
":",
"self",
".",
"owner",
".",
"sync",
"(",
")",
"notes",
"=",
"self",
".",
"owner",
".",
"notes",
".",
"values",
"(",
")",
"return",
"[",
"n",
"for",
"n",
"in",
"notes",
"if",
"n",
".",
"project_id",
"==",
... | Return a list of all of the project's notes.
:return: A list of notes.
:rtype: list of :class:`pytodoist.todoist.Note`
>>> from pytodoist import todoist
>>> user = todoist.login('john.doe@gmail.com', 'password')
>>> project = user.get_project('PyTodoist')
>>> notes = project.get_notes() | [
"Return",
"a",
"list",
"of",
"all",
"of",
"the",
"project",
"s",
"notes",
"."
] | 3359cbff485ebdbbb4ffbd58d71e21a817874dd7 | https://github.com/Garee/pytodoist/blob/3359cbff485ebdbbb4ffbd58d71e21a817874dd7/pytodoist/todoist.py#L1138-L1151 |
20,110 | Garee/pytodoist | pytodoist/todoist.py | Project.share | def share(self, email, message=None):
"""Share the project with another Todoist user.
:param email: The other user's email address.
:type email: str
:param message: Optional message to send with the invitation.
:type message: str
>>> from pytodoist import todoist
>>> user = todoist.login('john.doe@gmail.com', 'password')
>>> project = user.get_project('PyTodoist')
>>> project.share('jane.doe@gmail.com')
"""
args = {
'project_id': self.id,
'email': email,
'message': message
}
_perform_command(self.owner, 'share_project', args) | python | def share(self, email, message=None):
args = {
'project_id': self.id,
'email': email,
'message': message
}
_perform_command(self.owner, 'share_project', args) | [
"def",
"share",
"(",
"self",
",",
"email",
",",
"message",
"=",
"None",
")",
":",
"args",
"=",
"{",
"'project_id'",
":",
"self",
".",
"id",
",",
"'email'",
":",
"email",
",",
"'message'",
":",
"message",
"}",
"_perform_command",
"(",
"self",
".",
"ow... | Share the project with another Todoist user.
:param email: The other user's email address.
:type email: str
:param message: Optional message to send with the invitation.
:type message: str
>>> from pytodoist import todoist
>>> user = todoist.login('john.doe@gmail.com', 'password')
>>> project = user.get_project('PyTodoist')
>>> project.share('jane.doe@gmail.com') | [
"Share",
"the",
"project",
"with",
"another",
"Todoist",
"user",
"."
] | 3359cbff485ebdbbb4ffbd58d71e21a817874dd7 | https://github.com/Garee/pytodoist/blob/3359cbff485ebdbbb4ffbd58d71e21a817874dd7/pytodoist/todoist.py#L1153-L1171 |
20,111 | Garee/pytodoist | pytodoist/todoist.py | Project.delete_collaborator | def delete_collaborator(self, email):
"""Remove a collaborating user from the shared project.
:param email: The collaborator's email address.
:type email: str
>>> from pytodoist import todoist
>>> user = todoist.login('john.doe@gmail.com', 'password')
>>> project = user.get_project('PyTodoist')
>>> project.delete_collaborator('jane.doe@gmail.com')
"""
args = {
'project_id': self.id,
'email': email,
}
_perform_command(self.owner, 'delete_collaborator', args) | python | def delete_collaborator(self, email):
args = {
'project_id': self.id,
'email': email,
}
_perform_command(self.owner, 'delete_collaborator', args) | [
"def",
"delete_collaborator",
"(",
"self",
",",
"email",
")",
":",
"args",
"=",
"{",
"'project_id'",
":",
"self",
".",
"id",
",",
"'email'",
":",
"email",
",",
"}",
"_perform_command",
"(",
"self",
".",
"owner",
",",
"'delete_collaborator'",
",",
"args",
... | Remove a collaborating user from the shared project.
:param email: The collaborator's email address.
:type email: str
>>> from pytodoist import todoist
>>> user = todoist.login('john.doe@gmail.com', 'password')
>>> project = user.get_project('PyTodoist')
>>> project.delete_collaborator('jane.doe@gmail.com') | [
"Remove",
"a",
"collaborating",
"user",
"from",
"the",
"shared",
"project",
"."
] | 3359cbff485ebdbbb4ffbd58d71e21a817874dd7 | https://github.com/Garee/pytodoist/blob/3359cbff485ebdbbb4ffbd58d71e21a817874dd7/pytodoist/todoist.py#L1173-L1188 |
20,112 | Garee/pytodoist | pytodoist/todoist.py | Task.complete | def complete(self):
"""Mark the task complete.
>>> from pytodoist import todoist
>>> user = todoist.login('john.doe@gmail.com', 'password')
>>> project = user.get_project('PyTodoist')
>>> task = project.add_task('Install PyTodoist')
>>> task.complete()
"""
args = {
'id': self.id
}
_perform_command(self.project.owner, 'item_close', args) | python | def complete(self):
args = {
'id': self.id
}
_perform_command(self.project.owner, 'item_close', args) | [
"def",
"complete",
"(",
"self",
")",
":",
"args",
"=",
"{",
"'id'",
":",
"self",
".",
"id",
"}",
"_perform_command",
"(",
"self",
".",
"project",
".",
"owner",
",",
"'item_close'",
",",
"args",
")"
] | Mark the task complete.
>>> from pytodoist import todoist
>>> user = todoist.login('john.doe@gmail.com', 'password')
>>> project = user.get_project('PyTodoist')
>>> task = project.add_task('Install PyTodoist')
>>> task.complete() | [
"Mark",
"the",
"task",
"complete",
"."
] | 3359cbff485ebdbbb4ffbd58d71e21a817874dd7 | https://github.com/Garee/pytodoist/blob/3359cbff485ebdbbb4ffbd58d71e21a817874dd7/pytodoist/todoist.py#L1296-L1308 |
20,113 | Garee/pytodoist | pytodoist/todoist.py | Task.uncomplete | def uncomplete(self):
"""Mark the task uncomplete.
>>> from pytodoist import todoist
>>> user = todoist.login('john.doe@gmail.com', 'password')
>>> project = user.get_project('PyTodoist')
>>> task = project.add_task('Install PyTodoist')
>>> task.uncomplete()
"""
args = {
'project_id': self.project.id,
'ids': [self.id]
}
owner = self.project.owner
_perform_command(owner, 'item_uncomplete', args) | python | def uncomplete(self):
args = {
'project_id': self.project.id,
'ids': [self.id]
}
owner = self.project.owner
_perform_command(owner, 'item_uncomplete', args) | [
"def",
"uncomplete",
"(",
"self",
")",
":",
"args",
"=",
"{",
"'project_id'",
":",
"self",
".",
"project",
".",
"id",
",",
"'ids'",
":",
"[",
"self",
".",
"id",
"]",
"}",
"owner",
"=",
"self",
".",
"project",
".",
"owner",
"_perform_command",
"(",
... | Mark the task uncomplete.
>>> from pytodoist import todoist
>>> user = todoist.login('john.doe@gmail.com', 'password')
>>> project = user.get_project('PyTodoist')
>>> task = project.add_task('Install PyTodoist')
>>> task.uncomplete() | [
"Mark",
"the",
"task",
"uncomplete",
"."
] | 3359cbff485ebdbbb4ffbd58d71e21a817874dd7 | https://github.com/Garee/pytodoist/blob/3359cbff485ebdbbb4ffbd58d71e21a817874dd7/pytodoist/todoist.py#L1310-L1324 |
20,114 | Garee/pytodoist | pytodoist/todoist.py | Task.get_notes | def get_notes(self):
"""Return all notes attached to this Task.
:return: A list of all notes attached to this Task.
:rtype: list of :class:`pytodoist.todoist.Note`
>>> from pytodoist import todoist
>>> user = todoist.login('john.doe@gmail.com', 'password')
>>> project = user.get_project('PyTodoist')
>>> task = project.add_task('Install PyTodoist.')
>>> task.add_note('https://pypi.python.org/pypi')
>>> notes = task.get_notes()
>>> print(len(notes))
1
"""
owner = self.project.owner
owner.sync()
return [n for n in owner.notes.values() if n.item_id == self.id] | python | def get_notes(self):
owner = self.project.owner
owner.sync()
return [n for n in owner.notes.values() if n.item_id == self.id] | [
"def",
"get_notes",
"(",
"self",
")",
":",
"owner",
"=",
"self",
".",
"project",
".",
"owner",
"owner",
".",
"sync",
"(",
")",
"return",
"[",
"n",
"for",
"n",
"in",
"owner",
".",
"notes",
".",
"values",
"(",
")",
"if",
"n",
".",
"item_id",
"==",
... | Return all notes attached to this Task.
:return: A list of all notes attached to this Task.
:rtype: list of :class:`pytodoist.todoist.Note`
>>> from pytodoist import todoist
>>> user = todoist.login('john.doe@gmail.com', 'password')
>>> project = user.get_project('PyTodoist')
>>> task = project.add_task('Install PyTodoist.')
>>> task.add_note('https://pypi.python.org/pypi')
>>> notes = task.get_notes()
>>> print(len(notes))
1 | [
"Return",
"all",
"notes",
"attached",
"to",
"this",
"Task",
"."
] | 3359cbff485ebdbbb4ffbd58d71e21a817874dd7 | https://github.com/Garee/pytodoist/blob/3359cbff485ebdbbb4ffbd58d71e21a817874dd7/pytodoist/todoist.py#L1350-L1367 |
20,115 | Garee/pytodoist | pytodoist/todoist.py | Task.move | def move(self, project):
"""Move this task to another project.
:param project: The project to move the task to.
:type project: :class:`pytodoist.todoist.Project`
>>> from pytodoist import todoist
>>> user = todoist.login('john.doe@gmail.com', 'password')
>>> project = user.get_project('PyTodoist')
>>> task = project.add_task('Install PyTodoist')
>>> print(task.project.name)
PyTodoist
>>> inbox = user.get_project('Inbox')
>>> task.move(inbox)
>>> print(task.project.name)
Inbox
"""
args = {
'project_items': {self.project.id: [self.id]},
'to_project': project.id
}
_perform_command(self.project.owner, 'item_move', args)
self.project = project | python | def move(self, project):
args = {
'project_items': {self.project.id: [self.id]},
'to_project': project.id
}
_perform_command(self.project.owner, 'item_move', args)
self.project = project | [
"def",
"move",
"(",
"self",
",",
"project",
")",
":",
"args",
"=",
"{",
"'project_items'",
":",
"{",
"self",
".",
"project",
".",
"id",
":",
"[",
"self",
".",
"id",
"]",
"}",
",",
"'to_project'",
":",
"project",
".",
"id",
"}",
"_perform_command",
... | Move this task to another project.
:param project: The project to move the task to.
:type project: :class:`pytodoist.todoist.Project`
>>> from pytodoist import todoist
>>> user = todoist.login('john.doe@gmail.com', 'password')
>>> project = user.get_project('PyTodoist')
>>> task = project.add_task('Install PyTodoist')
>>> print(task.project.name)
PyTodoist
>>> inbox = user.get_project('Inbox')
>>> task.move(inbox)
>>> print(task.project.name)
Inbox | [
"Move",
"this",
"task",
"to",
"another",
"project",
"."
] | 3359cbff485ebdbbb4ffbd58d71e21a817874dd7 | https://github.com/Garee/pytodoist/blob/3359cbff485ebdbbb4ffbd58d71e21a817874dd7/pytodoist/todoist.py#L1369-L1391 |
20,116 | Garee/pytodoist | pytodoist/todoist.py | Task.add_date_reminder | def add_date_reminder(self, service, due_date):
"""Add a reminder to the task which activates on a given date.
.. warning:: Requires Todoist premium.
:param service: ```email```, ```sms``` or ```push``` for mobile.
:type service: str
:param due_date: The due date in UTC, formatted as
```YYYY-MM-DDTHH:MM```
:type due_date: str
>>> from pytodoist import todoist
>>> user = todoist.login('john.doe@gmail.com', 'password')
>>> project = user.get_project('PyTodoist')
>>> task = project.add_task('Install PyTodoist')
>>> task.add_date_reminder('email', '2015-12-01T09:00')
"""
args = {
'item_id': self.id,
'service': service,
'type': 'absolute',
'due_date_utc': due_date
}
_perform_command(self.project.owner, 'reminder_add', args) | python | def add_date_reminder(self, service, due_date):
args = {
'item_id': self.id,
'service': service,
'type': 'absolute',
'due_date_utc': due_date
}
_perform_command(self.project.owner, 'reminder_add', args) | [
"def",
"add_date_reminder",
"(",
"self",
",",
"service",
",",
"due_date",
")",
":",
"args",
"=",
"{",
"'item_id'",
":",
"self",
".",
"id",
",",
"'service'",
":",
"service",
",",
"'type'",
":",
"'absolute'",
",",
"'due_date_utc'",
":",
"due_date",
"}",
"_... | Add a reminder to the task which activates on a given date.
.. warning:: Requires Todoist premium.
:param service: ```email```, ```sms``` or ```push``` for mobile.
:type service: str
:param due_date: The due date in UTC, formatted as
```YYYY-MM-DDTHH:MM```
:type due_date: str
>>> from pytodoist import todoist
>>> user = todoist.login('john.doe@gmail.com', 'password')
>>> project = user.get_project('PyTodoist')
>>> task = project.add_task('Install PyTodoist')
>>> task.add_date_reminder('email', '2015-12-01T09:00') | [
"Add",
"a",
"reminder",
"to",
"the",
"task",
"which",
"activates",
"on",
"a",
"given",
"date",
"."
] | 3359cbff485ebdbbb4ffbd58d71e21a817874dd7 | https://github.com/Garee/pytodoist/blob/3359cbff485ebdbbb4ffbd58d71e21a817874dd7/pytodoist/todoist.py#L1393-L1416 |
20,117 | Garee/pytodoist | pytodoist/todoist.py | Task.add_location_reminder | def add_location_reminder(self, service, name, lat, long, trigger, radius):
"""Add a reminder to the task which activates on at a given location.
.. warning:: Requires Todoist premium.
:param service: ```email```, ```sms``` or ```push``` for mobile.
:type service: str
:param name: An alias for the location.
:type name: str
:param lat: The location latitude.
:type lat: float
:param long: The location longitude.
:type long: float
:param trigger: ```on_enter``` or ```on_leave```.
:type trigger: str
:param radius: The radius around the location that is still considered
the location.
:type radius: float
>>> from pytodoist import todoist
>>> user = todoist.login('john.doe@gmail.com', 'password')
>>> project = user.get_project('PyTodoist')
>>> task = project.add_task('Install PyTodoist')
>>> task.add_location_reminder('email', 'Leave Glasgow',
... 55.8580, 4.2590, 'on_leave', 100)
"""
args = {
'item_id': self.id,
'service': service,
'type': 'location',
'name': name,
'loc_lat': str(lat),
'loc_long': str(long),
'loc_trigger': trigger,
'radius': radius
}
_perform_command(self.project.owner, 'reminder_add', args) | python | def add_location_reminder(self, service, name, lat, long, trigger, radius):
args = {
'item_id': self.id,
'service': service,
'type': 'location',
'name': name,
'loc_lat': str(lat),
'loc_long': str(long),
'loc_trigger': trigger,
'radius': radius
}
_perform_command(self.project.owner, 'reminder_add', args) | [
"def",
"add_location_reminder",
"(",
"self",
",",
"service",
",",
"name",
",",
"lat",
",",
"long",
",",
"trigger",
",",
"radius",
")",
":",
"args",
"=",
"{",
"'item_id'",
":",
"self",
".",
"id",
",",
"'service'",
":",
"service",
",",
"'type'",
":",
"... | Add a reminder to the task which activates on at a given location.
.. warning:: Requires Todoist premium.
:param service: ```email```, ```sms``` or ```push``` for mobile.
:type service: str
:param name: An alias for the location.
:type name: str
:param lat: The location latitude.
:type lat: float
:param long: The location longitude.
:type long: float
:param trigger: ```on_enter``` or ```on_leave```.
:type trigger: str
:param radius: The radius around the location that is still considered
the location.
:type radius: float
>>> from pytodoist import todoist
>>> user = todoist.login('john.doe@gmail.com', 'password')
>>> project = user.get_project('PyTodoist')
>>> task = project.add_task('Install PyTodoist')
>>> task.add_location_reminder('email', 'Leave Glasgow',
... 55.8580, 4.2590, 'on_leave', 100) | [
"Add",
"a",
"reminder",
"to",
"the",
"task",
"which",
"activates",
"on",
"at",
"a",
"given",
"location",
"."
] | 3359cbff485ebdbbb4ffbd58d71e21a817874dd7 | https://github.com/Garee/pytodoist/blob/3359cbff485ebdbbb4ffbd58d71e21a817874dd7/pytodoist/todoist.py#L1418-L1454 |
20,118 | Garee/pytodoist | pytodoist/todoist.py | Task.get_reminders | def get_reminders(self):
"""Return a list of the task's reminders.
>>> from pytodoist import todoist
>>> user = todoist.login('john.doe@gmail.com', 'password')
>>> project = user.get_project('PyTodoist')
>>> task = project.add_task('Install PyTodoist')
>>> task.add_date_reminder('email', '2015-12-01T09:00')
>>> reminders = task.get_reminders()
"""
owner = self.project.owner
return [r for r in owner.get_reminders() if r.task.id == self.id] | python | def get_reminders(self):
owner = self.project.owner
return [r for r in owner.get_reminders() if r.task.id == self.id] | [
"def",
"get_reminders",
"(",
"self",
")",
":",
"owner",
"=",
"self",
".",
"project",
".",
"owner",
"return",
"[",
"r",
"for",
"r",
"in",
"owner",
".",
"get_reminders",
"(",
")",
"if",
"r",
".",
"task",
".",
"id",
"==",
"self",
".",
"id",
"]"
] | Return a list of the task's reminders.
>>> from pytodoist import todoist
>>> user = todoist.login('john.doe@gmail.com', 'password')
>>> project = user.get_project('PyTodoist')
>>> task = project.add_task('Install PyTodoist')
>>> task.add_date_reminder('email', '2015-12-01T09:00')
>>> reminders = task.get_reminders() | [
"Return",
"a",
"list",
"of",
"the",
"task",
"s",
"reminders",
"."
] | 3359cbff485ebdbbb4ffbd58d71e21a817874dd7 | https://github.com/Garee/pytodoist/blob/3359cbff485ebdbbb4ffbd58d71e21a817874dd7/pytodoist/todoist.py#L1456-L1467 |
20,119 | Garee/pytodoist | pytodoist/todoist.py | Task.delete | def delete(self):
"""Delete the task.
>>> from pytodoist import todoist
>>> user = todoist.login('john.doe@gmail.com', 'password')
>>> project = user.get_project('Homework')
>>> task = project.add_task('Read Chapter 4')
>>> task.delete()
"""
args = {'ids': [self.id]}
_perform_command(self.project.owner, 'item_delete', args)
del self.project.owner.tasks[self.id] | python | def delete(self):
args = {'ids': [self.id]}
_perform_command(self.project.owner, 'item_delete', args)
del self.project.owner.tasks[self.id] | [
"def",
"delete",
"(",
"self",
")",
":",
"args",
"=",
"{",
"'ids'",
":",
"[",
"self",
".",
"id",
"]",
"}",
"_perform_command",
"(",
"self",
".",
"project",
".",
"owner",
",",
"'item_delete'",
",",
"args",
")",
"del",
"self",
".",
"project",
".",
"ow... | Delete the task.
>>> from pytodoist import todoist
>>> user = todoist.login('john.doe@gmail.com', 'password')
>>> project = user.get_project('Homework')
>>> task = project.add_task('Read Chapter 4')
>>> task.delete() | [
"Delete",
"the",
"task",
"."
] | 3359cbff485ebdbbb4ffbd58d71e21a817874dd7 | https://github.com/Garee/pytodoist/blob/3359cbff485ebdbbb4ffbd58d71e21a817874dd7/pytodoist/todoist.py#L1469-L1480 |
20,120 | Garee/pytodoist | pytodoist/todoist.py | Note.delete | def delete(self):
"""Delete the note, removing it from it's task.
>>> from pytodoist import todoist
>>> user = todoist.login('john.doe@gmail.com', 'password')
>>> project = user.get_project('PyTodoist')
>>> task = project.add_task('Install PyTodoist.')
>>> note = task.add_note('https://pypi.python.org/pypi')
>>> note.delete()
>>> notes = task.get_notes()
>>> print(len(notes))
0
"""
args = {'id': self.id}
owner = self.task.project.owner
_perform_command(owner, 'note_delete', args) | python | def delete(self):
args = {'id': self.id}
owner = self.task.project.owner
_perform_command(owner, 'note_delete', args) | [
"def",
"delete",
"(",
"self",
")",
":",
"args",
"=",
"{",
"'id'",
":",
"self",
".",
"id",
"}",
"owner",
"=",
"self",
".",
"task",
".",
"project",
".",
"owner",
"_perform_command",
"(",
"owner",
",",
"'note_delete'",
",",
"args",
")"
] | Delete the note, removing it from it's task.
>>> from pytodoist import todoist
>>> user = todoist.login('john.doe@gmail.com', 'password')
>>> project = user.get_project('PyTodoist')
>>> task = project.add_task('Install PyTodoist.')
>>> note = task.add_note('https://pypi.python.org/pypi')
>>> note.delete()
>>> notes = task.get_notes()
>>> print(len(notes))
0 | [
"Delete",
"the",
"note",
"removing",
"it",
"from",
"it",
"s",
"task",
"."
] | 3359cbff485ebdbbb4ffbd58d71e21a817874dd7 | https://github.com/Garee/pytodoist/blob/3359cbff485ebdbbb4ffbd58d71e21a817874dd7/pytodoist/todoist.py#L1535-L1550 |
20,121 | Garee/pytodoist | pytodoist/todoist.py | Filter.update | def update(self):
"""Update the filter's details on Todoist.
You must call this method to register any local attribute changes with
Todoist.
>>> from pytodoist import todoist
>>> user = todoist.login('john.doe@gmail.com', 'password')
>>> overdue_filter = user.add_filter('Overdue', todoist.Query.OVERDUE)
>>> overdue_filter.name = 'OVERDUE!'
... # At this point Todoist still thinks the name is 'Overdue'.
>>> overdue_filter.update()
... # Now the name has been updated on Todoist.
"""
args = {attr: getattr(self, attr) for attr in self.to_update}
args['id'] = self.id
_perform_command(self.owner, 'filter_update', args) | python | def update(self):
args = {attr: getattr(self, attr) for attr in self.to_update}
args['id'] = self.id
_perform_command(self.owner, 'filter_update', args) | [
"def",
"update",
"(",
"self",
")",
":",
"args",
"=",
"{",
"attr",
":",
"getattr",
"(",
"self",
",",
"attr",
")",
"for",
"attr",
"in",
"self",
".",
"to_update",
"}",
"args",
"[",
"'id'",
"]",
"=",
"self",
".",
"id",
"_perform_command",
"(",
"self",
... | Update the filter's details on Todoist.
You must call this method to register any local attribute changes with
Todoist.
>>> from pytodoist import todoist
>>> user = todoist.login('john.doe@gmail.com', 'password')
>>> overdue_filter = user.add_filter('Overdue', todoist.Query.OVERDUE)
>>> overdue_filter.name = 'OVERDUE!'
... # At this point Todoist still thinks the name is 'Overdue'.
>>> overdue_filter.update()
... # Now the name has been updated on Todoist. | [
"Update",
"the",
"filter",
"s",
"details",
"on",
"Todoist",
"."
] | 3359cbff485ebdbbb4ffbd58d71e21a817874dd7 | https://github.com/Garee/pytodoist/blob/3359cbff485ebdbbb4ffbd58d71e21a817874dd7/pytodoist/todoist.py#L1634-L1650 |
20,122 | Robpol86/colorclass | colorclass/core.py | apply_text | def apply_text(incoming, func):
"""Call `func` on text portions of incoming color string.
:param iter incoming: Incoming string/ColorStr/string-like object to iterate.
:param func: Function to call with string portion as first and only parameter.
:return: Modified string, same class type as incoming string.
"""
split = RE_SPLIT.split(incoming)
for i, item in enumerate(split):
if not item or RE_SPLIT.match(item):
continue
split[i] = func(item)
return incoming.__class__().join(split) | python | def apply_text(incoming, func):
split = RE_SPLIT.split(incoming)
for i, item in enumerate(split):
if not item or RE_SPLIT.match(item):
continue
split[i] = func(item)
return incoming.__class__().join(split) | [
"def",
"apply_text",
"(",
"incoming",
",",
"func",
")",
":",
"split",
"=",
"RE_SPLIT",
".",
"split",
"(",
"incoming",
")",
"for",
"i",
",",
"item",
"in",
"enumerate",
"(",
"split",
")",
":",
"if",
"not",
"item",
"or",
"RE_SPLIT",
".",
"match",
"(",
... | Call `func` on text portions of incoming color string.
:param iter incoming: Incoming string/ColorStr/string-like object to iterate.
:param func: Function to call with string portion as first and only parameter.
:return: Modified string, same class type as incoming string. | [
"Call",
"func",
"on",
"text",
"portions",
"of",
"incoming",
"color",
"string",
"."
] | 692e2d6f5ad470b6221c8cb9641970dc5563a572 | https://github.com/Robpol86/colorclass/blob/692e2d6f5ad470b6221c8cb9641970dc5563a572/colorclass/core.py#L10-L23 |
20,123 | Robpol86/colorclass | colorclass/core.py | ColorBytes.decode | def decode(self, encoding='utf-8', errors='strict'):
"""Decode using the codec registered for encoding. Default encoding is 'utf-8'.
errors may be given to set a different error handling scheme. Default is 'strict' meaning that encoding errors
raise a UnicodeDecodeError. Other possible values are 'ignore' and 'replace' as well as any other name
registered with codecs.register_error that is able to handle UnicodeDecodeErrors.
:param str encoding: Codec.
:param str errors: Error handling scheme.
"""
original_class = getattr(self, 'original_class')
return original_class(super(ColorBytes, self).decode(encoding, errors)) | python | def decode(self, encoding='utf-8', errors='strict'):
original_class = getattr(self, 'original_class')
return original_class(super(ColorBytes, self).decode(encoding, errors)) | [
"def",
"decode",
"(",
"self",
",",
"encoding",
"=",
"'utf-8'",
",",
"errors",
"=",
"'strict'",
")",
":",
"original_class",
"=",
"getattr",
"(",
"self",
",",
"'original_class'",
")",
"return",
"original_class",
"(",
"super",
"(",
"ColorBytes",
",",
"self",
... | Decode using the codec registered for encoding. Default encoding is 'utf-8'.
errors may be given to set a different error handling scheme. Default is 'strict' meaning that encoding errors
raise a UnicodeDecodeError. Other possible values are 'ignore' and 'replace' as well as any other name
registered with codecs.register_error that is able to handle UnicodeDecodeErrors.
:param str encoding: Codec.
:param str errors: Error handling scheme. | [
"Decode",
"using",
"the",
"codec",
"registered",
"for",
"encoding",
".",
"Default",
"encoding",
"is",
"utf",
"-",
"8",
"."
] | 692e2d6f5ad470b6221c8cb9641970dc5563a572 | https://github.com/Robpol86/colorclass/blob/692e2d6f5ad470b6221c8cb9641970dc5563a572/colorclass/core.py#L37-L48 |
20,124 | Robpol86/colorclass | colorclass/core.py | ColorStr.center | def center(self, width, fillchar=None):
"""Return centered in a string of length width. Padding is done using the specified fill character or space.
:param int width: Length of output string.
:param str fillchar: Use this character instead of spaces.
"""
if fillchar is not None:
result = self.value_no_colors.center(width, fillchar)
else:
result = self.value_no_colors.center(width)
return self.__class__(result.replace(self.value_no_colors, self.value_colors), keep_tags=True) | python | def center(self, width, fillchar=None):
if fillchar is not None:
result = self.value_no_colors.center(width, fillchar)
else:
result = self.value_no_colors.center(width)
return self.__class__(result.replace(self.value_no_colors, self.value_colors), keep_tags=True) | [
"def",
"center",
"(",
"self",
",",
"width",
",",
"fillchar",
"=",
"None",
")",
":",
"if",
"fillchar",
"is",
"not",
"None",
":",
"result",
"=",
"self",
".",
"value_no_colors",
".",
"center",
"(",
"width",
",",
"fillchar",
")",
"else",
":",
"result",
"... | Return centered in a string of length width. Padding is done using the specified fill character or space.
:param int width: Length of output string.
:param str fillchar: Use this character instead of spaces. | [
"Return",
"centered",
"in",
"a",
"string",
"of",
"length",
"width",
".",
"Padding",
"is",
"done",
"using",
"the",
"specified",
"fill",
"character",
"or",
"space",
"."
] | 692e2d6f5ad470b6221c8cb9641970dc5563a572 | https://github.com/Robpol86/colorclass/blob/692e2d6f5ad470b6221c8cb9641970dc5563a572/colorclass/core.py#L111-L121 |
20,125 | Robpol86/colorclass | colorclass/core.py | ColorStr.endswith | def endswith(self, suffix, start=0, end=None):
"""Return True if ends with the specified suffix, False otherwise.
With optional start, test beginning at that position. With optional end, stop comparing at that position.
suffix can also be a tuple of strings to try.
:param str suffix: Suffix to search.
:param int start: Beginning position.
:param int end: Stop comparison at this position.
"""
args = [suffix, start] + ([] if end is None else [end])
return self.value_no_colors.endswith(*args) | python | def endswith(self, suffix, start=0, end=None):
args = [suffix, start] + ([] if end is None else [end])
return self.value_no_colors.endswith(*args) | [
"def",
"endswith",
"(",
"self",
",",
"suffix",
",",
"start",
"=",
"0",
",",
"end",
"=",
"None",
")",
":",
"args",
"=",
"[",
"suffix",
",",
"start",
"]",
"+",
"(",
"[",
"]",
"if",
"end",
"is",
"None",
"else",
"[",
"end",
"]",
")",
"return",
"s... | Return True if ends with the specified suffix, False otherwise.
With optional start, test beginning at that position. With optional end, stop comparing at that position.
suffix can also be a tuple of strings to try.
:param str suffix: Suffix to search.
:param int start: Beginning position.
:param int end: Stop comparison at this position. | [
"Return",
"True",
"if",
"ends",
"with",
"the",
"specified",
"suffix",
"False",
"otherwise",
"."
] | 692e2d6f5ad470b6221c8cb9641970dc5563a572 | https://github.com/Robpol86/colorclass/blob/692e2d6f5ad470b6221c8cb9641970dc5563a572/colorclass/core.py#L134-L145 |
20,126 | Robpol86/colorclass | colorclass/core.py | ColorStr.encode | def encode(self, encoding=None, errors='strict'):
"""Encode using the codec registered for encoding. encoding defaults to the default encoding.
errors may be given to set a different error handling scheme. Default is 'strict' meaning that encoding errors
raise a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and 'xmlcharrefreplace' as well as any
other name registered with codecs.register_error that is able to handle UnicodeEncodeErrors.
:param str encoding: Codec.
:param str errors: Error handling scheme.
"""
return ColorBytes(super(ColorStr, self).encode(encoding, errors), original_class=self.__class__) | python | def encode(self, encoding=None, errors='strict'):
return ColorBytes(super(ColorStr, self).encode(encoding, errors), original_class=self.__class__) | [
"def",
"encode",
"(",
"self",
",",
"encoding",
"=",
"None",
",",
"errors",
"=",
"'strict'",
")",
":",
"return",
"ColorBytes",
"(",
"super",
"(",
"ColorStr",
",",
"self",
")",
".",
"encode",
"(",
"encoding",
",",
"errors",
")",
",",
"original_class",
"=... | Encode using the codec registered for encoding. encoding defaults to the default encoding.
errors may be given to set a different error handling scheme. Default is 'strict' meaning that encoding errors
raise a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and 'xmlcharrefreplace' as well as any
other name registered with codecs.register_error that is able to handle UnicodeEncodeErrors.
:param str encoding: Codec.
:param str errors: Error handling scheme. | [
"Encode",
"using",
"the",
"codec",
"registered",
"for",
"encoding",
".",
"encoding",
"defaults",
"to",
"the",
"default",
"encoding",
"."
] | 692e2d6f5ad470b6221c8cb9641970dc5563a572 | https://github.com/Robpol86/colorclass/blob/692e2d6f5ad470b6221c8cb9641970dc5563a572/colorclass/core.py#L147-L157 |
20,127 | Robpol86/colorclass | colorclass/core.py | ColorStr.decode | def decode(self, encoding=None, errors='strict'):
"""Decode using the codec registered for encoding. encoding defaults to the default encoding.
errors may be given to set a different error handling scheme. Default is 'strict' meaning that encoding errors
raise a UnicodeDecodeError. Other possible values are 'ignore' and 'replace' as well as any other name
registered with codecs.register_error that is able to handle UnicodeDecodeErrors.
:param str encoding: Codec.
:param str errors: Error handling scheme.
"""
return self.__class__(super(ColorStr, self).decode(encoding, errors), keep_tags=True) | python | def decode(self, encoding=None, errors='strict'):
return self.__class__(super(ColorStr, self).decode(encoding, errors), keep_tags=True) | [
"def",
"decode",
"(",
"self",
",",
"encoding",
"=",
"None",
",",
"errors",
"=",
"'strict'",
")",
":",
"return",
"self",
".",
"__class__",
"(",
"super",
"(",
"ColorStr",
",",
"self",
")",
".",
"decode",
"(",
"encoding",
",",
"errors",
")",
",",
"keep_... | Decode using the codec registered for encoding. encoding defaults to the default encoding.
errors may be given to set a different error handling scheme. Default is 'strict' meaning that encoding errors
raise a UnicodeDecodeError. Other possible values are 'ignore' and 'replace' as well as any other name
registered with codecs.register_error that is able to handle UnicodeDecodeErrors.
:param str encoding: Codec.
:param str errors: Error handling scheme. | [
"Decode",
"using",
"the",
"codec",
"registered",
"for",
"encoding",
".",
"encoding",
"defaults",
"to",
"the",
"default",
"encoding",
"."
] | 692e2d6f5ad470b6221c8cb9641970dc5563a572 | https://github.com/Robpol86/colorclass/blob/692e2d6f5ad470b6221c8cb9641970dc5563a572/colorclass/core.py#L159-L169 |
20,128 | Robpol86/colorclass | colorclass/core.py | ColorStr.format | def format(self, *args, **kwargs):
"""Return a formatted version, using substitutions from args and kwargs.
The substitutions are identified by braces ('{' and '}').
"""
return self.__class__(super(ColorStr, self).format(*args, **kwargs), keep_tags=True) | python | def format(self, *args, **kwargs):
return self.__class__(super(ColorStr, self).format(*args, **kwargs), keep_tags=True) | [
"def",
"format",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"__class__",
"(",
"super",
"(",
"ColorStr",
",",
"self",
")",
".",
"format",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
",",
"keep_tags... | Return a formatted version, using substitutions from args and kwargs.
The substitutions are identified by braces ('{' and '}'). | [
"Return",
"a",
"formatted",
"version",
"using",
"substitutions",
"from",
"args",
"and",
"kwargs",
"."
] | 692e2d6f5ad470b6221c8cb9641970dc5563a572 | https://github.com/Robpol86/colorclass/blob/692e2d6f5ad470b6221c8cb9641970dc5563a572/colorclass/core.py#L182-L187 |
20,129 | Robpol86/colorclass | colorclass/core.py | ColorStr.join | def join(self, iterable):
"""Return a string which is the concatenation of the strings in the iterable.
:param iterable: Join items in this iterable.
"""
return self.__class__(super(ColorStr, self).join(iterable), keep_tags=True) | python | def join(self, iterable):
return self.__class__(super(ColorStr, self).join(iterable), keep_tags=True) | [
"def",
"join",
"(",
"self",
",",
"iterable",
")",
":",
"return",
"self",
".",
"__class__",
"(",
"super",
"(",
"ColorStr",
",",
"self",
")",
".",
"join",
"(",
"iterable",
")",
",",
"keep_tags",
"=",
"True",
")"
] | Return a string which is the concatenation of the strings in the iterable.
:param iterable: Join items in this iterable. | [
"Return",
"a",
"string",
"which",
"is",
"the",
"concatenation",
"of",
"the",
"strings",
"in",
"the",
"iterable",
"."
] | 692e2d6f5ad470b6221c8cb9641970dc5563a572 | https://github.com/Robpol86/colorclass/blob/692e2d6f5ad470b6221c8cb9641970dc5563a572/colorclass/core.py#L234-L239 |
20,130 | Robpol86/colorclass | colorclass/core.py | ColorStr.splitlines | def splitlines(self, keepends=False):
"""Return a list of the lines in the string, breaking at line boundaries.
Line breaks are not included in the resulting list unless keepends is given and True.
:param bool keepends: Include linebreaks.
"""
return [self.__class__(l) for l in self.value_colors.splitlines(keepends)] | python | def splitlines(self, keepends=False):
return [self.__class__(l) for l in self.value_colors.splitlines(keepends)] | [
"def",
"splitlines",
"(",
"self",
",",
"keepends",
"=",
"False",
")",
":",
"return",
"[",
"self",
".",
"__class__",
"(",
"l",
")",
"for",
"l",
"in",
"self",
".",
"value_colors",
".",
"splitlines",
"(",
"keepends",
")",
"]"
] | Return a list of the lines in the string, breaking at line boundaries.
Line breaks are not included in the resulting list unless keepends is given and True.
:param bool keepends: Include linebreaks. | [
"Return",
"a",
"list",
"of",
"the",
"lines",
"in",
"the",
"string",
"breaking",
"at",
"line",
"boundaries",
"."
] | 692e2d6f5ad470b6221c8cb9641970dc5563a572 | https://github.com/Robpol86/colorclass/blob/692e2d6f5ad470b6221c8cb9641970dc5563a572/colorclass/core.py#L285-L292 |
20,131 | Robpol86/colorclass | colorclass/core.py | ColorStr.startswith | def startswith(self, prefix, start=0, end=-1):
"""Return True if string starts with the specified prefix, False otherwise.
With optional start, test beginning at that position. With optional end, stop comparing at that position. prefix
can also be a tuple of strings to try.
:param str prefix: Prefix to search.
:param int start: Beginning position.
:param int end: Stop comparison at this position.
"""
return self.value_no_colors.startswith(prefix, start, end) | python | def startswith(self, prefix, start=0, end=-1):
return self.value_no_colors.startswith(prefix, start, end) | [
"def",
"startswith",
"(",
"self",
",",
"prefix",
",",
"start",
"=",
"0",
",",
"end",
"=",
"-",
"1",
")",
":",
"return",
"self",
".",
"value_no_colors",
".",
"startswith",
"(",
"prefix",
",",
"start",
",",
"end",
")"
] | Return True if string starts with the specified prefix, False otherwise.
With optional start, test beginning at that position. With optional end, stop comparing at that position. prefix
can also be a tuple of strings to try.
:param str prefix: Prefix to search.
:param int start: Beginning position.
:param int end: Stop comparison at this position. | [
"Return",
"True",
"if",
"string",
"starts",
"with",
"the",
"specified",
"prefix",
"False",
"otherwise",
"."
] | 692e2d6f5ad470b6221c8cb9641970dc5563a572 | https://github.com/Robpol86/colorclass/blob/692e2d6f5ad470b6221c8cb9641970dc5563a572/colorclass/core.py#L294-L304 |
20,132 | Robpol86/colorclass | colorclass/core.py | ColorStr.zfill | def zfill(self, width):
"""Pad a numeric string with zeros on the left, to fill a field of the specified width.
The string is never truncated.
:param int width: Length of output string.
"""
if not self.value_no_colors:
result = self.value_no_colors.zfill(width)
else:
result = self.value_colors.replace(self.value_no_colors, self.value_no_colors.zfill(width))
return self.__class__(result, keep_tags=True) | python | def zfill(self, width):
if not self.value_no_colors:
result = self.value_no_colors.zfill(width)
else:
result = self.value_colors.replace(self.value_no_colors, self.value_no_colors.zfill(width))
return self.__class__(result, keep_tags=True) | [
"def",
"zfill",
"(",
"self",
",",
"width",
")",
":",
"if",
"not",
"self",
".",
"value_no_colors",
":",
"result",
"=",
"self",
".",
"value_no_colors",
".",
"zfill",
"(",
"width",
")",
"else",
":",
"result",
"=",
"self",
".",
"value_colors",
".",
"replac... | Pad a numeric string with zeros on the left, to fill a field of the specified width.
The string is never truncated.
:param int width: Length of output string. | [
"Pad",
"a",
"numeric",
"string",
"with",
"zeros",
"on",
"the",
"left",
"to",
"fill",
"a",
"field",
"of",
"the",
"specified",
"width",
"."
] | 692e2d6f5ad470b6221c8cb9641970dc5563a572 | https://github.com/Robpol86/colorclass/blob/692e2d6f5ad470b6221c8cb9641970dc5563a572/colorclass/core.py#L331-L342 |
20,133 | Robpol86/colorclass | colorclass/color.py | Color.colorize | def colorize(cls, color, string, auto=False):
"""Color-code entire string using specified color.
:param str color: Color of string.
:param str string: String to colorize.
:param bool auto: Enable auto-color (dark/light terminal).
:return: Class instance for colorized string.
:rtype: Color
"""
tag = '{0}{1}'.format('auto' if auto else '', color)
return cls('{%s}%s{/%s}' % (tag, string, tag)) | python | def colorize(cls, color, string, auto=False):
tag = '{0}{1}'.format('auto' if auto else '', color)
return cls('{%s}%s{/%s}' % (tag, string, tag)) | [
"def",
"colorize",
"(",
"cls",
",",
"color",
",",
"string",
",",
"auto",
"=",
"False",
")",
":",
"tag",
"=",
"'{0}{1}'",
".",
"format",
"(",
"'auto'",
"if",
"auto",
"else",
"''",
",",
"color",
")",
"return",
"cls",
"(",
"'{%s}%s{/%s}'",
"%",
"(",
"... | Color-code entire string using specified color.
:param str color: Color of string.
:param str string: String to colorize.
:param bool auto: Enable auto-color (dark/light terminal).
:return: Class instance for colorized string.
:rtype: Color | [
"Color",
"-",
"code",
"entire",
"string",
"using",
"specified",
"color",
"."
] | 692e2d6f5ad470b6221c8cb9641970dc5563a572 | https://github.com/Robpol86/colorclass/blob/692e2d6f5ad470b6221c8cb9641970dc5563a572/colorclass/color.py#L17-L28 |
20,134 | Robpol86/colorclass | colorclass/codes.py | list_tags | def list_tags():
"""List the available tags.
:return: List of 4-item tuples: opening tag, closing tag, main ansi value, closing ansi value.
:rtype: list
"""
# Build reverse dictionary. Keys are closing tags, values are [closing ansi, opening tag, opening ansi].
reverse_dict = dict()
for tag, ansi in sorted(BASE_CODES.items()):
if tag.startswith('/'):
reverse_dict[tag] = [ansi, None, None]
else:
reverse_dict['/' + tag][1:] = [tag, ansi]
# Collapse
four_item_tuples = [(v[1], k, v[2], v[0]) for k, v in reverse_dict.items()]
# Sort.
def sorter(four_item):
"""Sort /all /fg /bg first, then b i u flash, then auto colors, then dark colors, finally light colors.
:param iter four_item: [opening tag, closing tag, main ansi value, closing ansi value]
:return Sorting weight.
:rtype: int
"""
if not four_item[2]: # /all /fg /bg
return four_item[3] - 200
if four_item[2] < 10 or four_item[0].startswith('auto'): # b f i u or auto colors
return four_item[2] - 100
return four_item[2]
four_item_tuples.sort(key=sorter)
return four_item_tuples | python | def list_tags():
# Build reverse dictionary. Keys are closing tags, values are [closing ansi, opening tag, opening ansi].
reverse_dict = dict()
for tag, ansi in sorted(BASE_CODES.items()):
if tag.startswith('/'):
reverse_dict[tag] = [ansi, None, None]
else:
reverse_dict['/' + tag][1:] = [tag, ansi]
# Collapse
four_item_tuples = [(v[1], k, v[2], v[0]) for k, v in reverse_dict.items()]
# Sort.
def sorter(four_item):
"""Sort /all /fg /bg first, then b i u flash, then auto colors, then dark colors, finally light colors.
:param iter four_item: [opening tag, closing tag, main ansi value, closing ansi value]
:return Sorting weight.
:rtype: int
"""
if not four_item[2]: # /all /fg /bg
return four_item[3] - 200
if four_item[2] < 10 or four_item[0].startswith('auto'): # b f i u or auto colors
return four_item[2] - 100
return four_item[2]
four_item_tuples.sort(key=sorter)
return four_item_tuples | [
"def",
"list_tags",
"(",
")",
":",
"# Build reverse dictionary. Keys are closing tags, values are [closing ansi, opening tag, opening ansi].",
"reverse_dict",
"=",
"dict",
"(",
")",
"for",
"tag",
",",
"ansi",
"in",
"sorted",
"(",
"BASE_CODES",
".",
"items",
"(",
")",
")... | List the available tags.
:return: List of 4-item tuples: opening tag, closing tag, main ansi value, closing ansi value.
:rtype: list | [
"List",
"the",
"available",
"tags",
"."
] | 692e2d6f5ad470b6221c8cb9641970dc5563a572 | https://github.com/Robpol86/colorclass/blob/692e2d6f5ad470b6221c8cb9641970dc5563a572/colorclass/codes.py#L196-L229 |
20,135 | Robpol86/colorclass | colorclass/codes.py | ANSICodeMapping.disable_if_no_tty | def disable_if_no_tty(cls):
"""Disable all colors only if there is no TTY available.
:return: True if colors are disabled, False if stderr or stdout is a TTY.
:rtype: bool
"""
if sys.stdout.isatty() or sys.stderr.isatty():
return False
cls.disable_all_colors()
return True | python | def disable_if_no_tty(cls):
if sys.stdout.isatty() or sys.stderr.isatty():
return False
cls.disable_all_colors()
return True | [
"def",
"disable_if_no_tty",
"(",
"cls",
")",
":",
"if",
"sys",
".",
"stdout",
".",
"isatty",
"(",
")",
"or",
"sys",
".",
"stderr",
".",
"isatty",
"(",
")",
":",
"return",
"False",
"cls",
".",
"disable_all_colors",
"(",
")",
"return",
"True"
] | Disable all colors only if there is no TTY available.
:return: True if colors are disabled, False if stderr or stdout is a TTY.
:rtype: bool | [
"Disable",
"all",
"colors",
"only",
"if",
"there",
"is",
"no",
"TTY",
"available",
"."
] | 692e2d6f5ad470b6221c8cb9641970dc5563a572 | https://github.com/Robpol86/colorclass/blob/692e2d6f5ad470b6221c8cb9641970dc5563a572/colorclass/codes.py#L94-L103 |
20,136 | Robpol86/colorclass | colorclass/windows.py | get_console_info | def get_console_info(kernel32, handle):
"""Get information about this current console window.
http://msdn.microsoft.com/en-us/library/windows/desktop/ms683231
https://code.google.com/p/colorama/issues/detail?id=47
https://bitbucket.org/pytest-dev/py/src/4617fe46/py/_io/terminalwriter.py
Windows 10 Insider since around February 2016 finally introduced support for ANSI colors. No need to replace stdout
and stderr streams to intercept colors and issue multiple SetConsoleTextAttribute() calls for these consoles.
:raise OSError: When GetConsoleScreenBufferInfo or GetConsoleMode API calls fail.
:param ctypes.windll.kernel32 kernel32: Loaded kernel32 instance.
:param int handle: stderr or stdout handle.
:return: Foreground and background colors (integers) as well as native ANSI support (bool).
:rtype: tuple
"""
# Query Win32 API.
csbi = ConsoleScreenBufferInfo() # Populated by GetConsoleScreenBufferInfo.
lpcsbi = ctypes.byref(csbi)
dword = ctypes.c_ulong() # Populated by GetConsoleMode.
lpdword = ctypes.byref(dword)
if not kernel32.GetConsoleScreenBufferInfo(handle, lpcsbi) or not kernel32.GetConsoleMode(handle, lpdword):
raise ctypes.WinError()
# Parse data.
# buffer_width = int(csbi.dwSize.X - 1)
# buffer_height = int(csbi.dwSize.Y)
# terminal_width = int(csbi.srWindow.Right - csbi.srWindow.Left)
# terminal_height = int(csbi.srWindow.Bottom - csbi.srWindow.Top)
fg_color = csbi.wAttributes % 16
bg_color = csbi.wAttributes & 240
native_ansi = bool(dword.value & ENABLE_VIRTUAL_TERMINAL_PROCESSING)
return fg_color, bg_color, native_ansi | python | def get_console_info(kernel32, handle):
# Query Win32 API.
csbi = ConsoleScreenBufferInfo() # Populated by GetConsoleScreenBufferInfo.
lpcsbi = ctypes.byref(csbi)
dword = ctypes.c_ulong() # Populated by GetConsoleMode.
lpdword = ctypes.byref(dword)
if not kernel32.GetConsoleScreenBufferInfo(handle, lpcsbi) or not kernel32.GetConsoleMode(handle, lpdword):
raise ctypes.WinError()
# Parse data.
# buffer_width = int(csbi.dwSize.X - 1)
# buffer_height = int(csbi.dwSize.Y)
# terminal_width = int(csbi.srWindow.Right - csbi.srWindow.Left)
# terminal_height = int(csbi.srWindow.Bottom - csbi.srWindow.Top)
fg_color = csbi.wAttributes % 16
bg_color = csbi.wAttributes & 240
native_ansi = bool(dword.value & ENABLE_VIRTUAL_TERMINAL_PROCESSING)
return fg_color, bg_color, native_ansi | [
"def",
"get_console_info",
"(",
"kernel32",
",",
"handle",
")",
":",
"# Query Win32 API.",
"csbi",
"=",
"ConsoleScreenBufferInfo",
"(",
")",
"# Populated by GetConsoleScreenBufferInfo.",
"lpcsbi",
"=",
"ctypes",
".",
"byref",
"(",
"csbi",
")",
"dword",
"=",
"ctypes"... | Get information about this current console window.
http://msdn.microsoft.com/en-us/library/windows/desktop/ms683231
https://code.google.com/p/colorama/issues/detail?id=47
https://bitbucket.org/pytest-dev/py/src/4617fe46/py/_io/terminalwriter.py
Windows 10 Insider since around February 2016 finally introduced support for ANSI colors. No need to replace stdout
and stderr streams to intercept colors and issue multiple SetConsoleTextAttribute() calls for these consoles.
:raise OSError: When GetConsoleScreenBufferInfo or GetConsoleMode API calls fail.
:param ctypes.windll.kernel32 kernel32: Loaded kernel32 instance.
:param int handle: stderr or stdout handle.
:return: Foreground and background colors (integers) as well as native ANSI support (bool).
:rtype: tuple | [
"Get",
"information",
"about",
"this",
"current",
"console",
"window",
"."
] | 692e2d6f5ad470b6221c8cb9641970dc5563a572 | https://github.com/Robpol86/colorclass/blob/692e2d6f5ad470b6221c8cb9641970dc5563a572/colorclass/windows.py#L113-L148 |
20,137 | Robpol86/colorclass | colorclass/windows.py | bg_color_native_ansi | def bg_color_native_ansi(kernel32, stderr, stdout):
"""Get background color and if console supports ANSI colors natively for both streams.
:param ctypes.windll.kernel32 kernel32: Loaded kernel32 instance.
:param int stderr: stderr handle.
:param int stdout: stdout handle.
:return: Background color (int) and native ANSI support (bool).
:rtype: tuple
"""
try:
if stderr == INVALID_HANDLE_VALUE:
raise OSError
bg_color, native_ansi = get_console_info(kernel32, stderr)[1:]
except OSError:
try:
if stdout == INVALID_HANDLE_VALUE:
raise OSError
bg_color, native_ansi = get_console_info(kernel32, stdout)[1:]
except OSError:
bg_color, native_ansi = WINDOWS_CODES['black'], False
return bg_color, native_ansi | python | def bg_color_native_ansi(kernel32, stderr, stdout):
try:
if stderr == INVALID_HANDLE_VALUE:
raise OSError
bg_color, native_ansi = get_console_info(kernel32, stderr)[1:]
except OSError:
try:
if stdout == INVALID_HANDLE_VALUE:
raise OSError
bg_color, native_ansi = get_console_info(kernel32, stdout)[1:]
except OSError:
bg_color, native_ansi = WINDOWS_CODES['black'], False
return bg_color, native_ansi | [
"def",
"bg_color_native_ansi",
"(",
"kernel32",
",",
"stderr",
",",
"stdout",
")",
":",
"try",
":",
"if",
"stderr",
"==",
"INVALID_HANDLE_VALUE",
":",
"raise",
"OSError",
"bg_color",
",",
"native_ansi",
"=",
"get_console_info",
"(",
"kernel32",
",",
"stderr",
... | Get background color and if console supports ANSI colors natively for both streams.
:param ctypes.windll.kernel32 kernel32: Loaded kernel32 instance.
:param int stderr: stderr handle.
:param int stdout: stdout handle.
:return: Background color (int) and native ANSI support (bool).
:rtype: tuple | [
"Get",
"background",
"color",
"and",
"if",
"console",
"supports",
"ANSI",
"colors",
"natively",
"for",
"both",
"streams",
"."
] | 692e2d6f5ad470b6221c8cb9641970dc5563a572 | https://github.com/Robpol86/colorclass/blob/692e2d6f5ad470b6221c8cb9641970dc5563a572/colorclass/windows.py#L151-L172 |
20,138 | Robpol86/colorclass | colorclass/windows.py | WindowsStream.colors | def colors(self):
"""Return the current foreground and background colors."""
try:
return get_console_info(self._kernel32, self._stream_handle)[:2]
except OSError:
return WINDOWS_CODES['white'], WINDOWS_CODES['black'] | python | def colors(self):
try:
return get_console_info(self._kernel32, self._stream_handle)[:2]
except OSError:
return WINDOWS_CODES['white'], WINDOWS_CODES['black'] | [
"def",
"colors",
"(",
"self",
")",
":",
"try",
":",
"return",
"get_console_info",
"(",
"self",
".",
"_kernel32",
",",
"self",
".",
"_stream_handle",
")",
"[",
":",
"2",
"]",
"except",
"OSError",
":",
"return",
"WINDOWS_CODES",
"[",
"'white'",
"]",
",",
... | Return the current foreground and background colors. | [
"Return",
"the",
"current",
"foreground",
"and",
"background",
"colors",
"."
] | 692e2d6f5ad470b6221c8cb9641970dc5563a572 | https://github.com/Robpol86/colorclass/blob/692e2d6f5ad470b6221c8cb9641970dc5563a572/colorclass/windows.py#L217-L222 |
20,139 | Robpol86/colorclass | colorclass/windows.py | WindowsStream.colors | def colors(self, color_code):
"""Change the foreground and background colors for subsequently printed characters.
None resets colors to their original values (when class was instantiated).
Since setting a color requires including both foreground and background codes (merged), setting just the
foreground color resets the background color to black, and vice versa.
This function first gets the current background and foreground colors, merges in the requested color code, and
sets the result.
However if we need to remove just the foreground color but leave the background color the same (or vice versa)
such as when {/red} is used, we must merge the default foreground color with the current background color. This
is the reason for those negative values.
:param int color_code: Color code from WINDOWS_CODES.
"""
if color_code is None:
color_code = WINDOWS_CODES['/all']
# Get current color code.
current_fg, current_bg = self.colors
# Handle special negative codes. Also determine the final color code.
if color_code == WINDOWS_CODES['/fg']:
final_color_code = self.default_fg | current_bg # Reset the foreground only.
elif color_code == WINDOWS_CODES['/bg']:
final_color_code = current_fg | self.default_bg # Reset the background only.
elif color_code == WINDOWS_CODES['/all']:
final_color_code = self.default_fg | self.default_bg # Reset both.
elif color_code == WINDOWS_CODES['bgblack']:
final_color_code = current_fg # Black background.
else:
new_is_bg = color_code in self.ALL_BG_CODES
final_color_code = color_code | (current_fg if new_is_bg else current_bg)
# Set new code.
self._kernel32.SetConsoleTextAttribute(self._stream_handle, final_color_code) | python | def colors(self, color_code):
if color_code is None:
color_code = WINDOWS_CODES['/all']
# Get current color code.
current_fg, current_bg = self.colors
# Handle special negative codes. Also determine the final color code.
if color_code == WINDOWS_CODES['/fg']:
final_color_code = self.default_fg | current_bg # Reset the foreground only.
elif color_code == WINDOWS_CODES['/bg']:
final_color_code = current_fg | self.default_bg # Reset the background only.
elif color_code == WINDOWS_CODES['/all']:
final_color_code = self.default_fg | self.default_bg # Reset both.
elif color_code == WINDOWS_CODES['bgblack']:
final_color_code = current_fg # Black background.
else:
new_is_bg = color_code in self.ALL_BG_CODES
final_color_code = color_code | (current_fg if new_is_bg else current_bg)
# Set new code.
self._kernel32.SetConsoleTextAttribute(self._stream_handle, final_color_code) | [
"def",
"colors",
"(",
"self",
",",
"color_code",
")",
":",
"if",
"color_code",
"is",
"None",
":",
"color_code",
"=",
"WINDOWS_CODES",
"[",
"'/all'",
"]",
"# Get current color code.",
"current_fg",
",",
"current_bg",
"=",
"self",
".",
"colors",
"# Handle special ... | Change the foreground and background colors for subsequently printed characters.
None resets colors to their original values (when class was instantiated).
Since setting a color requires including both foreground and background codes (merged), setting just the
foreground color resets the background color to black, and vice versa.
This function first gets the current background and foreground colors, merges in the requested color code, and
sets the result.
However if we need to remove just the foreground color but leave the background color the same (or vice versa)
such as when {/red} is used, we must merge the default foreground color with the current background color. This
is the reason for those negative values.
:param int color_code: Color code from WINDOWS_CODES. | [
"Change",
"the",
"foreground",
"and",
"background",
"colors",
"for",
"subsequently",
"printed",
"characters",
"."
] | 692e2d6f5ad470b6221c8cb9641970dc5563a572 | https://github.com/Robpol86/colorclass/blob/692e2d6f5ad470b6221c8cb9641970dc5563a572/colorclass/windows.py#L225-L262 |
20,140 | Robpol86/colorclass | colorclass/windows.py | WindowsStream.write | def write(self, p_str):
"""Write to stream.
:param str p_str: string to print.
"""
for segment in RE_SPLIT.split(p_str):
if not segment:
# Empty string. p_str probably starts with colors so the first item is always ''.
continue
if not RE_SPLIT.match(segment):
# No color codes, print regular text.
print(segment, file=self._original_stream, end='')
self._original_stream.flush()
continue
for color_code in (int(c) for c in RE_NUMBER_SEARCH.findall(segment)[0].split(';')):
if color_code in self.COMPILED_CODES:
self.colors = self.COMPILED_CODES[color_code] | python | def write(self, p_str):
for segment in RE_SPLIT.split(p_str):
if not segment:
# Empty string. p_str probably starts with colors so the first item is always ''.
continue
if not RE_SPLIT.match(segment):
# No color codes, print regular text.
print(segment, file=self._original_stream, end='')
self._original_stream.flush()
continue
for color_code in (int(c) for c in RE_NUMBER_SEARCH.findall(segment)[0].split(';')):
if color_code in self.COMPILED_CODES:
self.colors = self.COMPILED_CODES[color_code] | [
"def",
"write",
"(",
"self",
",",
"p_str",
")",
":",
"for",
"segment",
"in",
"RE_SPLIT",
".",
"split",
"(",
"p_str",
")",
":",
"if",
"not",
"segment",
":",
"# Empty string. p_str probably starts with colors so the first item is always ''.",
"continue",
"if",
"not",
... | Write to stream.
:param str p_str: string to print. | [
"Write",
"to",
"stream",
"."
] | 692e2d6f5ad470b6221c8cb9641970dc5563a572 | https://github.com/Robpol86/colorclass/blob/692e2d6f5ad470b6221c8cb9641970dc5563a572/colorclass/windows.py#L264-L280 |
20,141 | Robpol86/colorclass | colorclass/parse.py | prune_overridden | def prune_overridden(ansi_string):
"""Remove color codes that are rendered ineffective by subsequent codes in one escape sequence then sort codes.
:param str ansi_string: Incoming ansi_string with ANSI color codes.
:return: Color string with pruned color sequences.
:rtype: str
"""
multi_seqs = set(p for p in RE_ANSI.findall(ansi_string) if ';' in p[1]) # Sequences with multiple color codes.
for escape, codes in multi_seqs:
r_codes = list(reversed(codes.split(';')))
# Nuke everything before {/all}.
try:
r_codes = r_codes[:r_codes.index('0') + 1]
except ValueError:
pass
# Thin out groups.
for group in CODE_GROUPS:
for pos in reversed([i for i, n in enumerate(r_codes) if n in group][1:]):
r_codes.pop(pos)
# Done.
reduced_codes = ';'.join(sorted(r_codes, key=int))
if codes != reduced_codes:
ansi_string = ansi_string.replace(escape, '\033[' + reduced_codes + 'm')
return ansi_string | python | def prune_overridden(ansi_string):
multi_seqs = set(p for p in RE_ANSI.findall(ansi_string) if ';' in p[1]) # Sequences with multiple color codes.
for escape, codes in multi_seqs:
r_codes = list(reversed(codes.split(';')))
# Nuke everything before {/all}.
try:
r_codes = r_codes[:r_codes.index('0') + 1]
except ValueError:
pass
# Thin out groups.
for group in CODE_GROUPS:
for pos in reversed([i for i, n in enumerate(r_codes) if n in group][1:]):
r_codes.pop(pos)
# Done.
reduced_codes = ';'.join(sorted(r_codes, key=int))
if codes != reduced_codes:
ansi_string = ansi_string.replace(escape, '\033[' + reduced_codes + 'm')
return ansi_string | [
"def",
"prune_overridden",
"(",
"ansi_string",
")",
":",
"multi_seqs",
"=",
"set",
"(",
"p",
"for",
"p",
"in",
"RE_ANSI",
".",
"findall",
"(",
"ansi_string",
")",
"if",
"';'",
"in",
"p",
"[",
"1",
"]",
")",
"# Sequences with multiple color codes.",
"for",
... | Remove color codes that are rendered ineffective by subsequent codes in one escape sequence then sort codes.
:param str ansi_string: Incoming ansi_string with ANSI color codes.
:return: Color string with pruned color sequences.
:rtype: str | [
"Remove",
"color",
"codes",
"that",
"are",
"rendered",
"ineffective",
"by",
"subsequent",
"codes",
"in",
"one",
"escape",
"sequence",
"then",
"sort",
"codes",
"."
] | 692e2d6f5ad470b6221c8cb9641970dc5563a572 | https://github.com/Robpol86/colorclass/blob/692e2d6f5ad470b6221c8cb9641970dc5563a572/colorclass/parse.py#L17-L46 |
20,142 | Robpol86/colorclass | colorclass/parse.py | parse_input | def parse_input(tagged_string, disable_colors, keep_tags):
"""Perform the actual conversion of tags to ANSI escaped codes.
Provides a version of the input without any colors for len() and other methods.
:param str tagged_string: The input unicode value.
:param bool disable_colors: Strip all colors in both outputs.
:param bool keep_tags: Skip parsing curly bracket tags into ANSI escape sequences.
:return: 2-item tuple. First item is the parsed output. Second item is a version of the input without any colors.
:rtype: tuple
"""
codes = ANSICodeMapping(tagged_string)
output_colors = getattr(tagged_string, 'value_colors', tagged_string)
# Convert: '{b}{red}' -> '\033[1m\033[31m'
if not keep_tags:
for tag, replacement in (('{' + k + '}', '' if v is None else '\033[%dm' % v) for k, v in codes.items()):
output_colors = output_colors.replace(tag, replacement)
# Strip colors.
output_no_colors = RE_ANSI.sub('', output_colors)
if disable_colors:
return output_no_colors, output_no_colors
# Combine: '\033[1m\033[31m' -> '\033[1;31m'
while True:
simplified = RE_COMBINE.sub(r'\033[\1;\2m', output_colors)
if simplified == output_colors:
break
output_colors = simplified
# Prune: '\033[31;32;33;34;35m' -> '\033[35m'
output_colors = prune_overridden(output_colors)
# Deduplicate: '\033[1;mT\033[1;mE\033[1;mS\033[1;mT' -> '\033[1;mTEST'
previous_escape = None
segments = list()
for item in (i for i in RE_SPLIT.split(output_colors) if i):
if RE_SPLIT.match(item):
if item != previous_escape:
segments.append(item)
previous_escape = item
else:
segments.append(item)
output_colors = ''.join(segments)
return output_colors, output_no_colors | python | def parse_input(tagged_string, disable_colors, keep_tags):
codes = ANSICodeMapping(tagged_string)
output_colors = getattr(tagged_string, 'value_colors', tagged_string)
# Convert: '{b}{red}' -> '\033[1m\033[31m'
if not keep_tags:
for tag, replacement in (('{' + k + '}', '' if v is None else '\033[%dm' % v) for k, v in codes.items()):
output_colors = output_colors.replace(tag, replacement)
# Strip colors.
output_no_colors = RE_ANSI.sub('', output_colors)
if disable_colors:
return output_no_colors, output_no_colors
# Combine: '\033[1m\033[31m' -> '\033[1;31m'
while True:
simplified = RE_COMBINE.sub(r'\033[\1;\2m', output_colors)
if simplified == output_colors:
break
output_colors = simplified
# Prune: '\033[31;32;33;34;35m' -> '\033[35m'
output_colors = prune_overridden(output_colors)
# Deduplicate: '\033[1;mT\033[1;mE\033[1;mS\033[1;mT' -> '\033[1;mTEST'
previous_escape = None
segments = list()
for item in (i for i in RE_SPLIT.split(output_colors) if i):
if RE_SPLIT.match(item):
if item != previous_escape:
segments.append(item)
previous_escape = item
else:
segments.append(item)
output_colors = ''.join(segments)
return output_colors, output_no_colors | [
"def",
"parse_input",
"(",
"tagged_string",
",",
"disable_colors",
",",
"keep_tags",
")",
":",
"codes",
"=",
"ANSICodeMapping",
"(",
"tagged_string",
")",
"output_colors",
"=",
"getattr",
"(",
"tagged_string",
",",
"'value_colors'",
",",
"tagged_string",
")",
"# C... | Perform the actual conversion of tags to ANSI escaped codes.
Provides a version of the input without any colors for len() and other methods.
:param str tagged_string: The input unicode value.
:param bool disable_colors: Strip all colors in both outputs.
:param bool keep_tags: Skip parsing curly bracket tags into ANSI escape sequences.
:return: 2-item tuple. First item is the parsed output. Second item is a version of the input without any colors.
:rtype: tuple | [
"Perform",
"the",
"actual",
"conversion",
"of",
"tags",
"to",
"ANSI",
"escaped",
"codes",
"."
] | 692e2d6f5ad470b6221c8cb9641970dc5563a572 | https://github.com/Robpol86/colorclass/blob/692e2d6f5ad470b6221c8cb9641970dc5563a572/colorclass/parse.py#L49-L96 |
20,143 | Robpol86/colorclass | colorclass/search.py | build_color_index | def build_color_index(ansi_string):
"""Build an index between visible characters and a string with invisible color codes.
:param str ansi_string: String with color codes (ANSI escape sequences).
:return: Position of visible characters in color string (indexes match non-color string).
:rtype: tuple
"""
mapping = list()
color_offset = 0
for item in (i for i in RE_SPLIT.split(ansi_string) if i):
if RE_SPLIT.match(item):
color_offset += len(item)
else:
for _ in range(len(item)):
mapping.append(color_offset)
color_offset += 1
return tuple(mapping) | python | def build_color_index(ansi_string):
mapping = list()
color_offset = 0
for item in (i for i in RE_SPLIT.split(ansi_string) if i):
if RE_SPLIT.match(item):
color_offset += len(item)
else:
for _ in range(len(item)):
mapping.append(color_offset)
color_offset += 1
return tuple(mapping) | [
"def",
"build_color_index",
"(",
"ansi_string",
")",
":",
"mapping",
"=",
"list",
"(",
")",
"color_offset",
"=",
"0",
"for",
"item",
"in",
"(",
"i",
"for",
"i",
"in",
"RE_SPLIT",
".",
"split",
"(",
"ansi_string",
")",
"if",
"i",
")",
":",
"if",
"RE_S... | Build an index between visible characters and a string with invisible color codes.
:param str ansi_string: String with color codes (ANSI escape sequences).
:return: Position of visible characters in color string (indexes match non-color string).
:rtype: tuple | [
"Build",
"an",
"index",
"between",
"visible",
"characters",
"and",
"a",
"string",
"with",
"invisible",
"color",
"codes",
"."
] | 692e2d6f5ad470b6221c8cb9641970dc5563a572 | https://github.com/Robpol86/colorclass/blob/692e2d6f5ad470b6221c8cb9641970dc5563a572/colorclass/search.py#L6-L23 |
20,144 | Robpol86/colorclass | colorclass/search.py | find_char_color | def find_char_color(ansi_string, pos):
"""Determine what color a character is in the string.
:param str ansi_string: String with color codes (ANSI escape sequences).
:param int pos: Position of the character in the ansi_string.
:return: Character along with all surrounding color codes.
:rtype: str
"""
result = list()
position = 0 # Set to None when character is found.
for item in (i for i in RE_SPLIT.split(ansi_string) if i):
if RE_SPLIT.match(item):
result.append(item)
if position is not None:
position += len(item)
elif position is not None:
for char in item:
if position == pos:
result.append(char)
position = None
break
position += 1
return ''.join(result) | python | def find_char_color(ansi_string, pos):
result = list()
position = 0 # Set to None when character is found.
for item in (i for i in RE_SPLIT.split(ansi_string) if i):
if RE_SPLIT.match(item):
result.append(item)
if position is not None:
position += len(item)
elif position is not None:
for char in item:
if position == pos:
result.append(char)
position = None
break
position += 1
return ''.join(result) | [
"def",
"find_char_color",
"(",
"ansi_string",
",",
"pos",
")",
":",
"result",
"=",
"list",
"(",
")",
"position",
"=",
"0",
"# Set to None when character is found.",
"for",
"item",
"in",
"(",
"i",
"for",
"i",
"in",
"RE_SPLIT",
".",
"split",
"(",
"ansi_string"... | Determine what color a character is in the string.
:param str ansi_string: String with color codes (ANSI escape sequences).
:param int pos: Position of the character in the ansi_string.
:return: Character along with all surrounding color codes.
:rtype: str | [
"Determine",
"what",
"color",
"a",
"character",
"is",
"in",
"the",
"string",
"."
] | 692e2d6f5ad470b6221c8cb9641970dc5563a572 | https://github.com/Robpol86/colorclass/blob/692e2d6f5ad470b6221c8cb9641970dc5563a572/colorclass/search.py#L26-L49 |
20,145 | threeML/astromodels | astromodels/utils/angular_distance.py | angular_distance_fast | def angular_distance_fast(ra1, dec1, ra2, dec2):
"""
Compute angular distance using the Haversine formula. Use this one when you know you will never ask for points at
their antipodes. If this is not the case, use the angular_distance function which is slower, but works also for
antipodes.
:param lon1:
:param lat1:
:param lon2:
:param lat2:
:return:
"""
lon1 = np.deg2rad(ra1)
lat1 = np.deg2rad(dec1)
lon2 = np.deg2rad(ra2)
lat2 = np.deg2rad(dec2)
dlon = lon2 - lon1
dlat = lat2 - lat1
a = np.sin(dlat/2.0)**2 + np.cos(lat1) * np.cos(lat2) * np.sin(dlon /2.0)**2
c = 2 * np.arcsin(np.sqrt(a))
return np.rad2deg(c) | python | def angular_distance_fast(ra1, dec1, ra2, dec2):
lon1 = np.deg2rad(ra1)
lat1 = np.deg2rad(dec1)
lon2 = np.deg2rad(ra2)
lat2 = np.deg2rad(dec2)
dlon = lon2 - lon1
dlat = lat2 - lat1
a = np.sin(dlat/2.0)**2 + np.cos(lat1) * np.cos(lat2) * np.sin(dlon /2.0)**2
c = 2 * np.arcsin(np.sqrt(a))
return np.rad2deg(c) | [
"def",
"angular_distance_fast",
"(",
"ra1",
",",
"dec1",
",",
"ra2",
",",
"dec2",
")",
":",
"lon1",
"=",
"np",
".",
"deg2rad",
"(",
"ra1",
")",
"lat1",
"=",
"np",
".",
"deg2rad",
"(",
"dec1",
")",
"lon2",
"=",
"np",
".",
"deg2rad",
"(",
"ra2",
")... | Compute angular distance using the Haversine formula. Use this one when you know you will never ask for points at
their antipodes. If this is not the case, use the angular_distance function which is slower, but works also for
antipodes.
:param lon1:
:param lat1:
:param lon2:
:param lat2:
:return: | [
"Compute",
"angular",
"distance",
"using",
"the",
"Haversine",
"formula",
".",
"Use",
"this",
"one",
"when",
"you",
"know",
"you",
"will",
"never",
"ask",
"for",
"points",
"at",
"their",
"antipodes",
".",
"If",
"this",
"is",
"not",
"the",
"case",
"use",
... | 9aac365a372f77603039533df9a6b694c1e360d5 | https://github.com/threeML/astromodels/blob/9aac365a372f77603039533df9a6b694c1e360d5/astromodels/utils/angular_distance.py#L4-L26 |
20,146 | threeML/astromodels | astromodels/utils/angular_distance.py | angular_distance | def angular_distance(ra1, dec1, ra2, dec2):
"""
Returns the angular distance between two points, two sets of points, or a set of points and one point.
:param ra1: array or float, longitude of first point(s)
:param dec1: array or float, latitude of first point(s)
:param ra2: array or float, longitude of second point(s)
:param dec2: array or float, latitude of second point(s)
:return: angular distance(s) in degrees
"""
# Vincenty formula, slower than the Haversine formula in some cases, but stable also at antipodes
lon1 = np.deg2rad(ra1)
lat1 = np.deg2rad(dec1)
lon2 = np.deg2rad(ra2)
lat2 = np.deg2rad(dec2)
sdlon = np.sin(lon2 - lon1)
cdlon = np.cos(lon2 - lon1)
slat1 = np.sin(lat1)
slat2 = np.sin(lat2)
clat1 = np.cos(lat1)
clat2 = np.cos(lat2)
num1 = clat2 * sdlon
num2 = clat1 * slat2 - slat1 * clat2 * cdlon
denominator = slat1 * slat2 + clat1 * clat2 * cdlon
return np.rad2deg(np.arctan2(np.sqrt(num1 ** 2 + num2 ** 2), denominator)) | python | def angular_distance(ra1, dec1, ra2, dec2):
# Vincenty formula, slower than the Haversine formula in some cases, but stable also at antipodes
lon1 = np.deg2rad(ra1)
lat1 = np.deg2rad(dec1)
lon2 = np.deg2rad(ra2)
lat2 = np.deg2rad(dec2)
sdlon = np.sin(lon2 - lon1)
cdlon = np.cos(lon2 - lon1)
slat1 = np.sin(lat1)
slat2 = np.sin(lat2)
clat1 = np.cos(lat1)
clat2 = np.cos(lat2)
num1 = clat2 * sdlon
num2 = clat1 * slat2 - slat1 * clat2 * cdlon
denominator = slat1 * slat2 + clat1 * clat2 * cdlon
return np.rad2deg(np.arctan2(np.sqrt(num1 ** 2 + num2 ** 2), denominator)) | [
"def",
"angular_distance",
"(",
"ra1",
",",
"dec1",
",",
"ra2",
",",
"dec2",
")",
":",
"# Vincenty formula, slower than the Haversine formula in some cases, but stable also at antipodes",
"lon1",
"=",
"np",
".",
"deg2rad",
"(",
"ra1",
")",
"lat1",
"=",
"np",
".",
"d... | Returns the angular distance between two points, two sets of points, or a set of points and one point.
:param ra1: array or float, longitude of first point(s)
:param dec1: array or float, latitude of first point(s)
:param ra2: array or float, longitude of second point(s)
:param dec2: array or float, latitude of second point(s)
:return: angular distance(s) in degrees | [
"Returns",
"the",
"angular",
"distance",
"between",
"two",
"points",
"two",
"sets",
"of",
"points",
"or",
"a",
"set",
"of",
"points",
"and",
"one",
"point",
"."
] | 9aac365a372f77603039533df9a6b694c1e360d5 | https://github.com/threeML/astromodels/blob/9aac365a372f77603039533df9a6b694c1e360d5/astromodels/utils/angular_distance.py#L29-L58 |
20,147 | threeML/astromodels | astromodels/core/memoization.py | memoize | def memoize(method):
"""
A decorator for functions of sources which memoize the results of the last _CACHE_SIZE calls,
:param method: method to be memoized
:return: the decorated method
"""
cache = method.cache = collections.OrderedDict()
# Put these two methods in the local space (faster)
_get = cache.get
_popitem = cache.popitem
@functools.wraps(method)
def memoizer(instance, x, *args, **kwargs):
if not _WITH_MEMOIZATION or isinstance(x, u.Quantity):
# Memoization is not active or using units, do not use memoization
return method(instance, x, *args, **kwargs)
# Create a tuple because a tuple is hashable
unique_id = tuple(float(yy.value) for yy in instance.parameters.values()) + (x.size, x.min(), x.max())
# Create a unique identifier for this combination of inputs
key = hash(unique_id)
# Let's do it this way so we only look into the dictionary once
result = _get(key)
if result is not None:
return result
else:
result = method(instance, x, *args, **kwargs)
cache[key] = result
if len(cache) > _CACHE_SIZE:
# Remove half of the element (but at least 1, even if _CACHE_SIZE=1, which would be pretty idiotic ;-) )
[_popitem(False) for i in range(max(_CACHE_SIZE // 2, 1))]
return result
# Add the function as a "attribute" so we can access it
memoizer.input_object = method
return memoizer | python | def memoize(method):
cache = method.cache = collections.OrderedDict()
# Put these two methods in the local space (faster)
_get = cache.get
_popitem = cache.popitem
@functools.wraps(method)
def memoizer(instance, x, *args, **kwargs):
if not _WITH_MEMOIZATION or isinstance(x, u.Quantity):
# Memoization is not active or using units, do not use memoization
return method(instance, x, *args, **kwargs)
# Create a tuple because a tuple is hashable
unique_id = tuple(float(yy.value) for yy in instance.parameters.values()) + (x.size, x.min(), x.max())
# Create a unique identifier for this combination of inputs
key = hash(unique_id)
# Let's do it this way so we only look into the dictionary once
result = _get(key)
if result is not None:
return result
else:
result = method(instance, x, *args, **kwargs)
cache[key] = result
if len(cache) > _CACHE_SIZE:
# Remove half of the element (but at least 1, even if _CACHE_SIZE=1, which would be pretty idiotic ;-) )
[_popitem(False) for i in range(max(_CACHE_SIZE // 2, 1))]
return result
# Add the function as a "attribute" so we can access it
memoizer.input_object = method
return memoizer | [
"def",
"memoize",
"(",
"method",
")",
":",
"cache",
"=",
"method",
".",
"cache",
"=",
"collections",
".",
"OrderedDict",
"(",
")",
"# Put these two methods in the local space (faster)",
"_get",
"=",
"cache",
".",
"get",
"_popitem",
"=",
"cache",
".",
"popitem",
... | A decorator for functions of sources which memoize the results of the last _CACHE_SIZE calls,
:param method: method to be memoized
:return: the decorated method | [
"A",
"decorator",
"for",
"functions",
"of",
"sources",
"which",
"memoize",
"the",
"results",
"of",
"the",
"last",
"_CACHE_SIZE",
"calls"
] | 9aac365a372f77603039533df9a6b694c1e360d5 | https://github.com/threeML/astromodels/blob/9aac365a372f77603039533df9a6b694c1e360d5/astromodels/core/memoization.py#L36-L90 |
20,148 | threeML/astromodels | astromodels/core/model.py | Model.free_parameters | def free_parameters(self):
"""
Get a dictionary with all the free parameters in this model
:return: dictionary of free parameters
"""
# Refresh the list
self._update_parameters()
# Filter selecting only free parameters
free_parameters_dictionary = collections.OrderedDict()
for parameter_name, parameter in self._parameters.iteritems():
if parameter.free:
free_parameters_dictionary[parameter_name] = parameter
return free_parameters_dictionary | python | def free_parameters(self):
# Refresh the list
self._update_parameters()
# Filter selecting only free parameters
free_parameters_dictionary = collections.OrderedDict()
for parameter_name, parameter in self._parameters.iteritems():
if parameter.free:
free_parameters_dictionary[parameter_name] = parameter
return free_parameters_dictionary | [
"def",
"free_parameters",
"(",
"self",
")",
":",
"# Refresh the list",
"self",
".",
"_update_parameters",
"(",
")",
"# Filter selecting only free parameters",
"free_parameters_dictionary",
"=",
"collections",
".",
"OrderedDict",
"(",
")",
"for",
"parameter_name",
",",
"... | Get a dictionary with all the free parameters in this model
:return: dictionary of free parameters | [
"Get",
"a",
"dictionary",
"with",
"all",
"the",
"free",
"parameters",
"in",
"this",
"model"
] | 9aac365a372f77603039533df9a6b694c1e360d5 | https://github.com/threeML/astromodels/blob/9aac365a372f77603039533df9a6b694c1e360d5/astromodels/core/model.py#L186-L207 |
20,149 | threeML/astromodels | astromodels/core/model.py | Model.set_free_parameters | def set_free_parameters(self, values):
"""
Set the free parameters in the model to the provided values.
NOTE: of course, order matters
:param values: a list of new values
:return: None
"""
assert len(values) == len(self.free_parameters)
for parameter, this_value in zip(self.free_parameters.values(), values):
parameter.value = this_value | python | def set_free_parameters(self, values):
assert len(values) == len(self.free_parameters)
for parameter, this_value in zip(self.free_parameters.values(), values):
parameter.value = this_value | [
"def",
"set_free_parameters",
"(",
"self",
",",
"values",
")",
":",
"assert",
"len",
"(",
"values",
")",
"==",
"len",
"(",
"self",
".",
"free_parameters",
")",
"for",
"parameter",
",",
"this_value",
"in",
"zip",
"(",
"self",
".",
"free_parameters",
".",
... | Set the free parameters in the model to the provided values.
NOTE: of course, order matters
:param values: a list of new values
:return: None | [
"Set",
"the",
"free",
"parameters",
"in",
"the",
"model",
"to",
"the",
"provided",
"values",
"."
] | 9aac365a372f77603039533df9a6b694c1e360d5 | https://github.com/threeML/astromodels/blob/9aac365a372f77603039533df9a6b694c1e360d5/astromodels/core/model.py#L235-L249 |
20,150 | threeML/astromodels | astromodels/core/model.py | Model.add_independent_variable | def add_independent_variable(self, variable):
"""
Add a global independent variable to this model, such as time.
:param variable: an IndependentVariable instance
:return: none
"""
assert isinstance(variable, IndependentVariable), "Variable must be an instance of IndependentVariable"
if self._has_child(variable.name):
self._remove_child(variable.name)
self._add_child(variable)
# Add also to the list of independent variables
self._independent_variables[variable.name] = variable | python | def add_independent_variable(self, variable):
assert isinstance(variable, IndependentVariable), "Variable must be an instance of IndependentVariable"
if self._has_child(variable.name):
self._remove_child(variable.name)
self._add_child(variable)
# Add also to the list of independent variables
self._independent_variables[variable.name] = variable | [
"def",
"add_independent_variable",
"(",
"self",
",",
"variable",
")",
":",
"assert",
"isinstance",
"(",
"variable",
",",
"IndependentVariable",
")",
",",
"\"Variable must be an instance of IndependentVariable\"",
"if",
"self",
".",
"_has_child",
"(",
"variable",
".",
... | Add a global independent variable to this model, such as time.
:param variable: an IndependentVariable instance
:return: none | [
"Add",
"a",
"global",
"independent",
"variable",
"to",
"this",
"model",
"such",
"as",
"time",
"."
] | 9aac365a372f77603039533df9a6b694c1e360d5 | https://github.com/threeML/astromodels/blob/9aac365a372f77603039533df9a6b694c1e360d5/astromodels/core/model.py#L373-L390 |
20,151 | threeML/astromodels | astromodels/core/model.py | Model.remove_independent_variable | def remove_independent_variable(self, variable_name):
"""
Remove an independent variable which was added with add_independent_variable
:param variable_name: name of variable to remove
:return:
"""
self._remove_child(variable_name)
# Remove also from the list of independent variables
self._independent_variables.pop(variable_name) | python | def remove_independent_variable(self, variable_name):
self._remove_child(variable_name)
# Remove also from the list of independent variables
self._independent_variables.pop(variable_name) | [
"def",
"remove_independent_variable",
"(",
"self",
",",
"variable_name",
")",
":",
"self",
".",
"_remove_child",
"(",
"variable_name",
")",
"# Remove also from the list of independent variables",
"self",
".",
"_independent_variables",
".",
"pop",
"(",
"variable_name",
")"... | Remove an independent variable which was added with add_independent_variable
:param variable_name: name of variable to remove
:return: | [
"Remove",
"an",
"independent",
"variable",
"which",
"was",
"added",
"with",
"add_independent_variable"
] | 9aac365a372f77603039533df9a6b694c1e360d5 | https://github.com/threeML/astromodels/blob/9aac365a372f77603039533df9a6b694c1e360d5/astromodels/core/model.py#L392-L403 |
20,152 | threeML/astromodels | astromodels/core/model.py | Model.add_external_parameter | def add_external_parameter(self, parameter):
"""
Add a parameter that comes from something other than a function, to the model.
:param parameter: a Parameter instance
:return: none
"""
assert isinstance(parameter, Parameter), "Variable must be an instance of IndependentVariable"
if self._has_child(parameter.name):
# Remove it from the children only if it is a Parameter instance, otherwise don't, which will
# make the _add_child call fail (which is the expected behaviour! You shouldn't call two children
# with the same name)
if isinstance(self._get_child(parameter.name), Parameter):
warnings.warn("External parameter %s already exist in the model. Overwriting it..." % parameter.name,
RuntimeWarning)
self._remove_child(parameter.name)
# This will fail if another node with the same name is already in the model
self._add_child(parameter) | python | def add_external_parameter(self, parameter):
assert isinstance(parameter, Parameter), "Variable must be an instance of IndependentVariable"
if self._has_child(parameter.name):
# Remove it from the children only if it is a Parameter instance, otherwise don't, which will
# make the _add_child call fail (which is the expected behaviour! You shouldn't call two children
# with the same name)
if isinstance(self._get_child(parameter.name), Parameter):
warnings.warn("External parameter %s already exist in the model. Overwriting it..." % parameter.name,
RuntimeWarning)
self._remove_child(parameter.name)
# This will fail if another node with the same name is already in the model
self._add_child(parameter) | [
"def",
"add_external_parameter",
"(",
"self",
",",
"parameter",
")",
":",
"assert",
"isinstance",
"(",
"parameter",
",",
"Parameter",
")",
",",
"\"Variable must be an instance of IndependentVariable\"",
"if",
"self",
".",
"_has_child",
"(",
"parameter",
".",
"name",
... | Add a parameter that comes from something other than a function, to the model.
:param parameter: a Parameter instance
:return: none | [
"Add",
"a",
"parameter",
"that",
"comes",
"from",
"something",
"other",
"than",
"a",
"function",
"to",
"the",
"model",
"."
] | 9aac365a372f77603039533df9a6b694c1e360d5 | https://github.com/threeML/astromodels/blob/9aac365a372f77603039533df9a6b694c1e360d5/astromodels/core/model.py#L405-L430 |
20,153 | threeML/astromodels | astromodels/core/model.py | Model.unlink | def unlink(self, parameter):
"""
Sets free one or more parameters which have been linked previously
:param parameter: the parameter to be set free, can also be a list of parameters
:return: (none)
"""
if not isinstance(parameter,list):
# Make a list of one element
parameter_list = [parameter]
else:
# Make a copy to avoid tampering with the input
parameter_list = list(parameter)
for param in parameter_list:
if param.has_auxiliary_variable():
param.remove_auxiliary_variable()
else:
with warnings.catch_warnings():
warnings.simplefilter("always", RuntimeWarning)
warnings.warn("Parameter %s has no link to be removed." % param.path, RuntimeWarning) | python | def unlink(self, parameter):
if not isinstance(parameter,list):
# Make a list of one element
parameter_list = [parameter]
else:
# Make a copy to avoid tampering with the input
parameter_list = list(parameter)
for param in parameter_list:
if param.has_auxiliary_variable():
param.remove_auxiliary_variable()
else:
with warnings.catch_warnings():
warnings.simplefilter("always", RuntimeWarning)
warnings.warn("Parameter %s has no link to be removed." % param.path, RuntimeWarning) | [
"def",
"unlink",
"(",
"self",
",",
"parameter",
")",
":",
"if",
"not",
"isinstance",
"(",
"parameter",
",",
"list",
")",
":",
"# Make a list of one element",
"parameter_list",
"=",
"[",
"parameter",
"]",
"else",
":",
"# Make a copy to avoid tampering with the input"... | Sets free one or more parameters which have been linked previously
:param parameter: the parameter to be set free, can also be a list of parameters
:return: (none) | [
"Sets",
"free",
"one",
"or",
"more",
"parameters",
"which",
"have",
"been",
"linked",
"previously"
] | 9aac365a372f77603039533df9a6b694c1e360d5 | https://github.com/threeML/astromodels/blob/9aac365a372f77603039533df9a6b694c1e360d5/astromodels/core/model.py#L488-L513 |
20,154 | threeML/astromodels | astromodels/core/model.py | Model.display | def display(self, complete=False):
"""
Display information about the point source.
:param complete : if True, displays also information on fixed parameters
:return: (none)
"""
# Switch on the complete display flag
self._complete_display = bool(complete)
# This will automatically choose the best representation among repr and repr_html
super(Model, self).display()
# Go back to default
self._complete_display = False | python | def display(self, complete=False):
# Switch on the complete display flag
self._complete_display = bool(complete)
# This will automatically choose the best representation among repr and repr_html
super(Model, self).display()
# Go back to default
self._complete_display = False | [
"def",
"display",
"(",
"self",
",",
"complete",
"=",
"False",
")",
":",
"# Switch on the complete display flag",
"self",
".",
"_complete_display",
"=",
"bool",
"(",
"complete",
")",
"# This will automatically choose the best representation among repr and repr_html",
"super",
... | Display information about the point source.
:param complete : if True, displays also information on fixed parameters
:return: (none) | [
"Display",
"information",
"about",
"the",
"point",
"source",
"."
] | 9aac365a372f77603039533df9a6b694c1e360d5 | https://github.com/threeML/astromodels/blob/9aac365a372f77603039533df9a6b694c1e360d5/astromodels/core/model.py#L515-L532 |
20,155 | threeML/astromodels | astromodels/core/model.py | Model.save | def save(self, output_file, overwrite=False):
"""Save the model to disk"""
if os.path.exists(output_file) and overwrite is False:
raise ModelFileExists("The file %s exists already. If you want to overwrite it, use the 'overwrite=True' "
"options as 'model.save(\"%s\", overwrite=True)'. " % (output_file, output_file))
else:
data = self.to_dict_with_types()
# Write it to disk
try:
# Get the YAML representation of the data
representation = my_yaml.dump(data, default_flow_style=False)
with open(output_file, "w+") as f:
# Add a new line at the end of each voice (just for clarity)
f.write(representation.replace("\n", "\n\n"))
except IOError:
raise CannotWriteModel(os.path.dirname(os.path.abspath(output_file)),
"Could not write model file %s. Check your permissions to write or the "
"report on the free space which follows: " % output_file) | python | def save(self, output_file, overwrite=False):
if os.path.exists(output_file) and overwrite is False:
raise ModelFileExists("The file %s exists already. If you want to overwrite it, use the 'overwrite=True' "
"options as 'model.save(\"%s\", overwrite=True)'. " % (output_file, output_file))
else:
data = self.to_dict_with_types()
# Write it to disk
try:
# Get the YAML representation of the data
representation = my_yaml.dump(data, default_flow_style=False)
with open(output_file, "w+") as f:
# Add a new line at the end of each voice (just for clarity)
f.write(representation.replace("\n", "\n\n"))
except IOError:
raise CannotWriteModel(os.path.dirname(os.path.abspath(output_file)),
"Could not write model file %s. Check your permissions to write or the "
"report on the free space which follows: " % output_file) | [
"def",
"save",
"(",
"self",
",",
"output_file",
",",
"overwrite",
"=",
"False",
")",
":",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"output_file",
")",
"and",
"overwrite",
"is",
"False",
":",
"raise",
"ModelFileExists",
"(",
"\"The file %s exists already.... | Save the model to disk | [
"Save",
"the",
"model",
"to",
"disk"
] | 9aac365a372f77603039533df9a6b694c1e360d5 | https://github.com/threeML/astromodels/blob/9aac365a372f77603039533df9a6b694c1e360d5/astromodels/core/model.py#L915-L946 |
20,156 | threeML/astromodels | astromodels/core/model.py | Model.get_point_source_fluxes | def get_point_source_fluxes(self, id, energies, tag=None):
"""
Get the fluxes from the id-th point source
:param id: id of the source
:param energies: energies at which you need the flux
:param tag: a tuple (integration variable, a, b) specifying the integration to perform. If this
parameter is specified then the returned value will be the average flux for the source computed as the integral
between a and b over the integration variable divided by (b-a). The integration variable must be an independent
variable contained in the model. If b is None, then instead of integrating the integration variable will be
set to a and the model evaluated in a.
:return: fluxes
"""
return self._point_sources.values()[id](energies, tag=tag) | python | def get_point_source_fluxes(self, id, energies, tag=None):
return self._point_sources.values()[id](energies, tag=tag) | [
"def",
"get_point_source_fluxes",
"(",
"self",
",",
"id",
",",
"energies",
",",
"tag",
"=",
"None",
")",
":",
"return",
"self",
".",
"_point_sources",
".",
"values",
"(",
")",
"[",
"id",
"]",
"(",
"energies",
",",
"tag",
"=",
"tag",
")"
] | Get the fluxes from the id-th point source
:param id: id of the source
:param energies: energies at which you need the flux
:param tag: a tuple (integration variable, a, b) specifying the integration to perform. If this
parameter is specified then the returned value will be the average flux for the source computed as the integral
between a and b over the integration variable divided by (b-a). The integration variable must be an independent
variable contained in the model. If b is None, then instead of integrating the integration variable will be
set to a and the model evaluated in a.
:return: fluxes | [
"Get",
"the",
"fluxes",
"from",
"the",
"id",
"-",
"th",
"point",
"source"
] | 9aac365a372f77603039533df9a6b694c1e360d5 | https://github.com/threeML/astromodels/blob/9aac365a372f77603039533df9a6b694c1e360d5/astromodels/core/model.py#L968-L982 |
20,157 | threeML/astromodels | astromodels/core/model.py | Model.get_extended_source_fluxes | def get_extended_source_fluxes(self, id, j2000_ra, j2000_dec, energies):
"""
Get the flux of the id-th extended sources at the given position at the given energies
:param id: id of the source
:param j2000_ra: R.A. where the flux is desired
:param j2000_dec: Dec. where the flux is desired
:param energies: energies at which the flux is desired
:return: flux array
"""
return self._extended_sources.values()[id](j2000_ra, j2000_dec, energies) | python | def get_extended_source_fluxes(self, id, j2000_ra, j2000_dec, energies):
return self._extended_sources.values()[id](j2000_ra, j2000_dec, energies) | [
"def",
"get_extended_source_fluxes",
"(",
"self",
",",
"id",
",",
"j2000_ra",
",",
"j2000_dec",
",",
"energies",
")",
":",
"return",
"self",
".",
"_extended_sources",
".",
"values",
"(",
")",
"[",
"id",
"]",
"(",
"j2000_ra",
",",
"j2000_dec",
",",
"energie... | Get the flux of the id-th extended sources at the given position at the given energies
:param id: id of the source
:param j2000_ra: R.A. where the flux is desired
:param j2000_dec: Dec. where the flux is desired
:param energies: energies at which the flux is desired
:return: flux array | [
"Get",
"the",
"flux",
"of",
"the",
"id",
"-",
"th",
"extended",
"sources",
"at",
"the",
"given",
"position",
"at",
"the",
"given",
"energies"
] | 9aac365a372f77603039533df9a6b694c1e360d5 | https://github.com/threeML/astromodels/blob/9aac365a372f77603039533df9a6b694c1e360d5/astromodels/core/model.py#L996-L1007 |
20,158 | threeML/astromodels | astromodels/utils/long_path_formatter.py | long_path_formatter | def long_path_formatter(line, max_width=pd.get_option('max_colwidth')):
"""
If a path is longer than max_width, it substitute it with the first and last element,
joined by "...". For example 'this.is.a.long.path.which.we.want.to.shorten' becomes
'this...shorten'
:param line:
:param max_width:
:return:
"""
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 | python | 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 | [
"def",
"long_path_formatter",
"(",
"line",
",",
"max_width",
"=",
"pd",
".",
"get_option",
"(",
"'max_colwidth'",
")",
")",
":",
"if",
"len",
"(",
"line",
")",
">",
"max_width",
":",
"tokens",
"=",
"line",
".",
"split",
"(",
"\".\"",
")",
"trial1",
"="... | If a path is longer than max_width, it substitute it with the first and last element,
joined by "...". For example 'this.is.a.long.path.which.we.want.to.shorten' becomes
'this...shorten'
:param line:
:param max_width:
:return: | [
"If",
"a",
"path",
"is",
"longer",
"than",
"max_width",
"it",
"substitute",
"it",
"with",
"the",
"first",
"and",
"last",
"element",
"joined",
"by",
"...",
".",
"For",
"example",
"this",
".",
"is",
".",
"a",
".",
"long",
".",
"path",
".",
"which",
"."... | 9aac365a372f77603039533df9a6b694c1e360d5 | https://github.com/threeML/astromodels/blob/9aac365a372f77603039533df9a6b694c1e360d5/astromodels/utils/long_path_formatter.py#L4-L30 |
20,159 | threeML/astromodels | astromodels/sources/point_source.py | PointSource.has_free_parameters | def has_free_parameters(self):
"""
Returns True or False whether there is any parameter in this source
:return:
"""
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 | python | 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 | [
"def",
"has_free_parameters",
"(",
"self",
")",
":",
"for",
"component",
"in",
"self",
".",
"_components",
".",
"values",
"(",
")",
":",
"for",
"par",
"in",
"component",
".",
"shape",
".",
"parameters",
".",
"values",
"(",
")",
":",
"if",
"par",
".",
... | Returns True or False whether there is any parameter in this source
:return: | [
"Returns",
"True",
"or",
"False",
"whether",
"there",
"is",
"any",
"parameter",
"in",
"this",
"source"
] | 9aac365a372f77603039533df9a6b694c1e360d5 | https://github.com/threeML/astromodels/blob/9aac365a372f77603039533df9a6b694c1e360d5/astromodels/sources/point_source.py#L214-L235 |
20,160 | threeML/astromodels | astromodels/sources/point_source.py | PointSource._repr__base | def _repr__base(self, rich_output=False):
"""
Representation of the object
:param rich_output: if True, generates HTML, otherwise text
:return: the representation
"""
# Make a dictionary which will then be transformed in a list
repr_dict = collections.OrderedDict()
key = '%s (point source)' % self.name
repr_dict[key] = collections.OrderedDict()
repr_dict[key]['position'] = self._sky_position.to_dict(minimal=True)
repr_dict[key]['spectrum'] = collections.OrderedDict()
for component_name, component in self.components.iteritems():
repr_dict[key]['spectrum'][component_name] = component.to_dict(minimal=True)
return dict_to_list(repr_dict, rich_output) | python | def _repr__base(self, rich_output=False):
# Make a dictionary which will then be transformed in a list
repr_dict = collections.OrderedDict()
key = '%s (point source)' % self.name
repr_dict[key] = collections.OrderedDict()
repr_dict[key]['position'] = self._sky_position.to_dict(minimal=True)
repr_dict[key]['spectrum'] = collections.OrderedDict()
for component_name, component in self.components.iteritems():
repr_dict[key]['spectrum'][component_name] = component.to_dict(minimal=True)
return dict_to_list(repr_dict, rich_output) | [
"def",
"_repr__base",
"(",
"self",
",",
"rich_output",
"=",
"False",
")",
":",
"# Make a dictionary which will then be transformed in a list",
"repr_dict",
"=",
"collections",
".",
"OrderedDict",
"(",
")",
"key",
"=",
"'%s (point source)'",
"%",
"self",
".",
"name",
... | Representation of the object
:param rich_output: if True, generates HTML, otherwise text
:return: the representation | [
"Representation",
"of",
"the",
"object"
] | 9aac365a372f77603039533df9a6b694c1e360d5 | https://github.com/threeML/astromodels/blob/9aac365a372f77603039533df9a6b694c1e360d5/astromodels/sources/point_source.py#L287-L309 |
20,161 | threeML/astromodels | astromodels/functions/function.py | get_function | def get_function(function_name, composite_function_expression=None):
"""
Returns the function "name", which must be among the known functions or a composite function.
:param function_name: the name of the function (use 'composite' if the function is a composite function)
:param composite_function_expression: composite function specification such as
((((powerlaw{1} + (sin{2} * 3)) + (sin{2} * 25)) - (powerlaw{1} * 16)) + (sin{2} ** 3.0))
:return: the an instance of the requested class
"""
# Check whether this is a composite function or a simple function
if composite_function_expression is not None:
# Composite function
return _parse_function_expression(composite_function_expression)
else:
if function_name in _known_functions:
return _known_functions[function_name]()
else:
# Maybe this is a template
# NOTE: import here to avoid circular import
from astromodels.functions.template_model import TemplateModel, MissingDataFile
try:
instance = TemplateModel(function_name)
except MissingDataFile:
raise UnknownFunction("Function %s is not known. Known functions are: %s" %
(function_name, ",".join(_known_functions.keys())))
else:
return instance | python | def get_function(function_name, composite_function_expression=None):
# Check whether this is a composite function or a simple function
if composite_function_expression is not None:
# Composite function
return _parse_function_expression(composite_function_expression)
else:
if function_name in _known_functions:
return _known_functions[function_name]()
else:
# Maybe this is a template
# NOTE: import here to avoid circular import
from astromodels.functions.template_model import TemplateModel, MissingDataFile
try:
instance = TemplateModel(function_name)
except MissingDataFile:
raise UnknownFunction("Function %s is not known. Known functions are: %s" %
(function_name, ",".join(_known_functions.keys())))
else:
return instance | [
"def",
"get_function",
"(",
"function_name",
",",
"composite_function_expression",
"=",
"None",
")",
":",
"# Check whether this is a composite function or a simple function",
"if",
"composite_function_expression",
"is",
"not",
"None",
":",
"# Composite function",
"return",
"_pa... | Returns the function "name", which must be among the known functions or a composite function.
:param function_name: the name of the function (use 'composite' if the function is a composite function)
:param composite_function_expression: composite function specification such as
((((powerlaw{1} + (sin{2} * 3)) + (sin{2} * 25)) - (powerlaw{1} * 16)) + (sin{2} ** 3.0))
:return: the an instance of the requested class | [
"Returns",
"the",
"function",
"name",
"which",
"must",
"be",
"among",
"the",
"known",
"functions",
"or",
"a",
"composite",
"function",
"."
] | 9aac365a372f77603039533df9a6b694c1e360d5 | https://github.com/threeML/astromodels/blob/9aac365a372f77603039533df9a6b694c1e360d5/astromodels/functions/function.py#L1566-L1609 |
20,162 | threeML/astromodels | astromodels/functions/function.py | get_function_class | def get_function_class(function_name):
"""
Return the type for the requested function
:param function_name: the function to return
:return: the type for that function (i.e., this is a class, not an instance)
"""
if function_name in _known_functions:
return _known_functions[function_name]
else:
raise UnknownFunction("Function %s is not known. Known functions are: %s" %
(function_name, ",".join(_known_functions.keys()))) | python | def get_function_class(function_name):
if function_name in _known_functions:
return _known_functions[function_name]
else:
raise UnknownFunction("Function %s is not known. Known functions are: %s" %
(function_name, ",".join(_known_functions.keys()))) | [
"def",
"get_function_class",
"(",
"function_name",
")",
":",
"if",
"function_name",
"in",
"_known_functions",
":",
"return",
"_known_functions",
"[",
"function_name",
"]",
"else",
":",
"raise",
"UnknownFunction",
"(",
"\"Function %s is not known. Known functions are: %s\"",... | Return the type for the requested function
:param function_name: the function to return
:return: the type for that function (i.e., this is a class, not an instance) | [
"Return",
"the",
"type",
"for",
"the",
"requested",
"function"
] | 9aac365a372f77603039533df9a6b694c1e360d5 | https://github.com/threeML/astromodels/blob/9aac365a372f77603039533df9a6b694c1e360d5/astromodels/functions/function.py#L1612-L1627 |
20,163 | threeML/astromodels | astromodels/functions/function.py | FunctionMeta.check_calling_sequence | def check_calling_sequence(name, function_name, function, possible_variables):
"""
Check the calling sequence for the function looking for the variables specified.
One or more of the variables can be in the calling sequence. Note that the
order of the variables will be enforced.
It will also enforce that the first parameter in the calling sequence is called 'self'.
:param function: the function to check
:param possible_variables: a list of variables to check, The order is important, and will be enforced
:return: a tuple containing the list of found variables, and the name of the other parameters in the calling
sequence
"""
# Get calling sequence
# If the function has been memoized, it will have a "input_object" member
try:
calling_sequence = inspect.getargspec(function.input_object).args
except AttributeError:
# This might happen if the function is with memoization
calling_sequence = inspect.getargspec(function).args
assert calling_sequence[0] == 'self', "Wrong syntax for 'evaluate' in %s. The first argument " \
"should be called 'self'." % name
# Figure out how many variables are used
variables = filter(lambda var: var in possible_variables, calling_sequence)
# Check that they actually make sense. They must be used in the same order
# as specified in possible_variables
assert len(variables) > 0, "The name of the variables for 'evaluate' in %s must be one or more " \
"among %s, instead of %s" % (name, ','.join(possible_variables), ",".join(variables))
if variables != possible_variables[:len(variables)]:
raise AssertionError("The variables %s are out of order in '%s' of %s. Should be %s."
% (",".join(variables), function_name, name, possible_variables[:len(variables)]))
other_parameters = filter(lambda var: var not in variables and var != 'self', calling_sequence)
return variables, other_parameters | python | def check_calling_sequence(name, function_name, function, possible_variables):
# Get calling sequence
# If the function has been memoized, it will have a "input_object" member
try:
calling_sequence = inspect.getargspec(function.input_object).args
except AttributeError:
# This might happen if the function is with memoization
calling_sequence = inspect.getargspec(function).args
assert calling_sequence[0] == 'self', "Wrong syntax for 'evaluate' in %s. The first argument " \
"should be called 'self'." % name
# Figure out how many variables are used
variables = filter(lambda var: var in possible_variables, calling_sequence)
# Check that they actually make sense. They must be used in the same order
# as specified in possible_variables
assert len(variables) > 0, "The name of the variables for 'evaluate' in %s must be one or more " \
"among %s, instead of %s" % (name, ','.join(possible_variables), ",".join(variables))
if variables != possible_variables[:len(variables)]:
raise AssertionError("The variables %s are out of order in '%s' of %s. Should be %s."
% (",".join(variables), function_name, name, possible_variables[:len(variables)]))
other_parameters = filter(lambda var: var not in variables and var != 'self', calling_sequence)
return variables, other_parameters | [
"def",
"check_calling_sequence",
"(",
"name",
",",
"function_name",
",",
"function",
",",
"possible_variables",
")",
":",
"# Get calling sequence",
"# If the function has been memoized, it will have a \"input_object\" member",
"try",
":",
"calling_sequence",
"=",
"inspect",
"."... | Check the calling sequence for the function looking for the variables specified.
One or more of the variables can be in the calling sequence. Note that the
order of the variables will be enforced.
It will also enforce that the first parameter in the calling sequence is called 'self'.
:param function: the function to check
:param possible_variables: a list of variables to check, The order is important, and will be enforced
:return: a tuple containing the list of found variables, and the name of the other parameters in the calling
sequence | [
"Check",
"the",
"calling",
"sequence",
"for",
"the",
"function",
"looking",
"for",
"the",
"variables",
"specified",
".",
"One",
"or",
"more",
"of",
"the",
"variables",
"can",
"be",
"in",
"the",
"calling",
"sequence",
".",
"Note",
"that",
"the",
"order",
"o... | 9aac365a372f77603039533df9a6b694c1e360d5 | https://github.com/threeML/astromodels/blob/9aac365a372f77603039533df9a6b694c1e360d5/astromodels/functions/function.py#L339-L385 |
20,164 | threeML/astromodels | astromodels/functions/function.py | Function.free_parameters | def free_parameters(self):
"""
Returns a dictionary of free parameters for this function
:return: dictionary of free parameters
"""
free_parameters = collections.OrderedDict([(k,v) for k, v in self.parameters.iteritems() if v.free])
return free_parameters | python | def free_parameters(self):
free_parameters = collections.OrderedDict([(k,v) for k, v in self.parameters.iteritems() if v.free])
return free_parameters | [
"def",
"free_parameters",
"(",
"self",
")",
":",
"free_parameters",
"=",
"collections",
".",
"OrderedDict",
"(",
"[",
"(",
"k",
",",
"v",
")",
"for",
"k",
",",
"v",
"in",
"self",
".",
"parameters",
".",
"iteritems",
"(",
")",
"if",
"v",
".",
"free",
... | Returns a dictionary of free parameters for this function
:return: dictionary of free parameters | [
"Returns",
"a",
"dictionary",
"of",
"free",
"parameters",
"for",
"this",
"function"
] | 9aac365a372f77603039533df9a6b694c1e360d5 | https://github.com/threeML/astromodels/blob/9aac365a372f77603039533df9a6b694c1e360d5/astromodels/functions/function.py#L518-L527 |
20,165 | threeML/astromodels | astromodels/utils/data_files.py | _get_data_file_path | def _get_data_file_path(data_file):
"""
Returns the absolute path to the required data files.
:param data_file: relative path to the data file, relative to the astromodels/data path.
So to get the path to data/dark_matter/gammamc_dif.dat you need to use data_file="dark_matter/gammamc_dif.dat"
:return: absolute path of the data file
"""
try:
file_path = pkg_resources.resource_filename("astromodels", 'data/%s' % data_file)
except KeyError:
raise IOError("Could not read or find data file %s. Try reinstalling astromodels. If this does not fix your "
"problem, open an issue on github." % (data_file))
else:
return os.path.abspath(file_path) | python | def _get_data_file_path(data_file):
try:
file_path = pkg_resources.resource_filename("astromodels", 'data/%s' % data_file)
except KeyError:
raise IOError("Could not read or find data file %s. Try reinstalling astromodels. If this does not fix your "
"problem, open an issue on github." % (data_file))
else:
return os.path.abspath(file_path) | [
"def",
"_get_data_file_path",
"(",
"data_file",
")",
":",
"try",
":",
"file_path",
"=",
"pkg_resources",
".",
"resource_filename",
"(",
"\"astromodels\"",
",",
"'data/%s'",
"%",
"data_file",
")",
"except",
"KeyError",
":",
"raise",
"IOError",
"(",
"\"Could not rea... | Returns the absolute path to the required data files.
:param data_file: relative path to the data file, relative to the astromodels/data path.
So to get the path to data/dark_matter/gammamc_dif.dat you need to use data_file="dark_matter/gammamc_dif.dat"
:return: absolute path of the data file | [
"Returns",
"the",
"absolute",
"path",
"to",
"the",
"required",
"data",
"files",
"."
] | 9aac365a372f77603039533df9a6b694c1e360d5 | https://github.com/threeML/astromodels/blob/9aac365a372f77603039533df9a6b694c1e360d5/astromodels/utils/data_files.py#L5-L25 |
20,166 | threeML/astromodels | astromodels/functions/dark_matter/dm_models.py | DMFitFunction._setup | def _setup(self):
tablepath = _get_data_file_path("dark_matter/gammamc_dif.dat")
self._data = np.loadtxt(tablepath)
"""
Mapping between the channel codes and the rows in the gammamc file
1 : 8, # ee
2 : 6, # mumu
3 : 3, # tautau
4 : 1, # bb
5 : 2, # tt
6 : 7, # gg
7 : 4, # ww
8 : 5, # zz
9 : 0, # cc
10 : 10, # uu
11 : 11, # dd
12 : 9, # ss
"""
channel_index_mapping = {
1: 8, # ee
2: 6, # mumu
3: 3, # tautau
4: 1, # bb
5: 2, # tt
6: 7, # gg
7: 4, # ww
8: 5, # zz
9: 0, # cc
10: 10, # uu
11: 11, # dd
12: 9, # ss
}
# Number of decades in x = log10(E/M)
ndec = 10.0
xedge = np.linspace(0, 1.0, 251)
self._x = 0.5 * (xedge[1:] + xedge[:-1]) * ndec - ndec
ichan = channel_index_mapping[int(self.channel.value)]
# These are the mass points
self._mass = np.array([2.0, 4.0, 6.0, 8.0, 10.0,
25.0, 50.0, 80.3, 91.2, 100.0,
150.0, 176.0, 200.0, 250.0, 350.0, 500.0, 750.0,
1000.0, 1500.0, 2000.0, 3000.0, 5000.0, 7000.0, 1E4])
self._dn = self._data.reshape((12, 24, 250))
self._dn_interp = RegularGridInterpolator([self._mass, self._x],
self._dn[ichan, :, :],
bounds_error=False,
fill_value=None)
if self.mass.value > 10000:
print "Warning: DMFitFunction only appropriate for masses <= 10 TeV"
print "To model DM from 2 GeV < mass < 1 PeV use DMSpectra" | python | def _setup(self):
tablepath = _get_data_file_path("dark_matter/gammamc_dif.dat")
self._data = np.loadtxt(tablepath)
channel_index_mapping = {
1: 8, # ee
2: 6, # mumu
3: 3, # tautau
4: 1, # bb
5: 2, # tt
6: 7, # gg
7: 4, # ww
8: 5, # zz
9: 0, # cc
10: 10, # uu
11: 11, # dd
12: 9, # ss
}
# Number of decades in x = log10(E/M)
ndec = 10.0
xedge = np.linspace(0, 1.0, 251)
self._x = 0.5 * (xedge[1:] + xedge[:-1]) * ndec - ndec
ichan = channel_index_mapping[int(self.channel.value)]
# These are the mass points
self._mass = np.array([2.0, 4.0, 6.0, 8.0, 10.0,
25.0, 50.0, 80.3, 91.2, 100.0,
150.0, 176.0, 200.0, 250.0, 350.0, 500.0, 750.0,
1000.0, 1500.0, 2000.0, 3000.0, 5000.0, 7000.0, 1E4])
self._dn = self._data.reshape((12, 24, 250))
self._dn_interp = RegularGridInterpolator([self._mass, self._x],
self._dn[ichan, :, :],
bounds_error=False,
fill_value=None)
if self.mass.value > 10000:
print "Warning: DMFitFunction only appropriate for masses <= 10 TeV"
print "To model DM from 2 GeV < mass < 1 PeV use DMSpectra" | [
"def",
"_setup",
"(",
"self",
")",
":",
"tablepath",
"=",
"_get_data_file_path",
"(",
"\"dark_matter/gammamc_dif.dat\"",
")",
"self",
".",
"_data",
"=",
"np",
".",
"loadtxt",
"(",
"tablepath",
")",
"channel_index_mapping",
"=",
"{",
"1",
":",
"8",
",",
"# ee... | Mapping between the channel codes and the rows in the gammamc file
1 : 8, # ee
2 : 6, # mumu
3 : 3, # tautau
4 : 1, # bb
5 : 2, # tt
6 : 7, # gg
7 : 4, # ww
8 : 5, # zz
9 : 0, # cc
10 : 10, # uu
11 : 11, # dd
12 : 9, # ss | [
"Mapping",
"between",
"the",
"channel",
"codes",
"and",
"the",
"rows",
"in",
"the",
"gammamc",
"file"
] | 9aac365a372f77603039533df9a6b694c1e360d5 | https://github.com/threeML/astromodels/blob/9aac365a372f77603039533df9a6b694c1e360d5/astromodels/functions/dark_matter/dm_models.py#L48-L108 |
20,167 | threeML/astromodels | astromodels/functions/dark_matter/dm_models.py | DMSpectra._setup | def _setup(self):
# Get and open the two data files
tablepath_h = _get_data_file_path("dark_matter/dmSpecTab.npy")
self._data_h = np.load(tablepath_h)
tablepath_f = _get_data_file_path("dark_matter/gammamc_dif.dat")
self._data_f = np.loadtxt(tablepath_f)
"""
Mapping between the channel codes and the rows in the gammamc file
dmSpecTab.npy created to match this mapping too
1 : 8, # ee
2 : 6, # mumu
3 : 3, # tautau
4 : 1, # bb
5 : 2, # tt
6 : 7, # gg
7 : 4, # ww
8 : 5, # zz
9 : 0, # cc
10 : 10, # uu
11 : 11, # dd
12 : 9, # ss
"""
channel_index_mapping = {
1: 8, # ee
2: 6, # mumu
3: 3, # tautau
4: 1, # bb
5: 2, # tt
6: 7, # gg
7: 4, # ww
8: 5, # zz
9: 0, # cc
10: 10, # uu
11: 11, # dd
12: 9, # ss
}
# Number of decades in x = log10(E/M)
ndec = 10.0
xedge = np.linspace(0, 1.0, 251)
self._x = 0.5 * (xedge[1:] + xedge[:-1]) * ndec - ndec
ichan = channel_index_mapping[int(self.channel.value)]
# These are the mass points in GeV
self._mass_h = np.array([50., 61.2, 74.91, 91.69, 112.22, 137.36, 168.12, 205.78, 251.87, 308.29,
377.34, 461.86, 565.31, 691.93, 846.91, 1036.6, 1268.78, 1552.97, 1900.82,
2326.57, 2847.69, 3485.53, 4266.23, 5221.81, 6391.41, 7823.0, 9575.23,
11719.94, 14345.03, 17558.1, 21490.85, 26304.48, 32196.3, 39407.79, 48234.54,
59038.36, 72262.07, 88447.7, 108258.66, 132506.99, 162186.57, 198513.95,
242978.11, 297401.58, 364015.09, 445549.04, 545345.37, 667494.6, 817003.43, 1000000.])
# These are the mass points in GeV
self._mass_f = np.array([2.0, 4.0, 6.0, 8.0, 10.0,
25.0, 50.0, 80.3, 91.2, 100.0,
150.0, 176.0, 200.0, 250.0, 350.0, 500.0, 750.0,
1000.0, 1500.0, 2000.0, 3000.0, 5000.0, 7000.0, 1E4])
self._mass = np.append(self._mass_f, self._mass_h[27:])
self._dn_f = self._data_f.reshape((12, 24, 250))
# Is this really used?
self._dn_h = self._data_h
self._dn = np.zeros((12, len(self._mass), 250))
self._dn[:, 0:24, :] = self._dn_f
self._dn[:, 24:, :] = self._dn_h[:, 27:, :]
self._dn_interp = RegularGridInterpolator([self._mass, self._x],
self._dn[ichan, :, :],
bounds_error=False,
fill_value=None)
if self.channel.value in [1, 6, 7] and self.mass.value > 10000.:
print "ERROR: currently spectra for selected channel and mass not implemented."
print "Spectra for channels ['ee','gg','WW'] currently not available for mass > 10 TeV" | python | def _setup(self):
# Get and open the two data files
tablepath_h = _get_data_file_path("dark_matter/dmSpecTab.npy")
self._data_h = np.load(tablepath_h)
tablepath_f = _get_data_file_path("dark_matter/gammamc_dif.dat")
self._data_f = np.loadtxt(tablepath_f)
channel_index_mapping = {
1: 8, # ee
2: 6, # mumu
3: 3, # tautau
4: 1, # bb
5: 2, # tt
6: 7, # gg
7: 4, # ww
8: 5, # zz
9: 0, # cc
10: 10, # uu
11: 11, # dd
12: 9, # ss
}
# Number of decades in x = log10(E/M)
ndec = 10.0
xedge = np.linspace(0, 1.0, 251)
self._x = 0.5 * (xedge[1:] + xedge[:-1]) * ndec - ndec
ichan = channel_index_mapping[int(self.channel.value)]
# These are the mass points in GeV
self._mass_h = np.array([50., 61.2, 74.91, 91.69, 112.22, 137.36, 168.12, 205.78, 251.87, 308.29,
377.34, 461.86, 565.31, 691.93, 846.91, 1036.6, 1268.78, 1552.97, 1900.82,
2326.57, 2847.69, 3485.53, 4266.23, 5221.81, 6391.41, 7823.0, 9575.23,
11719.94, 14345.03, 17558.1, 21490.85, 26304.48, 32196.3, 39407.79, 48234.54,
59038.36, 72262.07, 88447.7, 108258.66, 132506.99, 162186.57, 198513.95,
242978.11, 297401.58, 364015.09, 445549.04, 545345.37, 667494.6, 817003.43, 1000000.])
# These are the mass points in GeV
self._mass_f = np.array([2.0, 4.0, 6.0, 8.0, 10.0,
25.0, 50.0, 80.3, 91.2, 100.0,
150.0, 176.0, 200.0, 250.0, 350.0, 500.0, 750.0,
1000.0, 1500.0, 2000.0, 3000.0, 5000.0, 7000.0, 1E4])
self._mass = np.append(self._mass_f, self._mass_h[27:])
self._dn_f = self._data_f.reshape((12, 24, 250))
# Is this really used?
self._dn_h = self._data_h
self._dn = np.zeros((12, len(self._mass), 250))
self._dn[:, 0:24, :] = self._dn_f
self._dn[:, 24:, :] = self._dn_h[:, 27:, :]
self._dn_interp = RegularGridInterpolator([self._mass, self._x],
self._dn[ichan, :, :],
bounds_error=False,
fill_value=None)
if self.channel.value in [1, 6, 7] and self.mass.value > 10000.:
print "ERROR: currently spectra for selected channel and mass not implemented."
print "Spectra for channels ['ee','gg','WW'] currently not available for mass > 10 TeV" | [
"def",
"_setup",
"(",
"self",
")",
":",
"# Get and open the two data files",
"tablepath_h",
"=",
"_get_data_file_path",
"(",
"\"dark_matter/dmSpecTab.npy\"",
")",
"self",
".",
"_data_h",
"=",
"np",
".",
"load",
"(",
"tablepath_h",
")",
"tablepath_f",
"=",
"_get_data... | Mapping between the channel codes and the rows in the gammamc file
dmSpecTab.npy created to match this mapping too
1 : 8, # ee
2 : 6, # mumu
3 : 3, # tautau
4 : 1, # bb
5 : 2, # tt
6 : 7, # gg
7 : 4, # ww
8 : 5, # zz
9 : 0, # cc
10 : 10, # uu
11 : 11, # dd
12 : 9, # ss | [
"Mapping",
"between",
"the",
"channel",
"codes",
"and",
"the",
"rows",
"in",
"the",
"gammamc",
"file",
"dmSpecTab",
".",
"npy",
"created",
"to",
"match",
"this",
"mapping",
"too"
] | 9aac365a372f77603039533df9a6b694c1e360d5 | https://github.com/threeML/astromodels/blob/9aac365a372f77603039533df9a6b694c1e360d5/astromodels/functions/dark_matter/dm_models.py#L209-L291 |
20,168 | threeML/astromodels | astromodels/utils/valid_variable.py | is_valid_variable_name | def is_valid_variable_name(string_to_check):
"""
Returns whether the provided name is a valid variable name in Python
:param string_to_check: the string to be checked
:return: True or False
"""
try:
parse('{} = None'.format(string_to_check))
return True
except (SyntaxError, ValueError, TypeError):
return False | python | def is_valid_variable_name(string_to_check):
try:
parse('{} = None'.format(string_to_check))
return True
except (SyntaxError, ValueError, TypeError):
return False | [
"def",
"is_valid_variable_name",
"(",
"string_to_check",
")",
":",
"try",
":",
"parse",
"(",
"'{} = None'",
".",
"format",
"(",
"string_to_check",
")",
")",
"return",
"True",
"except",
"(",
"SyntaxError",
",",
"ValueError",
",",
"TypeError",
")",
":",
"return"... | Returns whether the provided name is a valid variable name in Python
:param string_to_check: the string to be checked
:return: True or False | [
"Returns",
"whether",
"the",
"provided",
"name",
"is",
"a",
"valid",
"variable",
"name",
"in",
"Python"
] | 9aac365a372f77603039533df9a6b694c1e360d5 | https://github.com/threeML/astromodels/blob/9aac365a372f77603039533df9a6b694c1e360d5/astromodels/utils/valid_variable.py#L4-L19 |
20,169 | threeML/astromodels | astromodels/core/units.py | _check_unit | def _check_unit(new_unit, old_unit):
"""
Check that the new unit is compatible with the old unit for the quantity described by variable_name
:param new_unit: instance of astropy.units.Unit
:param old_unit: instance of astropy.units.Unit
:return: nothin
"""
try:
new_unit.physical_type
except AttributeError:
raise UnitMismatch("The provided unit (%s) has no physical type. Was expecting a unit for %s"
% (new_unit, old_unit.physical_type))
if new_unit.physical_type != old_unit.physical_type:
raise UnitMismatch("Physical type mismatch: you provided a unit for %s instead of a unit for %s"
% (new_unit.physical_type, old_unit.physical_type)) | python | def _check_unit(new_unit, old_unit):
try:
new_unit.physical_type
except AttributeError:
raise UnitMismatch("The provided unit (%s) has no physical type. Was expecting a unit for %s"
% (new_unit, old_unit.physical_type))
if new_unit.physical_type != old_unit.physical_type:
raise UnitMismatch("Physical type mismatch: you provided a unit for %s instead of a unit for %s"
% (new_unit.physical_type, old_unit.physical_type)) | [
"def",
"_check_unit",
"(",
"new_unit",
",",
"old_unit",
")",
":",
"try",
":",
"new_unit",
".",
"physical_type",
"except",
"AttributeError",
":",
"raise",
"UnitMismatch",
"(",
"\"The provided unit (%s) has no physical type. Was expecting a unit for %s\"",
"%",
"(",
"new_un... | Check that the new unit is compatible with the old unit for the quantity described by variable_name
:param new_unit: instance of astropy.units.Unit
:param old_unit: instance of astropy.units.Unit
:return: nothin | [
"Check",
"that",
"the",
"new",
"unit",
"is",
"compatible",
"with",
"the",
"old",
"unit",
"for",
"the",
"quantity",
"described",
"by",
"variable_name"
] | 9aac365a372f77603039533df9a6b694c1e360d5 | https://github.com/threeML/astromodels/blob/9aac365a372f77603039533df9a6b694c1e360d5/astromodels/core/units.py#L29-L50 |
20,170 | threeML/astromodels | astromodels/functions/functions.py | Log_parabola.peak_energy | def peak_energy(self):
"""
Returns the peak energy in the nuFnu spectrum
:return: peak energy in keV
"""
# Eq. 6 in Massaro et al. 2004
# (http://adsabs.harvard.edu/abs/2004A%26A...413..489M)
return self.piv.value * pow(10, ((2 + self.alpha.value) * np.log(10)) / (2 * self.beta.value)) | python | def peak_energy(self):
# Eq. 6 in Massaro et al. 2004
# (http://adsabs.harvard.edu/abs/2004A%26A...413..489M)
return self.piv.value * pow(10, ((2 + self.alpha.value) * np.log(10)) / (2 * self.beta.value)) | [
"def",
"peak_energy",
"(",
"self",
")",
":",
"# Eq. 6 in Massaro et al. 2004",
"# (http://adsabs.harvard.edu/abs/2004A%26A...413..489M)",
"return",
"self",
".",
"piv",
".",
"value",
"*",
"pow",
"(",
"10",
",",
"(",
"(",
"2",
"+",
"self",
".",
"alpha",
".",
"valu... | Returns the peak energy in the nuFnu spectrum
:return: peak energy in keV | [
"Returns",
"the",
"peak",
"energy",
"in",
"the",
"nuFnu",
"spectrum"
] | 9aac365a372f77603039533df9a6b694c1e360d5 | https://github.com/threeML/astromodels/blob/9aac365a372f77603039533df9a6b694c1e360d5/astromodels/functions/functions.py#L1562-L1572 |
20,171 | threeML/astromodels | astromodels/core/parameter.py | ParameterBase.in_unit_of | def in_unit_of(self, unit, as_quantity=False):
"""
Return the current value transformed to the new units
:param unit: either an astropy.Unit instance, or a string which can be converted to an astropy.Unit
instance, like "1 / (erg cm**2 s)"
:param as_quantity: if True, the method return an astropy.Quantity, if False just a floating point number.
Default is False
:return: either a floating point or a astropy.Quantity depending on the value of "as_quantity"
"""
new_unit = u.Unit(unit)
new_quantity = self.as_quantity.to(new_unit)
if as_quantity:
return new_quantity
else:
return new_quantity.value | python | def in_unit_of(self, unit, as_quantity=False):
new_unit = u.Unit(unit)
new_quantity = self.as_quantity.to(new_unit)
if as_quantity:
return new_quantity
else:
return new_quantity.value | [
"def",
"in_unit_of",
"(",
"self",
",",
"unit",
",",
"as_quantity",
"=",
"False",
")",
":",
"new_unit",
"=",
"u",
".",
"Unit",
"(",
"unit",
")",
"new_quantity",
"=",
"self",
".",
"as_quantity",
".",
"to",
"(",
"new_unit",
")",
"if",
"as_quantity",
":",
... | Return the current value transformed to the new units
:param unit: either an astropy.Unit instance, or a string which can be converted to an astropy.Unit
instance, like "1 / (erg cm**2 s)"
:param as_quantity: if True, the method return an astropy.Quantity, if False just a floating point number.
Default is False
:return: either a floating point or a astropy.Quantity depending on the value of "as_quantity" | [
"Return",
"the",
"current",
"value",
"transformed",
"to",
"the",
"new",
"units"
] | 9aac365a372f77603039533df9a6b694c1e360d5 | https://github.com/threeML/astromodels/blob/9aac365a372f77603039533df9a6b694c1e360d5/astromodels/core/parameter.py#L325-L346 |
20,172 | threeML/astromodels | astromodels/core/parameter.py | ParameterBase._get_value | def _get_value(self):
"""Return current parameter value"""
# This is going to be true (possibly) only for derived classes. It is here to make the code cleaner
# and also to avoid infinite recursion
if self._aux_variable:
return self._aux_variable['law'](self._aux_variable['variable'].value)
if self._transformation is None:
return self._internal_value
else:
# A transformation is set. Transform back from internal value to true value
#
# print("Interval value is %s" % self._internal_value)
# print("Returning %s" % self._transformation.backward(self._internal_value))
return self._transformation.backward(self._internal_value) | python | def _get_value(self):
# This is going to be true (possibly) only for derived classes. It is here to make the code cleaner
# and also to avoid infinite recursion
if self._aux_variable:
return self._aux_variable['law'](self._aux_variable['variable'].value)
if self._transformation is None:
return self._internal_value
else:
# A transformation is set. Transform back from internal value to true value
#
# print("Interval value is %s" % self._internal_value)
# print("Returning %s" % self._transformation.backward(self._internal_value))
return self._transformation.backward(self._internal_value) | [
"def",
"_get_value",
"(",
"self",
")",
":",
"# This is going to be true (possibly) only for derived classes. It is here to make the code cleaner",
"# and also to avoid infinite recursion",
"if",
"self",
".",
"_aux_variable",
":",
"return",
"self",
".",
"_aux_variable",
"[",
"'law... | Return current parameter value | [
"Return",
"current",
"parameter",
"value"
] | 9aac365a372f77603039533df9a6b694c1e360d5 | https://github.com/threeML/astromodels/blob/9aac365a372f77603039533df9a6b694c1e360d5/astromodels/core/parameter.py#L394-L415 |
20,173 | threeML/astromodels | astromodels/core/parameter.py | ParameterBase._set_value | def _set_value(self, new_value):
"""Sets the current value of the parameter, ensuring that it is within the allowed range."""
if self.min_value is not None and new_value < self.min_value:
raise SettingOutOfBounds(
"Trying to set parameter {0} = {1}, which is less than the minimum allowed {2}".format(
self.name, new_value, self.min_value))
if self.max_value is not None and new_value > self.max_value:
raise SettingOutOfBounds(
"Trying to set parameter {0} = {1}, which is more than the maximum allowed {2}".format(
self.name, new_value, self.max_value))
# Issue a warning if there is an auxiliary variable, as the setting does not have any effect
if self.has_auxiliary_variable():
with warnings.catch_warnings():
warnings.simplefilter("always", RuntimeWarning)
warnings.warn("You are trying to assign to a parameter which is either linked or "
"has auxiliary variables. The assignment has no effect.", RuntimeWarning)
# Save the value as a pure floating point to avoid the overhead of the astropy.units machinery when
# not needed
if self._transformation is None:
new_internal_value = new_value
else:
new_internal_value = self._transformation.forward(new_value)
# If the parameter has changed, update its value and call the callbacks if needed
if new_internal_value != self._internal_value:
# Update
self._internal_value = new_internal_value
# Call the callbacks (if any)
for callback in self._callbacks:
try:
callback(self)
except:
raise NotCallableOrErrorInCall("Could not call callback for parameter %s" % self.name) | python | def _set_value(self, new_value):
if self.min_value is not None and new_value < self.min_value:
raise SettingOutOfBounds(
"Trying to set parameter {0} = {1}, which is less than the minimum allowed {2}".format(
self.name, new_value, self.min_value))
if self.max_value is not None and new_value > self.max_value:
raise SettingOutOfBounds(
"Trying to set parameter {0} = {1}, which is more than the maximum allowed {2}".format(
self.name, new_value, self.max_value))
# Issue a warning if there is an auxiliary variable, as the setting does not have any effect
if self.has_auxiliary_variable():
with warnings.catch_warnings():
warnings.simplefilter("always", RuntimeWarning)
warnings.warn("You are trying to assign to a parameter which is either linked or "
"has auxiliary variables. The assignment has no effect.", RuntimeWarning)
# Save the value as a pure floating point to avoid the overhead of the astropy.units machinery when
# not needed
if self._transformation is None:
new_internal_value = new_value
else:
new_internal_value = self._transformation.forward(new_value)
# If the parameter has changed, update its value and call the callbacks if needed
if new_internal_value != self._internal_value:
# Update
self._internal_value = new_internal_value
# Call the callbacks (if any)
for callback in self._callbacks:
try:
callback(self)
except:
raise NotCallableOrErrorInCall("Could not call callback for parameter %s" % self.name) | [
"def",
"_set_value",
"(",
"self",
",",
"new_value",
")",
":",
"if",
"self",
".",
"min_value",
"is",
"not",
"None",
"and",
"new_value",
"<",
"self",
".",
"min_value",
":",
"raise",
"SettingOutOfBounds",
"(",
"\"Trying to set parameter {0} = {1}, which is less than th... | Sets the current value of the parameter, ensuring that it is within the allowed range. | [
"Sets",
"the",
"current",
"value",
"of",
"the",
"parameter",
"ensuring",
"that",
"it",
"is",
"within",
"the",
"allowed",
"range",
"."
] | 9aac365a372f77603039533df9a6b694c1e360d5 | https://github.com/threeML/astromodels/blob/9aac365a372f77603039533df9a6b694c1e360d5/astromodels/core/parameter.py#L420-L471 |
20,174 | threeML/astromodels | astromodels/core/parameter.py | ParameterBase._set_internal_value | def _set_internal_value(self, new_internal_value):
"""
This is supposed to be only used by fitting engines
:param new_internal_value: new value in internal representation
:return: none
"""
if new_internal_value != self._internal_value:
self._internal_value = new_internal_value
# Call callbacks if any
for callback in self._callbacks:
callback(self) | python | def _set_internal_value(self, new_internal_value):
if new_internal_value != self._internal_value:
self._internal_value = new_internal_value
# Call callbacks if any
for callback in self._callbacks:
callback(self) | [
"def",
"_set_internal_value",
"(",
"self",
",",
"new_internal_value",
")",
":",
"if",
"new_internal_value",
"!=",
"self",
".",
"_internal_value",
":",
"self",
".",
"_internal_value",
"=",
"new_internal_value",
"# Call callbacks if any",
"for",
"callback",
"in",
"self"... | This is supposed to be only used by fitting engines
:param new_internal_value: new value in internal representation
:return: none | [
"This",
"is",
"supposed",
"to",
"be",
"only",
"used",
"by",
"fitting",
"engines"
] | 9aac365a372f77603039533df9a6b694c1e360d5 | https://github.com/threeML/astromodels/blob/9aac365a372f77603039533df9a6b694c1e360d5/astromodels/core/parameter.py#L491-L507 |
20,175 | threeML/astromodels | astromodels/core/parameter.py | ParameterBase._set_min_value | def _set_min_value(self, min_value):
"""Sets current minimum allowed value"""
# Check that the min value can be transformed if a transformation is present
if self._transformation is not None:
if min_value is not None:
try:
_ = self._transformation.forward(min_value)
except FloatingPointError:
raise ValueError("The provided minimum %s cannot be transformed with the transformation %s which "
"is defined for the parameter %s" % (min_value,
type(self._transformation),
self.path))
# Store the minimum as a pure float
self._external_min_value = min_value
# Check that the current value of the parameter is still within the boundaries. If not, issue a warning
if self._external_min_value is not None and self.value < self._external_min_value:
warnings.warn("The current value of the parameter %s (%s) "
"was below the new minimum %s." % (self.name, self.value, self._external_min_value),
exceptions.RuntimeWarning)
self.value = self._external_min_value | python | def _set_min_value(self, min_value):
# Check that the min value can be transformed if a transformation is present
if self._transformation is not None:
if min_value is not None:
try:
_ = self._transformation.forward(min_value)
except FloatingPointError:
raise ValueError("The provided minimum %s cannot be transformed with the transformation %s which "
"is defined for the parameter %s" % (min_value,
type(self._transformation),
self.path))
# Store the minimum as a pure float
self._external_min_value = min_value
# Check that the current value of the parameter is still within the boundaries. If not, issue a warning
if self._external_min_value is not None and self.value < self._external_min_value:
warnings.warn("The current value of the parameter %s (%s) "
"was below the new minimum %s." % (self.name, self.value, self._external_min_value),
exceptions.RuntimeWarning)
self.value = self._external_min_value | [
"def",
"_set_min_value",
"(",
"self",
",",
"min_value",
")",
":",
"# Check that the min value can be transformed if a transformation is present",
"if",
"self",
".",
"_transformation",
"is",
"not",
"None",
":",
"if",
"min_value",
"is",
"not",
"None",
":",
"try",
":",
... | Sets current minimum allowed value | [
"Sets",
"current",
"minimum",
"allowed",
"value"
] | 9aac365a372f77603039533df9a6b694c1e360d5 | https://github.com/threeML/astromodels/blob/9aac365a372f77603039533df9a6b694c1e360d5/astromodels/core/parameter.py#L518-L550 |
20,176 | threeML/astromodels | astromodels/core/parameter.py | ParameterBase._set_max_value | def _set_max_value(self, max_value):
"""Sets current maximum allowed value"""
self._external_max_value = max_value
# Check that the current value of the parameter is still within the boundaries. If not, issue a warning
if self._external_max_value is not None and self.value > self._external_max_value:
warnings.warn("The current value of the parameter %s (%s) "
"was above the new maximum %s." % (self.name, self.value, self._external_max_value),
exceptions.RuntimeWarning)
self.value = self._external_max_value | python | def _set_max_value(self, max_value):
self._external_max_value = max_value
# Check that the current value of the parameter is still within the boundaries. If not, issue a warning
if self._external_max_value is not None and self.value > self._external_max_value:
warnings.warn("The current value of the parameter %s (%s) "
"was above the new maximum %s." % (self.name, self.value, self._external_max_value),
exceptions.RuntimeWarning)
self.value = self._external_max_value | [
"def",
"_set_max_value",
"(",
"self",
",",
"max_value",
")",
":",
"self",
".",
"_external_max_value",
"=",
"max_value",
"# Check that the current value of the parameter is still within the boundaries. If not, issue a warning",
"if",
"self",
".",
"_external_max_value",
"is",
"no... | Sets current maximum allowed value | [
"Sets",
"current",
"maximum",
"allowed",
"value"
] | 9aac365a372f77603039533df9a6b694c1e360d5 | https://github.com/threeML/astromodels/blob/9aac365a372f77603039533df9a6b694c1e360d5/astromodels/core/parameter.py#L600-L612 |
20,177 | threeML/astromodels | astromodels/core/parameter.py | ParameterBase._set_bounds | def _set_bounds(self, bounds):
"""Sets the boundaries for this parameter to min_value and max_value"""
# Use the properties so that the checks and the handling of units are made automatically
min_value, max_value = bounds
# Remove old boundaries to avoid problems with the new one, if the current value was within the old boundaries
# but is not within the new ones (it will then be adjusted automatically later)
self.min_value = None
self.max_value = None
self.min_value = min_value
self.max_value = max_value | python | def _set_bounds(self, bounds):
# Use the properties so that the checks and the handling of units are made automatically
min_value, max_value = bounds
# Remove old boundaries to avoid problems with the new one, if the current value was within the old boundaries
# but is not within the new ones (it will then be adjusted automatically later)
self.min_value = None
self.max_value = None
self.min_value = min_value
self.max_value = max_value | [
"def",
"_set_bounds",
"(",
"self",
",",
"bounds",
")",
":",
"# Use the properties so that the checks and the handling of units are made automatically",
"min_value",
",",
"max_value",
"=",
"bounds",
"# Remove old boundaries to avoid problems with the new one, if the current value was with... | Sets the boundaries for this parameter to min_value and max_value | [
"Sets",
"the",
"boundaries",
"for",
"this",
"parameter",
"to",
"min_value",
"and",
"max_value"
] | 9aac365a372f77603039533df9a6b694c1e360d5 | https://github.com/threeML/astromodels/blob/9aac365a372f77603039533df9a6b694c1e360d5/astromodels/core/parameter.py#L653-L667 |
20,178 | threeML/astromodels | astromodels/core/parameter.py | Parameter._set_prior | def _set_prior(self, prior):
"""Set prior for this parameter. The prior must be a function accepting the current value of the parameter
as input and giving the probability density as output."""
if prior is None:
# Removing prior
self._prior = None
else:
# Try and call the prior with the current value of the parameter
try:
_ = prior(self.value)
except:
raise NotCallableOrErrorInCall("Could not call the provided prior. " +
"Is it a function accepting the current value of the parameter?")
try:
prior.set_units(self.unit, u.dimensionless_unscaled)
except AttributeError:
raise NotCallableOrErrorInCall("It looks like the provided prior is not a astromodels function.")
self._prior = prior | python | def _set_prior(self, prior):
if prior is None:
# Removing prior
self._prior = None
else:
# Try and call the prior with the current value of the parameter
try:
_ = prior(self.value)
except:
raise NotCallableOrErrorInCall("Could not call the provided prior. " +
"Is it a function accepting the current value of the parameter?")
try:
prior.set_units(self.unit, u.dimensionless_unscaled)
except AttributeError:
raise NotCallableOrErrorInCall("It looks like the provided prior is not a astromodels function.")
self._prior = prior | [
"def",
"_set_prior",
"(",
"self",
",",
"prior",
")",
":",
"if",
"prior",
"is",
"None",
":",
"# Removing prior",
"self",
".",
"_prior",
"=",
"None",
"else",
":",
"# Try and call the prior with the current value of the parameter",
"try",
":",
"_",
"=",
"prior",
"(... | Set prior for this parameter. The prior must be a function accepting the current value of the parameter
as input and giving the probability density as output. | [
"Set",
"prior",
"for",
"this",
"parameter",
".",
"The",
"prior",
"must",
"be",
"a",
"function",
"accepting",
"the",
"current",
"value",
"of",
"the",
"parameter",
"as",
"input",
"and",
"giving",
"the",
"probability",
"density",
"as",
"output",
"."
] | 9aac365a372f77603039533df9a6b694c1e360d5 | https://github.com/threeML/astromodels/blob/9aac365a372f77603039533df9a6b694c1e360d5/astromodels/core/parameter.py#L916-L946 |
20,179 | threeML/astromodels | astromodels/core/parameter.py | Parameter.set_uninformative_prior | def set_uninformative_prior(self, prior_class):
"""
Sets the prior for the parameter to a uniform prior between the current minimum and maximum, or a
log-uniform prior between the current minimum and maximum.
NOTE: if the current minimum and maximum are not defined, the default bounds for the prior class will be used.
:param prior_class : the class to be used as prior (either Log_uniform_prior or Uniform_prior, or a class which
provide a lower_bound and an upper_bound properties)
:return: (none)
"""
prior_instance = prior_class()
if self.min_value is None:
raise ParameterMustHaveBounds("Parameter %s does not have a defined minimum. Set one first, then re-run "
"set_uninformative_prior" % self.path)
else:
try:
prior_instance.lower_bound = self.min_value
except SettingOutOfBounds:
raise SettingOutOfBounds("Cannot use minimum of %s for prior %s" % (self.min_value,
prior_instance.name))
if self.max_value is None:
raise ParameterMustHaveBounds("Parameter %s does not have a defined maximum. Set one first, then re-run "
"set_uninformative_prior" % self.path)
else: # pragma: no cover
try:
prior_instance.upper_bound = self.max_value
except SettingOutOfBounds:
raise SettingOutOfBounds("Cannot use maximum of %s for prior %s" % (self.max_value,
prior_instance.name))
assert np.isfinite(prior_instance.upper_bound.value),"The parameter %s must have a finite maximum" % self.name
assert np.isfinite(prior_instance.lower_bound.value),"The parameter %s must have a finite minimum" % self.name
self._set_prior(prior_instance) | python | def set_uninformative_prior(self, prior_class):
prior_instance = prior_class()
if self.min_value is None:
raise ParameterMustHaveBounds("Parameter %s does not have a defined minimum. Set one first, then re-run "
"set_uninformative_prior" % self.path)
else:
try:
prior_instance.lower_bound = self.min_value
except SettingOutOfBounds:
raise SettingOutOfBounds("Cannot use minimum of %s for prior %s" % (self.min_value,
prior_instance.name))
if self.max_value is None:
raise ParameterMustHaveBounds("Parameter %s does not have a defined maximum. Set one first, then re-run "
"set_uninformative_prior" % self.path)
else: # pragma: no cover
try:
prior_instance.upper_bound = self.max_value
except SettingOutOfBounds:
raise SettingOutOfBounds("Cannot use maximum of %s for prior %s" % (self.max_value,
prior_instance.name))
assert np.isfinite(prior_instance.upper_bound.value),"The parameter %s must have a finite maximum" % self.name
assert np.isfinite(prior_instance.lower_bound.value),"The parameter %s must have a finite minimum" % self.name
self._set_prior(prior_instance) | [
"def",
"set_uninformative_prior",
"(",
"self",
",",
"prior_class",
")",
":",
"prior_instance",
"=",
"prior_class",
"(",
")",
"if",
"self",
".",
"min_value",
"is",
"None",
":",
"raise",
"ParameterMustHaveBounds",
"(",
"\"Parameter %s does not have a defined minimum. Set ... | Sets the prior for the parameter to a uniform prior between the current minimum and maximum, or a
log-uniform prior between the current minimum and maximum.
NOTE: if the current minimum and maximum are not defined, the default bounds for the prior class will be used.
:param prior_class : the class to be used as prior (either Log_uniform_prior or Uniform_prior, or a class which
provide a lower_bound and an upper_bound properties)
:return: (none) | [
"Sets",
"the",
"prior",
"for",
"the",
"parameter",
"to",
"a",
"uniform",
"prior",
"between",
"the",
"current",
"minimum",
"and",
"maximum",
"or",
"a",
"log",
"-",
"uniform",
"prior",
"between",
"the",
"current",
"minimum",
"and",
"maximum",
"."
] | 9aac365a372f77603039533df9a6b694c1e360d5 | https://github.com/threeML/astromodels/blob/9aac365a372f77603039533df9a6b694c1e360d5/astromodels/core/parameter.py#L962-L1011 |
20,180 | threeML/astromodels | astromodels/core/parameter.py | Parameter.remove_auxiliary_variable | def remove_auxiliary_variable(self):
"""
Remove an existing auxiliary variable
:return:
"""
if not self.has_auxiliary_variable():
# do nothing, but print a warning
warnings.warn("Cannot remove a non-existing auxiliary variable", RuntimeWarning)
else:
# Remove the law from the children
self._remove_child(self._aux_variable['law'].name)
# Clean up the dictionary
self._aux_variable = {}
# Set the parameter to the status it has before the auxiliary variable was created
self.free = self._old_free | python | def remove_auxiliary_variable(self):
if not self.has_auxiliary_variable():
# do nothing, but print a warning
warnings.warn("Cannot remove a non-existing auxiliary variable", RuntimeWarning)
else:
# Remove the law from the children
self._remove_child(self._aux_variable['law'].name)
# Clean up the dictionary
self._aux_variable = {}
# Set the parameter to the status it has before the auxiliary variable was created
self.free = self._old_free | [
"def",
"remove_auxiliary_variable",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"has_auxiliary_variable",
"(",
")",
":",
"# do nothing, but print a warning",
"warnings",
".",
"warn",
"(",
"\"Cannot remove a non-existing auxiliary variable\"",
",",
"RuntimeWarning",
"... | Remove an existing auxiliary variable
:return: | [
"Remove",
"an",
"existing",
"auxiliary",
"variable"
] | 9aac365a372f77603039533df9a6b694c1e360d5 | https://github.com/threeML/astromodels/blob/9aac365a372f77603039533df9a6b694c1e360d5/astromodels/core/parameter.py#L1077-L1102 |
20,181 | threeML/astromodels | astromodels/core/tree.py | OldNode._get_child_from_path | def _get_child_from_path(self, path):
"""
Return a children below this level, starting from a path of the kind "this_level.something.something.name"
:param path: the key
:return: the child
"""
keys = path.split(".")
this_child = self
for key in keys:
try:
this_child = this_child._get_child(key)
except KeyError:
raise KeyError("Child %s not found" % path)
return this_child | python | def _get_child_from_path(self, path):
keys = path.split(".")
this_child = self
for key in keys:
try:
this_child = this_child._get_child(key)
except KeyError:
raise KeyError("Child %s not found" % path)
return this_child | [
"def",
"_get_child_from_path",
"(",
"self",
",",
"path",
")",
":",
"keys",
"=",
"path",
".",
"split",
"(",
"\".\"",
")",
"this_child",
"=",
"self",
"for",
"key",
"in",
"keys",
":",
"try",
":",
"this_child",
"=",
"this_child",
".",
"_get_child",
"(",
"k... | Return a children below this level, starting from a path of the kind "this_level.something.something.name"
:param path: the key
:return: the child | [
"Return",
"a",
"children",
"below",
"this",
"level",
"starting",
"from",
"a",
"path",
"of",
"the",
"kind",
"this_level",
".",
"something",
".",
"something",
".",
"name"
] | 9aac365a372f77603039533df9a6b694c1e360d5 | https://github.com/threeML/astromodels/blob/9aac365a372f77603039533df9a6b694c1e360d5/astromodels/core/tree.py#L210-L232 |
20,182 | threeML/astromodels | astromodels/core/tree.py | OldNode._find_instances | def _find_instances(self, cls):
"""
Find all the instances of cls below this node.
:return: a dictionary of instances of cls
"""
instances = collections.OrderedDict()
for child_name, child in self._children.iteritems():
if isinstance(child, cls):
key_name = ".".join(child._get_path())
instances[key_name] = child
# Now check if the instance has children,
# and if it does go deeper in the tree
# NOTE: an empty dictionary evaluate as False
if child._children:
instances.update(child._find_instances(cls))
else:
instances.update(child._find_instances(cls))
return instances | python | def _find_instances(self, cls):
instances = collections.OrderedDict()
for child_name, child in self._children.iteritems():
if isinstance(child, cls):
key_name = ".".join(child._get_path())
instances[key_name] = child
# Now check if the instance has children,
# and if it does go deeper in the tree
# NOTE: an empty dictionary evaluate as False
if child._children:
instances.update(child._find_instances(cls))
else:
instances.update(child._find_instances(cls))
return instances | [
"def",
"_find_instances",
"(",
"self",
",",
"cls",
")",
":",
"instances",
"=",
"collections",
".",
"OrderedDict",
"(",
")",
"for",
"child_name",
",",
"child",
"in",
"self",
".",
"_children",
".",
"iteritems",
"(",
")",
":",
"if",
"isinstance",
"(",
"chil... | Find all the instances of cls below this node.
:return: a dictionary of instances of cls | [
"Find",
"all",
"the",
"instances",
"of",
"cls",
"below",
"this",
"node",
"."
] | 9aac365a372f77603039533df9a6b694c1e360d5 | https://github.com/threeML/astromodels/blob/9aac365a372f77603039533df9a6b694c1e360d5/astromodels/core/tree.py#L299-L329 |
20,183 | threeML/astromodels | setup.py | find_library | def find_library(library_root, additional_places=None):
"""
Returns the name of the library without extension
:param library_root: root of the library to search, for example "cfitsio_" will match libcfitsio_1.2.3.4.so
:return: the name of the library found (NOTE: this is *not* the path), and a directory path if the library is not
in the system paths (and None otherwise). The name of libcfitsio_1.2.3.4.so will be cfitsio_1.2.3.4, in other words,
it will be what is needed to be passed to the linker during a c/c++ compilation, in the -l option
"""
# find_library searches for all system paths in a system independent way (but NOT those defined in
# LD_LIBRARY_PATH or DYLD_LIBRARY_PATH)
first_guess = ctypes.util.find_library(library_root)
if first_guess is not None:
# Found in one of the system paths
if sys.platform.lower().find("linux") >= 0:
# On linux the linker already knows about these paths, so we
# can return None as path
return sanitize_lib_name(first_guess), None
elif sys.platform.lower().find("darwin") >= 0:
# On Mac we still need to return the path, because the linker sometimes
# does not look into it
return sanitize_lib_name(first_guess), os.path.dirname(first_guess)
else:
# Windows is not supported
raise NotImplementedError("Platform %s is not supported" % sys.platform)
else:
# could not find it. Let's examine LD_LIBRARY_PATH or DYLD_LIBRARY_PATH
# (if they sanitize_lib_name(first_guess), are not defined, possible_locations will become [""] which will
# be handled by the next loop)
if sys.platform.lower().find("linux") >= 0:
# Unix / linux
possible_locations = os.environ.get("LD_LIBRARY_PATH", "").split(":")
elif sys.platform.lower().find("darwin") >= 0:
# Mac
possible_locations = os.environ.get("DYLD_LIBRARY_PATH", "").split(":")
else:
raise NotImplementedError("Platform %s is not supported" % sys.platform)
if additional_places is not None:
possible_locations.extend(additional_places)
# Now look into the search paths
library_name = None
library_dir = None
for search_path in possible_locations:
if search_path == "":
# This can happen if there are more than one :, or if nor LD_LIBRARY_PATH
# nor DYLD_LIBRARY_PATH are defined (because of the default use above for os.environ.get)
continue
results = glob.glob(os.path.join(search_path, "lib%s*" % library_root))
if len(results) >= 1:
# Results contain things like libXS.so, libXSPlot.so, libXSpippo.so
# If we are looking for libXS.so, we need to make sure that we get the right one!
for result in results:
if re.match("lib%s[\-_\.]" % library_root, os.path.basename(result)) is None:
continue
else:
# FOUND IT
# This is the full path of the library, like /usr/lib/libcfitsio_1.2.3.4
library_name = result
library_dir = search_path
break
else:
continue
if library_name is not None:
break
if library_name is None:
return None, None
else:
# Sanitize the library name to get from the fully-qualified path to just the library name
# (/usr/lib/libgfortran.so.3.0 becomes gfortran)
return sanitize_lib_name(library_name), library_dir | python | def find_library(library_root, additional_places=None):
# find_library searches for all system paths in a system independent way (but NOT those defined in
# LD_LIBRARY_PATH or DYLD_LIBRARY_PATH)
first_guess = ctypes.util.find_library(library_root)
if first_guess is not None:
# Found in one of the system paths
if sys.platform.lower().find("linux") >= 0:
# On linux the linker already knows about these paths, so we
# can return None as path
return sanitize_lib_name(first_guess), None
elif sys.platform.lower().find("darwin") >= 0:
# On Mac we still need to return the path, because the linker sometimes
# does not look into it
return sanitize_lib_name(first_guess), os.path.dirname(first_guess)
else:
# Windows is not supported
raise NotImplementedError("Platform %s is not supported" % sys.platform)
else:
# could not find it. Let's examine LD_LIBRARY_PATH or DYLD_LIBRARY_PATH
# (if they sanitize_lib_name(first_guess), are not defined, possible_locations will become [""] which will
# be handled by the next loop)
if sys.platform.lower().find("linux") >= 0:
# Unix / linux
possible_locations = os.environ.get("LD_LIBRARY_PATH", "").split(":")
elif sys.platform.lower().find("darwin") >= 0:
# Mac
possible_locations = os.environ.get("DYLD_LIBRARY_PATH", "").split(":")
else:
raise NotImplementedError("Platform %s is not supported" % sys.platform)
if additional_places is not None:
possible_locations.extend(additional_places)
# Now look into the search paths
library_name = None
library_dir = None
for search_path in possible_locations:
if search_path == "":
# This can happen if there are more than one :, or if nor LD_LIBRARY_PATH
# nor DYLD_LIBRARY_PATH are defined (because of the default use above for os.environ.get)
continue
results = glob.glob(os.path.join(search_path, "lib%s*" % library_root))
if len(results) >= 1:
# Results contain things like libXS.so, libXSPlot.so, libXSpippo.so
# If we are looking for libXS.so, we need to make sure that we get the right one!
for result in results:
if re.match("lib%s[\-_\.]" % library_root, os.path.basename(result)) is None:
continue
else:
# FOUND IT
# This is the full path of the library, like /usr/lib/libcfitsio_1.2.3.4
library_name = result
library_dir = search_path
break
else:
continue
if library_name is not None:
break
if library_name is None:
return None, None
else:
# Sanitize the library name to get from the fully-qualified path to just the library name
# (/usr/lib/libgfortran.so.3.0 becomes gfortran)
return sanitize_lib_name(library_name), library_dir | [
"def",
"find_library",
"(",
"library_root",
",",
"additional_places",
"=",
"None",
")",
":",
"# find_library searches for all system paths in a system independent way (but NOT those defined in",
"# LD_LIBRARY_PATH or DYLD_LIBRARY_PATH)",
"first_guess",
"=",
"ctypes",
".",
"util",
"... | Returns the name of the library without extension
:param library_root: root of the library to search, for example "cfitsio_" will match libcfitsio_1.2.3.4.so
:return: the name of the library found (NOTE: this is *not* the path), and a directory path if the library is not
in the system paths (and None otherwise). The name of libcfitsio_1.2.3.4.so will be cfitsio_1.2.3.4, in other words,
it will be what is needed to be passed to the linker during a c/c++ compilation, in the -l option | [
"Returns",
"the",
"name",
"of",
"the",
"library",
"without",
"extension"
] | 9aac365a372f77603039533df9a6b694c1e360d5 | https://github.com/threeML/astromodels/blob/9aac365a372f77603039533df9a6b694c1e360d5/setup.py#L54-L172 |
20,184 | threeML/astromodels | astromodels/utils/table.py | dict_to_table | def dict_to_table(dictionary, list_of_keys=None):
"""
Return a table representing the dictionary.
:param dictionary: the dictionary to represent
:param list_of_keys: optionally, only the keys in this list will be inserted in the table
:return: a Table instance
"""
# assert len(dictionary.values()) > 0, "Dictionary cannot be empty"
# Create an empty table
table = Table()
# If the dictionary is not empty, fill the table
if len(dictionary) > 0:
# Add the names as first column
table['name'] = dictionary.keys()
# Now add all other properties
# Use the first parameter as prototype
prototype = dictionary.values()[0]
column_names = prototype.keys()
# If we have a white list for the columns, use it
if list_of_keys is not None:
column_names = filter(lambda key: key in list_of_keys, column_names)
# Fill the table
for column_name in column_names:
table[column_name] = map(lambda x: x[column_name], dictionary.values())
return table | python | def dict_to_table(dictionary, list_of_keys=None):
# assert len(dictionary.values()) > 0, "Dictionary cannot be empty"
# Create an empty table
table = Table()
# If the dictionary is not empty, fill the table
if len(dictionary) > 0:
# Add the names as first column
table['name'] = dictionary.keys()
# Now add all other properties
# Use the first parameter as prototype
prototype = dictionary.values()[0]
column_names = prototype.keys()
# If we have a white list for the columns, use it
if list_of_keys is not None:
column_names = filter(lambda key: key in list_of_keys, column_names)
# Fill the table
for column_name in column_names:
table[column_name] = map(lambda x: x[column_name], dictionary.values())
return table | [
"def",
"dict_to_table",
"(",
"dictionary",
",",
"list_of_keys",
"=",
"None",
")",
":",
"# assert len(dictionary.values()) > 0, \"Dictionary cannot be empty\"",
"# Create an empty table",
"table",
"=",
"Table",
"(",
")",
"# If the dictionary is not empty, fill the table",
"if",
... | Return a table representing the dictionary.
:param dictionary: the dictionary to represent
:param list_of_keys: optionally, only the keys in this list will be inserted in the table
:return: a Table instance | [
"Return",
"a",
"table",
"representing",
"the",
"dictionary",
"."
] | 9aac365a372f77603039533df9a6b694c1e360d5 | https://github.com/threeML/astromodels/blob/9aac365a372f77603039533df9a6b694c1e360d5/astromodels/utils/table.py#L6-L49 |
20,185 | threeML/astromodels | astromodels/utils/table.py | Table._base_repr_ | def _base_repr_(self, html=False, show_name=True, **kwargs):
"""
Override the method in the astropy.Table class
to avoid displaying the description, and the format
of the columns
"""
table_id = 'table{id}'.format(id=id(self))
data_lines, outs = self.formatter._pformat_table(self,
tableid=table_id, html=html, max_width=(-1 if html else None),
show_name=show_name, show_unit=None, show_dtype=False)
out = '\n'.join(data_lines)
# if astropy.table.six.PY2 and isinstance(out, astropy.table.six.text_type):
# out = out.encode('utf-8')
return out | python | def _base_repr_(self, html=False, show_name=True, **kwargs):
table_id = 'table{id}'.format(id=id(self))
data_lines, outs = self.formatter._pformat_table(self,
tableid=table_id, html=html, max_width=(-1 if html else None),
show_name=show_name, show_unit=None, show_dtype=False)
out = '\n'.join(data_lines)
# if astropy.table.six.PY2 and isinstance(out, astropy.table.six.text_type):
# out = out.encode('utf-8')
return out | [
"def",
"_base_repr_",
"(",
"self",
",",
"html",
"=",
"False",
",",
"show_name",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"table_id",
"=",
"'table{id}'",
".",
"format",
"(",
"id",
"=",
"id",
"(",
"self",
")",
")",
"data_lines",
",",
"outs",
"... | Override the method in the astropy.Table class
to avoid displaying the description, and the format
of the columns | [
"Override",
"the",
"method",
"in",
"the",
"astropy",
".",
"Table",
"class",
"to",
"avoid",
"displaying",
"the",
"description",
"and",
"the",
"format",
"of",
"the",
"columns"
] | 9aac365a372f77603039533df9a6b694c1e360d5 | https://github.com/threeML/astromodels/blob/9aac365a372f77603039533df9a6b694c1e360d5/astromodels/utils/table.py#L60-L78 |
20,186 | eamigo86/graphene-django-extras | graphene_django_extras/views.py | ExtraGraphQLView.fetch_cache_key | def fetch_cache_key(request):
""" Returns a hashed cache key. """
m = hashlib.md5()
m.update(request.body)
return m.hexdigest() | python | def fetch_cache_key(request):
m = hashlib.md5()
m.update(request.body)
return m.hexdigest() | [
"def",
"fetch_cache_key",
"(",
"request",
")",
":",
"m",
"=",
"hashlib",
".",
"md5",
"(",
")",
"m",
".",
"update",
"(",
"request",
".",
"body",
")",
"return",
"m",
".",
"hexdigest",
"(",
")"
] | Returns a hashed cache key. | [
"Returns",
"a",
"hashed",
"cache",
"key",
"."
] | b27fd6b5128f6b6a500a8b7a497d76be72d6a232 | https://github.com/eamigo86/graphene-django-extras/blob/b27fd6b5128f6b6a500a8b7a497d76be72d6a232/graphene_django_extras/views.py#L42-L47 |
20,187 | eamigo86/graphene-django-extras | graphene_django_extras/views.py | ExtraGraphQLView.dispatch | def dispatch(self, request, *args, **kwargs):
""" Fetches queried data from graphql and returns cached & hashed key. """
if not graphql_api_settings.CACHE_ACTIVE:
return self.super_call(request, *args, **kwargs)
cache = caches["default"]
operation_ast = self.get_operation_ast(request)
if operation_ast and operation_ast.operation == "mutation":
cache.clear()
return self.super_call(request, *args, **kwargs)
cache_key = "_graplql_{}".format(self.fetch_cache_key(request))
response = cache.get(cache_key)
if not response:
response = self.super_call(request, *args, **kwargs)
# cache key and value
cache.set(cache_key, response, timeout=graphql_api_settings.CACHE_TIMEOUT)
return response | python | def dispatch(self, request, *args, **kwargs):
if not graphql_api_settings.CACHE_ACTIVE:
return self.super_call(request, *args, **kwargs)
cache = caches["default"]
operation_ast = self.get_operation_ast(request)
if operation_ast and operation_ast.operation == "mutation":
cache.clear()
return self.super_call(request, *args, **kwargs)
cache_key = "_graplql_{}".format(self.fetch_cache_key(request))
response = cache.get(cache_key)
if not response:
response = self.super_call(request, *args, **kwargs)
# cache key and value
cache.set(cache_key, response, timeout=graphql_api_settings.CACHE_TIMEOUT)
return response | [
"def",
"dispatch",
"(",
"self",
",",
"request",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"graphql_api_settings",
".",
"CACHE_ACTIVE",
":",
"return",
"self",
".",
"super_call",
"(",
"request",
",",
"*",
"args",
",",
"*",
"*",
... | Fetches queried data from graphql and returns cached & hashed key. | [
"Fetches",
"queried",
"data",
"from",
"graphql",
"and",
"returns",
"cached",
"&",
"hashed",
"key",
"."
] | b27fd6b5128f6b6a500a8b7a497d76be72d6a232 | https://github.com/eamigo86/graphene-django-extras/blob/b27fd6b5128f6b6a500a8b7a497d76be72d6a232/graphene_django_extras/views.py#L54-L74 |
20,188 | eamigo86/graphene-django-extras | graphene_django_extras/directives/date.py | _parse | def _parse(partial_dt):
"""
parse a partial datetime object to a complete datetime object
"""
dt = None
try:
if isinstance(partial_dt, datetime):
dt = partial_dt
if isinstance(partial_dt, date):
dt = _combine_date_time(partial_dt, time(0, 0, 0))
if isinstance(partial_dt, time):
dt = _combine_date_time(date.today(), partial_dt)
if isinstance(partial_dt, (int, float)):
dt = datetime.fromtimestamp(partial_dt)
if isinstance(partial_dt, (str, bytes)):
dt = parser.parse(partial_dt, default=timezone.now())
if dt is not None and timezone.is_naive(dt):
dt = timezone.make_aware(dt)
return dt
except ValueError:
return None | python | def _parse(partial_dt):
dt = None
try:
if isinstance(partial_dt, datetime):
dt = partial_dt
if isinstance(partial_dt, date):
dt = _combine_date_time(partial_dt, time(0, 0, 0))
if isinstance(partial_dt, time):
dt = _combine_date_time(date.today(), partial_dt)
if isinstance(partial_dt, (int, float)):
dt = datetime.fromtimestamp(partial_dt)
if isinstance(partial_dt, (str, bytes)):
dt = parser.parse(partial_dt, default=timezone.now())
if dt is not None and timezone.is_naive(dt):
dt = timezone.make_aware(dt)
return dt
except ValueError:
return None | [
"def",
"_parse",
"(",
"partial_dt",
")",
":",
"dt",
"=",
"None",
"try",
":",
"if",
"isinstance",
"(",
"partial_dt",
",",
"datetime",
")",
":",
"dt",
"=",
"partial_dt",
"if",
"isinstance",
"(",
"partial_dt",
",",
"date",
")",
":",
"dt",
"=",
"_combine_d... | parse a partial datetime object to a complete datetime object | [
"parse",
"a",
"partial",
"datetime",
"object",
"to",
"a",
"complete",
"datetime",
"object"
] | b27fd6b5128f6b6a500a8b7a497d76be72d6a232 | https://github.com/eamigo86/graphene-django-extras/blob/b27fd6b5128f6b6a500a8b7a497d76be72d6a232/graphene_django_extras/directives/date.py#L73-L94 |
20,189 | eamigo86/graphene-django-extras | graphene_django_extras/utils.py | clean_dict | def clean_dict(d):
"""
Remove all empty fields in a nested dict
"""
if not isinstance(d, (dict, list)):
return d
if isinstance(d, list):
return [v for v in (clean_dict(v) for v in d) if v]
return OrderedDict(
[(k, v) for k, v in ((k, clean_dict(v)) for k, v in list(d.items())) if v]
) | python | def clean_dict(d):
if not isinstance(d, (dict, list)):
return d
if isinstance(d, list):
return [v for v in (clean_dict(v) for v in d) if v]
return OrderedDict(
[(k, v) for k, v in ((k, clean_dict(v)) for k, v in list(d.items())) if v]
) | [
"def",
"clean_dict",
"(",
"d",
")",
":",
"if",
"not",
"isinstance",
"(",
"d",
",",
"(",
"dict",
",",
"list",
")",
")",
":",
"return",
"d",
"if",
"isinstance",
"(",
"d",
",",
"list",
")",
":",
"return",
"[",
"v",
"for",
"v",
"in",
"(",
"clean_di... | Remove all empty fields in a nested dict | [
"Remove",
"all",
"empty",
"fields",
"in",
"a",
"nested",
"dict"
] | b27fd6b5128f6b6a500a8b7a497d76be72d6a232 | https://github.com/eamigo86/graphene-django-extras/blob/b27fd6b5128f6b6a500a8b7a497d76be72d6a232/graphene_django_extras/utils.py#L168-L179 |
20,190 | eamigo86/graphene-django-extras | graphene_django_extras/utils.py | _get_queryset | def _get_queryset(klass):
"""
Returns a QuerySet from a Model, Manager, or QuerySet. Created to make
get_object_or_404 and get_list_or_404 more DRY.
Raises a ValueError if klass is not a Model, Manager, or QuerySet.
"""
if isinstance(klass, QuerySet):
return klass
elif isinstance(klass, Manager):
manager = klass
elif isinstance(klass, ModelBase):
manager = klass._default_manager
else:
if isinstance(klass, type):
klass__name = klass.__name__
else:
klass__name = klass.__class__.__name__
raise ValueError(
"Object is of type '{}', but must be a Django Model, "
"Manager, or QuerySet".format(klass__name)
)
return manager.all() | python | def _get_queryset(klass):
if isinstance(klass, QuerySet):
return klass
elif isinstance(klass, Manager):
manager = klass
elif isinstance(klass, ModelBase):
manager = klass._default_manager
else:
if isinstance(klass, type):
klass__name = klass.__name__
else:
klass__name = klass.__class__.__name__
raise ValueError(
"Object is of type '{}', but must be a Django Model, "
"Manager, or QuerySet".format(klass__name)
)
return manager.all() | [
"def",
"_get_queryset",
"(",
"klass",
")",
":",
"if",
"isinstance",
"(",
"klass",
",",
"QuerySet",
")",
":",
"return",
"klass",
"elif",
"isinstance",
"(",
"klass",
",",
"Manager",
")",
":",
"manager",
"=",
"klass",
"elif",
"isinstance",
"(",
"klass",
","... | Returns a QuerySet from a Model, Manager, or QuerySet. Created to make
get_object_or_404 and get_list_or_404 more DRY.
Raises a ValueError if klass is not a Model, Manager, or QuerySet. | [
"Returns",
"a",
"QuerySet",
"from",
"a",
"Model",
"Manager",
"or",
"QuerySet",
".",
"Created",
"to",
"make",
"get_object_or_404",
"and",
"get_list_or_404",
"more",
"DRY",
"."
] | b27fd6b5128f6b6a500a8b7a497d76be72d6a232 | https://github.com/eamigo86/graphene-django-extras/blob/b27fd6b5128f6b6a500a8b7a497d76be72d6a232/graphene_django_extras/utils.py#L224-L246 |
20,191 | Proteus-tech/tormor | tormor/schema.py | find_schema_paths | def find_schema_paths(schema_files_path=DEFAULT_SCHEMA_FILES_PATH):
"""Searches the locations in the `SCHEMA_FILES_PATH` to
try to find where the schema SQL files are located.
"""
paths = []
for path in schema_files_path:
if os.path.isdir(path):
paths.append(path)
if paths:
return paths
raise SchemaFilesNotFound("Searched " + os.pathsep.join(schema_files_path)) | python | def find_schema_paths(schema_files_path=DEFAULT_SCHEMA_FILES_PATH):
paths = []
for path in schema_files_path:
if os.path.isdir(path):
paths.append(path)
if paths:
return paths
raise SchemaFilesNotFound("Searched " + os.pathsep.join(schema_files_path)) | [
"def",
"find_schema_paths",
"(",
"schema_files_path",
"=",
"DEFAULT_SCHEMA_FILES_PATH",
")",
":",
"paths",
"=",
"[",
"]",
"for",
"path",
"in",
"schema_files_path",
":",
"if",
"os",
".",
"path",
".",
"isdir",
"(",
"path",
")",
":",
"paths",
".",
"append",
"... | Searches the locations in the `SCHEMA_FILES_PATH` to
try to find where the schema SQL files are located. | [
"Searches",
"the",
"locations",
"in",
"the",
"SCHEMA_FILES_PATH",
"to",
"try",
"to",
"find",
"where",
"the",
"schema",
"SQL",
"files",
"are",
"located",
"."
] | 3083b0cd2b9a4d21b20dfd5c27678b23660548d7 | https://github.com/Proteus-tech/tormor/blob/3083b0cd2b9a4d21b20dfd5c27678b23660548d7/tormor/schema.py#L41-L51 |
20,192 | plivo/sharq-server | runner.py | run | def run():
"""Exposes a CLI to configure the SharQ Server and runs the server."""
# create a arg parser and configure it.
parser = argparse.ArgumentParser(description='SharQ Server.')
parser.add_argument('-c', '--config', action='store', required=True,
help='Absolute path of the SharQ configuration file.',
dest='sharq_config')
parser.add_argument('-gc', '--gunicorn-config', action='store', required=False,
help='Gunicorn configuration file.',
dest='gunicorn_config')
parser.add_argument('--version', action='version', version='SharQ Server %s' % __version__)
args = parser.parse_args()
# read the configuration file and set gunicorn options.
config_parser = ConfigParser.SafeConfigParser()
# get the full path of the config file.
sharq_config = os.path.abspath(args.sharq_config)
config_parser.read(sharq_config)
host = config_parser.get('sharq-server', 'host')
port = config_parser.get('sharq-server', 'port')
bind = '%s:%s' % (host, port)
try:
workers = config_parser.get('sharq-server', 'workers')
except ConfigParser.NoOptionError:
workers = number_of_workers()
try:
accesslog = config_parser.get('sharq-server', 'accesslog')
except ConfigParser.NoOptionError:
accesslog = None
options = {
'bind': bind,
'workers': workers,
'worker_class': 'gevent' # required for sharq to function.
}
if accesslog:
options.update({
'accesslog': accesslog
})
if args.gunicorn_config:
gunicorn_config = os.path.abspath(args.gunicorn_config)
options.update({
'config': gunicorn_config
})
print """
___ _ ___ ___
/ __| |_ __ _ _ _ / _ \ / __| ___ _ ___ _____ _ _
\__ \ ' \/ _` | '_| (_) | \__ \/ -_) '_\ V / -_) '_|
|___/_||_\__,_|_| \__\_\ |___/\___|_| \_/\___|_|
Version: %s
Listening on: %s
""" % (__version__, bind)
server = setup_server(sharq_config)
SharQServerApplicationRunner(server.app, options).run() | python | def run():
# create a arg parser and configure it.
parser = argparse.ArgumentParser(description='SharQ Server.')
parser.add_argument('-c', '--config', action='store', required=True,
help='Absolute path of the SharQ configuration file.',
dest='sharq_config')
parser.add_argument('-gc', '--gunicorn-config', action='store', required=False,
help='Gunicorn configuration file.',
dest='gunicorn_config')
parser.add_argument('--version', action='version', version='SharQ Server %s' % __version__)
args = parser.parse_args()
# read the configuration file and set gunicorn options.
config_parser = ConfigParser.SafeConfigParser()
# get the full path of the config file.
sharq_config = os.path.abspath(args.sharq_config)
config_parser.read(sharq_config)
host = config_parser.get('sharq-server', 'host')
port = config_parser.get('sharq-server', 'port')
bind = '%s:%s' % (host, port)
try:
workers = config_parser.get('sharq-server', 'workers')
except ConfigParser.NoOptionError:
workers = number_of_workers()
try:
accesslog = config_parser.get('sharq-server', 'accesslog')
except ConfigParser.NoOptionError:
accesslog = None
options = {
'bind': bind,
'workers': workers,
'worker_class': 'gevent' # required for sharq to function.
}
if accesslog:
options.update({
'accesslog': accesslog
})
if args.gunicorn_config:
gunicorn_config = os.path.abspath(args.gunicorn_config)
options.update({
'config': gunicorn_config
})
print """
___ _ ___ ___
/ __| |_ __ _ _ _ / _ \ / __| ___ _ ___ _____ _ _
\__ \ ' \/ _` | '_| (_) | \__ \/ -_) '_\ V / -_) '_|
|___/_||_\__,_|_| \__\_\ |___/\___|_| \_/\___|_|
Version: %s
Listening on: %s
""" % (__version__, bind)
server = setup_server(sharq_config)
SharQServerApplicationRunner(server.app, options).run() | [
"def",
"run",
"(",
")",
":",
"# create a arg parser and configure it.",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"'SharQ Server.'",
")",
"parser",
".",
"add_argument",
"(",
"'-c'",
",",
"'--config'",
",",
"action",
"=",
"'store'",... | Exposes a CLI to configure the SharQ Server and runs the server. | [
"Exposes",
"a",
"CLI",
"to",
"configure",
"the",
"SharQ",
"Server",
"and",
"runs",
"the",
"server",
"."
] | 9f4c50eb5ee28d1084591febc4a3a34d7ffd0556 | https://github.com/plivo/sharq-server/blob/9f4c50eb5ee28d1084591febc4a3a34d7ffd0556/runner.py#L38-L97 |
20,193 | plivo/sharq-server | sharq_server/server.py | setup_server | def setup_server(config_path):
"""Configure SharQ server, start the requeue loop
and return the server."""
# configure the SharQ server
server = SharQServer(config_path)
# start the requeue loop
gevent.spawn(server.requeue)
return server | python | def setup_server(config_path):
# configure the SharQ server
server = SharQServer(config_path)
# start the requeue loop
gevent.spawn(server.requeue)
return server | [
"def",
"setup_server",
"(",
"config_path",
")",
":",
"# configure the SharQ server",
"server",
"=",
"SharQServer",
"(",
"config_path",
")",
"# start the requeue loop",
"gevent",
".",
"spawn",
"(",
"server",
".",
"requeue",
")",
"return",
"server"
] | Configure SharQ server, start the requeue loop
and return the server. | [
"Configure",
"SharQ",
"server",
"start",
"the",
"requeue",
"loop",
"and",
"return",
"the",
"server",
"."
] | 9f4c50eb5ee28d1084591febc4a3a34d7ffd0556 | https://github.com/plivo/sharq-server/blob/9f4c50eb5ee28d1084591febc4a3a34d7ffd0556/sharq_server/server.py#L204-L212 |
20,194 | plivo/sharq-server | sharq_server/server.py | SharQServer.requeue | def requeue(self):
"""Loop endlessly and requeue expired jobs."""
job_requeue_interval = float(
self.config.get('sharq', 'job_requeue_interval'))
while True:
self.sq.requeue()
gevent.sleep(job_requeue_interval / 1000.00) | python | def requeue(self):
job_requeue_interval = float(
self.config.get('sharq', 'job_requeue_interval'))
while True:
self.sq.requeue()
gevent.sleep(job_requeue_interval / 1000.00) | [
"def",
"requeue",
"(",
"self",
")",
":",
"job_requeue_interval",
"=",
"float",
"(",
"self",
".",
"config",
".",
"get",
"(",
"'sharq'",
",",
"'job_requeue_interval'",
")",
")",
"while",
"True",
":",
"self",
".",
"sq",
".",
"requeue",
"(",
")",
"gevent",
... | Loop endlessly and requeue expired jobs. | [
"Loop",
"endlessly",
"and",
"requeue",
"expired",
"jobs",
"."
] | 9f4c50eb5ee28d1084591febc4a3a34d7ffd0556 | https://github.com/plivo/sharq-server/blob/9f4c50eb5ee28d1084591febc4a3a34d7ffd0556/sharq_server/server.py#L57-L63 |
20,195 | plivo/sharq-server | sharq_server/server.py | SharQServer._view_enqueue | def _view_enqueue(self, queue_type, queue_id):
"""Enqueues a job into SharQ."""
response = {
'status': 'failure'
}
try:
request_data = json.loads(request.data)
except Exception, e:
response['message'] = e.message
return jsonify(**response), 400
request_data.update({
'queue_type': queue_type,
'queue_id': queue_id
})
try:
response = self.sq.enqueue(**request_data)
except Exception, e:
response['message'] = e.message
return jsonify(**response), 400
return jsonify(**response), 201 | python | def _view_enqueue(self, queue_type, queue_id):
response = {
'status': 'failure'
}
try:
request_data = json.loads(request.data)
except Exception, e:
response['message'] = e.message
return jsonify(**response), 400
request_data.update({
'queue_type': queue_type,
'queue_id': queue_id
})
try:
response = self.sq.enqueue(**request_data)
except Exception, e:
response['message'] = e.message
return jsonify(**response), 400
return jsonify(**response), 201 | [
"def",
"_view_enqueue",
"(",
"self",
",",
"queue_type",
",",
"queue_id",
")",
":",
"response",
"=",
"{",
"'status'",
":",
"'failure'",
"}",
"try",
":",
"request_data",
"=",
"json",
".",
"loads",
"(",
"request",
".",
"data",
")",
"except",
"Exception",
",... | Enqueues a job into SharQ. | [
"Enqueues",
"a",
"job",
"into",
"SharQ",
"."
] | 9f4c50eb5ee28d1084591febc4a3a34d7ffd0556 | https://github.com/plivo/sharq-server/blob/9f4c50eb5ee28d1084591febc4a3a34d7ffd0556/sharq_server/server.py#L69-L91 |
20,196 | plivo/sharq-server | sharq_server/server.py | SharQServer._view_dequeue | def _view_dequeue(self, queue_type):
"""Dequeues a job from SharQ."""
response = {
'status': 'failure'
}
request_data = {
'queue_type': queue_type
}
try:
response = self.sq.dequeue(**request_data)
if response['status'] == 'failure':
return jsonify(**response), 404
except Exception, e:
response['message'] = e.message
return jsonify(**response), 400
return jsonify(**response) | python | def _view_dequeue(self, queue_type):
response = {
'status': 'failure'
}
request_data = {
'queue_type': queue_type
}
try:
response = self.sq.dequeue(**request_data)
if response['status'] == 'failure':
return jsonify(**response), 404
except Exception, e:
response['message'] = e.message
return jsonify(**response), 400
return jsonify(**response) | [
"def",
"_view_dequeue",
"(",
"self",
",",
"queue_type",
")",
":",
"response",
"=",
"{",
"'status'",
":",
"'failure'",
"}",
"request_data",
"=",
"{",
"'queue_type'",
":",
"queue_type",
"}",
"try",
":",
"response",
"=",
"self",
".",
"sq",
".",
"dequeue",
"... | Dequeues a job from SharQ. | [
"Dequeues",
"a",
"job",
"from",
"SharQ",
"."
] | 9f4c50eb5ee28d1084591febc4a3a34d7ffd0556 | https://github.com/plivo/sharq-server/blob/9f4c50eb5ee28d1084591febc4a3a34d7ffd0556/sharq_server/server.py#L93-L110 |
20,197 | plivo/sharq-server | sharq_server/server.py | SharQServer._view_finish | def _view_finish(self, queue_type, queue_id, job_id):
"""Marks a job as finished in SharQ."""
response = {
'status': 'failure'
}
request_data = {
'queue_type': queue_type,
'queue_id': queue_id,
'job_id': job_id
}
try:
response = self.sq.finish(**request_data)
if response['status'] == 'failure':
return jsonify(**response), 404
except Exception, e:
response['message'] = e.message
return jsonify(**response), 400
return jsonify(**response) | python | def _view_finish(self, queue_type, queue_id, job_id):
response = {
'status': 'failure'
}
request_data = {
'queue_type': queue_type,
'queue_id': queue_id,
'job_id': job_id
}
try:
response = self.sq.finish(**request_data)
if response['status'] == 'failure':
return jsonify(**response), 404
except Exception, e:
response['message'] = e.message
return jsonify(**response), 400
return jsonify(**response) | [
"def",
"_view_finish",
"(",
"self",
",",
"queue_type",
",",
"queue_id",
",",
"job_id",
")",
":",
"response",
"=",
"{",
"'status'",
":",
"'failure'",
"}",
"request_data",
"=",
"{",
"'queue_type'",
":",
"queue_type",
",",
"'queue_id'",
":",
"queue_id",
",",
... | Marks a job as finished in SharQ. | [
"Marks",
"a",
"job",
"as",
"finished",
"in",
"SharQ",
"."
] | 9f4c50eb5ee28d1084591febc4a3a34d7ffd0556 | https://github.com/plivo/sharq-server/blob/9f4c50eb5ee28d1084591febc4a3a34d7ffd0556/sharq_server/server.py#L112-L131 |
20,198 | plivo/sharq-server | sharq_server/server.py | SharQServer._view_interval | def _view_interval(self, queue_type, queue_id):
"""Updates the queue interval in SharQ."""
response = {
'status': 'failure'
}
try:
request_data = json.loads(request.data)
interval = request_data['interval']
except Exception, e:
response['message'] = e.message
return jsonify(**response), 400
request_data = {
'queue_type': queue_type,
'queue_id': queue_id,
'interval': interval
}
try:
response = self.sq.interval(**request_data)
if response['status'] == 'failure':
return jsonify(**response), 404
except Exception, e:
response['message'] = e.message
return jsonify(**response), 400
return jsonify(**response) | python | def _view_interval(self, queue_type, queue_id):
response = {
'status': 'failure'
}
try:
request_data = json.loads(request.data)
interval = request_data['interval']
except Exception, e:
response['message'] = e.message
return jsonify(**response), 400
request_data = {
'queue_type': queue_type,
'queue_id': queue_id,
'interval': interval
}
try:
response = self.sq.interval(**request_data)
if response['status'] == 'failure':
return jsonify(**response), 404
except Exception, e:
response['message'] = e.message
return jsonify(**response), 400
return jsonify(**response) | [
"def",
"_view_interval",
"(",
"self",
",",
"queue_type",
",",
"queue_id",
")",
":",
"response",
"=",
"{",
"'status'",
":",
"'failure'",
"}",
"try",
":",
"request_data",
"=",
"json",
".",
"loads",
"(",
"request",
".",
"data",
")",
"interval",
"=",
"reques... | Updates the queue interval in SharQ. | [
"Updates",
"the",
"queue",
"interval",
"in",
"SharQ",
"."
] | 9f4c50eb5ee28d1084591febc4a3a34d7ffd0556 | https://github.com/plivo/sharq-server/blob/9f4c50eb5ee28d1084591febc4a3a34d7ffd0556/sharq_server/server.py#L133-L159 |
20,199 | plivo/sharq-server | sharq_server/server.py | SharQServer._view_metrics | def _view_metrics(self, queue_type, queue_id):
"""Gets SharQ metrics based on the params."""
response = {
'status': 'failure'
}
request_data = {}
if queue_type:
request_data['queue_type'] = queue_type
if queue_id:
request_data['queue_id'] = queue_id
try:
response = self.sq.metrics(**request_data)
except Exception, e:
response['message'] = e.message
return jsonify(**response), 400
return jsonify(**response) | python | def _view_metrics(self, queue_type, queue_id):
response = {
'status': 'failure'
}
request_data = {}
if queue_type:
request_data['queue_type'] = queue_type
if queue_id:
request_data['queue_id'] = queue_id
try:
response = self.sq.metrics(**request_data)
except Exception, e:
response['message'] = e.message
return jsonify(**response), 400
return jsonify(**response) | [
"def",
"_view_metrics",
"(",
"self",
",",
"queue_type",
",",
"queue_id",
")",
":",
"response",
"=",
"{",
"'status'",
":",
"'failure'",
"}",
"request_data",
"=",
"{",
"}",
"if",
"queue_type",
":",
"request_data",
"[",
"'queue_type'",
"]",
"=",
"queue_type",
... | Gets SharQ metrics based on the params. | [
"Gets",
"SharQ",
"metrics",
"based",
"on",
"the",
"params",
"."
] | 9f4c50eb5ee28d1084591febc4a3a34d7ffd0556 | https://github.com/plivo/sharq-server/blob/9f4c50eb5ee28d1084591febc4a3a34d7ffd0556/sharq_server/server.py#L161-L178 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.