code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def find_by_text(text, _connection=None, page_size=100, page_number=0,
sort_by=enums.DEFAULT_SORT_BY, sort_order=enums.DEFAULT_SORT_ORDER):
"""
List videos that match the ``text`` in title or description.
"""
return connection.ItemResultSet('find_videos_by_text',
Video, _connection, page_size, page_number, sort_by, sort_order,
text=text) | List videos that match the ``text`` in title or description. | Below is the the instruction that describes the task:
### Input:
List videos that match the ``text`` in title or description.
### Response:
def find_by_text(text, _connection=None, page_size=100, page_number=0,
sort_by=enums.DEFAULT_SORT_BY, sort_order=enums.DEFAULT_SORT_ORDER):
"""
List videos that match the ``text`` in title or description.
"""
return connection.ItemResultSet('find_videos_by_text',
Video, _connection, page_size, page_number, sort_by, sort_order,
text=text) |
def read_backend(self):
'''Returns the :class:`stdnet.BackendStructure`.
'''
session = self.session
if session is not None:
if self._field:
return session.model(self._field.model).read_backend
else:
return session.model(self).read_backend | Returns the :class:`stdnet.BackendStructure`. | Below is the the instruction that describes the task:
### Input:
Returns the :class:`stdnet.BackendStructure`.
### Response:
def read_backend(self):
'''Returns the :class:`stdnet.BackendStructure`.
'''
session = self.session
if session is not None:
if self._field:
return session.model(self._field.model).read_backend
else:
return session.model(self).read_backend |
def create_history_filename(self):
"""Create history_filename with INITHISTORY if it doesn't exist."""
if self.history_filename and not osp.isfile(self.history_filename):
try:
encoding.writelines(self.INITHISTORY, self.history_filename)
except EnvironmentError:
pass | Create history_filename with INITHISTORY if it doesn't exist. | Below is the the instruction that describes the task:
### Input:
Create history_filename with INITHISTORY if it doesn't exist.
### Response:
def create_history_filename(self):
"""Create history_filename with INITHISTORY if it doesn't exist."""
if self.history_filename and not osp.isfile(self.history_filename):
try:
encoding.writelines(self.INITHISTORY, self.history_filename)
except EnvironmentError:
pass |
def parse(
self,
value: str,
type_: typing.Type[typing.Any] = str,
subtype: typing.Type[typing.Any] = str,
) -> typing.Any:
"""
Parse value from string.
Convert :code:`value` to
.. code-block:: python
>>> parser = Config()
>>> parser.parse('12345', type_=int)
<<< 12345
>>>
>>> parser.parse('1,2,3,4', type_=list, subtype=int)
<<< [1, 2, 3, 4]
:param value: string
:param type\\_: the type to return
:param subtype: subtype for iterator types
:return: the parsed config value
"""
if type_ is bool:
return type_(value.lower() in self.TRUE_STRINGS)
try:
if isinstance(type_, type) and issubclass(
type_, (list, tuple, set, frozenset)
):
return type_(
self.parse(v.strip(" "), subtype)
for v in value.split(",")
if value.strip(" ")
)
return type_(value)
except ValueError as e:
raise ConfigError(*e.args) | Parse value from string.
Convert :code:`value` to
.. code-block:: python
>>> parser = Config()
>>> parser.parse('12345', type_=int)
<<< 12345
>>>
>>> parser.parse('1,2,3,4', type_=list, subtype=int)
<<< [1, 2, 3, 4]
:param value: string
:param type\\_: the type to return
:param subtype: subtype for iterator types
:return: the parsed config value | Below is the the instruction that describes the task:
### Input:
Parse value from string.
Convert :code:`value` to
.. code-block:: python
>>> parser = Config()
>>> parser.parse('12345', type_=int)
<<< 12345
>>>
>>> parser.parse('1,2,3,4', type_=list, subtype=int)
<<< [1, 2, 3, 4]
:param value: string
:param type\\_: the type to return
:param subtype: subtype for iterator types
:return: the parsed config value
### Response:
def parse(
self,
value: str,
type_: typing.Type[typing.Any] = str,
subtype: typing.Type[typing.Any] = str,
) -> typing.Any:
"""
Parse value from string.
Convert :code:`value` to
.. code-block:: python
>>> parser = Config()
>>> parser.parse('12345', type_=int)
<<< 12345
>>>
>>> parser.parse('1,2,3,4', type_=list, subtype=int)
<<< [1, 2, 3, 4]
:param value: string
:param type\\_: the type to return
:param subtype: subtype for iterator types
:return: the parsed config value
"""
if type_ is bool:
return type_(value.lower() in self.TRUE_STRINGS)
try:
if isinstance(type_, type) and issubclass(
type_, (list, tuple, set, frozenset)
):
return type_(
self.parse(v.strip(" "), subtype)
for v in value.split(",")
if value.strip(" ")
)
return type_(value)
except ValueError as e:
raise ConfigError(*e.args) |
def export_db(self, dirpath):
"""
Copy all database info to a given directory.
Used primarily for testing; production users
should just pull a backup db from ~/.blockstack-server/backups
(or whatever the working directory is)
"""
if self.db is not None:
self.db.commit()
import virtualchain_hooks
db_path = os.path.join(dirpath, os.path.basename(self.get_db_path()))
snapshots_path = os.path.join(dirpath, os.path.basename(virtualchain.get_snapshots_filename(virtualchain_hooks, self.working_dir)))
atlas_path = os.path.join(dirpath, 'atlas.db')
subdomain_path = os.path.join(dirpath, 'subdomains.db')
subdomain_queue_path = os.path.join(dirpath, 'subdomains.db.queue')
src_atlas_path = os.path.join(self.working_dir, 'atlas.db')
src_subdomain_path = os.path.join(self.working_dir, 'subdomains.db')
src_subdomain_queue_path = os.path.join(self.working_dir, 'subdomains.db.queue')
virtualchain.sqlite3_backup(self.get_db_path(), db_path)
virtualchain.sqlite3_backup(virtualchain.get_snapshots_filename(virtualchain_hooks, self.working_dir), snapshots_path)
if os.path.exists(src_atlas_path):
virtualchain.sqlite3_backup(src_atlas_path, atlas_path)
if os.path.exists(src_subdomain_path):
virtualchain.sqlite3_backup(src_subdomain_path, subdomain_path)
if os.path.exists(src_subdomain_queue_path):
virtualchain.sqlite3_backup(src_subdomain_queue_path, subdomain_queue_path) | Copy all database info to a given directory.
Used primarily for testing; production users
should just pull a backup db from ~/.blockstack-server/backups
(or whatever the working directory is) | Below is the the instruction that describes the task:
### Input:
Copy all database info to a given directory.
Used primarily for testing; production users
should just pull a backup db from ~/.blockstack-server/backups
(or whatever the working directory is)
### Response:
def export_db(self, dirpath):
"""
Copy all database info to a given directory.
Used primarily for testing; production users
should just pull a backup db from ~/.blockstack-server/backups
(or whatever the working directory is)
"""
if self.db is not None:
self.db.commit()
import virtualchain_hooks
db_path = os.path.join(dirpath, os.path.basename(self.get_db_path()))
snapshots_path = os.path.join(dirpath, os.path.basename(virtualchain.get_snapshots_filename(virtualchain_hooks, self.working_dir)))
atlas_path = os.path.join(dirpath, 'atlas.db')
subdomain_path = os.path.join(dirpath, 'subdomains.db')
subdomain_queue_path = os.path.join(dirpath, 'subdomains.db.queue')
src_atlas_path = os.path.join(self.working_dir, 'atlas.db')
src_subdomain_path = os.path.join(self.working_dir, 'subdomains.db')
src_subdomain_queue_path = os.path.join(self.working_dir, 'subdomains.db.queue')
virtualchain.sqlite3_backup(self.get_db_path(), db_path)
virtualchain.sqlite3_backup(virtualchain.get_snapshots_filename(virtualchain_hooks, self.working_dir), snapshots_path)
if os.path.exists(src_atlas_path):
virtualchain.sqlite3_backup(src_atlas_path, atlas_path)
if os.path.exists(src_subdomain_path):
virtualchain.sqlite3_backup(src_subdomain_path, subdomain_path)
if os.path.exists(src_subdomain_queue_path):
virtualchain.sqlite3_backup(src_subdomain_queue_path, subdomain_queue_path) |
def encode_corpus(self, corpus, output_path):
"""
Encode all utterances of the given corpus and store them in a :class:`audiomate.container.Container`.
Args:
corpus (Corpus): The corpus to process.
output_path (str): The path to store the container with the encoded data.
Returns:
Container: The container with the encoded data.
"""
out_container = containers.Container(output_path)
out_container.open()
for utterance in corpus.utterances.values():
data = self.encode_utterance(utterance, corpus=corpus)
out_container.set(utterance.idx, data)
out_container.close()
return out_container | Encode all utterances of the given corpus and store them in a :class:`audiomate.container.Container`.
Args:
corpus (Corpus): The corpus to process.
output_path (str): The path to store the container with the encoded data.
Returns:
Container: The container with the encoded data. | Below is the the instruction that describes the task:
### Input:
Encode all utterances of the given corpus and store them in a :class:`audiomate.container.Container`.
Args:
corpus (Corpus): The corpus to process.
output_path (str): The path to store the container with the encoded data.
Returns:
Container: The container with the encoded data.
### Response:
def encode_corpus(self, corpus, output_path):
"""
Encode all utterances of the given corpus and store them in a :class:`audiomate.container.Container`.
Args:
corpus (Corpus): The corpus to process.
output_path (str): The path to store the container with the encoded data.
Returns:
Container: The container with the encoded data.
"""
out_container = containers.Container(output_path)
out_container.open()
for utterance in corpus.utterances.values():
data = self.encode_utterance(utterance, corpus=corpus)
out_container.set(utterance.idx, data)
out_container.close()
return out_container |
def update(self, process_list):
"""Update the AMP"""
# Get the Nginx status
logger.debug('{}: Update stats using status URL {}'.format(self.NAME, self.get('status_url')))
res = requests.get(self.get('status_url'))
if res.ok:
# u'Active connections: 1 \nserver accepts handled requests\n 1 1 1 \nReading: 0 Writing: 1 Waiting: 0 \n'
self.set_result(res.text.rstrip())
else:
logger.debug('{}: Can not grab status URL {} ({})'.format(self.NAME, self.get('status_url'), res.reason))
return self.result() | Update the AMP | Below is the the instruction that describes the task:
### Input:
Update the AMP
### Response:
def update(self, process_list):
"""Update the AMP"""
# Get the Nginx status
logger.debug('{}: Update stats using status URL {}'.format(self.NAME, self.get('status_url')))
res = requests.get(self.get('status_url'))
if res.ok:
# u'Active connections: 1 \nserver accepts handled requests\n 1 1 1 \nReading: 0 Writing: 1 Waiting: 0 \n'
self.set_result(res.text.rstrip())
else:
logger.debug('{}: Can not grab status URL {} ({})'.format(self.NAME, self.get('status_url'), res.reason))
return self.result() |
def save_value(self, name, value):
"""Save value to session"""
session_name = 'list_{}_{}_{}'.format(self.kwargs.get('app'), self.kwargs.get('model'), name)
self.request.session[session_name] = value
setattr(self, name, value)
return value | Save value to session | Below is the the instruction that describes the task:
### Input:
Save value to session
### Response:
def save_value(self, name, value):
"""Save value to session"""
session_name = 'list_{}_{}_{}'.format(self.kwargs.get('app'), self.kwargs.get('model'), name)
self.request.session[session_name] = value
setattr(self, name, value)
return value |
def _check_valid_label(self, label):
"""Validate label and its shape."""
if len(label.shape) != 2 or label.shape[1] < 5:
msg = "Label with shape (1+, 5+) required, %s received." % str(label)
raise RuntimeError(msg)
valid_label = np.where(np.logical_and(label[:, 0] >= 0, label[:, 3] > label[:, 1],
label[:, 4] > label[:, 2]))[0]
if valid_label.size < 1:
raise RuntimeError('Invalid label occurs.') | Validate label and its shape. | Below is the the instruction that describes the task:
### Input:
Validate label and its shape.
### Response:
def _check_valid_label(self, label):
"""Validate label and its shape."""
if len(label.shape) != 2 or label.shape[1] < 5:
msg = "Label with shape (1+, 5+) required, %s received." % str(label)
raise RuntimeError(msg)
valid_label = np.where(np.logical_and(label[:, 0] >= 0, label[:, 3] > label[:, 1],
label[:, 4] > label[:, 2]))[0]
if valid_label.size < 1:
raise RuntimeError('Invalid label occurs.') |
def process_internal_commands(self):
'''This function processes internal commands
'''
with self._main_lock:
self.check_output_redirect()
program_threads_alive = {}
all_threads = threadingEnumerate()
program_threads_dead = []
with self._lock_running_thread_ids:
reset_cache = not self._running_thread_ids
for t in all_threads:
if getattr(t, 'is_pydev_daemon_thread', False):
pass # I.e.: skip the DummyThreads created from pydev daemon threads
elif isinstance(t, PyDBDaemonThread):
pydev_log.error_once('Error in debugger: Found PyDBDaemonThread not marked with is_pydev_daemon_thread=True.')
elif is_thread_alive(t):
if reset_cache:
# Fix multiprocessing debug with breakpoints in both main and child processes
# (https://youtrack.jetbrains.com/issue/PY-17092) When the new process is created, the main
# thread in the new process already has the attribute 'pydevd_id', so the new thread doesn't
# get new id with its process number and the debugger loses access to both threads.
# Therefore we should update thread_id for every main thread in the new process.
clear_cached_thread_id(t)
thread_id = get_thread_id(t)
program_threads_alive[thread_id] = t
self.notify_thread_created(thread_id, t, use_lock=False)
# Compute and notify about threads which are no longer alive.
thread_ids = list(self._running_thread_ids.keys())
for thread_id in thread_ids:
if thread_id not in program_threads_alive:
program_threads_dead.append(thread_id)
for thread_id in program_threads_dead:
self.notify_thread_not_alive(thread_id, use_lock=False)
# Without self._lock_running_thread_ids
if len(program_threads_alive) == 0:
self.finish_debugging_session()
for t in all_threads:
if hasattr(t, 'do_kill_pydev_thread'):
t.do_kill_pydev_thread()
else:
# Actually process the commands now (make sure we don't have a lock for _lock_running_thread_ids
# acquired at this point as it could lead to a deadlock if some command evaluated tried to
# create a thread and wait for it -- which would try to notify about it getting that lock).
curr_thread_id = get_current_thread_id(threadingCurrentThread())
for thread_id in (curr_thread_id, '*'):
queue = self.get_internal_queue(thread_id)
# some commands must be processed by the thread itself... if that's the case,
# we will re-add the commands to the queue after executing.
cmds_to_add_back = []
try:
while True:
int_cmd = queue.get(False)
if not self.mpl_hooks_in_debug_console and isinstance(int_cmd, InternalConsoleExec):
# add import hooks for matplotlib patches if only debug console was started
try:
self.init_matplotlib_in_debug_console()
self.mpl_in_use = True
except:
pydev_log.debug("Matplotlib support in debug console failed", traceback.format_exc())
self.mpl_hooks_in_debug_console = True
if int_cmd.can_be_executed_by(curr_thread_id):
pydev_log.verbose("processing internal command ", int_cmd)
int_cmd.do_it(self)
else:
pydev_log.verbose("NOT processing internal command ", int_cmd)
cmds_to_add_back.append(int_cmd)
except _queue.Empty: # @UndefinedVariable
# this is how we exit
for int_cmd in cmds_to_add_back:
queue.put(int_cmd) | This function processes internal commands | Below is the the instruction that describes the task:
### Input:
This function processes internal commands
### Response:
def process_internal_commands(self):
'''This function processes internal commands
'''
with self._main_lock:
self.check_output_redirect()
program_threads_alive = {}
all_threads = threadingEnumerate()
program_threads_dead = []
with self._lock_running_thread_ids:
reset_cache = not self._running_thread_ids
for t in all_threads:
if getattr(t, 'is_pydev_daemon_thread', False):
pass # I.e.: skip the DummyThreads created from pydev daemon threads
elif isinstance(t, PyDBDaemonThread):
pydev_log.error_once('Error in debugger: Found PyDBDaemonThread not marked with is_pydev_daemon_thread=True.')
elif is_thread_alive(t):
if reset_cache:
# Fix multiprocessing debug with breakpoints in both main and child processes
# (https://youtrack.jetbrains.com/issue/PY-17092) When the new process is created, the main
# thread in the new process already has the attribute 'pydevd_id', so the new thread doesn't
# get new id with its process number and the debugger loses access to both threads.
# Therefore we should update thread_id for every main thread in the new process.
clear_cached_thread_id(t)
thread_id = get_thread_id(t)
program_threads_alive[thread_id] = t
self.notify_thread_created(thread_id, t, use_lock=False)
# Compute and notify about threads which are no longer alive.
thread_ids = list(self._running_thread_ids.keys())
for thread_id in thread_ids:
if thread_id not in program_threads_alive:
program_threads_dead.append(thread_id)
for thread_id in program_threads_dead:
self.notify_thread_not_alive(thread_id, use_lock=False)
# Without self._lock_running_thread_ids
if len(program_threads_alive) == 0:
self.finish_debugging_session()
for t in all_threads:
if hasattr(t, 'do_kill_pydev_thread'):
t.do_kill_pydev_thread()
else:
# Actually process the commands now (make sure we don't have a lock for _lock_running_thread_ids
# acquired at this point as it could lead to a deadlock if some command evaluated tried to
# create a thread and wait for it -- which would try to notify about it getting that lock).
curr_thread_id = get_current_thread_id(threadingCurrentThread())
for thread_id in (curr_thread_id, '*'):
queue = self.get_internal_queue(thread_id)
# some commands must be processed by the thread itself... if that's the case,
# we will re-add the commands to the queue after executing.
cmds_to_add_back = []
try:
while True:
int_cmd = queue.get(False)
if not self.mpl_hooks_in_debug_console and isinstance(int_cmd, InternalConsoleExec):
# add import hooks for matplotlib patches if only debug console was started
try:
self.init_matplotlib_in_debug_console()
self.mpl_in_use = True
except:
pydev_log.debug("Matplotlib support in debug console failed", traceback.format_exc())
self.mpl_hooks_in_debug_console = True
if int_cmd.can_be_executed_by(curr_thread_id):
pydev_log.verbose("processing internal command ", int_cmd)
int_cmd.do_it(self)
else:
pydev_log.verbose("NOT processing internal command ", int_cmd)
cmds_to_add_back.append(int_cmd)
except _queue.Empty: # @UndefinedVariable
# this is how we exit
for int_cmd in cmds_to_add_back:
queue.put(int_cmd) |
def ssml_sub(self, words, alias=None, **kwargs):
"""
Create a <Sub> element
:param words: Words to be substituted
:param alias: Substitute a different word (or pronunciation) for selected text such as an acronym or abbreviation
:param kwargs: additional attributes
:returns: <Sub> element
"""
return self.nest(SsmlSub(words, alias=alias, **kwargs)) | Create a <Sub> element
:param words: Words to be substituted
:param alias: Substitute a different word (or pronunciation) for selected text such as an acronym or abbreviation
:param kwargs: additional attributes
:returns: <Sub> element | Below is the the instruction that describes the task:
### Input:
Create a <Sub> element
:param words: Words to be substituted
:param alias: Substitute a different word (or pronunciation) for selected text such as an acronym or abbreviation
:param kwargs: additional attributes
:returns: <Sub> element
### Response:
def ssml_sub(self, words, alias=None, **kwargs):
"""
Create a <Sub> element
:param words: Words to be substituted
:param alias: Substitute a different word (or pronunciation) for selected text such as an acronym or abbreviation
:param kwargs: additional attributes
:returns: <Sub> element
"""
return self.nest(SsmlSub(words, alias=alias, **kwargs)) |
def get_log_records_access(f):
"""Access to getLogRecords() controlled by settings.PUBLIC_LOG_RECORDS."""
@functools.wraps(f)
def wrapper(request, *args, **kwargs):
if not django.conf.settings.PUBLIC_LOG_RECORDS:
trusted(request)
return f(request, *args, **kwargs)
return wrapper | Access to getLogRecords() controlled by settings.PUBLIC_LOG_RECORDS. | Below is the the instruction that describes the task:
### Input:
Access to getLogRecords() controlled by settings.PUBLIC_LOG_RECORDS.
### Response:
def get_log_records_access(f):
"""Access to getLogRecords() controlled by settings.PUBLIC_LOG_RECORDS."""
@functools.wraps(f)
def wrapper(request, *args, **kwargs):
if not django.conf.settings.PUBLIC_LOG_RECORDS:
trusted(request)
return f(request, *args, **kwargs)
return wrapper |
def create_menu(self, menu_data):
"""
创建自定义菜单 ::
# -*- coding: utf-8 -*-
wechat = WechatBasic(appid='appid', appsecret='appsecret')
wechat.create_menu({
'button':[
{
'type': 'click',
'name': '今日歌曲',
'key': 'V1001_TODAY_MUSIC'
},
{
'type': 'click',
'name': '歌手简介',
'key': 'V1001_TODAY_SINGER'
},
{
'name': '菜单',
'sub_button': [
{
'type': 'view',
'name': '搜索',
'url': 'http://www.soso.com/'
},
{
'type': 'view',
'name': '视频',
'url': 'http://v.qq.com/'
},
{
'type': 'click',
'name': '赞一下我们',
'key': 'V1001_GOOD'
}
]
}
]})
详情请参考 http://mp.weixin.qq.com/wiki/13/43de8269be54a0a6f64413e4dfa94f39.html
:param menu_data: Python 字典
:return: 返回的 JSON 数据包
"""
menu_data = self._transcoding_dict(menu_data)
return self.request.post(
url='https://api.weixin.qq.com/cgi-bin/menu/create',
data=menu_data
) | 创建自定义菜单 ::
# -*- coding: utf-8 -*-
wechat = WechatBasic(appid='appid', appsecret='appsecret')
wechat.create_menu({
'button':[
{
'type': 'click',
'name': '今日歌曲',
'key': 'V1001_TODAY_MUSIC'
},
{
'type': 'click',
'name': '歌手简介',
'key': 'V1001_TODAY_SINGER'
},
{
'name': '菜单',
'sub_button': [
{
'type': 'view',
'name': '搜索',
'url': 'http://www.soso.com/'
},
{
'type': 'view',
'name': '视频',
'url': 'http://v.qq.com/'
},
{
'type': 'click',
'name': '赞一下我们',
'key': 'V1001_GOOD'
}
]
}
]})
详情请参考 http://mp.weixin.qq.com/wiki/13/43de8269be54a0a6f64413e4dfa94f39.html
:param menu_data: Python 字典
:return: 返回的 JSON 数据包 | Below is the the instruction that describes the task:
### Input:
创建自定义菜单 ::
# -*- coding: utf-8 -*-
wechat = WechatBasic(appid='appid', appsecret='appsecret')
wechat.create_menu({
'button':[
{
'type': 'click',
'name': '今日歌曲',
'key': 'V1001_TODAY_MUSIC'
},
{
'type': 'click',
'name': '歌手简介',
'key': 'V1001_TODAY_SINGER'
},
{
'name': '菜单',
'sub_button': [
{
'type': 'view',
'name': '搜索',
'url': 'http://www.soso.com/'
},
{
'type': 'view',
'name': '视频',
'url': 'http://v.qq.com/'
},
{
'type': 'click',
'name': '赞一下我们',
'key': 'V1001_GOOD'
}
]
}
]})
详情请参考 http://mp.weixin.qq.com/wiki/13/43de8269be54a0a6f64413e4dfa94f39.html
:param menu_data: Python 字典
:return: 返回的 JSON 数据包
### Response:
def create_menu(self, menu_data):
"""
创建自定义菜单 ::
# -*- coding: utf-8 -*-
wechat = WechatBasic(appid='appid', appsecret='appsecret')
wechat.create_menu({
'button':[
{
'type': 'click',
'name': '今日歌曲',
'key': 'V1001_TODAY_MUSIC'
},
{
'type': 'click',
'name': '歌手简介',
'key': 'V1001_TODAY_SINGER'
},
{
'name': '菜单',
'sub_button': [
{
'type': 'view',
'name': '搜索',
'url': 'http://www.soso.com/'
},
{
'type': 'view',
'name': '视频',
'url': 'http://v.qq.com/'
},
{
'type': 'click',
'name': '赞一下我们',
'key': 'V1001_GOOD'
}
]
}
]})
详情请参考 http://mp.weixin.qq.com/wiki/13/43de8269be54a0a6f64413e4dfa94f39.html
:param menu_data: Python 字典
:return: 返回的 JSON 数据包
"""
menu_data = self._transcoding_dict(menu_data)
return self.request.post(
url='https://api.weixin.qq.com/cgi-bin/menu/create',
data=menu_data
) |
def _on_cluster_data_moved(self, response, command, future):
"""Process the ``MOVED`` response from a Redis cluster node.
:param bytes response: The response from the Redis server
:param command: The command that was being executed
:type command: tredis.client.Command
:param future: The execution future
:type future: tornado.concurrent.Future
"""
LOGGER.debug('on_cluster_data_moved(%r, %r, %r)', response, command,
future)
parts = response.split(' ')
name = '{}:{}'.format(*common.split_connection_host_port(parts[2]))
LOGGER.debug('Moved to %r', name)
if name not in self._cluster:
raise exceptions.ConnectionError(
'{} is not connected'.format(name))
self._cluster[name].execute(
command._replace(connection=self._cluster[name]), future) | Process the ``MOVED`` response from a Redis cluster node.
:param bytes response: The response from the Redis server
:param command: The command that was being executed
:type command: tredis.client.Command
:param future: The execution future
:type future: tornado.concurrent.Future | Below is the the instruction that describes the task:
### Input:
Process the ``MOVED`` response from a Redis cluster node.
:param bytes response: The response from the Redis server
:param command: The command that was being executed
:type command: tredis.client.Command
:param future: The execution future
:type future: tornado.concurrent.Future
### Response:
def _on_cluster_data_moved(self, response, command, future):
"""Process the ``MOVED`` response from a Redis cluster node.
:param bytes response: The response from the Redis server
:param command: The command that was being executed
:type command: tredis.client.Command
:param future: The execution future
:type future: tornado.concurrent.Future
"""
LOGGER.debug('on_cluster_data_moved(%r, %r, %r)', response, command,
future)
parts = response.split(' ')
name = '{}:{}'.format(*common.split_connection_host_port(parts[2]))
LOGGER.debug('Moved to %r', name)
if name not in self._cluster:
raise exceptions.ConnectionError(
'{} is not connected'.format(name))
self._cluster[name].execute(
command._replace(connection=self._cluster[name]), future) |
def krb5_unparse_principal_name(name):
"""Split a Kerberos principal name into parts
Returns:
* ('host', hostname, realm) for a host principal
* (servicename, hostname, realm) for a service principal
* (None, username, realm) for a user principal
:param text name: Kerberos principal name
:return: (service, host, realm) or (None, username, realm)
"""
prefix, realm = name.split(u'@')
if u'/' in prefix:
service, host = prefix.rsplit(u'/', 1)
return service, host, realm
else:
return None, prefix, realm | Split a Kerberos principal name into parts
Returns:
* ('host', hostname, realm) for a host principal
* (servicename, hostname, realm) for a service principal
* (None, username, realm) for a user principal
:param text name: Kerberos principal name
:return: (service, host, realm) or (None, username, realm) | Below is the the instruction that describes the task:
### Input:
Split a Kerberos principal name into parts
Returns:
* ('host', hostname, realm) for a host principal
* (servicename, hostname, realm) for a service principal
* (None, username, realm) for a user principal
:param text name: Kerberos principal name
:return: (service, host, realm) or (None, username, realm)
### Response:
def krb5_unparse_principal_name(name):
"""Split a Kerberos principal name into parts
Returns:
* ('host', hostname, realm) for a host principal
* (servicename, hostname, realm) for a service principal
* (None, username, realm) for a user principal
:param text name: Kerberos principal name
:return: (service, host, realm) or (None, username, realm)
"""
prefix, realm = name.split(u'@')
if u'/' in prefix:
service, host = prefix.rsplit(u'/', 1)
return service, host, realm
else:
return None, prefix, realm |
def computePreRec(cm, class_names):
'''
This function computes the precision, recall and f1 measures,
given a confusion matrix
'''
n_classes = cm.shape[0]
if len(class_names) != n_classes:
print("Error in computePreRec! Confusion matrix and class_names "
"list must be of the same size!")
return
precision = []
recall = []
f1 = []
for i, c in enumerate(class_names):
precision.append(cm[i,i] / numpy.sum(cm[:,i]))
recall.append(cm[i,i] / numpy.sum(cm[i,:]))
f1.append( 2 * precision[-1] * recall[-1] / (precision[-1] + recall[-1]))
return recall, precision, f1 | This function computes the precision, recall and f1 measures,
given a confusion matrix | Below is the the instruction that describes the task:
### Input:
This function computes the precision, recall and f1 measures,
given a confusion matrix
### Response:
def computePreRec(cm, class_names):
'''
This function computes the precision, recall and f1 measures,
given a confusion matrix
'''
n_classes = cm.shape[0]
if len(class_names) != n_classes:
print("Error in computePreRec! Confusion matrix and class_names "
"list must be of the same size!")
return
precision = []
recall = []
f1 = []
for i, c in enumerate(class_names):
precision.append(cm[i,i] / numpy.sum(cm[:,i]))
recall.append(cm[i,i] / numpy.sum(cm[i,:]))
f1.append( 2 * precision[-1] * recall[-1] / (precision[-1] + recall[-1]))
return recall, precision, f1 |
def get_current_client_name(self, short=False):
"""Get the current client name."""
client = self.get_current_client()
if client:
if short:
return client.get_short_name()
else:
return client.get_filename() | Get the current client name. | Below is the the instruction that describes the task:
### Input:
Get the current client name.
### Response:
def get_current_client_name(self, short=False):
"""Get the current client name."""
client = self.get_current_client()
if client:
if short:
return client.get_short_name()
else:
return client.get_filename() |
def expect_optional_token(lexer: Lexer, kind: TokenKind) -> Optional[Token]:
"""Expect the next token optionally to be of the given kind.
If the next token is of the given kind, return that token after advancing the lexer.
Otherwise, do not change the parser state and return None.
"""
token = lexer.token
if token.kind == kind:
lexer.advance()
return token
return None | Expect the next token optionally to be of the given kind.
If the next token is of the given kind, return that token after advancing the lexer.
Otherwise, do not change the parser state and return None. | Below is the the instruction that describes the task:
### Input:
Expect the next token optionally to be of the given kind.
If the next token is of the given kind, return that token after advancing the lexer.
Otherwise, do not change the parser state and return None.
### Response:
def expect_optional_token(lexer: Lexer, kind: TokenKind) -> Optional[Token]:
"""Expect the next token optionally to be of the given kind.
If the next token is of the given kind, return that token after advancing the lexer.
Otherwise, do not change the parser state and return None.
"""
token = lexer.token
if token.kind == kind:
lexer.advance()
return token
return None |
def OnDirectionChoice(self, event):
"""Direction choice event handler"""
label = self.direction_choicectrl.GetItems()[event.GetSelection()]
param = self.choice_label2param[label]
self.attrs["direction"] = param
post_command_event(self, self.DrawChartMsg) | Direction choice event handler | Below is the the instruction that describes the task:
### Input:
Direction choice event handler
### Response:
def OnDirectionChoice(self, event):
"""Direction choice event handler"""
label = self.direction_choicectrl.GetItems()[event.GetSelection()]
param = self.choice_label2param[label]
self.attrs["direction"] = param
post_command_event(self, self.DrawChartMsg) |
def transform_coords(self, width, height):
"""Return the current absolute coordinates of the touch event,
transformed to screen coordinates.
For events not of type :attr:`~libinput.constant.EventType.TOUCH_DOWN`,
:attr:`~libinput.constant.EventType.TOUCH_MOTION`, this method
raises :exc:`AttributeError`.
Args:
width (int): The current output screen width.
height (int): The current output screen height.
Returns:
(float, float): The current absolute (x, y) coordinates transformed
to screen coordinates.
"""
if self.type not in {EventType.TOUCH_DOWN, EventType.TOUCH_MOTION}:
raise AttributeError(_wrong_meth.format(self.type))
x = self._libinput.libinput_event_touch_get_x_transformed(
self._handle, width)
y = self._libinput.libinput_event_touch_get_y_transformed(
self._handle, height)
return x, y | Return the current absolute coordinates of the touch event,
transformed to screen coordinates.
For events not of type :attr:`~libinput.constant.EventType.TOUCH_DOWN`,
:attr:`~libinput.constant.EventType.TOUCH_MOTION`, this method
raises :exc:`AttributeError`.
Args:
width (int): The current output screen width.
height (int): The current output screen height.
Returns:
(float, float): The current absolute (x, y) coordinates transformed
to screen coordinates. | Below is the the instruction that describes the task:
### Input:
Return the current absolute coordinates of the touch event,
transformed to screen coordinates.
For events not of type :attr:`~libinput.constant.EventType.TOUCH_DOWN`,
:attr:`~libinput.constant.EventType.TOUCH_MOTION`, this method
raises :exc:`AttributeError`.
Args:
width (int): The current output screen width.
height (int): The current output screen height.
Returns:
(float, float): The current absolute (x, y) coordinates transformed
to screen coordinates.
### Response:
def transform_coords(self, width, height):
"""Return the current absolute coordinates of the touch event,
transformed to screen coordinates.
For events not of type :attr:`~libinput.constant.EventType.TOUCH_DOWN`,
:attr:`~libinput.constant.EventType.TOUCH_MOTION`, this method
raises :exc:`AttributeError`.
Args:
width (int): The current output screen width.
height (int): The current output screen height.
Returns:
(float, float): The current absolute (x, y) coordinates transformed
to screen coordinates.
"""
if self.type not in {EventType.TOUCH_DOWN, EventType.TOUCH_MOTION}:
raise AttributeError(_wrong_meth.format(self.type))
x = self._libinput.libinput_event_touch_get_x_transformed(
self._handle, width)
y = self._libinput.libinput_event_touch_get_y_transformed(
self._handle, height)
return x, y |
def find_duplicates(l: list) -> set:
"""
Return the duplicates in a list.
The function relies on
https://stackoverflow.com/questions/9835762/find-and-list-duplicates-in-a-list .
Parameters
----------
l : list
Name
Returns
-------
set
Duplicated values
>>> find_duplicates([1,2,3])
set()
>>> find_duplicates([1,2,1])
{1}
"""
return set([x for x in l if l.count(x) > 1]) | Return the duplicates in a list.
The function relies on
https://stackoverflow.com/questions/9835762/find-and-list-duplicates-in-a-list .
Parameters
----------
l : list
Name
Returns
-------
set
Duplicated values
>>> find_duplicates([1,2,3])
set()
>>> find_duplicates([1,2,1])
{1} | Below is the the instruction that describes the task:
### Input:
Return the duplicates in a list.
The function relies on
https://stackoverflow.com/questions/9835762/find-and-list-duplicates-in-a-list .
Parameters
----------
l : list
Name
Returns
-------
set
Duplicated values
>>> find_duplicates([1,2,3])
set()
>>> find_duplicates([1,2,1])
{1}
### Response:
def find_duplicates(l: list) -> set:
"""
Return the duplicates in a list.
The function relies on
https://stackoverflow.com/questions/9835762/find-and-list-duplicates-in-a-list .
Parameters
----------
l : list
Name
Returns
-------
set
Duplicated values
>>> find_duplicates([1,2,3])
set()
>>> find_duplicates([1,2,1])
{1}
"""
return set([x for x in l if l.count(x) > 1]) |
def confirm_value(self, widget, x, y):
"""event called clicking on the gauge and so changing its value.
propagates the new value
"""
self.gauge.onmousedown(self.gauge, x, y)
params = (self.gauge.value)
return params | event called clicking on the gauge and so changing its value.
propagates the new value | Below is the the instruction that describes the task:
### Input:
event called clicking on the gauge and so changing its value.
propagates the new value
### Response:
def confirm_value(self, widget, x, y):
"""event called clicking on the gauge and so changing its value.
propagates the new value
"""
self.gauge.onmousedown(self.gauge, x, y)
params = (self.gauge.value)
return params |
def PCExtension(*args, **kwargs):
"""
Parameters
==========
template_regexps: list of 3-tuples
e.g. [(pattern1, target1, subsd1), ...], used to generate
templated code
pass_extra_compile_args: bool
should ext.extra_compile_args be passed along? default: False
"""
vals = {}
intercept = {
'build_callbacks': (), # tuple of (callback, args, kwargs)
'link_ext': True,
'build_files': (),
'dist_files': (), # work around stackoverflow.com/questions/2994396/
'template_regexps': [],
'pass_extra_compile_args': False, # use distutils extra_compile_args?
'pycompilation_compile_kwargs': {},
'pycompilation_link_kwargs': {},
}
for k, v in intercept.items():
vals[k] = kwargs.pop(k, v)
intercept2 = {
'logger': None,
'only_update': True,
}
for k, v in intercept2.items():
vck = kwargs.pop(k, v)
vck = vals['pycompilation_compile_kwargs'].pop(k, vck)
vck = vck or vals['pycompilation_link_kwargs'].pop(k, vck)
vals[k] = vck
instance = Extension(*args, **kwargs)
if vals['logger'] is True:
# interpret as we should instantiate a logger
import logging
logging.basicConfig(level=logging.DEBUG)
vals['logger'] = logging.getLogger('PCExtension')
for k, v in vals.items():
setattr(instance, k, v)
return instance | Parameters
==========
template_regexps: list of 3-tuples
e.g. [(pattern1, target1, subsd1), ...], used to generate
templated code
pass_extra_compile_args: bool
should ext.extra_compile_args be passed along? default: False | Below is the the instruction that describes the task:
### Input:
Parameters
==========
template_regexps: list of 3-tuples
e.g. [(pattern1, target1, subsd1), ...], used to generate
templated code
pass_extra_compile_args: bool
should ext.extra_compile_args be passed along? default: False
### Response:
def PCExtension(*args, **kwargs):
"""
Parameters
==========
template_regexps: list of 3-tuples
e.g. [(pattern1, target1, subsd1), ...], used to generate
templated code
pass_extra_compile_args: bool
should ext.extra_compile_args be passed along? default: False
"""
vals = {}
intercept = {
'build_callbacks': (), # tuple of (callback, args, kwargs)
'link_ext': True,
'build_files': (),
'dist_files': (), # work around stackoverflow.com/questions/2994396/
'template_regexps': [],
'pass_extra_compile_args': False, # use distutils extra_compile_args?
'pycompilation_compile_kwargs': {},
'pycompilation_link_kwargs': {},
}
for k, v in intercept.items():
vals[k] = kwargs.pop(k, v)
intercept2 = {
'logger': None,
'only_update': True,
}
for k, v in intercept2.items():
vck = kwargs.pop(k, v)
vck = vals['pycompilation_compile_kwargs'].pop(k, vck)
vck = vck or vals['pycompilation_link_kwargs'].pop(k, vck)
vals[k] = vck
instance = Extension(*args, **kwargs)
if vals['logger'] is True:
# interpret as we should instantiate a logger
import logging
logging.basicConfig(level=logging.DEBUG)
vals['logger'] = logging.getLogger('PCExtension')
for k, v in vals.items():
setattr(instance, k, v)
return instance |
def plot_spectra(self, nmax, convention='power', unit='per_l', base=10.,
maxcolumns=3, xscale='lin', yscale='log', grid=True,
xlim=(None, None), ylim=(None, None), show=True,
title=True, axes_labelsize=None, tick_labelsize=None,
title_labelsize=None, ax=None, fname=None):
"""
Plot the spectra of the best-concentrated Slepian functions.
Usage
-----
x.plot_spectra(nmax, [convention, unit, base, maxcolumns, xscale,
yscale, grid, xlim, ylim, show, title,
axes_labelsize, tick_labelsize, title_labelsize,
ax, fname])
Parameters
----------
nmax : int
The number of Slepian functions to plot.
convention : str, optional, default = 'power'
The type of spectra to plot: 'power' for power spectrum, and
'energy' for energy spectrum.
unit : str, optional, default = 'per_l'
If 'per_l', return the total contribution to the spectrum for each
spherical harmonic degree l. If 'per_lm', return the average
contribution to the spectrum for each coefficient at spherical
harmonic degree l. If 'per_dlogl', return the spectrum per log
interval dlog_a(l).
base : float, optional, default = 10.
The logarithm base when calculating the 'per_dlogl' spectrum.
maxcolumns : int, optional, default = 3
The maximum number of columns to use when plotting the spectra
of multiple localization windows.
xscale : str, optional, default = 'lin'
Scale of the x axis: 'lin' for linear or 'log' for logarithmic.
yscale : str, optional, default = 'log'
Scale of the y axis: 'lin' for linear or 'log' for logarithmic.
grid : bool, optional, default = True
If True, plot grid lines.
xlim : tuple, optional, default = (None, None)
The upper and lower limits used for the x axis.
ylim : tuple, optional, default = (None, None)
The lower and upper limits used for the y axis.
show : bool, optional, default = True
If True, plot the image to the screen.
title : bool, optional, default = True
If True, plot a legend on top of each subplot providing the taper
number and 1 minus the concentration factor.
axes_labelsize : int, optional, default = None
The font size for the x and y axes labels.
tick_labelsize : int, optional, default = None
The font size for the x and y tick labels.
title_labelsize : int, optional, default = None
The font size for the subplot titles.
ax : matplotlib axes object, optional, default = None
An array of matplotlib axes objects where the plots will appear.
fname : str, optional, default = None
If present, save the image to the file.
"""
if axes_labelsize is None:
axes_labelsize = _mpl.rcParams['axes.labelsize']
if tick_labelsize is None:
tick_labelsize = _mpl.rcParams['xtick.labelsize']
if title_labelsize is None:
title_labelsize = _mpl.rcParams['axes.titlesize']
degrees = self.degrees()
spectrum = self.spectra(nmax=nmax, convention=convention, unit=unit,
base=base)
ncolumns = min(maxcolumns, nmax)
nrows = _np.ceil(nmax / ncolumns).astype(int)
figsize = (_mpl.rcParams['figure.figsize'][0],
_mpl.rcParams['figure.figsize'][0]
* 0.7 * nrows / ncolumns + 0.41)
if ax is None:
fig, axes = _plt.subplots(nrows, ncolumns, figsize=figsize,
sharex='all', sharey='all')
else:
if hasattr(ax, 'flatten') and ax.size < nmax:
raise ValueError('ax.size must be greater or equal to nmax. ' +
'nmax = {:s}'.format(repr(nmax)) +
' and ax.size = {:s}.'.format(repr(ax.size)))
axes = ax
if ax is None:
if nrows > 1:
for axtemp in axes[:-1, :].flatten():
for xlabel_i in axtemp.get_xticklabels():
xlabel_i.set_visible(False)
axtemp.set_xlabel('', visible=False)
for axtemp in axes[:, 1:].flatten():
for ylabel_i in axtemp.get_yticklabels():
ylabel_i.set_visible(False)
axtemp.set_ylabel('', visible=False)
elif nmax > 1:
for axtemp in axes[1:].flatten():
for ylabel_i in axtemp.get_yticklabels():
ylabel_i.set_visible(False)
axtemp.set_ylabel('', visible=False)
if ylim == (None, None):
upper = spectrum[:, :min(self.nmax, nmax)].max()
lower = upper * 1.e-6
ylim = (lower, 5 * upper)
if xlim == (None, None):
if xscale == 'lin':
xlim = (degrees[0], degrees[-1])
for alpha in range(min(self.nmax, nmax)):
evalue = self.eigenvalues[alpha]
if min(self.nmax, nmax) == 1 and ax is None:
axtemp = axes
elif hasattr(axes, 'flatten'):
axtemp = axes.flatten()[alpha]
else:
axtemp = axes[alpha]
if (convention == 'power'):
axtemp.set_ylabel('Power', fontsize=axes_labelsize)
else:
axtemp.set_ylabel('Energy', fontsize=axes_labelsize)
if yscale == 'log':
axtemp.set_yscale('log', basey=base)
if xscale == 'log':
axtemp.set_xscale('log', basex=base)
axtemp.plot(degrees[1:], spectrum[1:, alpha],
label='#{:d} [loss={:2.2g}]'
.format(alpha, 1-evalue))
else:
axtemp.plot(degrees[0:], spectrum[0:, alpha],
label='#{:d} [loss={:2.2g}]'
.format(alpha, 1-evalue))
axtemp.set_xlabel('Spherical harmonic degree',
fontsize=axes_labelsize)
axtemp.set(xlim=xlim, ylim=ylim)
axtemp.minorticks_on()
axtemp.grid(grid, which='major')
axtemp.tick_params(labelsize=tick_labelsize)
if title is True:
axtemp.set_title('#{:d} [loss={:2.2g}]'
.format(alpha, 1-evalue),
fontsize=title_labelsize)
if ax is None:
fig.tight_layout(pad=0.5)
if show:
fig.show()
if fname is not None:
fig.savefig(fname)
return fig, axes | Plot the spectra of the best-concentrated Slepian functions.
Usage
-----
x.plot_spectra(nmax, [convention, unit, base, maxcolumns, xscale,
yscale, grid, xlim, ylim, show, title,
axes_labelsize, tick_labelsize, title_labelsize,
ax, fname])
Parameters
----------
nmax : int
The number of Slepian functions to plot.
convention : str, optional, default = 'power'
The type of spectra to plot: 'power' for power spectrum, and
'energy' for energy spectrum.
unit : str, optional, default = 'per_l'
If 'per_l', return the total contribution to the spectrum for each
spherical harmonic degree l. If 'per_lm', return the average
contribution to the spectrum for each coefficient at spherical
harmonic degree l. If 'per_dlogl', return the spectrum per log
interval dlog_a(l).
base : float, optional, default = 10.
The logarithm base when calculating the 'per_dlogl' spectrum.
maxcolumns : int, optional, default = 3
The maximum number of columns to use when plotting the spectra
of multiple localization windows.
xscale : str, optional, default = 'lin'
Scale of the x axis: 'lin' for linear or 'log' for logarithmic.
yscale : str, optional, default = 'log'
Scale of the y axis: 'lin' for linear or 'log' for logarithmic.
grid : bool, optional, default = True
If True, plot grid lines.
xlim : tuple, optional, default = (None, None)
The upper and lower limits used for the x axis.
ylim : tuple, optional, default = (None, None)
The lower and upper limits used for the y axis.
show : bool, optional, default = True
If True, plot the image to the screen.
title : bool, optional, default = True
If True, plot a legend on top of each subplot providing the taper
number and 1 minus the concentration factor.
axes_labelsize : int, optional, default = None
The font size for the x and y axes labels.
tick_labelsize : int, optional, default = None
The font size for the x and y tick labels.
title_labelsize : int, optional, default = None
The font size for the subplot titles.
ax : matplotlib axes object, optional, default = None
An array of matplotlib axes objects where the plots will appear.
fname : str, optional, default = None
If present, save the image to the file. | Below is the the instruction that describes the task:
### Input:
Plot the spectra of the best-concentrated Slepian functions.
Usage
-----
x.plot_spectra(nmax, [convention, unit, base, maxcolumns, xscale,
yscale, grid, xlim, ylim, show, title,
axes_labelsize, tick_labelsize, title_labelsize,
ax, fname])
Parameters
----------
nmax : int
The number of Slepian functions to plot.
convention : str, optional, default = 'power'
The type of spectra to plot: 'power' for power spectrum, and
'energy' for energy spectrum.
unit : str, optional, default = 'per_l'
If 'per_l', return the total contribution to the spectrum for each
spherical harmonic degree l. If 'per_lm', return the average
contribution to the spectrum for each coefficient at spherical
harmonic degree l. If 'per_dlogl', return the spectrum per log
interval dlog_a(l).
base : float, optional, default = 10.
The logarithm base when calculating the 'per_dlogl' spectrum.
maxcolumns : int, optional, default = 3
The maximum number of columns to use when plotting the spectra
of multiple localization windows.
xscale : str, optional, default = 'lin'
Scale of the x axis: 'lin' for linear or 'log' for logarithmic.
yscale : str, optional, default = 'log'
Scale of the y axis: 'lin' for linear or 'log' for logarithmic.
grid : bool, optional, default = True
If True, plot grid lines.
xlim : tuple, optional, default = (None, None)
The upper and lower limits used for the x axis.
ylim : tuple, optional, default = (None, None)
The lower and upper limits used for the y axis.
show : bool, optional, default = True
If True, plot the image to the screen.
title : bool, optional, default = True
If True, plot a legend on top of each subplot providing the taper
number and 1 minus the concentration factor.
axes_labelsize : int, optional, default = None
The font size for the x and y axes labels.
tick_labelsize : int, optional, default = None
The font size for the x and y tick labels.
title_labelsize : int, optional, default = None
The font size for the subplot titles.
ax : matplotlib axes object, optional, default = None
An array of matplotlib axes objects where the plots will appear.
fname : str, optional, default = None
If present, save the image to the file.
### Response:
def plot_spectra(self, nmax, convention='power', unit='per_l', base=10.,
maxcolumns=3, xscale='lin', yscale='log', grid=True,
xlim=(None, None), ylim=(None, None), show=True,
title=True, axes_labelsize=None, tick_labelsize=None,
title_labelsize=None, ax=None, fname=None):
"""
Plot the spectra of the best-concentrated Slepian functions.
Usage
-----
x.plot_spectra(nmax, [convention, unit, base, maxcolumns, xscale,
yscale, grid, xlim, ylim, show, title,
axes_labelsize, tick_labelsize, title_labelsize,
ax, fname])
Parameters
----------
nmax : int
The number of Slepian functions to plot.
convention : str, optional, default = 'power'
The type of spectra to plot: 'power' for power spectrum, and
'energy' for energy spectrum.
unit : str, optional, default = 'per_l'
If 'per_l', return the total contribution to the spectrum for each
spherical harmonic degree l. If 'per_lm', return the average
contribution to the spectrum for each coefficient at spherical
harmonic degree l. If 'per_dlogl', return the spectrum per log
interval dlog_a(l).
base : float, optional, default = 10.
The logarithm base when calculating the 'per_dlogl' spectrum.
maxcolumns : int, optional, default = 3
The maximum number of columns to use when plotting the spectra
of multiple localization windows.
xscale : str, optional, default = 'lin'
Scale of the x axis: 'lin' for linear or 'log' for logarithmic.
yscale : str, optional, default = 'log'
Scale of the y axis: 'lin' for linear or 'log' for logarithmic.
grid : bool, optional, default = True
If True, plot grid lines.
xlim : tuple, optional, default = (None, None)
The upper and lower limits used for the x axis.
ylim : tuple, optional, default = (None, None)
The lower and upper limits used for the y axis.
show : bool, optional, default = True
If True, plot the image to the screen.
title : bool, optional, default = True
If True, plot a legend on top of each subplot providing the taper
number and 1 minus the concentration factor.
axes_labelsize : int, optional, default = None
The font size for the x and y axes labels.
tick_labelsize : int, optional, default = None
The font size for the x and y tick labels.
title_labelsize : int, optional, default = None
The font size for the subplot titles.
ax : matplotlib axes object, optional, default = None
An array of matplotlib axes objects where the plots will appear.
fname : str, optional, default = None
If present, save the image to the file.
"""
if axes_labelsize is None:
axes_labelsize = _mpl.rcParams['axes.labelsize']
if tick_labelsize is None:
tick_labelsize = _mpl.rcParams['xtick.labelsize']
if title_labelsize is None:
title_labelsize = _mpl.rcParams['axes.titlesize']
degrees = self.degrees()
spectrum = self.spectra(nmax=nmax, convention=convention, unit=unit,
base=base)
ncolumns = min(maxcolumns, nmax)
nrows = _np.ceil(nmax / ncolumns).astype(int)
figsize = (_mpl.rcParams['figure.figsize'][0],
_mpl.rcParams['figure.figsize'][0]
* 0.7 * nrows / ncolumns + 0.41)
if ax is None:
fig, axes = _plt.subplots(nrows, ncolumns, figsize=figsize,
sharex='all', sharey='all')
else:
if hasattr(ax, 'flatten') and ax.size < nmax:
raise ValueError('ax.size must be greater or equal to nmax. ' +
'nmax = {:s}'.format(repr(nmax)) +
' and ax.size = {:s}.'.format(repr(ax.size)))
axes = ax
if ax is None:
if nrows > 1:
for axtemp in axes[:-1, :].flatten():
for xlabel_i in axtemp.get_xticklabels():
xlabel_i.set_visible(False)
axtemp.set_xlabel('', visible=False)
for axtemp in axes[:, 1:].flatten():
for ylabel_i in axtemp.get_yticklabels():
ylabel_i.set_visible(False)
axtemp.set_ylabel('', visible=False)
elif nmax > 1:
for axtemp in axes[1:].flatten():
for ylabel_i in axtemp.get_yticklabels():
ylabel_i.set_visible(False)
axtemp.set_ylabel('', visible=False)
if ylim == (None, None):
upper = spectrum[:, :min(self.nmax, nmax)].max()
lower = upper * 1.e-6
ylim = (lower, 5 * upper)
if xlim == (None, None):
if xscale == 'lin':
xlim = (degrees[0], degrees[-1])
for alpha in range(min(self.nmax, nmax)):
evalue = self.eigenvalues[alpha]
if min(self.nmax, nmax) == 1 and ax is None:
axtemp = axes
elif hasattr(axes, 'flatten'):
axtemp = axes.flatten()[alpha]
else:
axtemp = axes[alpha]
if (convention == 'power'):
axtemp.set_ylabel('Power', fontsize=axes_labelsize)
else:
axtemp.set_ylabel('Energy', fontsize=axes_labelsize)
if yscale == 'log':
axtemp.set_yscale('log', basey=base)
if xscale == 'log':
axtemp.set_xscale('log', basex=base)
axtemp.plot(degrees[1:], spectrum[1:, alpha],
label='#{:d} [loss={:2.2g}]'
.format(alpha, 1-evalue))
else:
axtemp.plot(degrees[0:], spectrum[0:, alpha],
label='#{:d} [loss={:2.2g}]'
.format(alpha, 1-evalue))
axtemp.set_xlabel('Spherical harmonic degree',
fontsize=axes_labelsize)
axtemp.set(xlim=xlim, ylim=ylim)
axtemp.minorticks_on()
axtemp.grid(grid, which='major')
axtemp.tick_params(labelsize=tick_labelsize)
if title is True:
axtemp.set_title('#{:d} [loss={:2.2g}]'
.format(alpha, 1-evalue),
fontsize=title_labelsize)
if ax is None:
fig.tight_layout(pad=0.5)
if show:
fig.show()
if fname is not None:
fig.savefig(fname)
return fig, axes |
def to_utc(value, defaulttz=None):
"""Convert datetime.datetime time to UTC
If value doesn't have tzinfo, then defaulttz is set.
Default value of defaulttz is local time zone.
"""
if defaulttz is None:
defaulttz = tzlocal()
return _convert(value, tzutc(), defaulttz) | Convert datetime.datetime time to UTC
If value doesn't have tzinfo, then defaulttz is set.
Default value of defaulttz is local time zone. | Below is the the instruction that describes the task:
### Input:
Convert datetime.datetime time to UTC
If value doesn't have tzinfo, then defaulttz is set.
Default value of defaulttz is local time zone.
### Response:
def to_utc(value, defaulttz=None):
"""Convert datetime.datetime time to UTC
If value doesn't have tzinfo, then defaulttz is set.
Default value of defaulttz is local time zone.
"""
if defaulttz is None:
defaulttz = tzlocal()
return _convert(value, tzutc(), defaulttz) |
def _post_start(self):
"""Set stdout to non-blocking
VLC does not always return a newline when reading status so in order to
be lazy and still use the read API without caring about how much output
there is we switch stdout to nonblocking mode and just read a large
chunk of datin order to be lazy and still use the read API without
caring about how much output there is we switch stdout to nonblocking
mode and just read a large chunk of data.
"""
flags = fcntl.fcntl(self._process.stdout, fcntl.F_GETFL)
fcntl.fcntl(self._process.stdout, fcntl.F_SETFL, flags | os.O_NONBLOCK) | Set stdout to non-blocking
VLC does not always return a newline when reading status so in order to
be lazy and still use the read API without caring about how much output
there is we switch stdout to nonblocking mode and just read a large
chunk of datin order to be lazy and still use the read API without
caring about how much output there is we switch stdout to nonblocking
mode and just read a large chunk of data. | Below is the the instruction that describes the task:
### Input:
Set stdout to non-blocking
VLC does not always return a newline when reading status so in order to
be lazy and still use the read API without caring about how much output
there is we switch stdout to nonblocking mode and just read a large
chunk of datin order to be lazy and still use the read API without
caring about how much output there is we switch stdout to nonblocking
mode and just read a large chunk of data.
### Response:
def _post_start(self):
"""Set stdout to non-blocking
VLC does not always return a newline when reading status so in order to
be lazy and still use the read API without caring about how much output
there is we switch stdout to nonblocking mode and just read a large
chunk of datin order to be lazy and still use the read API without
caring about how much output there is we switch stdout to nonblocking
mode and just read a large chunk of data.
"""
flags = fcntl.fcntl(self._process.stdout, fcntl.F_GETFL)
fcntl.fcntl(self._process.stdout, fcntl.F_SETFL, flags | os.O_NONBLOCK) |
def get_real_rating(self):
"""get_rating()
Returns the unmodified average rating."""
if not (self.votes and self.score):
return 0
return float(self.score)/self.votes | get_rating()
Returns the unmodified average rating. | Below is the the instruction that describes the task:
### Input:
get_rating()
Returns the unmodified average rating.
### Response:
def get_real_rating(self):
"""get_rating()
Returns the unmodified average rating."""
if not (self.votes and self.score):
return 0
return float(self.score)/self.votes |
def type(self, type):
# pylint: disable=redefined-builtin
"""Setter method; for a description see the getter method."""
type = _ensure_unicode(type)
# We perform this check after the initialization to avoid errors
# in test tools that show the object with repr().
if type not in ALL_CIMTYPES:
raise ValueError(
_format("Invalid CIM type: {0}", type))
# pylint: disable=attribute-defined-outside-init
self._type = type | Setter method; for a description see the getter method. | Below is the the instruction that describes the task:
### Input:
Setter method; for a description see the getter method.
### Response:
def type(self, type):
# pylint: disable=redefined-builtin
"""Setter method; for a description see the getter method."""
type = _ensure_unicode(type)
# We perform this check after the initialization to avoid errors
# in test tools that show the object with repr().
if type not in ALL_CIMTYPES:
raise ValueError(
_format("Invalid CIM type: {0}", type))
# pylint: disable=attribute-defined-outside-init
self._type = type |
def __basis(self, xi, p, compute_derivatives=False):
"""Recursive Cox - de Boor function (for internal use).
Compute basis functions and optionally their first derivatives.
"""
if p == 0:
return self.__basis0(xi)
else:
basis_p_minus_1 = self.__basis(xi, p - 1)
first_term_numerator = xi - self.knot_vector[:-p]
first_term_denominator = self.knot_vector[p:] - self.knot_vector[:-p]
second_term_numerator = self.knot_vector[(p + 1):] - xi
second_term_denominator = (self.knot_vector[(p + 1):] -
self.knot_vector[1:-p])
#Change numerator in last recursion if derivatives are desired
if compute_derivatives and p == self.p:
first_term_numerator = p
second_term_numerator = -p
#Disable divide by zero error because we check for it
with np.errstate(divide='ignore', invalid='ignore'):
first_term = np.where(first_term_denominator != 0.0,
(first_term_numerator /
first_term_denominator), 0.0)
second_term = np.where(second_term_denominator != 0.0,
(second_term_numerator /
second_term_denominator), 0.0)
return (first_term[:-1] * basis_p_minus_1[:-1] +
second_term * basis_p_minus_1[1:]) | Recursive Cox - de Boor function (for internal use).
Compute basis functions and optionally their first derivatives. | Below is the the instruction that describes the task:
### Input:
Recursive Cox - de Boor function (for internal use).
Compute basis functions and optionally their first derivatives.
### Response:
def __basis(self, xi, p, compute_derivatives=False):
"""Recursive Cox - de Boor function (for internal use).
Compute basis functions and optionally their first derivatives.
"""
if p == 0:
return self.__basis0(xi)
else:
basis_p_minus_1 = self.__basis(xi, p - 1)
first_term_numerator = xi - self.knot_vector[:-p]
first_term_denominator = self.knot_vector[p:] - self.knot_vector[:-p]
second_term_numerator = self.knot_vector[(p + 1):] - xi
second_term_denominator = (self.knot_vector[(p + 1):] -
self.knot_vector[1:-p])
#Change numerator in last recursion if derivatives are desired
if compute_derivatives and p == self.p:
first_term_numerator = p
second_term_numerator = -p
#Disable divide by zero error because we check for it
with np.errstate(divide='ignore', invalid='ignore'):
first_term = np.where(first_term_denominator != 0.0,
(first_term_numerator /
first_term_denominator), 0.0)
second_term = np.where(second_term_denominator != 0.0,
(second_term_numerator /
second_term_denominator), 0.0)
return (first_term[:-1] * basis_p_minus_1[:-1] +
second_term * basis_p_minus_1[1:]) |
def true_range(close_data, period):
"""
True Range.
Formula:
TRt = MAX(abs(Ht - Lt), abs(Ht - Ct-1), abs(Lt - Ct-1))
"""
catch_errors.check_for_period_error(close_data, period)
tr = [np.max([np.max(close_data[idx+1-period:idx+1]) -
np.min(close_data[idx+1-period:idx+1]),
abs(np.max(close_data[idx+1-period:idx+1]) -
close_data[idx-1]),
abs(np.min(close_data[idx+1-period:idx+1]) -
close_data[idx-1])]) for idx in range(period-1, len(close_data))]
tr = fill_for_noncomputable_vals(close_data, tr)
return tr | True Range.
Formula:
TRt = MAX(abs(Ht - Lt), abs(Ht - Ct-1), abs(Lt - Ct-1)) | Below is the the instruction that describes the task:
### Input:
True Range.
Formula:
TRt = MAX(abs(Ht - Lt), abs(Ht - Ct-1), abs(Lt - Ct-1))
### Response:
def true_range(close_data, period):
"""
True Range.
Formula:
TRt = MAX(abs(Ht - Lt), abs(Ht - Ct-1), abs(Lt - Ct-1))
"""
catch_errors.check_for_period_error(close_data, period)
tr = [np.max([np.max(close_data[idx+1-period:idx+1]) -
np.min(close_data[idx+1-period:idx+1]),
abs(np.max(close_data[idx+1-period:idx+1]) -
close_data[idx-1]),
abs(np.min(close_data[idx+1-period:idx+1]) -
close_data[idx-1])]) for idx in range(period-1, len(close_data))]
tr = fill_for_noncomputable_vals(close_data, tr)
return tr |
def format_x_tick(axis,
major_locator=None,
major_formatter=None,
minor_locator=None,
minor_formatter=None):
"""Set x axis's format.
This method is designed for time axis.
**中文文档**
设置X轴格式。
"""
if major_locator:
axis.xaxis.set_major_locator(major_locator)
if major_formatter:
axis.xaxis.set_major_formatter(major_formatter)
if minor_locator:
axis.xaxis.set_minor_locator(minor_locator)
if minor_formatter:
axis.xaxis.set_minor_formatter(minor_formatter)
axis.autoscale_view()
plt.setp(axis.xaxis.get_majorticklabels(), rotation=90)
plt.setp(axis.xaxis.get_minorticklabels(), rotation=90)
axis.grid() | Set x axis's format.
This method is designed for time axis.
**中文文档**
设置X轴格式。 | Below is the the instruction that describes the task:
### Input:
Set x axis's format.
This method is designed for time axis.
**中文文档**
设置X轴格式。
### Response:
def format_x_tick(axis,
major_locator=None,
major_formatter=None,
minor_locator=None,
minor_formatter=None):
"""Set x axis's format.
This method is designed for time axis.
**中文文档**
设置X轴格式。
"""
if major_locator:
axis.xaxis.set_major_locator(major_locator)
if major_formatter:
axis.xaxis.set_major_formatter(major_formatter)
if minor_locator:
axis.xaxis.set_minor_locator(minor_locator)
if minor_formatter:
axis.xaxis.set_minor_formatter(minor_formatter)
axis.autoscale_view()
plt.setp(axis.xaxis.get_majorticklabels(), rotation=90)
plt.setp(axis.xaxis.get_minorticklabels(), rotation=90)
axis.grid() |
def predict_log_proba(self, X):
"""Log of proability estimates.
For dask inputs, a dask array or dataframe is returned. For other
inputs (NumPy array, pandas dataframe, scipy sparse matrix), the
regular return value is returned.
If the underlying estimator does not have a ``predict_proba``
method, then an ``AttributeError`` is raised.
Parameters
----------
X : array or dataframe
Returns
-------
y : array-like
"""
self._check_method("predict_log_proba")
return da.log(self.predict_proba(X)) | Log of proability estimates.
For dask inputs, a dask array or dataframe is returned. For other
inputs (NumPy array, pandas dataframe, scipy sparse matrix), the
regular return value is returned.
If the underlying estimator does not have a ``predict_proba``
method, then an ``AttributeError`` is raised.
Parameters
----------
X : array or dataframe
Returns
-------
y : array-like | Below is the the instruction that describes the task:
### Input:
Log of proability estimates.
For dask inputs, a dask array or dataframe is returned. For other
inputs (NumPy array, pandas dataframe, scipy sparse matrix), the
regular return value is returned.
If the underlying estimator does not have a ``predict_proba``
method, then an ``AttributeError`` is raised.
Parameters
----------
X : array or dataframe
Returns
-------
y : array-like
### Response:
def predict_log_proba(self, X):
"""Log of proability estimates.
For dask inputs, a dask array or dataframe is returned. For other
inputs (NumPy array, pandas dataframe, scipy sparse matrix), the
regular return value is returned.
If the underlying estimator does not have a ``predict_proba``
method, then an ``AttributeError`` is raised.
Parameters
----------
X : array or dataframe
Returns
-------
y : array-like
"""
self._check_method("predict_log_proba")
return da.log(self.predict_proba(X)) |
def _parse_csv_header_lcc_csv_v1(headerlines):
'''
This parses the header of the LCC CSV V1 LC format.
'''
# the first three lines indicate the format name, comment char, separator
commentchar = headerlines[1]
separator = headerlines[2]
headerlines = [x.lstrip('%s ' % commentchar) for x in headerlines[3:]]
# next, find the indices of the various LC sections
metadatastart = headerlines.index('OBJECT METADATA')
columnstart = headerlines.index('COLUMN DEFINITIONS')
lcstart = headerlines.index('LIGHTCURVE')
metadata = ' ' .join(headerlines[metadatastart+1:columnstart-1])
columns = ' ' .join(headerlines[columnstart+1:lcstart-1])
metadata = json.loads(metadata)
columns = json.loads(columns)
return metadata, columns, separator | This parses the header of the LCC CSV V1 LC format. | Below is the the instruction that describes the task:
### Input:
This parses the header of the LCC CSV V1 LC format.
### Response:
def _parse_csv_header_lcc_csv_v1(headerlines):
'''
This parses the header of the LCC CSV V1 LC format.
'''
# the first three lines indicate the format name, comment char, separator
commentchar = headerlines[1]
separator = headerlines[2]
headerlines = [x.lstrip('%s ' % commentchar) for x in headerlines[3:]]
# next, find the indices of the various LC sections
metadatastart = headerlines.index('OBJECT METADATA')
columnstart = headerlines.index('COLUMN DEFINITIONS')
lcstart = headerlines.index('LIGHTCURVE')
metadata = ' ' .join(headerlines[metadatastart+1:columnstart-1])
columns = ' ' .join(headerlines[columnstart+1:lcstart-1])
metadata = json.loads(metadata)
columns = json.loads(columns)
return metadata, columns, separator |
def apply_check_config(self, config):
"""
Takes a validated config dictionary and sets the `uri`, `use_https`
and `method` attributes based on the config's contents.
"""
self.uri = config["uri"]
self.use_https = config.get("https", False)
self.method = config.get("method", "GET") | Takes a validated config dictionary and sets the `uri`, `use_https`
and `method` attributes based on the config's contents. | Below is the the instruction that describes the task:
### Input:
Takes a validated config dictionary and sets the `uri`, `use_https`
and `method` attributes based on the config's contents.
### Response:
def apply_check_config(self, config):
"""
Takes a validated config dictionary and sets the `uri`, `use_https`
and `method` attributes based on the config's contents.
"""
self.uri = config["uri"]
self.use_https = config.get("https", False)
self.method = config.get("method", "GET") |
def extend(self, api, route="", base_url="", http=True, cli=True, **kwargs):
"""Adds handlers from a different Hug API to this one - to create a single API"""
api = API(api)
if http and hasattr(api, '_http'):
self.http.extend(api.http, route, base_url, **kwargs)
if cli and hasattr(api, '_cli'):
self.cli.extend(api.cli, **kwargs)
for directive in getattr(api, '_directives', {}).values():
self.add_directive(directive)
for startup_handler in (api.startup_handlers or ()):
self.add_startup_handler(startup_handler) | Adds handlers from a different Hug API to this one - to create a single API | Below is the the instruction that describes the task:
### Input:
Adds handlers from a different Hug API to this one - to create a single API
### Response:
def extend(self, api, route="", base_url="", http=True, cli=True, **kwargs):
"""Adds handlers from a different Hug API to this one - to create a single API"""
api = API(api)
if http and hasattr(api, '_http'):
self.http.extend(api.http, route, base_url, **kwargs)
if cli and hasattr(api, '_cli'):
self.cli.extend(api.cli, **kwargs)
for directive in getattr(api, '_directives', {}).values():
self.add_directive(directive)
for startup_handler in (api.startup_handlers or ()):
self.add_startup_handler(startup_handler) |
def fill_luis_event_properties(
self,
recognizer_result: RecognizerResult,
turn_context: TurnContext,
telemetry_properties: Dict[str, str] = None,
) -> Dict[str, str]:
"""Fills the event properties for LuisResult event for telemetry.
These properties are logged when the recognizer is called.
:param recognizer_result: Last activity sent from user.
:type recognizer_result: RecognizerResult
:param turn_context: Context object containing information for a single turn of conversation with a user.
:type turn_context: TurnContext
:param telemetry_properties: Additional properties to be logged to telemetry with the LuisResult event, defaults to None
:param telemetry_properties: Dict[str, str], optional
:return: A dictionary that is sent as "Properties" to IBotTelemetryClient.TrackEvent method for the BotMessageSend event.
:rtype: Dict[str, str]
"""
intents = recognizer_result.intents
top_two_intents = (
sorted(intents.keys(), key=lambda k: intents[k].score, reverse=True)[:2]
if intents
else []
)
intent_name, intent_score = LuisRecognizer._get_top_k_intent_score(
top_two_intents, intents, index=0
)
intent2_name, intent2_score = LuisRecognizer._get_top_k_intent_score(
top_two_intents, intents, index=1
)
# Add the intent score and conversation id properties
properties: Dict[str, str] = {
LuisTelemetryConstants.application_id_property: self._application.application_id,
LuisTelemetryConstants.intent_property: intent_name,
LuisTelemetryConstants.intent_score_property: intent_score,
LuisTelemetryConstants.intent2_property: intent2_name,
LuisTelemetryConstants.intent_score2_property: intent2_score,
LuisTelemetryConstants.from_id_property: turn_context.activity.from_property.id,
}
sentiment = recognizer_result.properties.get("sentiment")
if sentiment is not None and isinstance(sentiment, Dict):
label = sentiment.get("label")
if label is not None:
properties[LuisTelemetryConstants.sentiment_label_property] = str(label)
score = sentiment.get("score")
if score is not None:
properties[LuisTelemetryConstants.sentiment_score_property] = str(score)
entities = None
if recognizer_result.entities is not None:
entities = json.dumps(recognizer_result.entities)
properties[LuisTelemetryConstants.entities_property] = entities
# Use the LogPersonalInformation flag to toggle logging PII data, text is a common example
if self.log_personal_information and turn_context.activity.text:
properties[
LuisTelemetryConstants.question_property
] = turn_context.activity.text
# Additional Properties can override "stock" properties.
if telemetry_properties is not None:
for key in telemetry_properties:
properties[key] = telemetry_properties[key]
return properties | Fills the event properties for LuisResult event for telemetry.
These properties are logged when the recognizer is called.
:param recognizer_result: Last activity sent from user.
:type recognizer_result: RecognizerResult
:param turn_context: Context object containing information for a single turn of conversation with a user.
:type turn_context: TurnContext
:param telemetry_properties: Additional properties to be logged to telemetry with the LuisResult event, defaults to None
:param telemetry_properties: Dict[str, str], optional
:return: A dictionary that is sent as "Properties" to IBotTelemetryClient.TrackEvent method for the BotMessageSend event.
:rtype: Dict[str, str] | Below is the the instruction that describes the task:
### Input:
Fills the event properties for LuisResult event for telemetry.
These properties are logged when the recognizer is called.
:param recognizer_result: Last activity sent from user.
:type recognizer_result: RecognizerResult
:param turn_context: Context object containing information for a single turn of conversation with a user.
:type turn_context: TurnContext
:param telemetry_properties: Additional properties to be logged to telemetry with the LuisResult event, defaults to None
:param telemetry_properties: Dict[str, str], optional
:return: A dictionary that is sent as "Properties" to IBotTelemetryClient.TrackEvent method for the BotMessageSend event.
:rtype: Dict[str, str]
### Response:
def fill_luis_event_properties(
self,
recognizer_result: RecognizerResult,
turn_context: TurnContext,
telemetry_properties: Dict[str, str] = None,
) -> Dict[str, str]:
"""Fills the event properties for LuisResult event for telemetry.
These properties are logged when the recognizer is called.
:param recognizer_result: Last activity sent from user.
:type recognizer_result: RecognizerResult
:param turn_context: Context object containing information for a single turn of conversation with a user.
:type turn_context: TurnContext
:param telemetry_properties: Additional properties to be logged to telemetry with the LuisResult event, defaults to None
:param telemetry_properties: Dict[str, str], optional
:return: A dictionary that is sent as "Properties" to IBotTelemetryClient.TrackEvent method for the BotMessageSend event.
:rtype: Dict[str, str]
"""
intents = recognizer_result.intents
top_two_intents = (
sorted(intents.keys(), key=lambda k: intents[k].score, reverse=True)[:2]
if intents
else []
)
intent_name, intent_score = LuisRecognizer._get_top_k_intent_score(
top_two_intents, intents, index=0
)
intent2_name, intent2_score = LuisRecognizer._get_top_k_intent_score(
top_two_intents, intents, index=1
)
# Add the intent score and conversation id properties
properties: Dict[str, str] = {
LuisTelemetryConstants.application_id_property: self._application.application_id,
LuisTelemetryConstants.intent_property: intent_name,
LuisTelemetryConstants.intent_score_property: intent_score,
LuisTelemetryConstants.intent2_property: intent2_name,
LuisTelemetryConstants.intent_score2_property: intent2_score,
LuisTelemetryConstants.from_id_property: turn_context.activity.from_property.id,
}
sentiment = recognizer_result.properties.get("sentiment")
if sentiment is not None and isinstance(sentiment, Dict):
label = sentiment.get("label")
if label is not None:
properties[LuisTelemetryConstants.sentiment_label_property] = str(label)
score = sentiment.get("score")
if score is not None:
properties[LuisTelemetryConstants.sentiment_score_property] = str(score)
entities = None
if recognizer_result.entities is not None:
entities = json.dumps(recognizer_result.entities)
properties[LuisTelemetryConstants.entities_property] = entities
# Use the LogPersonalInformation flag to toggle logging PII data, text is a common example
if self.log_personal_information and turn_context.activity.text:
properties[
LuisTelemetryConstants.question_property
] = turn_context.activity.text
# Additional Properties can override "stock" properties.
if telemetry_properties is not None:
for key in telemetry_properties:
properties[key] = telemetry_properties[key]
return properties |
def parse_url(url_data):
"""Parse a URL."""
if url_data.is_directory():
# both ftp and file links represent directories as HTML data
key = "html"
elif url_data.is_file() and firefox.has_sqlite and firefox.extension.search(url_data.url):
key = "firefox"
elif url_data.scheme == "itms-services":
key = "itms_services"
else:
# determine parse routine according to content types
mime = url_data.content_type
key = url_data.ContentMimetypes[mime]
funcname = "parse_"+key
if funcname in globals():
globals()[funcname](url_data)
else:
url_data.aggregate.plugin_manager.run_parser_plugins(url_data, pagetype=key) | Parse a URL. | Below is the the instruction that describes the task:
### Input:
Parse a URL.
### Response:
def parse_url(url_data):
"""Parse a URL."""
if url_data.is_directory():
# both ftp and file links represent directories as HTML data
key = "html"
elif url_data.is_file() and firefox.has_sqlite and firefox.extension.search(url_data.url):
key = "firefox"
elif url_data.scheme == "itms-services":
key = "itms_services"
else:
# determine parse routine according to content types
mime = url_data.content_type
key = url_data.ContentMimetypes[mime]
funcname = "parse_"+key
if funcname in globals():
globals()[funcname](url_data)
else:
url_data.aggregate.plugin_manager.run_parser_plugins(url_data, pagetype=key) |
def get_admins_from_django(homedir):
return ["root@localhost"]
""" Get admin's emails from django settings """
path = homedir + "/settings/basic.py"
if not os.path.exists(path):
path = homedir + "/settings.py"
if not os.path.exists(path):
return
mod = compiler.parseFile(path)
for node in mod.node.nodes:
try:
if node.asList()[0].name == "ADMINS":
# print dir(node.asList()[1].nodes)
# print node.asList()[1].nodes
return [it.nodes[1].value for it in node.asList()[1].asList()]
except:
pass | Get admin's emails from django settings | Below is the the instruction that describes the task:
### Input:
Get admin's emails from django settings
### Response:
def get_admins_from_django(homedir):
return ["root@localhost"]
""" Get admin's emails from django settings """
path = homedir + "/settings/basic.py"
if not os.path.exists(path):
path = homedir + "/settings.py"
if not os.path.exists(path):
return
mod = compiler.parseFile(path)
for node in mod.node.nodes:
try:
if node.asList()[0].name == "ADMINS":
# print dir(node.asList()[1].nodes)
# print node.asList()[1].nodes
return [it.nodes[1].value for it in node.asList()[1].asList()]
except:
pass |
def updateEmotionTone(user, emotionTone, maintainHistory):
"""
updateEmotionTone updates the user emotion tone with the primary emotion -
the emotion tone that has a score greater than or equal to the
EMOTION_SCORE_THRESHOLD; otherwise primary emotion will be 'neutral'
@param user a json object representing user information (tone) to be used in
conversing with the Conversation Service
@param emotionTone a json object containing the emotion tones in the payload
returned by the Tone Analyzer
"""
maxScore = 0.0
primaryEmotion = None
primaryEmotionScore = None
for tone in emotionTone['tones']:
if tone['score'] > maxScore:
maxScore = tone['score']
primaryEmotion = tone['tone_name'].lower()
primaryEmotionScore = tone['score']
if maxScore <= PRIMARY_EMOTION_SCORE_THRESHOLD:
primaryEmotion = 'neutral'
primaryEmotionScore = None
# update user emotion tone
user['tone']['emotion']['current'] = primaryEmotion
if maintainHistory:
if 'history' not in user['tone']['emotion']:
user['tone']['emotion']['history'] = []
user['tone']['emotion']['history'].append({
'tone_name': primaryEmotion,
'score': primaryEmotionScore
}) | updateEmotionTone updates the user emotion tone with the primary emotion -
the emotion tone that has a score greater than or equal to the
EMOTION_SCORE_THRESHOLD; otherwise primary emotion will be 'neutral'
@param user a json object representing user information (tone) to be used in
conversing with the Conversation Service
@param emotionTone a json object containing the emotion tones in the payload
returned by the Tone Analyzer | Below is the the instruction that describes the task:
### Input:
updateEmotionTone updates the user emotion tone with the primary emotion -
the emotion tone that has a score greater than or equal to the
EMOTION_SCORE_THRESHOLD; otherwise primary emotion will be 'neutral'
@param user a json object representing user information (tone) to be used in
conversing with the Conversation Service
@param emotionTone a json object containing the emotion tones in the payload
returned by the Tone Analyzer
### Response:
def updateEmotionTone(user, emotionTone, maintainHistory):
"""
updateEmotionTone updates the user emotion tone with the primary emotion -
the emotion tone that has a score greater than or equal to the
EMOTION_SCORE_THRESHOLD; otherwise primary emotion will be 'neutral'
@param user a json object representing user information (tone) to be used in
conversing with the Conversation Service
@param emotionTone a json object containing the emotion tones in the payload
returned by the Tone Analyzer
"""
maxScore = 0.0
primaryEmotion = None
primaryEmotionScore = None
for tone in emotionTone['tones']:
if tone['score'] > maxScore:
maxScore = tone['score']
primaryEmotion = tone['tone_name'].lower()
primaryEmotionScore = tone['score']
if maxScore <= PRIMARY_EMOTION_SCORE_THRESHOLD:
primaryEmotion = 'neutral'
primaryEmotionScore = None
# update user emotion tone
user['tone']['emotion']['current'] = primaryEmotion
if maintainHistory:
if 'history' not in user['tone']['emotion']:
user['tone']['emotion']['history'] = []
user['tone']['emotion']['history'].append({
'tone_name': primaryEmotion,
'score': primaryEmotionScore
}) |
def section(self, title=None):
""" Returns the :class:`~plexapi.library.LibrarySection` that matches the specified title.
Parameters:
title (str): Title of the section to return.
"""
for section in self.sections():
if section.title.lower() == title.lower():
return section
raise NotFound('Invalid library section: %s' % title) | Returns the :class:`~plexapi.library.LibrarySection` that matches the specified title.
Parameters:
title (str): Title of the section to return. | Below is the the instruction that describes the task:
### Input:
Returns the :class:`~plexapi.library.LibrarySection` that matches the specified title.
Parameters:
title (str): Title of the section to return.
### Response:
def section(self, title=None):
""" Returns the :class:`~plexapi.library.LibrarySection` that matches the specified title.
Parameters:
title (str): Title of the section to return.
"""
for section in self.sections():
if section.title.lower() == title.lower():
return section
raise NotFound('Invalid library section: %s' % title) |
def initialize_all_targets():
"""
Initialize all targets. Necessary before targets can be looked up
via the :class:`Target` class.
"""
ffi.lib.LLVMPY_InitializeAllTargetInfos()
ffi.lib.LLVMPY_InitializeAllTargets()
ffi.lib.LLVMPY_InitializeAllTargetMCs() | Initialize all targets. Necessary before targets can be looked up
via the :class:`Target` class. | Below is the the instruction that describes the task:
### Input:
Initialize all targets. Necessary before targets can be looked up
via the :class:`Target` class.
### Response:
def initialize_all_targets():
"""
Initialize all targets. Necessary before targets can be looked up
via the :class:`Target` class.
"""
ffi.lib.LLVMPY_InitializeAllTargetInfos()
ffi.lib.LLVMPY_InitializeAllTargets()
ffi.lib.LLVMPY_InitializeAllTargetMCs() |
def _gids_to_genes(gids, ssm_locs, cnv_ssms, data):
"""Convert support ids for SNPs and SSMs into associated genes.
"""
locs = collections.defaultdict(set)
for gid in gids:
cur_locs = []
try:
cur_locs.append(ssm_locs[gid])
except KeyError:
for ssm_loc in cnv_ssms.get(gid, []):
cur_locs.append(ssm_locs[ssm_loc])
for chrom, pos in cur_locs:
locs[chrom].add(pos)
genes = set([])
with tx_tmpdir(data) as tmpdir:
chrom_prefix = "chr" if next(ref.file_contigs(dd.get_ref_file(data))).name.startswith("chr") else ""
loc_file = os.path.join(tmpdir, "battenberg_find_genes.bed")
with open(loc_file, "w") as out_handle:
for chrom in sorted(locs.keys()):
for loc in sorted(list(locs[chrom])):
out_handle.write("%s%s\t%s\t%s\n" % (chrom_prefix, chrom, loc - 1, loc))
ann_file = annotate.add_genes(loc_file, data, max_distance=10000)
for r in pybedtools.BedTool(ann_file):
for gene in r.name.split(","):
if gene != ".":
genes.add(gene)
return sorted(list(genes)) | Convert support ids for SNPs and SSMs into associated genes. | Below is the the instruction that describes the task:
### Input:
Convert support ids for SNPs and SSMs into associated genes.
### Response:
def _gids_to_genes(gids, ssm_locs, cnv_ssms, data):
"""Convert support ids for SNPs and SSMs into associated genes.
"""
locs = collections.defaultdict(set)
for gid in gids:
cur_locs = []
try:
cur_locs.append(ssm_locs[gid])
except KeyError:
for ssm_loc in cnv_ssms.get(gid, []):
cur_locs.append(ssm_locs[ssm_loc])
for chrom, pos in cur_locs:
locs[chrom].add(pos)
genes = set([])
with tx_tmpdir(data) as tmpdir:
chrom_prefix = "chr" if next(ref.file_contigs(dd.get_ref_file(data))).name.startswith("chr") else ""
loc_file = os.path.join(tmpdir, "battenberg_find_genes.bed")
with open(loc_file, "w") as out_handle:
for chrom in sorted(locs.keys()):
for loc in sorted(list(locs[chrom])):
out_handle.write("%s%s\t%s\t%s\n" % (chrom_prefix, chrom, loc - 1, loc))
ann_file = annotate.add_genes(loc_file, data, max_distance=10000)
for r in pybedtools.BedTool(ann_file):
for gene in r.name.split(","):
if gene != ".":
genes.add(gene)
return sorted(list(genes)) |
def main():
'''Main routine.'''
# process arguments
if len(sys.argv) < 3:
usage()
rgname = sys.argv[1]
vmss = sys.argv[2]
# Load Azure app defaults
try:
with open('azurermconfig.json') as config_file:
config_data = json.load(config_file)
except FileNotFoundError:
sys.exit("Error: Expecting azurermconfig.json in current folder")
tenant_id = config_data['tenantId']
app_id = config_data['appId']
app_secret = config_data['appSecret']
sub_id = config_data['subscriptionId']
access_token = azurerm.get_access_token(tenant_id, app_id, app_secret)
# get metric definitions
provider = 'Microsoft.Compute'
resource_type = 'virtualMachineScaleSets'
metric_definitions = azurerm.list_metric_defs_for_resource(access_token, sub_id, rgname,
provider, resource_type, vmss)
print(json.dumps(metric_definitions, sort_keys=False, indent=2, separators=(',', ': ')))
metrics = azurerm.get_metrics_for_resource(access_token, sub_id, rgname,
provider, resource_type, vmss)
print(json.dumps(metrics, sort_keys=False, indent=2, separators=(',', ': '))) | Main routine. | Below is the the instruction that describes the task:
### Input:
Main routine.
### Response:
def main():
'''Main routine.'''
# process arguments
if len(sys.argv) < 3:
usage()
rgname = sys.argv[1]
vmss = sys.argv[2]
# Load Azure app defaults
try:
with open('azurermconfig.json') as config_file:
config_data = json.load(config_file)
except FileNotFoundError:
sys.exit("Error: Expecting azurermconfig.json in current folder")
tenant_id = config_data['tenantId']
app_id = config_data['appId']
app_secret = config_data['appSecret']
sub_id = config_data['subscriptionId']
access_token = azurerm.get_access_token(tenant_id, app_id, app_secret)
# get metric definitions
provider = 'Microsoft.Compute'
resource_type = 'virtualMachineScaleSets'
metric_definitions = azurerm.list_metric_defs_for_resource(access_token, sub_id, rgname,
provider, resource_type, vmss)
print(json.dumps(metric_definitions, sort_keys=False, indent=2, separators=(',', ': ')))
metrics = azurerm.get_metrics_for_resource(access_token, sub_id, rgname,
provider, resource_type, vmss)
print(json.dumps(metrics, sort_keys=False, indent=2, separators=(',', ': '))) |
def retrieve_config(element):
'''retrieve_config
High-level api: Retrive config from rpc-reply.
Parameters
----------
element : `Element`
A rpc-reply or content of Config instance.
Returns
-------
Element
A new element which represents config data.
'''
if not etree.iselement(element):
raise TypeError("argument 'element' must be Element not '{}'" \
.format(type(element)))
ret = etree.Element(config_tag, nsmap={'nc': nc_url})
ret.extend(deepcopy(element.xpath('/nc:rpc-reply/nc:data/*',
namespaces={'nc': nc_url})))
ret.extend(deepcopy(element.xpath('/nc:data/*',
namespaces={'nc': nc_url})))
ret.extend(deepcopy(element.xpath('/nc:config/*',
namespaces={'nc': nc_url})))
ret.extend(deepcopy(element.xpath('/nc:rpc/nc:edit-config/nc:config/*',
namespaces={'nc': nc_url})))
ret.extend(deepcopy(element.xpath('/nc:edit-config/nc:config/*',
namespaces={'nc': nc_url})))
return ret | retrieve_config
High-level api: Retrive config from rpc-reply.
Parameters
----------
element : `Element`
A rpc-reply or content of Config instance.
Returns
-------
Element
A new element which represents config data. | Below is the the instruction that describes the task:
### Input:
retrieve_config
High-level api: Retrive config from rpc-reply.
Parameters
----------
element : `Element`
A rpc-reply or content of Config instance.
Returns
-------
Element
A new element which represents config data.
### Response:
def retrieve_config(element):
'''retrieve_config
High-level api: Retrive config from rpc-reply.
Parameters
----------
element : `Element`
A rpc-reply or content of Config instance.
Returns
-------
Element
A new element which represents config data.
'''
if not etree.iselement(element):
raise TypeError("argument 'element' must be Element not '{}'" \
.format(type(element)))
ret = etree.Element(config_tag, nsmap={'nc': nc_url})
ret.extend(deepcopy(element.xpath('/nc:rpc-reply/nc:data/*',
namespaces={'nc': nc_url})))
ret.extend(deepcopy(element.xpath('/nc:data/*',
namespaces={'nc': nc_url})))
ret.extend(deepcopy(element.xpath('/nc:config/*',
namespaces={'nc': nc_url})))
ret.extend(deepcopy(element.xpath('/nc:rpc/nc:edit-config/nc:config/*',
namespaces={'nc': nc_url})))
ret.extend(deepcopy(element.xpath('/nc:edit-config/nc:config/*',
namespaces={'nc': nc_url})))
return ret |
def recall_series(y_true, y_score, k=None, value=True):
"""
Returns series of length k whose i-th entry is the recall in the top i
"""
y_true, y_score = to_float(y_true, y_score)
top = _argsort(y_score, k)
if not value:
y_true = 1-y_true
a = np.nan_to_num(y_true[top]).cumsum()
return pd.Series(a, index=np.arange(1, len(a)+1)) | Returns series of length k whose i-th entry is the recall in the top i | Below is the the instruction that describes the task:
### Input:
Returns series of length k whose i-th entry is the recall in the top i
### Response:
def recall_series(y_true, y_score, k=None, value=True):
"""
Returns series of length k whose i-th entry is the recall in the top i
"""
y_true, y_score = to_float(y_true, y_score)
top = _argsort(y_score, k)
if not value:
y_true = 1-y_true
a = np.nan_to_num(y_true[top]).cumsum()
return pd.Series(a, index=np.arange(1, len(a)+1)) |
def transaction_commit(self, transaction_id, **kwargs):
"""Commit a transaction.
:param transaction_id: ID of transaction to be committed.
:param **kwargs: Further parameters for the transport layer.
"""
if transaction_id not in self.__transactions:
raise workflows.Error("Attempting to commit unknown transaction")
self.log.debug("Committing transaction %s", transaction_id)
self.__transactions.remove(transaction_id)
self._transaction_commit(transaction_id, **kwargs) | Commit a transaction.
:param transaction_id: ID of transaction to be committed.
:param **kwargs: Further parameters for the transport layer. | Below is the the instruction that describes the task:
### Input:
Commit a transaction.
:param transaction_id: ID of transaction to be committed.
:param **kwargs: Further parameters for the transport layer.
### Response:
def transaction_commit(self, transaction_id, **kwargs):
"""Commit a transaction.
:param transaction_id: ID of transaction to be committed.
:param **kwargs: Further parameters for the transport layer.
"""
if transaction_id not in self.__transactions:
raise workflows.Error("Attempting to commit unknown transaction")
self.log.debug("Committing transaction %s", transaction_id)
self.__transactions.remove(transaction_id)
self._transaction_commit(transaction_id, **kwargs) |
def insert(self, value):
"""Insert an occurrence of `value` into the btree."""
i = 0
n = len(self._tree)
while i < n:
cur = self._tree[i]
self._counts[i] += 1
if value < cur:
i = 2 * i + 1
elif value > cur:
i = 2 * i + 2
else:
return
raise ValueError("Value %s not contained in tree." "Also, the counts are now messed up." % value) | Insert an occurrence of `value` into the btree. | Below is the the instruction that describes the task:
### Input:
Insert an occurrence of `value` into the btree.
### Response:
def insert(self, value):
"""Insert an occurrence of `value` into the btree."""
i = 0
n = len(self._tree)
while i < n:
cur = self._tree[i]
self._counts[i] += 1
if value < cur:
i = 2 * i + 1
elif value > cur:
i = 2 * i + 2
else:
return
raise ValueError("Value %s not contained in tree." "Also, the counts are now messed up." % value) |
def get_connection(self, *args, **kwargs):
"Get a connection from the pool"
self._checkpid()
try:
connection = self._available_connections.pop()
except IndexError:
connection = self.make_connection()
self._in_use_connections.add(connection)
return connection | Get a connection from the pool | Below is the the instruction that describes the task:
### Input:
Get a connection from the pool
### Response:
def get_connection(self, *args, **kwargs):
"Get a connection from the pool"
self._checkpid()
try:
connection = self._available_connections.pop()
except IndexError:
connection = self.make_connection()
self._in_use_connections.add(connection)
return connection |
def calculate_usage(self, cpu, total, busy):
"""
calculates usage
"""
diff_total = total - self.prev_total[cpu]
diff_busy = busy - self.prev_busy[cpu]
self.prev_total[cpu] = total
self.prev_busy[cpu] = busy
if diff_total == 0:
return 0
else:
return int(diff_busy / diff_total * 100) | calculates usage | Below is the the instruction that describes the task:
### Input:
calculates usage
### Response:
def calculate_usage(self, cpu, total, busy):
"""
calculates usage
"""
diff_total = total - self.prev_total[cpu]
diff_busy = busy - self.prev_busy[cpu]
self.prev_total[cpu] = total
self.prev_busy[cpu] = busy
if diff_total == 0:
return 0
else:
return int(diff_busy / diff_total * 100) |
def proximal_l1_l2(space, lam=1, g=None):
r"""Proximal operator factory of the group-L1-L2 norm/distance.
Implements the proximal operator of the functional ::
F(x) = lam || |x - g|_2 ||_1
with ``x`` and ``g`` elements in ``space``, and scaling factor ``lam``.
Here, ``|.|_2`` is the pointwise Euclidean norm of a vector-valued
function.
Parameters
----------
space : `LinearSpace` or `ProductSpace`
Domain of the functional.
lam : positive float, optional
Scaling factor or regularization parameter.
g : ``space`` element, optional
Element to which the L1-L2 distance is taken.
Default: ``space.zero``.
Returns
-------
prox_factory : function
Factory for the proximal operator to be initialized
Notes
-----
For the functional
.. math::
F(x) = \lambda \| |x - g|_2 \|_1,
and a step size :math:`\sigma`, the proximal operator of
:math:`\sigma F` is given as the "soft-shrinkage" operator
.. math::
\mathrm{prox}_{\sigma F}(x) =
\begin{cases}
g, & \text{where } |x - g|_2 \leq \sigma\lambda, \\
x - \sigma\lambda \frac{x - g}{|x - g|_2}, & \text{elsewhere.}
\end{cases}
Here, all operations are to be read pointwise.
See Also
--------
proximal_l1 : Scalar or non-isotropic vectorial variant
"""
lam = float(lam)
if g is not None and g not in space:
raise TypeError('{!r} is not an element of {!r}'.format(g, space))
class ProximalL1L2(Operator):
"""Proximal operator of the group-L1-L2 norm/distance."""
def __init__(self, sigma):
"""Initialize a new instance.
Parameters
----------
sigma : positive float
Step size parameter.
"""
super(ProximalL1L2, self).__init__(
domain=space, range=space, linear=False)
self.sigma = float(sigma)
def _call(self, x, out):
"""Return ``self(x, out=out)``."""
# diff = x - g
if g is not None:
diff = x - g
else:
if x is out:
# Handle aliased `x` and `out` (original `x` needed later)
diff = x.copy()
else:
diff = x
# We write the operator as
# x - (x - g) / max(|x - g|_2 / sig*lam, 1)
pwnorm = PointwiseNorm(self.domain, exponent=2)
denom = pwnorm(diff)
denom /= self.sigma * lam
denom.ufuncs.maximum(1, out=denom)
# out = (x - g) / denom
for out_i, diff_i in zip(out, diff):
diff_i.divide(denom, out=out_i)
# out = x - ...
out.lincomb(1, x, -1, out)
return ProximalL1L2 | r"""Proximal operator factory of the group-L1-L2 norm/distance.
Implements the proximal operator of the functional ::
F(x) = lam || |x - g|_2 ||_1
with ``x`` and ``g`` elements in ``space``, and scaling factor ``lam``.
Here, ``|.|_2`` is the pointwise Euclidean norm of a vector-valued
function.
Parameters
----------
space : `LinearSpace` or `ProductSpace`
Domain of the functional.
lam : positive float, optional
Scaling factor or regularization parameter.
g : ``space`` element, optional
Element to which the L1-L2 distance is taken.
Default: ``space.zero``.
Returns
-------
prox_factory : function
Factory for the proximal operator to be initialized
Notes
-----
For the functional
.. math::
F(x) = \lambda \| |x - g|_2 \|_1,
and a step size :math:`\sigma`, the proximal operator of
:math:`\sigma F` is given as the "soft-shrinkage" operator
.. math::
\mathrm{prox}_{\sigma F}(x) =
\begin{cases}
g, & \text{where } |x - g|_2 \leq \sigma\lambda, \\
x - \sigma\lambda \frac{x - g}{|x - g|_2}, & \text{elsewhere.}
\end{cases}
Here, all operations are to be read pointwise.
See Also
--------
proximal_l1 : Scalar or non-isotropic vectorial variant | Below is the the instruction that describes the task:
### Input:
r"""Proximal operator factory of the group-L1-L2 norm/distance.
Implements the proximal operator of the functional ::
F(x) = lam || |x - g|_2 ||_1
with ``x`` and ``g`` elements in ``space``, and scaling factor ``lam``.
Here, ``|.|_2`` is the pointwise Euclidean norm of a vector-valued
function.
Parameters
----------
space : `LinearSpace` or `ProductSpace`
Domain of the functional.
lam : positive float, optional
Scaling factor or regularization parameter.
g : ``space`` element, optional
Element to which the L1-L2 distance is taken.
Default: ``space.zero``.
Returns
-------
prox_factory : function
Factory for the proximal operator to be initialized
Notes
-----
For the functional
.. math::
F(x) = \lambda \| |x - g|_2 \|_1,
and a step size :math:`\sigma`, the proximal operator of
:math:`\sigma F` is given as the "soft-shrinkage" operator
.. math::
\mathrm{prox}_{\sigma F}(x) =
\begin{cases}
g, & \text{where } |x - g|_2 \leq \sigma\lambda, \\
x - \sigma\lambda \frac{x - g}{|x - g|_2}, & \text{elsewhere.}
\end{cases}
Here, all operations are to be read pointwise.
See Also
--------
proximal_l1 : Scalar or non-isotropic vectorial variant
### Response:
def proximal_l1_l2(space, lam=1, g=None):
r"""Proximal operator factory of the group-L1-L2 norm/distance.
Implements the proximal operator of the functional ::
F(x) = lam || |x - g|_2 ||_1
with ``x`` and ``g`` elements in ``space``, and scaling factor ``lam``.
Here, ``|.|_2`` is the pointwise Euclidean norm of a vector-valued
function.
Parameters
----------
space : `LinearSpace` or `ProductSpace`
Domain of the functional.
lam : positive float, optional
Scaling factor or regularization parameter.
g : ``space`` element, optional
Element to which the L1-L2 distance is taken.
Default: ``space.zero``.
Returns
-------
prox_factory : function
Factory for the proximal operator to be initialized
Notes
-----
For the functional
.. math::
F(x) = \lambda \| |x - g|_2 \|_1,
and a step size :math:`\sigma`, the proximal operator of
:math:`\sigma F` is given as the "soft-shrinkage" operator
.. math::
\mathrm{prox}_{\sigma F}(x) =
\begin{cases}
g, & \text{where } |x - g|_2 \leq \sigma\lambda, \\
x - \sigma\lambda \frac{x - g}{|x - g|_2}, & \text{elsewhere.}
\end{cases}
Here, all operations are to be read pointwise.
See Also
--------
proximal_l1 : Scalar or non-isotropic vectorial variant
"""
lam = float(lam)
if g is not None and g not in space:
raise TypeError('{!r} is not an element of {!r}'.format(g, space))
class ProximalL1L2(Operator):
"""Proximal operator of the group-L1-L2 norm/distance."""
def __init__(self, sigma):
"""Initialize a new instance.
Parameters
----------
sigma : positive float
Step size parameter.
"""
super(ProximalL1L2, self).__init__(
domain=space, range=space, linear=False)
self.sigma = float(sigma)
def _call(self, x, out):
"""Return ``self(x, out=out)``."""
# diff = x - g
if g is not None:
diff = x - g
else:
if x is out:
# Handle aliased `x` and `out` (original `x` needed later)
diff = x.copy()
else:
diff = x
# We write the operator as
# x - (x - g) / max(|x - g|_2 / sig*lam, 1)
pwnorm = PointwiseNorm(self.domain, exponent=2)
denom = pwnorm(diff)
denom /= self.sigma * lam
denom.ufuncs.maximum(1, out=denom)
# out = (x - g) / denom
for out_i, diff_i in zip(out, diff):
diff_i.divide(denom, out=out_i)
# out = x - ...
out.lincomb(1, x, -1, out)
return ProximalL1L2 |
def _append_slash_if_dir_path(self, relpath):
"""For a dir path return a path that has a trailing slash."""
if self._isdir_raw(relpath):
return self._append_trailing_slash(relpath)
return relpath | For a dir path return a path that has a trailing slash. | Below is the the instruction that describes the task:
### Input:
For a dir path return a path that has a trailing slash.
### Response:
def _append_slash_if_dir_path(self, relpath):
"""For a dir path return a path that has a trailing slash."""
if self._isdir_raw(relpath):
return self._append_trailing_slash(relpath)
return relpath |
def bool_check(*args, func=None):
"""Check if arguments are bytes type."""
func = func or inspect.stack()[2][3]
for var in args:
if not isinstance(var, bool):
name = type(var).__name__
raise BoolError(
f'Function {func} expected bool, {name} got instead.') | Check if arguments are bytes type. | Below is the the instruction that describes the task:
### Input:
Check if arguments are bytes type.
### Response:
def bool_check(*args, func=None):
"""Check if arguments are bytes type."""
func = func or inspect.stack()[2][3]
for var in args:
if not isinstance(var, bool):
name = type(var).__name__
raise BoolError(
f'Function {func} expected bool, {name} got instead.') |
def fetch_social_friend_ids(self, social_auth_user):
"""
fetches the user's social friends from its provider
user is an instance of UserSocialAuth
returns collection of ids
this method can be used asynchronously as a background process (celery)
"""
# Type check
self.assert_user_is_social_auth_user(social_auth_user)
# Get friend finder backend
friends_provider = SocialFriendsFinderBackendFactory.get_backend(social_auth_user.provider)
# Get friend ids
friend_ids = friends_provider.fetch_friend_ids(social_auth_user)
return friend_ids | fetches the user's social friends from its provider
user is an instance of UserSocialAuth
returns collection of ids
this method can be used asynchronously as a background process (celery) | Below is the the instruction that describes the task:
### Input:
fetches the user's social friends from its provider
user is an instance of UserSocialAuth
returns collection of ids
this method can be used asynchronously as a background process (celery)
### Response:
def fetch_social_friend_ids(self, social_auth_user):
"""
fetches the user's social friends from its provider
user is an instance of UserSocialAuth
returns collection of ids
this method can be used asynchronously as a background process (celery)
"""
# Type check
self.assert_user_is_social_auth_user(social_auth_user)
# Get friend finder backend
friends_provider = SocialFriendsFinderBackendFactory.get_backend(social_auth_user.provider)
# Get friend ids
friend_ids = friends_provider.fetch_friend_ids(social_auth_user)
return friend_ids |
def auth_as(self, user):
"""auth as a user temporarily"""
old_user = self._user
self.auth(user)
try:
yield
finally:
self.auth(old_user) | auth as a user temporarily | Below is the the instruction that describes the task:
### Input:
auth as a user temporarily
### Response:
def auth_as(self, user):
"""auth as a user temporarily"""
old_user = self._user
self.auth(user)
try:
yield
finally:
self.auth(old_user) |
def append(a, vancestors):
"""
Append ``a`` to the list of the virtual ancestors, unless it is already
included.
"""
add = True
for j, va in enumerate(vancestors):
if issubclass(va, a):
add = False
break
if issubclass(a, va):
vancestors[j] = a
add = False
if add:
vancestors.append(a) | Append ``a`` to the list of the virtual ancestors, unless it is already
included. | Below is the the instruction that describes the task:
### Input:
Append ``a`` to the list of the virtual ancestors, unless it is already
included.
### Response:
def append(a, vancestors):
"""
Append ``a`` to the list of the virtual ancestors, unless it is already
included.
"""
add = True
for j, va in enumerate(vancestors):
if issubclass(va, a):
add = False
break
if issubclass(a, va):
vancestors[j] = a
add = False
if add:
vancestors.append(a) |
def z(self):
"Day of the year; i.e. '0' to '365'"
doy = self.year_days[self.data.month] + self.data.day
if self.L() and self.data.month > 2:
doy += 1
return doy | Day of the year; i.e. '0' to '365 | Below is the the instruction that describes the task:
### Input:
Day of the year; i.e. '0' to '365
### Response:
def z(self):
"Day of the year; i.e. '0' to '365'"
doy = self.year_days[self.data.month] + self.data.day
if self.L() and self.data.month > 2:
doy += 1
return doy |
def ping(self):
"""Ping this hook.
:returns: bool
"""
url = self._build_url('pings', base_url=self._api)
return self._boolean(self._post(url), 204, 404) | Ping this hook.
:returns: bool | Below is the the instruction that describes the task:
### Input:
Ping this hook.
:returns: bool
### Response:
def ping(self):
"""Ping this hook.
:returns: bool
"""
url = self._build_url('pings', base_url=self._api)
return self._boolean(self._post(url), 204, 404) |
def register_work(self, work, deps=None, manager=None, workdir=None):
"""
Register a new :class:`Work` and add it to the internal list, taking into account possible dependencies.
Args:
work: :class:`Work` object.
deps: List of :class:`Dependency` objects specifying the dependency of this node.
An empy list of deps implies that this node has no dependencies.
manager: The :class:`TaskManager` responsible for the submission of the task.
If manager is None, we use the `TaskManager` specified during the creation of the work.
workdir: The name of the directory used for the :class:`Work`.
Returns:
The registered :class:`Work`.
"""
if getattr(self, "workdir", None) is not None:
# The flow has a directory, build the named of the directory of the work.
work_workdir = None
if workdir is None:
work_workdir = os.path.join(self.workdir, "w" + str(len(self)))
else:
work_workdir = os.path.join(self.workdir, os.path.basename(workdir))
work.set_workdir(work_workdir)
if manager is not None:
work.set_manager(manager)
self.works.append(work)
if deps:
deps = [Dependency(node, exts) for node, exts in deps.items()]
work.add_deps(deps)
return work | Register a new :class:`Work` and add it to the internal list, taking into account possible dependencies.
Args:
work: :class:`Work` object.
deps: List of :class:`Dependency` objects specifying the dependency of this node.
An empy list of deps implies that this node has no dependencies.
manager: The :class:`TaskManager` responsible for the submission of the task.
If manager is None, we use the `TaskManager` specified during the creation of the work.
workdir: The name of the directory used for the :class:`Work`.
Returns:
The registered :class:`Work`. | Below is the the instruction that describes the task:
### Input:
Register a new :class:`Work` and add it to the internal list, taking into account possible dependencies.
Args:
work: :class:`Work` object.
deps: List of :class:`Dependency` objects specifying the dependency of this node.
An empy list of deps implies that this node has no dependencies.
manager: The :class:`TaskManager` responsible for the submission of the task.
If manager is None, we use the `TaskManager` specified during the creation of the work.
workdir: The name of the directory used for the :class:`Work`.
Returns:
The registered :class:`Work`.
### Response:
def register_work(self, work, deps=None, manager=None, workdir=None):
"""
Register a new :class:`Work` and add it to the internal list, taking into account possible dependencies.
Args:
work: :class:`Work` object.
deps: List of :class:`Dependency` objects specifying the dependency of this node.
An empy list of deps implies that this node has no dependencies.
manager: The :class:`TaskManager` responsible for the submission of the task.
If manager is None, we use the `TaskManager` specified during the creation of the work.
workdir: The name of the directory used for the :class:`Work`.
Returns:
The registered :class:`Work`.
"""
if getattr(self, "workdir", None) is not None:
# The flow has a directory, build the named of the directory of the work.
work_workdir = None
if workdir is None:
work_workdir = os.path.join(self.workdir, "w" + str(len(self)))
else:
work_workdir = os.path.join(self.workdir, os.path.basename(workdir))
work.set_workdir(work_workdir)
if manager is not None:
work.set_manager(manager)
self.works.append(work)
if deps:
deps = [Dependency(node, exts) for node, exts in deps.items()]
work.add_deps(deps)
return work |
def authors2marc(self, key, value):
"""Populate the ``100`` MARC field.
Also populates the ``700`` and the ``701`` MARC fields through side effects.
"""
value = force_list(value)
def _get_ids(value):
ids = {
'i': [],
'j': [],
}
if value.get('ids'):
for _id in value.get('ids'):
if _id.get('schema') == 'INSPIRE ID':
ids['i'].append(_id.get('value'))
elif _id.get('schema') == 'ORCID':
ids['j'].append('ORCID:' + _id.get('value'))
elif _id.get('schema') == 'JACOW':
ids['j'].append(_id.get('value'))
elif _id.get('schema') == 'CERN':
ids['j'].append('CCID-' + _id.get('value')[5:])
return ids
def _get_affiliations(value):
return [
aff.get('value') for aff in value.get('affiliations', [])
]
def _get_affiliations_identifiers(value):
return [
u'{}:{}'.format(aff.get('schema'), aff.get('value')) for aff in value.get('affiliations_identifiers', [])
]
def _get_inspire_roles(value):
values = force_list(value.get('inspire_roles'))
return ['ed.' for role in values if role == 'editor']
def _get_raw_affiliations(value):
return [
aff.get('value') for aff in value.get('raw_affiliations', [])
]
def get_value_100_700(value):
ids = _get_ids(value)
return {
'a': value.get('full_name'),
'e': _get_inspire_roles(value),
'q': value.get('alternative_names'),
'i': ids.get('i'),
'j': ids.get('j'),
'm': value.get('emails'),
't': _get_affiliations_identifiers(value),
'u': _get_affiliations(value),
'v': _get_raw_affiliations(value),
}
def get_value_701(value):
ids = _get_ids(value)
return {
'a': value.get('full_name'),
'q': value.get('alternative_names'),
'i': ids.get('i'),
'j': ids.get('j'),
'u': _get_affiliations(value),
'v': _get_raw_affiliations(value),
}
if len(value) > 1:
self["700"] = []
self["701"] = []
for author in value[1:]:
is_supervisor = 'supervisor' in author.get('inspire_roles', [])
if is_supervisor:
self["701"].append(get_value_701(author))
else:
self["700"].append(get_value_100_700(author))
return get_value_100_700(value[0]) | Populate the ``100`` MARC field.
Also populates the ``700`` and the ``701`` MARC fields through side effects. | Below is the the instruction that describes the task:
### Input:
Populate the ``100`` MARC field.
Also populates the ``700`` and the ``701`` MARC fields through side effects.
### Response:
def authors2marc(self, key, value):
"""Populate the ``100`` MARC field.
Also populates the ``700`` and the ``701`` MARC fields through side effects.
"""
value = force_list(value)
def _get_ids(value):
ids = {
'i': [],
'j': [],
}
if value.get('ids'):
for _id in value.get('ids'):
if _id.get('schema') == 'INSPIRE ID':
ids['i'].append(_id.get('value'))
elif _id.get('schema') == 'ORCID':
ids['j'].append('ORCID:' + _id.get('value'))
elif _id.get('schema') == 'JACOW':
ids['j'].append(_id.get('value'))
elif _id.get('schema') == 'CERN':
ids['j'].append('CCID-' + _id.get('value')[5:])
return ids
def _get_affiliations(value):
return [
aff.get('value') for aff in value.get('affiliations', [])
]
def _get_affiliations_identifiers(value):
return [
u'{}:{}'.format(aff.get('schema'), aff.get('value')) for aff in value.get('affiliations_identifiers', [])
]
def _get_inspire_roles(value):
values = force_list(value.get('inspire_roles'))
return ['ed.' for role in values if role == 'editor']
def _get_raw_affiliations(value):
return [
aff.get('value') for aff in value.get('raw_affiliations', [])
]
def get_value_100_700(value):
ids = _get_ids(value)
return {
'a': value.get('full_name'),
'e': _get_inspire_roles(value),
'q': value.get('alternative_names'),
'i': ids.get('i'),
'j': ids.get('j'),
'm': value.get('emails'),
't': _get_affiliations_identifiers(value),
'u': _get_affiliations(value),
'v': _get_raw_affiliations(value),
}
def get_value_701(value):
ids = _get_ids(value)
return {
'a': value.get('full_name'),
'q': value.get('alternative_names'),
'i': ids.get('i'),
'j': ids.get('j'),
'u': _get_affiliations(value),
'v': _get_raw_affiliations(value),
}
if len(value) > 1:
self["700"] = []
self["701"] = []
for author in value[1:]:
is_supervisor = 'supervisor' in author.get('inspire_roles', [])
if is_supervisor:
self["701"].append(get_value_701(author))
else:
self["700"].append(get_value_100_700(author))
return get_value_100_700(value[0]) |
def track_enrollment(pathway, user_id, course_run_id, url_path=None):
"""
Emit a track event for enterprise course enrollment.
"""
track_event(user_id, 'edx.bi.user.enterprise.onboarding', {
'pathway': pathway,
'url_path': url_path,
'course_run_id': course_run_id,
}) | Emit a track event for enterprise course enrollment. | Below is the the instruction that describes the task:
### Input:
Emit a track event for enterprise course enrollment.
### Response:
def track_enrollment(pathway, user_id, course_run_id, url_path=None):
"""
Emit a track event for enterprise course enrollment.
"""
track_event(user_id, 'edx.bi.user.enterprise.onboarding', {
'pathway': pathway,
'url_path': url_path,
'course_run_id': course_run_id,
}) |
def get_input_photo(photo):
"""Similar to :meth:`get_input_peer`, but for photos"""
try:
if photo.SUBCLASS_OF_ID == 0x846363e0: # crc32(b'InputPhoto'):
return photo
except AttributeError:
_raise_cast_fail(photo, 'InputPhoto')
if isinstance(photo, types.photos.Photo):
photo = photo.photo
if isinstance(photo, types.Photo):
return types.InputPhoto(id=photo.id, access_hash=photo.access_hash,
file_reference=photo.file_reference)
if isinstance(photo, types.PhotoEmpty):
return types.InputPhotoEmpty()
if isinstance(photo, types.messages.ChatFull):
photo = photo.full_chat
if isinstance(photo, types.ChannelFull):
return get_input_photo(photo.chat_photo)
elif isinstance(photo, types.UserFull):
return get_input_photo(photo.profile_photo)
elif isinstance(photo, (types.Channel, types.Chat, types.User)):
return get_input_photo(photo.photo)
if isinstance(photo, (types.UserEmpty, types.ChatEmpty,
types.ChatForbidden, types.ChannelForbidden)):
return types.InputPhotoEmpty()
_raise_cast_fail(photo, 'InputPhoto') | Similar to :meth:`get_input_peer`, but for photos | Below is the the instruction that describes the task:
### Input:
Similar to :meth:`get_input_peer`, but for photos
### Response:
def get_input_photo(photo):
"""Similar to :meth:`get_input_peer`, but for photos"""
try:
if photo.SUBCLASS_OF_ID == 0x846363e0: # crc32(b'InputPhoto'):
return photo
except AttributeError:
_raise_cast_fail(photo, 'InputPhoto')
if isinstance(photo, types.photos.Photo):
photo = photo.photo
if isinstance(photo, types.Photo):
return types.InputPhoto(id=photo.id, access_hash=photo.access_hash,
file_reference=photo.file_reference)
if isinstance(photo, types.PhotoEmpty):
return types.InputPhotoEmpty()
if isinstance(photo, types.messages.ChatFull):
photo = photo.full_chat
if isinstance(photo, types.ChannelFull):
return get_input_photo(photo.chat_photo)
elif isinstance(photo, types.UserFull):
return get_input_photo(photo.profile_photo)
elif isinstance(photo, (types.Channel, types.Chat, types.User)):
return get_input_photo(photo.photo)
if isinstance(photo, (types.UserEmpty, types.ChatEmpty,
types.ChatForbidden, types.ChannelForbidden)):
return types.InputPhotoEmpty()
_raise_cast_fail(photo, 'InputPhoto') |
def get_queryset(self):
"""
This viewset provides a helper attribute to prefetch related models
based on the include specified in the URL.
__all__ can be used to specify a prefetch which should be done regardless of the include
.. code:: python
# When MyViewSet is called with ?include=author it will prefetch author and authorbio
class MyViewSet(viewsets.ModelViewSet):
queryset = Book.objects.all()
prefetch_for_includes = {
'__all__': [],
'author': ['author', 'author__authorbio'],
'category.section': ['category']
}
"""
qs = super(PrefetchForIncludesHelperMixin, self).get_queryset()
if not hasattr(self, 'prefetch_for_includes'):
return qs
includes = self.request.GET.get('include', '').split(',')
for inc in includes + ['__all__']:
prefetches = self.prefetch_for_includes.get(inc)
if prefetches:
qs = qs.prefetch_related(*prefetches)
return qs | This viewset provides a helper attribute to prefetch related models
based on the include specified in the URL.
__all__ can be used to specify a prefetch which should be done regardless of the include
.. code:: python
# When MyViewSet is called with ?include=author it will prefetch author and authorbio
class MyViewSet(viewsets.ModelViewSet):
queryset = Book.objects.all()
prefetch_for_includes = {
'__all__': [],
'author': ['author', 'author__authorbio'],
'category.section': ['category']
} | Below is the the instruction that describes the task:
### Input:
This viewset provides a helper attribute to prefetch related models
based on the include specified in the URL.
__all__ can be used to specify a prefetch which should be done regardless of the include
.. code:: python
# When MyViewSet is called with ?include=author it will prefetch author and authorbio
class MyViewSet(viewsets.ModelViewSet):
queryset = Book.objects.all()
prefetch_for_includes = {
'__all__': [],
'author': ['author', 'author__authorbio'],
'category.section': ['category']
}
### Response:
def get_queryset(self):
"""
This viewset provides a helper attribute to prefetch related models
based on the include specified in the URL.
__all__ can be used to specify a prefetch which should be done regardless of the include
.. code:: python
# When MyViewSet is called with ?include=author it will prefetch author and authorbio
class MyViewSet(viewsets.ModelViewSet):
queryset = Book.objects.all()
prefetch_for_includes = {
'__all__': [],
'author': ['author', 'author__authorbio'],
'category.section': ['category']
}
"""
qs = super(PrefetchForIncludesHelperMixin, self).get_queryset()
if not hasattr(self, 'prefetch_for_includes'):
return qs
includes = self.request.GET.get('include', '').split(',')
for inc in includes + ['__all__']:
prefetches = self.prefetch_for_includes.get(inc)
if prefetches:
qs = qs.prefetch_related(*prefetches)
return qs |
def fit(self,vxvv,vxvv_err=None,pot=None,radec=False,lb=False,
customsky=False,lb_to_customsky=None,pmllpmbb_to_customsky=None,
tintJ=10,ntintJ=1000,integrate_method='dopr54_c',
**kwargs):
"""
NAME:
fit
PURPOSE:
fit an Orbit to data using the current orbit as the initial condition
INPUT:
vxvv - [:,6] array of positions and velocities along the orbit (if not lb=True or radec=True, these need to be in natural units [/ro,/vo], cannot be Quantities)
vxvv_err= [:,6] array of errors on positions and velocities along the orbit (if None, these are set to 0.01) (if not lb=True or radec=True, these need to be in natural units [/ro,/vo], cannot be Quantities)
pot= Potential to fit the orbit in
Keywords related to the input data:
radec= if True, input vxvv and vxvv are [ra,dec,d,mu_ra, mu_dec,vlos] in [deg,deg,kpc,mas/yr,mas/yr,km/s] (all J2000.0; mu_ra = mu_ra * cos dec); the attributes of the current Orbit are used to convert between these coordinates and Galactocentric coordinates
lb= if True, input vxvv and vxvv are [long,lat,d,mu_ll, mu_bb,vlos] in [deg,deg,kpc,mas/yr,mas/yr,km/s] (mu_ll = mu_ll * cos lat); the attributes of the current Orbit are used to convert between these coordinates and Galactocentric coordinates
customsky= if True, input vxvv and vxvv_err are [custom long,custom lat,d,mu_customll, mu_custombb,vlos] in [deg,deg,kpc,mas/yr,mas/yr,km/s] (mu_ll = mu_ll * cos lat) where custom longitude and custom latitude are a custom set of sky coordinates (e.g., ecliptic) and the proper motions are also expressed in these coordinats; you need to provide the functions lb_to_customsky and pmllpmbb_to_customsky to convert to the custom sky coordinates (these should have the same inputs and outputs as lb_to_radec and pmllpmbb_to_pmrapmdec); the attributes of the current Orbit are used to convert between these coordinates and Galactocentric coordinates
obs=[X,Y,Z,vx,vy,vz] - (optional) position and velocity of observer
(in kpc and km/s; entries can be Quantity) (default=Object-wide default)
Cannot be an Orbit instance with the orbit of the reference point, as w/ the ra etc. functions
Y is ignored and always assumed to be zero
ro= distance in kpc corresponding to R=1. (default: taken from object; can be Quantity)
vo= velocity in km/s corresponding to v=1. (default: taken from object; can be Quantity)
lb_to_customsky= function that converts l,b,degree=False to the custom sky coordinates (like lb_to_radec); needs to be given when customsky=True
pmllpmbb_to_customsky= function that converts pmll,pmbb,l,b,degree=False to proper motions in the custom sky coordinates (like pmllpmbb_to_pmrapmdec); needs to be given when customsky=True
Keywords related to the orbit integrations:
tintJ= (default: 10) time to integrate orbits for fitting the orbit (can be Quantity)
ntintJ= (default: 1000) number of time-integration points
integrate_method= (default: 'dopr54_c') integration method to use
disp= (False) display the optimizer's convergence message
OUTPUT:
max of log likelihood
HISTORY:
2014-06-17 - Written - Bovy (IAS)
"""
pot= flatten_potential(pot)
_check_potential_dim(self,pot)
_check_consistent_units(self,pot)
return self._orb.fit(vxvv,vxvv_err=vxvv_err,pot=pot,
radec=radec,lb=lb,
customsky=customsky,
lb_to_customsky=lb_to_customsky,
pmllpmbb_to_customsky=pmllpmbb_to_customsky,
tintJ=tintJ,ntintJ=ntintJ,
integrate_method=integrate_method,
**kwargs) | NAME:
fit
PURPOSE:
fit an Orbit to data using the current orbit as the initial condition
INPUT:
vxvv - [:,6] array of positions and velocities along the orbit (if not lb=True or radec=True, these need to be in natural units [/ro,/vo], cannot be Quantities)
vxvv_err= [:,6] array of errors on positions and velocities along the orbit (if None, these are set to 0.01) (if not lb=True or radec=True, these need to be in natural units [/ro,/vo], cannot be Quantities)
pot= Potential to fit the orbit in
Keywords related to the input data:
radec= if True, input vxvv and vxvv are [ra,dec,d,mu_ra, mu_dec,vlos] in [deg,deg,kpc,mas/yr,mas/yr,km/s] (all J2000.0; mu_ra = mu_ra * cos dec); the attributes of the current Orbit are used to convert between these coordinates and Galactocentric coordinates
lb= if True, input vxvv and vxvv are [long,lat,d,mu_ll, mu_bb,vlos] in [deg,deg,kpc,mas/yr,mas/yr,km/s] (mu_ll = mu_ll * cos lat); the attributes of the current Orbit are used to convert between these coordinates and Galactocentric coordinates
customsky= if True, input vxvv and vxvv_err are [custom long,custom lat,d,mu_customll, mu_custombb,vlos] in [deg,deg,kpc,mas/yr,mas/yr,km/s] (mu_ll = mu_ll * cos lat) where custom longitude and custom latitude are a custom set of sky coordinates (e.g., ecliptic) and the proper motions are also expressed in these coordinats; you need to provide the functions lb_to_customsky and pmllpmbb_to_customsky to convert to the custom sky coordinates (these should have the same inputs and outputs as lb_to_radec and pmllpmbb_to_pmrapmdec); the attributes of the current Orbit are used to convert between these coordinates and Galactocentric coordinates
obs=[X,Y,Z,vx,vy,vz] - (optional) position and velocity of observer
(in kpc and km/s; entries can be Quantity) (default=Object-wide default)
Cannot be an Orbit instance with the orbit of the reference point, as w/ the ra etc. functions
Y is ignored and always assumed to be zero
ro= distance in kpc corresponding to R=1. (default: taken from object; can be Quantity)
vo= velocity in km/s corresponding to v=1. (default: taken from object; can be Quantity)
lb_to_customsky= function that converts l,b,degree=False to the custom sky coordinates (like lb_to_radec); needs to be given when customsky=True
pmllpmbb_to_customsky= function that converts pmll,pmbb,l,b,degree=False to proper motions in the custom sky coordinates (like pmllpmbb_to_pmrapmdec); needs to be given when customsky=True
Keywords related to the orbit integrations:
tintJ= (default: 10) time to integrate orbits for fitting the orbit (can be Quantity)
ntintJ= (default: 1000) number of time-integration points
integrate_method= (default: 'dopr54_c') integration method to use
disp= (False) display the optimizer's convergence message
OUTPUT:
max of log likelihood
HISTORY:
2014-06-17 - Written - Bovy (IAS) | Below is the the instruction that describes the task:
### Input:
NAME:
fit
PURPOSE:
fit an Orbit to data using the current orbit as the initial condition
INPUT:
vxvv - [:,6] array of positions and velocities along the orbit (if not lb=True or radec=True, these need to be in natural units [/ro,/vo], cannot be Quantities)
vxvv_err= [:,6] array of errors on positions and velocities along the orbit (if None, these are set to 0.01) (if not lb=True or radec=True, these need to be in natural units [/ro,/vo], cannot be Quantities)
pot= Potential to fit the orbit in
Keywords related to the input data:
radec= if True, input vxvv and vxvv are [ra,dec,d,mu_ra, mu_dec,vlos] in [deg,deg,kpc,mas/yr,mas/yr,km/s] (all J2000.0; mu_ra = mu_ra * cos dec); the attributes of the current Orbit are used to convert between these coordinates and Galactocentric coordinates
lb= if True, input vxvv and vxvv are [long,lat,d,mu_ll, mu_bb,vlos] in [deg,deg,kpc,mas/yr,mas/yr,km/s] (mu_ll = mu_ll * cos lat); the attributes of the current Orbit are used to convert between these coordinates and Galactocentric coordinates
customsky= if True, input vxvv and vxvv_err are [custom long,custom lat,d,mu_customll, mu_custombb,vlos] in [deg,deg,kpc,mas/yr,mas/yr,km/s] (mu_ll = mu_ll * cos lat) where custom longitude and custom latitude are a custom set of sky coordinates (e.g., ecliptic) and the proper motions are also expressed in these coordinats; you need to provide the functions lb_to_customsky and pmllpmbb_to_customsky to convert to the custom sky coordinates (these should have the same inputs and outputs as lb_to_radec and pmllpmbb_to_pmrapmdec); the attributes of the current Orbit are used to convert between these coordinates and Galactocentric coordinates
obs=[X,Y,Z,vx,vy,vz] - (optional) position and velocity of observer
(in kpc and km/s; entries can be Quantity) (default=Object-wide default)
Cannot be an Orbit instance with the orbit of the reference point, as w/ the ra etc. functions
Y is ignored and always assumed to be zero
ro= distance in kpc corresponding to R=1. (default: taken from object; can be Quantity)
vo= velocity in km/s corresponding to v=1. (default: taken from object; can be Quantity)
lb_to_customsky= function that converts l,b,degree=False to the custom sky coordinates (like lb_to_radec); needs to be given when customsky=True
pmllpmbb_to_customsky= function that converts pmll,pmbb,l,b,degree=False to proper motions in the custom sky coordinates (like pmllpmbb_to_pmrapmdec); needs to be given when customsky=True
Keywords related to the orbit integrations:
tintJ= (default: 10) time to integrate orbits for fitting the orbit (can be Quantity)
ntintJ= (default: 1000) number of time-integration points
integrate_method= (default: 'dopr54_c') integration method to use
disp= (False) display the optimizer's convergence message
OUTPUT:
max of log likelihood
HISTORY:
2014-06-17 - Written - Bovy (IAS)
### Response:
def fit(self,vxvv,vxvv_err=None,pot=None,radec=False,lb=False,
customsky=False,lb_to_customsky=None,pmllpmbb_to_customsky=None,
tintJ=10,ntintJ=1000,integrate_method='dopr54_c',
**kwargs):
"""
NAME:
fit
PURPOSE:
fit an Orbit to data using the current orbit as the initial condition
INPUT:
vxvv - [:,6] array of positions and velocities along the orbit (if not lb=True or radec=True, these need to be in natural units [/ro,/vo], cannot be Quantities)
vxvv_err= [:,6] array of errors on positions and velocities along the orbit (if None, these are set to 0.01) (if not lb=True or radec=True, these need to be in natural units [/ro,/vo], cannot be Quantities)
pot= Potential to fit the orbit in
Keywords related to the input data:
radec= if True, input vxvv and vxvv are [ra,dec,d,mu_ra, mu_dec,vlos] in [deg,deg,kpc,mas/yr,mas/yr,km/s] (all J2000.0; mu_ra = mu_ra * cos dec); the attributes of the current Orbit are used to convert between these coordinates and Galactocentric coordinates
lb= if True, input vxvv and vxvv are [long,lat,d,mu_ll, mu_bb,vlos] in [deg,deg,kpc,mas/yr,mas/yr,km/s] (mu_ll = mu_ll * cos lat); the attributes of the current Orbit are used to convert between these coordinates and Galactocentric coordinates
customsky= if True, input vxvv and vxvv_err are [custom long,custom lat,d,mu_customll, mu_custombb,vlos] in [deg,deg,kpc,mas/yr,mas/yr,km/s] (mu_ll = mu_ll * cos lat) where custom longitude and custom latitude are a custom set of sky coordinates (e.g., ecliptic) and the proper motions are also expressed in these coordinats; you need to provide the functions lb_to_customsky and pmllpmbb_to_customsky to convert to the custom sky coordinates (these should have the same inputs and outputs as lb_to_radec and pmllpmbb_to_pmrapmdec); the attributes of the current Orbit are used to convert between these coordinates and Galactocentric coordinates
obs=[X,Y,Z,vx,vy,vz] - (optional) position and velocity of observer
(in kpc and km/s; entries can be Quantity) (default=Object-wide default)
Cannot be an Orbit instance with the orbit of the reference point, as w/ the ra etc. functions
Y is ignored and always assumed to be zero
ro= distance in kpc corresponding to R=1. (default: taken from object; can be Quantity)
vo= velocity in km/s corresponding to v=1. (default: taken from object; can be Quantity)
lb_to_customsky= function that converts l,b,degree=False to the custom sky coordinates (like lb_to_radec); needs to be given when customsky=True
pmllpmbb_to_customsky= function that converts pmll,pmbb,l,b,degree=False to proper motions in the custom sky coordinates (like pmllpmbb_to_pmrapmdec); needs to be given when customsky=True
Keywords related to the orbit integrations:
tintJ= (default: 10) time to integrate orbits for fitting the orbit (can be Quantity)
ntintJ= (default: 1000) number of time-integration points
integrate_method= (default: 'dopr54_c') integration method to use
disp= (False) display the optimizer's convergence message
OUTPUT:
max of log likelihood
HISTORY:
2014-06-17 - Written - Bovy (IAS)
"""
pot= flatten_potential(pot)
_check_potential_dim(self,pot)
_check_consistent_units(self,pot)
return self._orb.fit(vxvv,vxvv_err=vxvv_err,pot=pot,
radec=radec,lb=lb,
customsky=customsky,
lb_to_customsky=lb_to_customsky,
pmllpmbb_to_customsky=pmllpmbb_to_customsky,
tintJ=tintJ,ntintJ=ntintJ,
integrate_method=integrate_method,
**kwargs) |
def htmlsafe_json_dumps(obj, dumper=None, **kwargs):
"""Works exactly like :func:`dumps` but is safe for use in ``<script>``
tags. It accepts the same arguments and returns a JSON string. Note that
this is available in templates through the ``|tojson`` filter which will
also mark the result as safe. Due to how this function escapes certain
characters this is safe even if used outside of ``<script>`` tags.
The following characters are escaped in strings:
- ``<``
- ``>``
- ``&``
- ``'``
This makes it safe to embed such strings in any place in HTML with the
notable exception of double quoted attributes. In that case single
quote your attributes or HTML escape it in addition.
"""
if dumper is None:
dumper = json.dumps
rv = dumper(obj, **kwargs) \
.replace(u'<', u'\\u003c') \
.replace(u'>', u'\\u003e') \
.replace(u'&', u'\\u0026') \
.replace(u"'", u'\\u0027')
return Markup(rv) | Works exactly like :func:`dumps` but is safe for use in ``<script>``
tags. It accepts the same arguments and returns a JSON string. Note that
this is available in templates through the ``|tojson`` filter which will
also mark the result as safe. Due to how this function escapes certain
characters this is safe even if used outside of ``<script>`` tags.
The following characters are escaped in strings:
- ``<``
- ``>``
- ``&``
- ``'``
This makes it safe to embed such strings in any place in HTML with the
notable exception of double quoted attributes. In that case single
quote your attributes or HTML escape it in addition. | Below is the the instruction that describes the task:
### Input:
Works exactly like :func:`dumps` but is safe for use in ``<script>``
tags. It accepts the same arguments and returns a JSON string. Note that
this is available in templates through the ``|tojson`` filter which will
also mark the result as safe. Due to how this function escapes certain
characters this is safe even if used outside of ``<script>`` tags.
The following characters are escaped in strings:
- ``<``
- ``>``
- ``&``
- ``'``
This makes it safe to embed such strings in any place in HTML with the
notable exception of double quoted attributes. In that case single
quote your attributes or HTML escape it in addition.
### Response:
def htmlsafe_json_dumps(obj, dumper=None, **kwargs):
"""Works exactly like :func:`dumps` but is safe for use in ``<script>``
tags. It accepts the same arguments and returns a JSON string. Note that
this is available in templates through the ``|tojson`` filter which will
also mark the result as safe. Due to how this function escapes certain
characters this is safe even if used outside of ``<script>`` tags.
The following characters are escaped in strings:
- ``<``
- ``>``
- ``&``
- ``'``
This makes it safe to embed such strings in any place in HTML with the
notable exception of double quoted attributes. In that case single
quote your attributes or HTML escape it in addition.
"""
if dumper is None:
dumper = json.dumps
rv = dumper(obj, **kwargs) \
.replace(u'<', u'\\u003c') \
.replace(u'>', u'\\u003e') \
.replace(u'&', u'\\u0026') \
.replace(u"'", u'\\u0027')
return Markup(rv) |
def resize(self, size, interp='bilinear'):
"""Resize the image.
Parameters
----------
size : int, float, or tuple
* int - Percentage of current size.
* float - Fraction of current size.
* tuple - Size of the output image.
interp : :obj:`str`, optional
Interpolation to use for re-sizing ('nearest', 'lanczos', 'bilinear',
'bicubic', or 'cubic')
Returns
-------
:obj:`IrImage`
The resized image.
"""
resized_data = sm.imresize(self._data, size, interp=interp)
return IrImage(resized_data, self._frame) | Resize the image.
Parameters
----------
size : int, float, or tuple
* int - Percentage of current size.
* float - Fraction of current size.
* tuple - Size of the output image.
interp : :obj:`str`, optional
Interpolation to use for re-sizing ('nearest', 'lanczos', 'bilinear',
'bicubic', or 'cubic')
Returns
-------
:obj:`IrImage`
The resized image. | Below is the the instruction that describes the task:
### Input:
Resize the image.
Parameters
----------
size : int, float, or tuple
* int - Percentage of current size.
* float - Fraction of current size.
* tuple - Size of the output image.
interp : :obj:`str`, optional
Interpolation to use for re-sizing ('nearest', 'lanczos', 'bilinear',
'bicubic', or 'cubic')
Returns
-------
:obj:`IrImage`
The resized image.
### Response:
def resize(self, size, interp='bilinear'):
"""Resize the image.
Parameters
----------
size : int, float, or tuple
* int - Percentage of current size.
* float - Fraction of current size.
* tuple - Size of the output image.
interp : :obj:`str`, optional
Interpolation to use for re-sizing ('nearest', 'lanczos', 'bilinear',
'bicubic', or 'cubic')
Returns
-------
:obj:`IrImage`
The resized image.
"""
resized_data = sm.imresize(self._data, size, interp=interp)
return IrImage(resized_data, self._frame) |
def update_variables(self) -> None:
"""Add the general |ChangeItem.value| with the |Device| specific base
variable and assign the result to the respective target variable.
>>> from hydpy.core.examples import prepare_full_example_2
>>> hp, pub, TestIO = prepare_full_example_2()
>>> from hydpy.models.hland_v1 import FIELD
>>> for element in hp.elements.catchment:
... control = element.model.parameters.control
... control.nmbzones(3)
... control.zonetype(FIELD)
... control.rfcf(1.1)
>>> from hydpy.core.itemtools import AddItem
>>> item = AddItem(
... 'sfcf', 'hland_v1', 'control.sfcf', 'control.rfcf', 1)
>>> item.collect_variables(pub.selections)
>>> land_dill = hp.elements.land_dill
>>> land_dill.model.parameters.control.sfcf
sfcf(?)
>>> item.value = -0.1, 0.0, 0.1
>>> item.update_variables()
>>> land_dill.model.parameters.control.sfcf
sfcf(1.0, 1.1, 1.2)
>>> land_dill.model.parameters.control.rfcf.shape = 2
>>> land_dill.model.parameters.control.rfcf = 1.1
>>> item.update_variables() # doctest: +ELLIPSIS
Traceback (most recent call last):
...
ValueError: When trying to add the value(s) `[-0.1 0. 0.1]` of \
AddItem `sfcf` and the value(s) `[ 1.1 1.1]` of variable `rfcf` of element \
`land_dill`, the following error occurred: operands could not be broadcast \
together with shapes (2,) (3,)...
"""
value = self.value
for device, target in self.device2target.items():
base = self.device2base[device]
try:
result = base.value + value
except BaseException:
raise objecttools.augment_excmessage(
f'When trying to add the value(s) `{value}` of '
f'AddItem `{self.name}` and the value(s) `{base.value}` '
f'of variable {objecttools.devicephrase(base)}')
self.update_variable(target, result) | Add the general |ChangeItem.value| with the |Device| specific base
variable and assign the result to the respective target variable.
>>> from hydpy.core.examples import prepare_full_example_2
>>> hp, pub, TestIO = prepare_full_example_2()
>>> from hydpy.models.hland_v1 import FIELD
>>> for element in hp.elements.catchment:
... control = element.model.parameters.control
... control.nmbzones(3)
... control.zonetype(FIELD)
... control.rfcf(1.1)
>>> from hydpy.core.itemtools import AddItem
>>> item = AddItem(
... 'sfcf', 'hland_v1', 'control.sfcf', 'control.rfcf', 1)
>>> item.collect_variables(pub.selections)
>>> land_dill = hp.elements.land_dill
>>> land_dill.model.parameters.control.sfcf
sfcf(?)
>>> item.value = -0.1, 0.0, 0.1
>>> item.update_variables()
>>> land_dill.model.parameters.control.sfcf
sfcf(1.0, 1.1, 1.2)
>>> land_dill.model.parameters.control.rfcf.shape = 2
>>> land_dill.model.parameters.control.rfcf = 1.1
>>> item.update_variables() # doctest: +ELLIPSIS
Traceback (most recent call last):
...
ValueError: When trying to add the value(s) `[-0.1 0. 0.1]` of \
AddItem `sfcf` and the value(s) `[ 1.1 1.1]` of variable `rfcf` of element \
`land_dill`, the following error occurred: operands could not be broadcast \
together with shapes (2,) (3,)... | Below is the the instruction that describes the task:
### Input:
Add the general |ChangeItem.value| with the |Device| specific base
variable and assign the result to the respective target variable.
>>> from hydpy.core.examples import prepare_full_example_2
>>> hp, pub, TestIO = prepare_full_example_2()
>>> from hydpy.models.hland_v1 import FIELD
>>> for element in hp.elements.catchment:
... control = element.model.parameters.control
... control.nmbzones(3)
... control.zonetype(FIELD)
... control.rfcf(1.1)
>>> from hydpy.core.itemtools import AddItem
>>> item = AddItem(
... 'sfcf', 'hland_v1', 'control.sfcf', 'control.rfcf', 1)
>>> item.collect_variables(pub.selections)
>>> land_dill = hp.elements.land_dill
>>> land_dill.model.parameters.control.sfcf
sfcf(?)
>>> item.value = -0.1, 0.0, 0.1
>>> item.update_variables()
>>> land_dill.model.parameters.control.sfcf
sfcf(1.0, 1.1, 1.2)
>>> land_dill.model.parameters.control.rfcf.shape = 2
>>> land_dill.model.parameters.control.rfcf = 1.1
>>> item.update_variables() # doctest: +ELLIPSIS
Traceback (most recent call last):
...
ValueError: When trying to add the value(s) `[-0.1 0. 0.1]` of \
AddItem `sfcf` and the value(s) `[ 1.1 1.1]` of variable `rfcf` of element \
`land_dill`, the following error occurred: operands could not be broadcast \
together with shapes (2,) (3,)...
### Response:
def update_variables(self) -> None:
"""Add the general |ChangeItem.value| with the |Device| specific base
variable and assign the result to the respective target variable.
>>> from hydpy.core.examples import prepare_full_example_2
>>> hp, pub, TestIO = prepare_full_example_2()
>>> from hydpy.models.hland_v1 import FIELD
>>> for element in hp.elements.catchment:
... control = element.model.parameters.control
... control.nmbzones(3)
... control.zonetype(FIELD)
... control.rfcf(1.1)
>>> from hydpy.core.itemtools import AddItem
>>> item = AddItem(
... 'sfcf', 'hland_v1', 'control.sfcf', 'control.rfcf', 1)
>>> item.collect_variables(pub.selections)
>>> land_dill = hp.elements.land_dill
>>> land_dill.model.parameters.control.sfcf
sfcf(?)
>>> item.value = -0.1, 0.0, 0.1
>>> item.update_variables()
>>> land_dill.model.parameters.control.sfcf
sfcf(1.0, 1.1, 1.2)
>>> land_dill.model.parameters.control.rfcf.shape = 2
>>> land_dill.model.parameters.control.rfcf = 1.1
>>> item.update_variables() # doctest: +ELLIPSIS
Traceback (most recent call last):
...
ValueError: When trying to add the value(s) `[-0.1 0. 0.1]` of \
AddItem `sfcf` and the value(s) `[ 1.1 1.1]` of variable `rfcf` of element \
`land_dill`, the following error occurred: operands could not be broadcast \
together with shapes (2,) (3,)...
"""
value = self.value
for device, target in self.device2target.items():
base = self.device2base[device]
try:
result = base.value + value
except BaseException:
raise objecttools.augment_excmessage(
f'When trying to add the value(s) `{value}` of '
f'AddItem `{self.name}` and the value(s) `{base.value}` '
f'of variable {objecttools.devicephrase(base)}')
self.update_variable(target, result) |
def connectionMade(self):
""" Called when a connection is made, and used to send out headers """
headers = [
"GET %s HTTP/1.1" % ("/room/%s/live.json" % self.factory.get_stream().get_room_id())
]
connection_headers = self.factory.get_stream().get_connection().get_headers()
for header in connection_headers:
headers.append("%s: %s" % (header, connection_headers[header]))
headers.append("Host: streaming.campfirenow.com")
self.transport.write("\r\n".join(headers) + "\r\n\r\n")
self.factory.get_stream().set_protocol(self) | Called when a connection is made, and used to send out headers | Below is the the instruction that describes the task:
### Input:
Called when a connection is made, and used to send out headers
### Response:
def connectionMade(self):
""" Called when a connection is made, and used to send out headers """
headers = [
"GET %s HTTP/1.1" % ("/room/%s/live.json" % self.factory.get_stream().get_room_id())
]
connection_headers = self.factory.get_stream().get_connection().get_headers()
for header in connection_headers:
headers.append("%s: %s" % (header, connection_headers[header]))
headers.append("Host: streaming.campfirenow.com")
self.transport.write("\r\n".join(headers) + "\r\n\r\n")
self.factory.get_stream().set_protocol(self) |
def validate(self):
"""Validate that the Literal is correctly representable."""
# Literals representing boolean values or None are correctly representable and supported.
if self.value is None or self.value is True or self.value is False:
return
# Literal safe strings are correctly representable and supported.
if isinstance(self.value, six.string_types):
validate_safe_string(self.value)
return
# Literal ints are correctly representable and supported.
if isinstance(self.value, int):
return
# Literal empty lists, and non-empty lists of safe strings, are
# correctly representable and supported.
if isinstance(self.value, list):
if len(self.value) > 0:
for x in self.value:
validate_safe_string(x)
return
raise GraphQLCompilationError(u'Cannot represent literal: {}'.format(self.value)) | Validate that the Literal is correctly representable. | Below is the the instruction that describes the task:
### Input:
Validate that the Literal is correctly representable.
### Response:
def validate(self):
"""Validate that the Literal is correctly representable."""
# Literals representing boolean values or None are correctly representable and supported.
if self.value is None or self.value is True or self.value is False:
return
# Literal safe strings are correctly representable and supported.
if isinstance(self.value, six.string_types):
validate_safe_string(self.value)
return
# Literal ints are correctly representable and supported.
if isinstance(self.value, int):
return
# Literal empty lists, and non-empty lists of safe strings, are
# correctly representable and supported.
if isinstance(self.value, list):
if len(self.value) > 0:
for x in self.value:
validate_safe_string(x)
return
raise GraphQLCompilationError(u'Cannot represent literal: {}'.format(self.value)) |
def plot_density(
xall, yall, ax=None, cmap=None,
ncontours=100, vmin=None, vmax=None, levels=None,
cbar=True, cax=None, cbar_label='sample density',
cbar_orientation='vertical', logscale=False, nbins=100,
weights=None, avoid_zero_count=False, **kwargs):
"""Plot a two-dimensional density map using a histogram of
scattered data.
Parameters
----------
xall : ndarray(T)
Sample x-coordinates.
yall : ndarray(T)
Sample y-coordinates.
ax : matplotlib.Axes object, optional, default=None
The ax to plot to; if ax=None, a new ax (and fig) is created.
cmap : matplotlib colormap, optional, default=None
The color map to use.
ncontours : int, optional, default=100
Number of contour levels.
vmin : float, optional, default=None
Lowest z-value to be plotted.
vmax : float, optional, default=None
Highest z-value to be plotted.
levels : iterable of float, optional, default=None
Contour levels to plot.
cbar : boolean, optional, default=True
Plot a color bar.
cax : matplotlib.Axes object, optional, default=None
Plot the colorbar into a custom axes object instead of
stealing space from ax.
cbar_label : str, optional, default='sample density'
Colorbar label string; use None to suppress it.
cbar_orientation : str, optional, default='vertical'
Colorbar orientation; choose 'vertical' or 'horizontal'.
logscale : boolean, optional, default=False
Plot the z-values in logscale.
nbins : int, optional, default=100
Number of histogram bins used in each dimension.
weights : ndarray(T), optional, default=None
Sample weights; by default all samples have the same weight.
avoid_zero_count : bool, optional, default=True
Avoid zero counts by lifting all histogram elements to the
minimum value before computing the free energy. If False,
zero histogram counts would yield infinity in the free energy.
Optional parameters for contourf (**kwargs)
-------------------------------------------
corner_mask : boolean, optional
Enable/disable corner masking, which only has an effect if
z is a masked array. If False, any quad touching a masked
point is masked out. If True, only the triangular corners
of quads nearest those points are always masked out, other
triangular corners comprising three unmasked points are
contoured as usual.
Defaults to rcParams['contour.corner_mask'], which
defaults to True.
alpha : float
The alpha blending value.
locator : [ None | ticker.Locator subclass ]
If locator is None, the default MaxNLocator is used. The
locator is used to determine the contour levels if they are
not given explicitly via the levels argument.
extend : [ ‘neither’ | ‘both’ | ‘min’ | ‘max’ ]
Unless this is ‘neither’, contour levels are automatically
added to one or both ends of the range so that all data are
included. These added ranges are then mapped to the special
colormap values which default to the ends of the
colormap range, but can be set via
matplotlib.colors.Colormap.set_under() and
matplotlib.colors.Colormap.set_over() methods.
xunits, yunits : [ None | registered units ]
Override axis units by specifying an instance of a
matplotlib.units.ConversionInterface.
antialiased : boolean, optional
Enable antialiasing, overriding the defaults. For filled
contours, the default is True. For line contours, it is
taken from rcParams[‘lines.antialiased’].
nchunk : [ 0 | integer ]
If 0, no subdivision of the domain. Specify a positive
integer to divide the domain into subdomains of nchunk by
nchunk quads. Chunking reduces the maximum length of polygons
generated by the contouring algorithm which reduces the
rendering workload passed on to the backend and also requires
slightly less RAM. It can however introduce rendering
artifacts at chunk boundaries depending on the backend, the
antialiased flag and value of alpha.
hatches :
A list of cross hatch patterns to use on the filled areas.
If None, no hatching will be added to the contour. Hatching
is supported in the PostScript, PDF, SVG and Agg backends
only.
zorder : float
Set the zorder for the artist. Artists with lower zorder
values are drawn first.
Returns
-------
fig : matplotlib.Figure object
The figure in which the used ax resides.
ax : matplotlib.Axes object
The ax in which the map was plotted.
misc : dict
Contains a matplotlib.contour.QuadContourSet 'mappable' and,
if requested, a matplotlib.Colorbar object 'cbar'.
"""
x, y, z = get_histogram(
xall, yall, nbins=nbins, weights=weights,
avoid_zero_count=avoid_zero_count)
pi = _to_density(z)
pi = _np.ma.masked_where(pi <= 0, pi)
if logscale:
from matplotlib.colors import LogNorm
norm = LogNorm(vmin=vmin, vmax=vmax)
if levels is None:
levels = _np.logspace(
_np.floor(_np.log10(pi.min())),
_np.ceil(_np.log10(pi.max())),
ncontours + 1)
else:
norm = None
fig, ax, misc = plot_map(
x, y, pi, ax=ax, cmap=cmap,
ncontours=ncontours, vmin=vmin, vmax=vmax, levels=levels,
cbar=cbar, cax=cax, cbar_label=cbar_label,
cbar_orientation=cbar_orientation, norm=norm,
**kwargs)
if cbar and logscale:
from matplotlib.ticker import LogLocator
misc['cbar'].set_ticks(LogLocator(base=10.0, subs=range(10)))
return fig, ax, misc | Plot a two-dimensional density map using a histogram of
scattered data.
Parameters
----------
xall : ndarray(T)
Sample x-coordinates.
yall : ndarray(T)
Sample y-coordinates.
ax : matplotlib.Axes object, optional, default=None
The ax to plot to; if ax=None, a new ax (and fig) is created.
cmap : matplotlib colormap, optional, default=None
The color map to use.
ncontours : int, optional, default=100
Number of contour levels.
vmin : float, optional, default=None
Lowest z-value to be plotted.
vmax : float, optional, default=None
Highest z-value to be plotted.
levels : iterable of float, optional, default=None
Contour levels to plot.
cbar : boolean, optional, default=True
Plot a color bar.
cax : matplotlib.Axes object, optional, default=None
Plot the colorbar into a custom axes object instead of
stealing space from ax.
cbar_label : str, optional, default='sample density'
Colorbar label string; use None to suppress it.
cbar_orientation : str, optional, default='vertical'
Colorbar orientation; choose 'vertical' or 'horizontal'.
logscale : boolean, optional, default=False
Plot the z-values in logscale.
nbins : int, optional, default=100
Number of histogram bins used in each dimension.
weights : ndarray(T), optional, default=None
Sample weights; by default all samples have the same weight.
avoid_zero_count : bool, optional, default=True
Avoid zero counts by lifting all histogram elements to the
minimum value before computing the free energy. If False,
zero histogram counts would yield infinity in the free energy.
Optional parameters for contourf (**kwargs)
-------------------------------------------
corner_mask : boolean, optional
Enable/disable corner masking, which only has an effect if
z is a masked array. If False, any quad touching a masked
point is masked out. If True, only the triangular corners
of quads nearest those points are always masked out, other
triangular corners comprising three unmasked points are
contoured as usual.
Defaults to rcParams['contour.corner_mask'], which
defaults to True.
alpha : float
The alpha blending value.
locator : [ None | ticker.Locator subclass ]
If locator is None, the default MaxNLocator is used. The
locator is used to determine the contour levels if they are
not given explicitly via the levels argument.
extend : [ ‘neither’ | ‘both’ | ‘min’ | ‘max’ ]
Unless this is ‘neither’, contour levels are automatically
added to one or both ends of the range so that all data are
included. These added ranges are then mapped to the special
colormap values which default to the ends of the
colormap range, but can be set via
matplotlib.colors.Colormap.set_under() and
matplotlib.colors.Colormap.set_over() methods.
xunits, yunits : [ None | registered units ]
Override axis units by specifying an instance of a
matplotlib.units.ConversionInterface.
antialiased : boolean, optional
Enable antialiasing, overriding the defaults. For filled
contours, the default is True. For line contours, it is
taken from rcParams[‘lines.antialiased’].
nchunk : [ 0 | integer ]
If 0, no subdivision of the domain. Specify a positive
integer to divide the domain into subdomains of nchunk by
nchunk quads. Chunking reduces the maximum length of polygons
generated by the contouring algorithm which reduces the
rendering workload passed on to the backend and also requires
slightly less RAM. It can however introduce rendering
artifacts at chunk boundaries depending on the backend, the
antialiased flag and value of alpha.
hatches :
A list of cross hatch patterns to use on the filled areas.
If None, no hatching will be added to the contour. Hatching
is supported in the PostScript, PDF, SVG and Agg backends
only.
zorder : float
Set the zorder for the artist. Artists with lower zorder
values are drawn first.
Returns
-------
fig : matplotlib.Figure object
The figure in which the used ax resides.
ax : matplotlib.Axes object
The ax in which the map was plotted.
misc : dict
Contains a matplotlib.contour.QuadContourSet 'mappable' and,
if requested, a matplotlib.Colorbar object 'cbar'. | Below is the the instruction that describes the task:
### Input:
Plot a two-dimensional density map using a histogram of
scattered data.
Parameters
----------
xall : ndarray(T)
Sample x-coordinates.
yall : ndarray(T)
Sample y-coordinates.
ax : matplotlib.Axes object, optional, default=None
The ax to plot to; if ax=None, a new ax (and fig) is created.
cmap : matplotlib colormap, optional, default=None
The color map to use.
ncontours : int, optional, default=100
Number of contour levels.
vmin : float, optional, default=None
Lowest z-value to be plotted.
vmax : float, optional, default=None
Highest z-value to be plotted.
levels : iterable of float, optional, default=None
Contour levels to plot.
cbar : boolean, optional, default=True
Plot a color bar.
cax : matplotlib.Axes object, optional, default=None
Plot the colorbar into a custom axes object instead of
stealing space from ax.
cbar_label : str, optional, default='sample density'
Colorbar label string; use None to suppress it.
cbar_orientation : str, optional, default='vertical'
Colorbar orientation; choose 'vertical' or 'horizontal'.
logscale : boolean, optional, default=False
Plot the z-values in logscale.
nbins : int, optional, default=100
Number of histogram bins used in each dimension.
weights : ndarray(T), optional, default=None
Sample weights; by default all samples have the same weight.
avoid_zero_count : bool, optional, default=True
Avoid zero counts by lifting all histogram elements to the
minimum value before computing the free energy. If False,
zero histogram counts would yield infinity in the free energy.
Optional parameters for contourf (**kwargs)
-------------------------------------------
corner_mask : boolean, optional
Enable/disable corner masking, which only has an effect if
z is a masked array. If False, any quad touching a masked
point is masked out. If True, only the triangular corners
of quads nearest those points are always masked out, other
triangular corners comprising three unmasked points are
contoured as usual.
Defaults to rcParams['contour.corner_mask'], which
defaults to True.
alpha : float
The alpha blending value.
locator : [ None | ticker.Locator subclass ]
If locator is None, the default MaxNLocator is used. The
locator is used to determine the contour levels if they are
not given explicitly via the levels argument.
extend : [ ‘neither’ | ‘both’ | ‘min’ | ‘max’ ]
Unless this is ‘neither’, contour levels are automatically
added to one or both ends of the range so that all data are
included. These added ranges are then mapped to the special
colormap values which default to the ends of the
colormap range, but can be set via
matplotlib.colors.Colormap.set_under() and
matplotlib.colors.Colormap.set_over() methods.
xunits, yunits : [ None | registered units ]
Override axis units by specifying an instance of a
matplotlib.units.ConversionInterface.
antialiased : boolean, optional
Enable antialiasing, overriding the defaults. For filled
contours, the default is True. For line contours, it is
taken from rcParams[‘lines.antialiased’].
nchunk : [ 0 | integer ]
If 0, no subdivision of the domain. Specify a positive
integer to divide the domain into subdomains of nchunk by
nchunk quads. Chunking reduces the maximum length of polygons
generated by the contouring algorithm which reduces the
rendering workload passed on to the backend and also requires
slightly less RAM. It can however introduce rendering
artifacts at chunk boundaries depending on the backend, the
antialiased flag and value of alpha.
hatches :
A list of cross hatch patterns to use on the filled areas.
If None, no hatching will be added to the contour. Hatching
is supported in the PostScript, PDF, SVG and Agg backends
only.
zorder : float
Set the zorder for the artist. Artists with lower zorder
values are drawn first.
Returns
-------
fig : matplotlib.Figure object
The figure in which the used ax resides.
ax : matplotlib.Axes object
The ax in which the map was plotted.
misc : dict
Contains a matplotlib.contour.QuadContourSet 'mappable' and,
if requested, a matplotlib.Colorbar object 'cbar'.
### Response:
def plot_density(
xall, yall, ax=None, cmap=None,
ncontours=100, vmin=None, vmax=None, levels=None,
cbar=True, cax=None, cbar_label='sample density',
cbar_orientation='vertical', logscale=False, nbins=100,
weights=None, avoid_zero_count=False, **kwargs):
"""Plot a two-dimensional density map using a histogram of
scattered data.
Parameters
----------
xall : ndarray(T)
Sample x-coordinates.
yall : ndarray(T)
Sample y-coordinates.
ax : matplotlib.Axes object, optional, default=None
The ax to plot to; if ax=None, a new ax (and fig) is created.
cmap : matplotlib colormap, optional, default=None
The color map to use.
ncontours : int, optional, default=100
Number of contour levels.
vmin : float, optional, default=None
Lowest z-value to be plotted.
vmax : float, optional, default=None
Highest z-value to be plotted.
levels : iterable of float, optional, default=None
Contour levels to plot.
cbar : boolean, optional, default=True
Plot a color bar.
cax : matplotlib.Axes object, optional, default=None
Plot the colorbar into a custom axes object instead of
stealing space from ax.
cbar_label : str, optional, default='sample density'
Colorbar label string; use None to suppress it.
cbar_orientation : str, optional, default='vertical'
Colorbar orientation; choose 'vertical' or 'horizontal'.
logscale : boolean, optional, default=False
Plot the z-values in logscale.
nbins : int, optional, default=100
Number of histogram bins used in each dimension.
weights : ndarray(T), optional, default=None
Sample weights; by default all samples have the same weight.
avoid_zero_count : bool, optional, default=True
Avoid zero counts by lifting all histogram elements to the
minimum value before computing the free energy. If False,
zero histogram counts would yield infinity in the free energy.
Optional parameters for contourf (**kwargs)
-------------------------------------------
corner_mask : boolean, optional
Enable/disable corner masking, which only has an effect if
z is a masked array. If False, any quad touching a masked
point is masked out. If True, only the triangular corners
of quads nearest those points are always masked out, other
triangular corners comprising three unmasked points are
contoured as usual.
Defaults to rcParams['contour.corner_mask'], which
defaults to True.
alpha : float
The alpha blending value.
locator : [ None | ticker.Locator subclass ]
If locator is None, the default MaxNLocator is used. The
locator is used to determine the contour levels if they are
not given explicitly via the levels argument.
extend : [ ‘neither’ | ‘both’ | ‘min’ | ‘max’ ]
Unless this is ‘neither’, contour levels are automatically
added to one or both ends of the range so that all data are
included. These added ranges are then mapped to the special
colormap values which default to the ends of the
colormap range, but can be set via
matplotlib.colors.Colormap.set_under() and
matplotlib.colors.Colormap.set_over() methods.
xunits, yunits : [ None | registered units ]
Override axis units by specifying an instance of a
matplotlib.units.ConversionInterface.
antialiased : boolean, optional
Enable antialiasing, overriding the defaults. For filled
contours, the default is True. For line contours, it is
taken from rcParams[‘lines.antialiased’].
nchunk : [ 0 | integer ]
If 0, no subdivision of the domain. Specify a positive
integer to divide the domain into subdomains of nchunk by
nchunk quads. Chunking reduces the maximum length of polygons
generated by the contouring algorithm which reduces the
rendering workload passed on to the backend and also requires
slightly less RAM. It can however introduce rendering
artifacts at chunk boundaries depending on the backend, the
antialiased flag and value of alpha.
hatches :
A list of cross hatch patterns to use on the filled areas.
If None, no hatching will be added to the contour. Hatching
is supported in the PostScript, PDF, SVG and Agg backends
only.
zorder : float
Set the zorder for the artist. Artists with lower zorder
values are drawn first.
Returns
-------
fig : matplotlib.Figure object
The figure in which the used ax resides.
ax : matplotlib.Axes object
The ax in which the map was plotted.
misc : dict
Contains a matplotlib.contour.QuadContourSet 'mappable' and,
if requested, a matplotlib.Colorbar object 'cbar'.
"""
x, y, z = get_histogram(
xall, yall, nbins=nbins, weights=weights,
avoid_zero_count=avoid_zero_count)
pi = _to_density(z)
pi = _np.ma.masked_where(pi <= 0, pi)
if logscale:
from matplotlib.colors import LogNorm
norm = LogNorm(vmin=vmin, vmax=vmax)
if levels is None:
levels = _np.logspace(
_np.floor(_np.log10(pi.min())),
_np.ceil(_np.log10(pi.max())),
ncontours + 1)
else:
norm = None
fig, ax, misc = plot_map(
x, y, pi, ax=ax, cmap=cmap,
ncontours=ncontours, vmin=vmin, vmax=vmax, levels=levels,
cbar=cbar, cax=cax, cbar_label=cbar_label,
cbar_orientation=cbar_orientation, norm=norm,
**kwargs)
if cbar and logscale:
from matplotlib.ticker import LogLocator
misc['cbar'].set_ticks(LogLocator(base=10.0, subs=range(10)))
return fig, ax, misc |
def create_interconnect(self, location_entries, timeout=-1):
"""
Creates an interconnect at the given location.
Warning:
It does not create the LOGICAL INTERCONNECT itself.
It will fail if no interconnect is already present on the specified position.
Args:
location_entries (dict): Dictionary with location entries.
timeout:
Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation
in OneView; it just stops waiting for its completion.
Returns:
dict: Created interconnect.
"""
return self._helper.create(location_entries, uri=self.locations_uri, timeout=timeout) | Creates an interconnect at the given location.
Warning:
It does not create the LOGICAL INTERCONNECT itself.
It will fail if no interconnect is already present on the specified position.
Args:
location_entries (dict): Dictionary with location entries.
timeout:
Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation
in OneView; it just stops waiting for its completion.
Returns:
dict: Created interconnect. | Below is the the instruction that describes the task:
### Input:
Creates an interconnect at the given location.
Warning:
It does not create the LOGICAL INTERCONNECT itself.
It will fail if no interconnect is already present on the specified position.
Args:
location_entries (dict): Dictionary with location entries.
timeout:
Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation
in OneView; it just stops waiting for its completion.
Returns:
dict: Created interconnect.
### Response:
def create_interconnect(self, location_entries, timeout=-1):
"""
Creates an interconnect at the given location.
Warning:
It does not create the LOGICAL INTERCONNECT itself.
It will fail if no interconnect is already present on the specified position.
Args:
location_entries (dict): Dictionary with location entries.
timeout:
Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation
in OneView; it just stops waiting for its completion.
Returns:
dict: Created interconnect.
"""
return self._helper.create(location_entries, uri=self.locations_uri, timeout=timeout) |
def get_abs_sciobj_file_path_by_url(file_url):
"""Get the absolute path to the file holding an object's bytes.
- ``file_url`` is an absolute or relative file:// url as stored in the DB.
"""
assert_sciobj_store_exists()
m = re.match(r'file://(.*?)/(.*)', file_url, re.IGNORECASE)
if m.group(1) == RELATIVE_PATH_MAGIC_HOST_STR:
return os.path.join(get_abs_sciobj_store_path(), m.group(2))
assert os.path.isabs(m.group(2))
return m.group(2) | Get the absolute path to the file holding an object's bytes.
- ``file_url`` is an absolute or relative file:// url as stored in the DB. | Below is the the instruction that describes the task:
### Input:
Get the absolute path to the file holding an object's bytes.
- ``file_url`` is an absolute or relative file:// url as stored in the DB.
### Response:
def get_abs_sciobj_file_path_by_url(file_url):
"""Get the absolute path to the file holding an object's bytes.
- ``file_url`` is an absolute or relative file:// url as stored in the DB.
"""
assert_sciobj_store_exists()
m = re.match(r'file://(.*?)/(.*)', file_url, re.IGNORECASE)
if m.group(1) == RELATIVE_PATH_MAGIC_HOST_STR:
return os.path.join(get_abs_sciobj_store_path(), m.group(2))
assert os.path.isabs(m.group(2))
return m.group(2) |
def append(self, entry):
"""Append an entry to self"""
if not self.is_appendable(entry):
raise ValueError('entry not appendable')
self.data += entry.data | Append an entry to self | Below is the the instruction that describes the task:
### Input:
Append an entry to self
### Response:
def append(self, entry):
"""Append an entry to self"""
if not self.is_appendable(entry):
raise ValueError('entry not appendable')
self.data += entry.data |
def vector_to_symmetric(v):
'''Convert an iterable into a symmetric matrix.'''
np = len(v)
N = (int(sqrt(1 + 8*np)) - 1)//2
if N*(N+1)//2 != np:
raise ValueError('Cannot convert vector to symmetric matrix')
sym = ndarray((N,N))
iterable = iter(v)
for r in range(N):
for c in range(r+1):
sym[r,c] = sym[c,r] = iterable.next()
return sym | Convert an iterable into a symmetric matrix. | Below is the the instruction that describes the task:
### Input:
Convert an iterable into a symmetric matrix.
### Response:
def vector_to_symmetric(v):
'''Convert an iterable into a symmetric matrix.'''
np = len(v)
N = (int(sqrt(1 + 8*np)) - 1)//2
if N*(N+1)//2 != np:
raise ValueError('Cannot convert vector to symmetric matrix')
sym = ndarray((N,N))
iterable = iter(v)
for r in range(N):
for c in range(r+1):
sym[r,c] = sym[c,r] = iterable.next()
return sym |
def add_months_to_date(months, date):
"""Add a number of months to a date"""
month = date.month
new_month = month + months
years = 0
while new_month < 1:
new_month += 12
years -= 1
while new_month > 12:
new_month -= 12
years += 1
# month = timestamp.month
year = date.year + years
try:
return datetime.date(year, new_month, date.day)
except ValueError:
# This means that the day exceeds the last day of the month, i.e. it is 30th March, and we are finding the day
# 1 month ago, and it is trying to return 30th February
if months > 0:
# We are adding, so use the first day of the next month
new_month += 1
if new_month > 12:
new_month -= 12
year += 1
return datetime.datetime(year, new_month, 1)
else:
# We are subtracting - use the last day of the same month
new_day = calendar.monthrange(year, new_month)[1]
return datetime.datetime(year, new_month, new_day) | Add a number of months to a date | Below is the the instruction that describes the task:
### Input:
Add a number of months to a date
### Response:
def add_months_to_date(months, date):
"""Add a number of months to a date"""
month = date.month
new_month = month + months
years = 0
while new_month < 1:
new_month += 12
years -= 1
while new_month > 12:
new_month -= 12
years += 1
# month = timestamp.month
year = date.year + years
try:
return datetime.date(year, new_month, date.day)
except ValueError:
# This means that the day exceeds the last day of the month, i.e. it is 30th March, and we are finding the day
# 1 month ago, and it is trying to return 30th February
if months > 0:
# We are adding, so use the first day of the next month
new_month += 1
if new_month > 12:
new_month -= 12
year += 1
return datetime.datetime(year, new_month, 1)
else:
# We are subtracting - use the last day of the same month
new_day = calendar.monthrange(year, new_month)[1]
return datetime.datetime(year, new_month, new_day) |
def segment_lengths(neurites, neurite_type=NeuriteType.all):
'''Lengths of the segments in a collection of neurites'''
def _seg_len(sec):
'''list of segment lengths of a section'''
return np.linalg.norm(np.diff(sec.points[:, COLS.XYZ], axis=0), axis=1)
return map_segments(_seg_len, neurites, neurite_type) | Lengths of the segments in a collection of neurites | Below is the the instruction that describes the task:
### Input:
Lengths of the segments in a collection of neurites
### Response:
def segment_lengths(neurites, neurite_type=NeuriteType.all):
'''Lengths of the segments in a collection of neurites'''
def _seg_len(sec):
'''list of segment lengths of a section'''
return np.linalg.norm(np.diff(sec.points[:, COLS.XYZ], axis=0), axis=1)
return map_segments(_seg_len, neurites, neurite_type) |
def visualize_conv_weights(filters, name):
"""Visualize use weights in convolution filters.
Args:
filters: tensor containing the weights [H,W,Cin,Cout]
name: label for tensorboard
Returns:
image of all weight
"""
with tf.name_scope('visualize_w_' + name):
filters = tf.transpose(filters, (3, 2, 0, 1)) # [h, w, cin, cout] -> [cout, cin, h, w]
filters = tf.unstack(filters) # --> cout * [cin, h, w]
filters = tf.concat(filters, 1) # --> [cin, cout * h, w]
filters = tf.unstack(filters) # --> cin * [cout * h, w]
filters = tf.concat(filters, 1) # --> [cout * h, cin * w]
filters = tf.expand_dims(filters, 0)
filters = tf.expand_dims(filters, -1)
tf.summary.image('visualize_w_' + name, filters) | Visualize use weights in convolution filters.
Args:
filters: tensor containing the weights [H,W,Cin,Cout]
name: label for tensorboard
Returns:
image of all weight | Below is the the instruction that describes the task:
### Input:
Visualize use weights in convolution filters.
Args:
filters: tensor containing the weights [H,W,Cin,Cout]
name: label for tensorboard
Returns:
image of all weight
### Response:
def visualize_conv_weights(filters, name):
"""Visualize use weights in convolution filters.
Args:
filters: tensor containing the weights [H,W,Cin,Cout]
name: label for tensorboard
Returns:
image of all weight
"""
with tf.name_scope('visualize_w_' + name):
filters = tf.transpose(filters, (3, 2, 0, 1)) # [h, w, cin, cout] -> [cout, cin, h, w]
filters = tf.unstack(filters) # --> cout * [cin, h, w]
filters = tf.concat(filters, 1) # --> [cin, cout * h, w]
filters = tf.unstack(filters) # --> cin * [cout * h, w]
filters = tf.concat(filters, 1) # --> [cout * h, cin * w]
filters = tf.expand_dims(filters, 0)
filters = tf.expand_dims(filters, -1)
tf.summary.image('visualize_w_' + name, filters) |
def IntegerDifference(left: vertex_constructor_param_types, right: vertex_constructor_param_types, label: Optional[str]=None) -> Vertex:
"""
Subtracts one vertex from another
:param left: the vertex to be subtracted from
:param right: the vertex to subtract
"""
return Integer(context.jvm_view().IntegerDifferenceVertex, label, cast_to_integer_vertex(left), cast_to_integer_vertex(right)) | Subtracts one vertex from another
:param left: the vertex to be subtracted from
:param right: the vertex to subtract | Below is the the instruction that describes the task:
### Input:
Subtracts one vertex from another
:param left: the vertex to be subtracted from
:param right: the vertex to subtract
### Response:
def IntegerDifference(left: vertex_constructor_param_types, right: vertex_constructor_param_types, label: Optional[str]=None) -> Vertex:
"""
Subtracts one vertex from another
:param left: the vertex to be subtracted from
:param right: the vertex to subtract
"""
return Integer(context.jvm_view().IntegerDifferenceVertex, label, cast_to_integer_vertex(left), cast_to_integer_vertex(right)) |
def com(self, center1_x, center1_y, center2_x, center2_y, Fm):
"""
:return: center of mass
"""
com_x = (Fm * center1_x + center2_x)/(Fm + 1.)
com_y = (Fm * center1_y + center2_y)/(Fm + 1.)
return com_x, com_y | :return: center of mass | Below is the the instruction that describes the task:
### Input:
:return: center of mass
### Response:
def com(self, center1_x, center1_y, center2_x, center2_y, Fm):
"""
:return: center of mass
"""
com_x = (Fm * center1_x + center2_x)/(Fm + 1.)
com_y = (Fm * center1_y + center2_y)/(Fm + 1.)
return com_x, com_y |
def api_send_mail(request, key=None, hproPk=None):
"""Send a email. Posts parameters are used"""
if not check_api_key(request, key, hproPk):
return HttpResponseForbidden
sender = request.POST.get('sender', settings.MAIL_SENDER)
dests = request.POST.getlist('dests')
subject = request.POST['subject']
message = request.POST['message']
html_message = request.POST.get('html_message')
if html_message and html_message.lower() == 'false':
html_message = False
if 'response_id' in request.POST:
key = hproPk + ':' + request.POST['response_id']
else:
key = None
generic_send_mail(sender, dests, subject, message, key, 'PlugIt API (%s)' % (hproPk or 'StandAlone',), html_message)
return HttpResponse(json.dumps({}), content_type="application/json") | Send a email. Posts parameters are used | Below is the the instruction that describes the task:
### Input:
Send a email. Posts parameters are used
### Response:
def api_send_mail(request, key=None, hproPk=None):
"""Send a email. Posts parameters are used"""
if not check_api_key(request, key, hproPk):
return HttpResponseForbidden
sender = request.POST.get('sender', settings.MAIL_SENDER)
dests = request.POST.getlist('dests')
subject = request.POST['subject']
message = request.POST['message']
html_message = request.POST.get('html_message')
if html_message and html_message.lower() == 'false':
html_message = False
if 'response_id' in request.POST:
key = hproPk + ':' + request.POST['response_id']
else:
key = None
generic_send_mail(sender, dests, subject, message, key, 'PlugIt API (%s)' % (hproPk or 'StandAlone',), html_message)
return HttpResponse(json.dumps({}), content_type="application/json") |
def filter_from_opts(**kw):
'''Build a AND filter from the provided kwargs defaulting to an
empty 'and' filter (@todo: API workaround) if nothing is provided.
If the 'filter_json' argument is provided, this will be assumed to contain
a filter specification and will be anded with other filters. If the
'filter_json' is a search, the search filter value will be used.
All kw values should be tuple or list
'''
filter_in = kw.pop('filter_json', None)
active = and_filter_from_opts(kw)
if filter_in:
filter_in = filter_in.get('filter', filter_in)
if len(active['config']) > 0:
active = filters.and_filter(active, filter_in)
else:
active = filter_in
return active | Build a AND filter from the provided kwargs defaulting to an
empty 'and' filter (@todo: API workaround) if nothing is provided.
If the 'filter_json' argument is provided, this will be assumed to contain
a filter specification and will be anded with other filters. If the
'filter_json' is a search, the search filter value will be used.
All kw values should be tuple or list | Below is the the instruction that describes the task:
### Input:
Build a AND filter from the provided kwargs defaulting to an
empty 'and' filter (@todo: API workaround) if nothing is provided.
If the 'filter_json' argument is provided, this will be assumed to contain
a filter specification and will be anded with other filters. If the
'filter_json' is a search, the search filter value will be used.
All kw values should be tuple or list
### Response:
def filter_from_opts(**kw):
'''Build a AND filter from the provided kwargs defaulting to an
empty 'and' filter (@todo: API workaround) if nothing is provided.
If the 'filter_json' argument is provided, this will be assumed to contain
a filter specification and will be anded with other filters. If the
'filter_json' is a search, the search filter value will be used.
All kw values should be tuple or list
'''
filter_in = kw.pop('filter_json', None)
active = and_filter_from_opts(kw)
if filter_in:
filter_in = filter_in.get('filter', filter_in)
if len(active['config']) > 0:
active = filters.and_filter(active, filter_in)
else:
active = filter_in
return active |
def generate_private_investment(asset_manager_id=None, asset_id=None, client_id=None):
attributes = generate_common(asset_manager_id=asset_manager_id, asset_id=asset_id)
"""currency, display_name"""
private_investment = PrivateInvestment(client_id=client_id or random_string(5),
asset_issuer_id=random_string(8),
category='Private Equity',
sub_category='Leverage Buyout Funds',
num_shares=1000,
price_share=1000,
share_type='Ordinary Shares',
maturity_date=random_date(),
lock_up_period=52,
investment_term=52,
**attributes)
return private_investment | currency, display_name | Below is the the instruction that describes the task:
### Input:
currency, display_name
### Response:
def generate_private_investment(asset_manager_id=None, asset_id=None, client_id=None):
attributes = generate_common(asset_manager_id=asset_manager_id, asset_id=asset_id)
"""currency, display_name"""
private_investment = PrivateInvestment(client_id=client_id or random_string(5),
asset_issuer_id=random_string(8),
category='Private Equity',
sub_category='Leverage Buyout Funds',
num_shares=1000,
price_share=1000,
share_type='Ordinary Shares',
maturity_date=random_date(),
lock_up_period=52,
investment_term=52,
**attributes)
return private_investment |
def get_file_mode_for_writing(context):
"""Get file mode for writing from tar['format'].
This should return w:, w:gz, w:bz2 or w:xz. If user specified something
wacky in tar.Format, that's their business.
"""
format = context['tar'].get('format', None)
# slightly weird double-check because falsy format could mean either format
# doesn't exist in input, OR that it exists and is empty. Exists-but-empty
# has special meaning - default to no compression.
if format or format == '':
mode = f"w:{context.get_formatted_string(format)}"
else:
mode = 'w:xz'
return mode | Get file mode for writing from tar['format'].
This should return w:, w:gz, w:bz2 or w:xz. If user specified something
wacky in tar.Format, that's their business. | Below is the the instruction that describes the task:
### Input:
Get file mode for writing from tar['format'].
This should return w:, w:gz, w:bz2 or w:xz. If user specified something
wacky in tar.Format, that's their business.
### Response:
def get_file_mode_for_writing(context):
"""Get file mode for writing from tar['format'].
This should return w:, w:gz, w:bz2 or w:xz. If user specified something
wacky in tar.Format, that's their business.
"""
format = context['tar'].get('format', None)
# slightly weird double-check because falsy format could mean either format
# doesn't exist in input, OR that it exists and is empty. Exists-but-empty
# has special meaning - default to no compression.
if format or format == '':
mode = f"w:{context.get_formatted_string(format)}"
else:
mode = 'w:xz'
return mode |
def _get_table_size(p_alphabet, p_num):
"""
Returns a prime number that is suitable for the hash table size. The size
is dependent on the alphabet used, and the number of items that need to be
hashed. The table size is at least 100 times larger than the number of
items to be hashed, to avoid collisions.
When the alphabet is too little or too large, then _TableSizeException is
raised. Currently an alphabet of 10 to 40 characters is supported.
"""
try:
for width, size in sorted(_TABLE_SIZES[len(p_alphabet)].items()):
if p_num < size * 0.01:
return width, size
except KeyError:
pass
raise _TableSizeException('Could not find appropriate table size for given alphabet') | Returns a prime number that is suitable for the hash table size. The size
is dependent on the alphabet used, and the number of items that need to be
hashed. The table size is at least 100 times larger than the number of
items to be hashed, to avoid collisions.
When the alphabet is too little or too large, then _TableSizeException is
raised. Currently an alphabet of 10 to 40 characters is supported. | Below is the the instruction that describes the task:
### Input:
Returns a prime number that is suitable for the hash table size. The size
is dependent on the alphabet used, and the number of items that need to be
hashed. The table size is at least 100 times larger than the number of
items to be hashed, to avoid collisions.
When the alphabet is too little or too large, then _TableSizeException is
raised. Currently an alphabet of 10 to 40 characters is supported.
### Response:
def _get_table_size(p_alphabet, p_num):
"""
Returns a prime number that is suitable for the hash table size. The size
is dependent on the alphabet used, and the number of items that need to be
hashed. The table size is at least 100 times larger than the number of
items to be hashed, to avoid collisions.
When the alphabet is too little or too large, then _TableSizeException is
raised. Currently an alphabet of 10 to 40 characters is supported.
"""
try:
for width, size in sorted(_TABLE_SIZES[len(p_alphabet)].items()):
if p_num < size * 0.01:
return width, size
except KeyError:
pass
raise _TableSizeException('Could not find appropriate table size for given alphabet') |
def _start_execution_in_container(
self, args, stdin, stdout, stderr, env, root_dir, cwd, temp_dir,
memlimit, memory_nodes,
cgroups, output_dir, result_files_patterns, parent_setup_fn,
child_setup_fn, parent_cleanup_fn):
"""Execute the given command and measure its resource usage similarly to super()._start_execution(),
but inside a container implemented using Linux namespaces.
The command has no network access (only loopback),
a fresh directory as /tmp and no write access outside of this,
and it does not see other processes except itself.
"""
assert self._use_namespaces
if root_dir is None:
env.update(self._env_override)
args = self._build_cmdline(args, env=env)
# We have three processes involved:
# parent: the current Python process in which RunExecutor is executing
# child: child process in new namespace (PID 1 in inner namespace),
# configures inner namespace, serves as dummy init,
# collects result of grandchild and passes it to parent
# grandchild: child of child process (PID 2 in inner namespace), exec()s tool
# We need the following communication steps between these proceses:
# 1a) grandchild tells parent its PID (in outer namespace).
# 1b) grandchild tells parent that it is ready and measurement should begin.
# 2) parent tells grandchild that measurement has begun and tool should
# be exec()ed.
# 3) child tells parent about return value and resource consumption of grandchild.
# 1a and 1b are done together by sending the PID through a pipe.
# 2 is done by sending a null byte through a pipe.
# 3 is done by sending a pickled object through the same pipe as #2.
# We cannot use the same pipe for both directions, because otherwise a sender might
# read the bytes it has sent itself.
# Error codes from child to parent
CHILD_OSERROR = 128
CHILD_UNKNOWN_ERROR = 129
from_parent, to_grandchild = os.pipe() # "downstream" pipe parent->grandchild
from_grandchild, to_parent = os.pipe() # "upstream" pipe grandchild/child->parent
# The protocol for these pipes is that first the parent sends the marker for user mappings,
# then the grand child sends its outer PID back,
# and finally the parent sends its completion marker.
# After the run, the child sends the result of the grand child and then waits
# until the pipes are closed, before it terminates.
MARKER_USER_MAPPING_COMPLETED = b'A'
MARKER_PARENT_COMPLETED = b'B'
# If the current directory is within one of the bind mounts we create,
# we need to cd into this directory again, otherwise we would not see the bind mount,
# but the directory behind it. Thus we always set cwd to force a change of directory.
if root_dir is None:
cwd = os.path.abspath(cwd or os.curdir)
else:
root_dir = os.path.abspath(root_dir)
cwd = os.path.abspath(cwd)
def grandchild():
"""Setup everything inside the process that finally exec()s the tool."""
try:
# We know that this process has PID 2 in the inner namespace,
# but we actually need to know its PID in the outer namespace
# such that parent can put us into the correct cgroups.
# According to http://man7.org/linux/man-pages/man7/pid_namespaces.7.html,
# there are two ways to achieve this: sending a message with the PID
# via a socket (but Python < 3.3 lacks a convenient API for sendmsg),
# and reading /proc/self in the outer procfs instance (that's what we do).
my_outer_pid = container.get_my_pid_from_procfs()
container.mount_proc()
container.drop_capabilities()
container.reset_signal_handling()
child_setup_fn() # Do some other setup the caller wants.
# Signal readiness to parent by sending our PID and wait until parent is also ready
os.write(to_parent, str(my_outer_pid).encode())
received = os.read(from_parent, 1)
assert received == MARKER_PARENT_COMPLETED, received
finally:
# close remaining ends of pipe
os.close(from_parent)
os.close(to_parent)
# here Python will exec() the tool for us
def child():
"""Setup everything inside the container, start the tool, and wait for result."""
try:
logging.debug("Child: child process of RunExecutor with PID %d started",
container.get_my_pid_from_procfs())
# Put all received signals on hold until we handle them later.
container.block_all_signals()
# We want to avoid leaking file descriptors to the executed child.
# It is also nice if the child has only the minimal necessary file descriptors,
# to avoid keeping other pipes and files open, e.g., those that the parent
# uses to communicate with other containers (if containers are started in parallel).
# Thus we do not use the close_fds feature of subprocess.Popen,
# but do the same here manually.
# We keep the relevant ends of our pipes, and stdin/out/err of child and grandchild.
necessary_fds = {sys.stdin, sys.stdout, sys.stderr,
to_parent, from_parent, stdin, stdout, stderr} - {None}
container.close_open_fds(keep_files=necessary_fds)
try:
if self._container_system_config:
# A standard hostname increases reproducibility.
libc.sethostname(container.CONTAINER_HOSTNAME)
if not self._allow_network:
container.activate_network_interface("lo")
# Wait until user mapping is finished, this is necessary for filesystem writes
received = os.read(from_parent, len(MARKER_USER_MAPPING_COMPLETED))
assert received == MARKER_USER_MAPPING_COMPLETED, received
if root_dir is not None:
self._setup_root_filesystem(root_dir)
else:
self._setup_container_filesystem(
temp_dir,
output_dir if result_files_patterns else None,
memlimit,
memory_nodes)
except EnvironmentError as e:
logging.critical("Failed to configure container: %s", e)
return CHILD_OSERROR
try:
os.chdir(cwd)
except EnvironmentError as e:
logging.critical(
"Cannot change into working directory inside container: %s", e)
return CHILD_OSERROR
try:
grandchild_proc = subprocess.Popen(args,
stdin=stdin,
stdout=stdout, stderr=stderr,
env=env,
close_fds=False,
preexec_fn=grandchild)
except (EnvironmentError, RuntimeError) as e:
logging.critical("Cannot start process: %s", e)
return CHILD_OSERROR
# keep capability for unmount if necessary later
necessary_capabilities = [libc.CAP_SYS_ADMIN] if result_files_patterns else []
container.drop_capabilities(keep=necessary_capabilities)
# Close other fds that were still necessary above.
container.close_open_fds(keep_files={sys.stdout, sys.stderr, to_parent, from_parent})
# Set up signal handlers to forward signals to grandchild
# (because we are PID 1, there is a special signal handling otherwise).
# cf. dumb-init project: https://github.com/Yelp/dumb-init
# Also wait for grandchild and return its result.
if _HAS_SIGWAIT:
grandchild_result = container.wait_for_child_and_forward_all_signals(
grandchild_proc.pid, args[0])
else:
container.forward_all_signals_async(grandchild_proc.pid, args[0])
grandchild_result = self._wait_for_process(grandchild_proc.pid, args[0])
logging.debug("Child: process %s terminated with exit code %d.",
args[0], grandchild_result[0])
if result_files_patterns:
# Remove the bind mount that _setup_container_filesystem added
# such that the parent can access the result files.
libc.umount(temp_dir.encode())
os.write(to_parent, pickle.dumps(grandchild_result))
os.close(to_parent)
# Now the parent copies the output files, we need to wait until this is finished.
# If the child terminates, the container file system and its tmpfs go away.
os.read(from_parent, 1)
os.close(from_parent)
return 0
except EnvironmentError as e:
logging.exception("Error in child process of RunExecutor")
return CHILD_OSERROR
except:
# Need to catch everything because this method always needs to return a int
# (we are inside a C callback that requires returning int).
logging.exception("Error in child process of RunExecutor")
return CHILD_UNKNOWN_ERROR
try: # parent
try:
child_pid = container.execute_in_namespace(child, use_network_ns=not self._allow_network)
except OSError as e:
raise BenchExecException(
"Creating namespace for container mode failed: " + os.strerror(e.errno))
logging.debug("Parent: child process of RunExecutor with PID %d started.", child_pid)
def check_child_exit_code():
"""Check if the child process terminated cleanly and raise an error otherwise."""
child_exitcode, unused_child_rusage = self._wait_for_process(child_pid, args[0])
child_exitcode = util.ProcessExitCode.from_raw(child_exitcode)
logging.debug("Parent: child process of RunExecutor with PID %d terminated with %s.",
child_pid, child_exitcode)
if child_exitcode:
if child_exitcode.value:
if child_exitcode.value == CHILD_OSERROR:
# This was an OSError in the child, details were already logged
raise BenchExecException("execution in container failed, check log for details")
elif child_exitcode.value == CHILD_UNKNOWN_ERROR:
raise BenchExecException("unexpected error in container")
raise OSError(child_exitcode.value, os.strerror(child_exitcode.value))
raise OSError(0, "Child process of RunExecutor terminated with " + str(child_exitcode))
# Close unnecessary ends of pipes such that read() does not block forever
# if all other processes have terminated.
os.close(from_parent)
os.close(to_parent)
container.setup_user_mapping(child_pid, uid=self._uid, gid=self._gid)
os.write(to_grandchild, MARKER_USER_MAPPING_COMPLETED) # signal child to continue
try:
grandchild_pid = int(os.read(from_grandchild, 10)) # 10 bytes is enough for 32bit int
except ValueError:
# probably empty read, i.e., pipe closed, i.e., child or grandchild failed
check_child_exit_code()
assert False, "Child process of RunExecutor terminated cleanly but did not send expected data."
logging.debug("Parent: executing %s in grand child with PID %d via child with PID %d.",
args[0], grandchild_pid, child_pid)
# start measurements
cgroups.add_task(grandchild_pid)
parent_setup = parent_setup_fn()
# Signal grandchild that setup is finished
os.write(to_grandchild, MARKER_PARENT_COMPLETED)
# Copy file descriptor, otherwise we could not close from_grandchild in finally block
# and would leak a file descriptor in case of exception.
from_grandchild_copy = os.dup(from_grandchild)
to_grandchild_copy = os.dup(to_grandchild)
finally:
os.close(from_grandchild)
os.close(to_grandchild)
def wait_for_grandchild():
# 1024 bytes ought to be enough for everyone^Wour pickled result
try:
received = os.read(from_grandchild_copy, 1024)
except OSError as e:
if self.PROCESS_KILLED and e.errno == errno.EINTR:
# Read was interrupted because of Ctrl+C, we just try again
received = os.read(from_grandchild_copy, 1024)
else:
raise e
exitcode, ru_child = pickle.loads(received)
base_path = "/proc/{}/root".format(child_pid)
parent_cleanup = parent_cleanup_fn(
parent_setup, util.ProcessExitCode.from_raw(exitcode), base_path)
if result_files_patterns:
# As long as the child process exists we can access the container file system here
self._transfer_output_files(
base_path + temp_dir,
cwd,
output_dir,
result_files_patterns)
os.close(from_grandchild_copy)
os.close(to_grandchild_copy) # signal child that it can terminate
check_child_exit_code()
return exitcode, ru_child, parent_cleanup
return grandchild_pid, wait_for_grandchild | Execute the given command and measure its resource usage similarly to super()._start_execution(),
but inside a container implemented using Linux namespaces.
The command has no network access (only loopback),
a fresh directory as /tmp and no write access outside of this,
and it does not see other processes except itself. | Below is the the instruction that describes the task:
### Input:
Execute the given command and measure its resource usage similarly to super()._start_execution(),
but inside a container implemented using Linux namespaces.
The command has no network access (only loopback),
a fresh directory as /tmp and no write access outside of this,
and it does not see other processes except itself.
### Response:
def _start_execution_in_container(
self, args, stdin, stdout, stderr, env, root_dir, cwd, temp_dir,
memlimit, memory_nodes,
cgroups, output_dir, result_files_patterns, parent_setup_fn,
child_setup_fn, parent_cleanup_fn):
"""Execute the given command and measure its resource usage similarly to super()._start_execution(),
but inside a container implemented using Linux namespaces.
The command has no network access (only loopback),
a fresh directory as /tmp and no write access outside of this,
and it does not see other processes except itself.
"""
assert self._use_namespaces
if root_dir is None:
env.update(self._env_override)
args = self._build_cmdline(args, env=env)
# We have three processes involved:
# parent: the current Python process in which RunExecutor is executing
# child: child process in new namespace (PID 1 in inner namespace),
# configures inner namespace, serves as dummy init,
# collects result of grandchild and passes it to parent
# grandchild: child of child process (PID 2 in inner namespace), exec()s tool
# We need the following communication steps between these proceses:
# 1a) grandchild tells parent its PID (in outer namespace).
# 1b) grandchild tells parent that it is ready and measurement should begin.
# 2) parent tells grandchild that measurement has begun and tool should
# be exec()ed.
# 3) child tells parent about return value and resource consumption of grandchild.
# 1a and 1b are done together by sending the PID through a pipe.
# 2 is done by sending a null byte through a pipe.
# 3 is done by sending a pickled object through the same pipe as #2.
# We cannot use the same pipe for both directions, because otherwise a sender might
# read the bytes it has sent itself.
# Error codes from child to parent
CHILD_OSERROR = 128
CHILD_UNKNOWN_ERROR = 129
from_parent, to_grandchild = os.pipe() # "downstream" pipe parent->grandchild
from_grandchild, to_parent = os.pipe() # "upstream" pipe grandchild/child->parent
# The protocol for these pipes is that first the parent sends the marker for user mappings,
# then the grand child sends its outer PID back,
# and finally the parent sends its completion marker.
# After the run, the child sends the result of the grand child and then waits
# until the pipes are closed, before it terminates.
MARKER_USER_MAPPING_COMPLETED = b'A'
MARKER_PARENT_COMPLETED = b'B'
# If the current directory is within one of the bind mounts we create,
# we need to cd into this directory again, otherwise we would not see the bind mount,
# but the directory behind it. Thus we always set cwd to force a change of directory.
if root_dir is None:
cwd = os.path.abspath(cwd or os.curdir)
else:
root_dir = os.path.abspath(root_dir)
cwd = os.path.abspath(cwd)
def grandchild():
"""Setup everything inside the process that finally exec()s the tool."""
try:
# We know that this process has PID 2 in the inner namespace,
# but we actually need to know its PID in the outer namespace
# such that parent can put us into the correct cgroups.
# According to http://man7.org/linux/man-pages/man7/pid_namespaces.7.html,
# there are two ways to achieve this: sending a message with the PID
# via a socket (but Python < 3.3 lacks a convenient API for sendmsg),
# and reading /proc/self in the outer procfs instance (that's what we do).
my_outer_pid = container.get_my_pid_from_procfs()
container.mount_proc()
container.drop_capabilities()
container.reset_signal_handling()
child_setup_fn() # Do some other setup the caller wants.
# Signal readiness to parent by sending our PID and wait until parent is also ready
os.write(to_parent, str(my_outer_pid).encode())
received = os.read(from_parent, 1)
assert received == MARKER_PARENT_COMPLETED, received
finally:
# close remaining ends of pipe
os.close(from_parent)
os.close(to_parent)
# here Python will exec() the tool for us
def child():
"""Setup everything inside the container, start the tool, and wait for result."""
try:
logging.debug("Child: child process of RunExecutor with PID %d started",
container.get_my_pid_from_procfs())
# Put all received signals on hold until we handle them later.
container.block_all_signals()
# We want to avoid leaking file descriptors to the executed child.
# It is also nice if the child has only the minimal necessary file descriptors,
# to avoid keeping other pipes and files open, e.g., those that the parent
# uses to communicate with other containers (if containers are started in parallel).
# Thus we do not use the close_fds feature of subprocess.Popen,
# but do the same here manually.
# We keep the relevant ends of our pipes, and stdin/out/err of child and grandchild.
necessary_fds = {sys.stdin, sys.stdout, sys.stderr,
to_parent, from_parent, stdin, stdout, stderr} - {None}
container.close_open_fds(keep_files=necessary_fds)
try:
if self._container_system_config:
# A standard hostname increases reproducibility.
libc.sethostname(container.CONTAINER_HOSTNAME)
if not self._allow_network:
container.activate_network_interface("lo")
# Wait until user mapping is finished, this is necessary for filesystem writes
received = os.read(from_parent, len(MARKER_USER_MAPPING_COMPLETED))
assert received == MARKER_USER_MAPPING_COMPLETED, received
if root_dir is not None:
self._setup_root_filesystem(root_dir)
else:
self._setup_container_filesystem(
temp_dir,
output_dir if result_files_patterns else None,
memlimit,
memory_nodes)
except EnvironmentError as e:
logging.critical("Failed to configure container: %s", e)
return CHILD_OSERROR
try:
os.chdir(cwd)
except EnvironmentError as e:
logging.critical(
"Cannot change into working directory inside container: %s", e)
return CHILD_OSERROR
try:
grandchild_proc = subprocess.Popen(args,
stdin=stdin,
stdout=stdout, stderr=stderr,
env=env,
close_fds=False,
preexec_fn=grandchild)
except (EnvironmentError, RuntimeError) as e:
logging.critical("Cannot start process: %s", e)
return CHILD_OSERROR
# keep capability for unmount if necessary later
necessary_capabilities = [libc.CAP_SYS_ADMIN] if result_files_patterns else []
container.drop_capabilities(keep=necessary_capabilities)
# Close other fds that were still necessary above.
container.close_open_fds(keep_files={sys.stdout, sys.stderr, to_parent, from_parent})
# Set up signal handlers to forward signals to grandchild
# (because we are PID 1, there is a special signal handling otherwise).
# cf. dumb-init project: https://github.com/Yelp/dumb-init
# Also wait for grandchild and return its result.
if _HAS_SIGWAIT:
grandchild_result = container.wait_for_child_and_forward_all_signals(
grandchild_proc.pid, args[0])
else:
container.forward_all_signals_async(grandchild_proc.pid, args[0])
grandchild_result = self._wait_for_process(grandchild_proc.pid, args[0])
logging.debug("Child: process %s terminated with exit code %d.",
args[0], grandchild_result[0])
if result_files_patterns:
# Remove the bind mount that _setup_container_filesystem added
# such that the parent can access the result files.
libc.umount(temp_dir.encode())
os.write(to_parent, pickle.dumps(grandchild_result))
os.close(to_parent)
# Now the parent copies the output files, we need to wait until this is finished.
# If the child terminates, the container file system and its tmpfs go away.
os.read(from_parent, 1)
os.close(from_parent)
return 0
except EnvironmentError as e:
logging.exception("Error in child process of RunExecutor")
return CHILD_OSERROR
except:
# Need to catch everything because this method always needs to return a int
# (we are inside a C callback that requires returning int).
logging.exception("Error in child process of RunExecutor")
return CHILD_UNKNOWN_ERROR
try: # parent
try:
child_pid = container.execute_in_namespace(child, use_network_ns=not self._allow_network)
except OSError as e:
raise BenchExecException(
"Creating namespace for container mode failed: " + os.strerror(e.errno))
logging.debug("Parent: child process of RunExecutor with PID %d started.", child_pid)
def check_child_exit_code():
"""Check if the child process terminated cleanly and raise an error otherwise."""
child_exitcode, unused_child_rusage = self._wait_for_process(child_pid, args[0])
child_exitcode = util.ProcessExitCode.from_raw(child_exitcode)
logging.debug("Parent: child process of RunExecutor with PID %d terminated with %s.",
child_pid, child_exitcode)
if child_exitcode:
if child_exitcode.value:
if child_exitcode.value == CHILD_OSERROR:
# This was an OSError in the child, details were already logged
raise BenchExecException("execution in container failed, check log for details")
elif child_exitcode.value == CHILD_UNKNOWN_ERROR:
raise BenchExecException("unexpected error in container")
raise OSError(child_exitcode.value, os.strerror(child_exitcode.value))
raise OSError(0, "Child process of RunExecutor terminated with " + str(child_exitcode))
# Close unnecessary ends of pipes such that read() does not block forever
# if all other processes have terminated.
os.close(from_parent)
os.close(to_parent)
container.setup_user_mapping(child_pid, uid=self._uid, gid=self._gid)
os.write(to_grandchild, MARKER_USER_MAPPING_COMPLETED) # signal child to continue
try:
grandchild_pid = int(os.read(from_grandchild, 10)) # 10 bytes is enough for 32bit int
except ValueError:
# probably empty read, i.e., pipe closed, i.e., child or grandchild failed
check_child_exit_code()
assert False, "Child process of RunExecutor terminated cleanly but did not send expected data."
logging.debug("Parent: executing %s in grand child with PID %d via child with PID %d.",
args[0], grandchild_pid, child_pid)
# start measurements
cgroups.add_task(grandchild_pid)
parent_setup = parent_setup_fn()
# Signal grandchild that setup is finished
os.write(to_grandchild, MARKER_PARENT_COMPLETED)
# Copy file descriptor, otherwise we could not close from_grandchild in finally block
# and would leak a file descriptor in case of exception.
from_grandchild_copy = os.dup(from_grandchild)
to_grandchild_copy = os.dup(to_grandchild)
finally:
os.close(from_grandchild)
os.close(to_grandchild)
def wait_for_grandchild():
# 1024 bytes ought to be enough for everyone^Wour pickled result
try:
received = os.read(from_grandchild_copy, 1024)
except OSError as e:
if self.PROCESS_KILLED and e.errno == errno.EINTR:
# Read was interrupted because of Ctrl+C, we just try again
received = os.read(from_grandchild_copy, 1024)
else:
raise e
exitcode, ru_child = pickle.loads(received)
base_path = "/proc/{}/root".format(child_pid)
parent_cleanup = parent_cleanup_fn(
parent_setup, util.ProcessExitCode.from_raw(exitcode), base_path)
if result_files_patterns:
# As long as the child process exists we can access the container file system here
self._transfer_output_files(
base_path + temp_dir,
cwd,
output_dir,
result_files_patterns)
os.close(from_grandchild_copy)
os.close(to_grandchild_copy) # signal child that it can terminate
check_child_exit_code()
return exitcode, ru_child, parent_cleanup
return grandchild_pid, wait_for_grandchild |
def match_handle(loc, tokens):
"""Process match blocks."""
if len(tokens) == 4:
matches, match_type, item, stmts = tokens
cond = None
elif len(tokens) == 5:
matches, match_type, item, cond, stmts = tokens
else:
raise CoconutInternalException("invalid match statement tokens", tokens)
if match_type == "in":
invert = False
elif match_type == "not in":
invert = True
else:
raise CoconutInternalException("invalid match type", match_type)
matching = Matcher(loc, match_check_var)
matching.match(matches, match_to_var)
if cond:
matching.add_guard(cond)
return (
match_to_var + " = " + item + "\n"
+ matching.build(stmts, invert=invert)
) | Process match blocks. | Below is the the instruction that describes the task:
### Input:
Process match blocks.
### Response:
def match_handle(loc, tokens):
"""Process match blocks."""
if len(tokens) == 4:
matches, match_type, item, stmts = tokens
cond = None
elif len(tokens) == 5:
matches, match_type, item, cond, stmts = tokens
else:
raise CoconutInternalException("invalid match statement tokens", tokens)
if match_type == "in":
invert = False
elif match_type == "not in":
invert = True
else:
raise CoconutInternalException("invalid match type", match_type)
matching = Matcher(loc, match_check_var)
matching.match(matches, match_to_var)
if cond:
matching.add_guard(cond)
return (
match_to_var + " = " + item + "\n"
+ matching.build(stmts, invert=invert)
) |
def owners(self):
"""Legacy access to owner role.
DEPRECATED: use ``policy["roles/owners"]`` instead."""
result = set()
for role in self._OWNER_ROLES:
for member in self._bindings.get(role, ()):
result.add(member)
return frozenset(result) | Legacy access to owner role.
DEPRECATED: use ``policy["roles/owners"]`` instead. | Below is the the instruction that describes the task:
### Input:
Legacy access to owner role.
DEPRECATED: use ``policy["roles/owners"]`` instead.
### Response:
def owners(self):
"""Legacy access to owner role.
DEPRECATED: use ``policy["roles/owners"]`` instead."""
result = set()
for role in self._OWNER_ROLES:
for member in self._bindings.get(role, ()):
result.add(member)
return frozenset(result) |
def _get_next_task_from_raylet(self):
"""Get the next task from the raylet.
Returns:
A task from the raylet.
"""
with profiling.profile("worker_idle"):
task = self.raylet_client.get_task()
# Automatically restrict the GPUs available to this task.
ray.utils.set_cuda_visible_devices(ray.get_gpu_ids())
return task | Get the next task from the raylet.
Returns:
A task from the raylet. | Below is the the instruction that describes the task:
### Input:
Get the next task from the raylet.
Returns:
A task from the raylet.
### Response:
def _get_next_task_from_raylet(self):
"""Get the next task from the raylet.
Returns:
A task from the raylet.
"""
with profiling.profile("worker_idle"):
task = self.raylet_client.get_task()
# Automatically restrict the GPUs available to this task.
ray.utils.set_cuda_visible_devices(ray.get_gpu_ids())
return task |
def virtual(opts, virtualname, filename):
'''
Returns the __virtual__.
'''
if ((HAS_NAPALM and NAPALM_MAJOR >= 2) or HAS_NAPALM_BASE) and (is_proxy(opts) or is_minion(opts)):
return virtualname
else:
return (
False,
(
'"{vname}"" {filename} cannot be loaded: '
'NAPALM is not installed: ``pip install napalm``'
).format(
vname=virtualname,
filename='({filename})'.format(filename=filename)
)
) | Returns the __virtual__. | Below is the the instruction that describes the task:
### Input:
Returns the __virtual__.
### Response:
def virtual(opts, virtualname, filename):
'''
Returns the __virtual__.
'''
if ((HAS_NAPALM and NAPALM_MAJOR >= 2) or HAS_NAPALM_BASE) and (is_proxy(opts) or is_minion(opts)):
return virtualname
else:
return (
False,
(
'"{vname}"" {filename} cannot be loaded: '
'NAPALM is not installed: ``pip install napalm``'
).format(
vname=virtualname,
filename='({filename})'.format(filename=filename)
)
) |
def _build_brokers(self, brokers):
"""Build broker objects using broker-ids."""
for broker_id, metadata in six.iteritems(brokers):
self.brokers[broker_id] = self._create_broker(broker_id, metadata) | Build broker objects using broker-ids. | Below is the the instruction that describes the task:
### Input:
Build broker objects using broker-ids.
### Response:
def _build_brokers(self, brokers):
"""Build broker objects using broker-ids."""
for broker_id, metadata in six.iteritems(brokers):
self.brokers[broker_id] = self._create_broker(broker_id, metadata) |
def run_c_extension_with_fallback(
log_function,
extension,
c_function,
py_function,
args,
rconf
):
"""
Run a function calling a C extension, falling back
to a pure Python function if the former does not succeed.
:param function log_function: a logger function
:param string extension: the name of the extension
:param function c_function: the (Python) function calling the C extension
:param function py_function: the (Python) function providing the fallback
:param rconf: the runtime configuration
:type rconf: :class:`aeneas.runtimeconfiguration.RuntimeConfiguration`
:rtype: depends on the extension being called
:raises: RuntimeError: if both the C extension and
the pure Python code did not succeed.
.. versionadded:: 1.4.0
"""
computed = False
if not rconf[u"c_extensions"]:
log_function(u"C extensions disabled")
elif extension not in rconf:
log_function([u"C extension '%s' not recognized", extension])
elif not rconf[extension]:
log_function([u"C extension '%s' disabled", extension])
else:
log_function([u"C extension '%s' enabled", extension])
if c_function is None:
log_function(u"C function is None")
elif can_run_c_extension(extension):
log_function([u"C extension '%s' enabled and it can be loaded", extension])
computed, result = c_function(*args)
else:
log_function([u"C extension '%s' enabled but it cannot be loaded", extension])
if not computed:
if py_function is None:
log_function(u"Python function is None")
else:
log_function(u"Running the pure Python code")
computed, result = py_function(*args)
if not computed:
raise RuntimeError(u"Both the C extension and the pure Python code failed. (Wrong arguments? Input too big?)")
return result | Run a function calling a C extension, falling back
to a pure Python function if the former does not succeed.
:param function log_function: a logger function
:param string extension: the name of the extension
:param function c_function: the (Python) function calling the C extension
:param function py_function: the (Python) function providing the fallback
:param rconf: the runtime configuration
:type rconf: :class:`aeneas.runtimeconfiguration.RuntimeConfiguration`
:rtype: depends on the extension being called
:raises: RuntimeError: if both the C extension and
the pure Python code did not succeed.
.. versionadded:: 1.4.0 | Below is the the instruction that describes the task:
### Input:
Run a function calling a C extension, falling back
to a pure Python function if the former does not succeed.
:param function log_function: a logger function
:param string extension: the name of the extension
:param function c_function: the (Python) function calling the C extension
:param function py_function: the (Python) function providing the fallback
:param rconf: the runtime configuration
:type rconf: :class:`aeneas.runtimeconfiguration.RuntimeConfiguration`
:rtype: depends on the extension being called
:raises: RuntimeError: if both the C extension and
the pure Python code did not succeed.
.. versionadded:: 1.4.0
### Response:
def run_c_extension_with_fallback(
log_function,
extension,
c_function,
py_function,
args,
rconf
):
"""
Run a function calling a C extension, falling back
to a pure Python function if the former does not succeed.
:param function log_function: a logger function
:param string extension: the name of the extension
:param function c_function: the (Python) function calling the C extension
:param function py_function: the (Python) function providing the fallback
:param rconf: the runtime configuration
:type rconf: :class:`aeneas.runtimeconfiguration.RuntimeConfiguration`
:rtype: depends on the extension being called
:raises: RuntimeError: if both the C extension and
the pure Python code did not succeed.
.. versionadded:: 1.4.0
"""
computed = False
if not rconf[u"c_extensions"]:
log_function(u"C extensions disabled")
elif extension not in rconf:
log_function([u"C extension '%s' not recognized", extension])
elif not rconf[extension]:
log_function([u"C extension '%s' disabled", extension])
else:
log_function([u"C extension '%s' enabled", extension])
if c_function is None:
log_function(u"C function is None")
elif can_run_c_extension(extension):
log_function([u"C extension '%s' enabled and it can be loaded", extension])
computed, result = c_function(*args)
else:
log_function([u"C extension '%s' enabled but it cannot be loaded", extension])
if not computed:
if py_function is None:
log_function(u"Python function is None")
else:
log_function(u"Running the pure Python code")
computed, result = py_function(*args)
if not computed:
raise RuntimeError(u"Both the C extension and the pure Python code failed. (Wrong arguments? Input too big?)")
return result |
def open(self, target_uri, **kwargs):
"""Open target uri.
:param target_uri: Uri to open
:type target_uri: string
:returns: Target object
"""
target = urlsplit(target_uri, scheme=self.default_opener)
opener = self.get_opener(target.scheme)
query = opener.conform_query(target.query)
target = opener.get_target(
target.scheme,
target.path,
target.fragment,
target.username,
target.password,
target.hostname,
target.port,
query,
**kwargs
)
target.opener_path = target_uri
return target | Open target uri.
:param target_uri: Uri to open
:type target_uri: string
:returns: Target object | Below is the the instruction that describes the task:
### Input:
Open target uri.
:param target_uri: Uri to open
:type target_uri: string
:returns: Target object
### Response:
def open(self, target_uri, **kwargs):
"""Open target uri.
:param target_uri: Uri to open
:type target_uri: string
:returns: Target object
"""
target = urlsplit(target_uri, scheme=self.default_opener)
opener = self.get_opener(target.scheme)
query = opener.conform_query(target.query)
target = opener.get_target(
target.scheme,
target.path,
target.fragment,
target.username,
target.password,
target.hostname,
target.port,
query,
**kwargs
)
target.opener_path = target_uri
return target |
def deleteBy(self, func):
'Delete rows for which func(row) is true. Returns number of deleted rows.'
oldrows = copy(self.rows)
oldidx = self.cursorRowIndex
ndeleted = 0
row = None # row to re-place cursor after
while oldidx < len(oldrows):
if not func(oldrows[oldidx]):
row = self.rows[oldidx]
break
oldidx += 1
self.rows.clear()
for r in Progress(oldrows, 'deleting'):
if not func(r):
self.rows.append(r)
if r is row:
self.cursorRowIndex = len(self.rows)-1
else:
ndeleted += 1
status('deleted %s %s' % (ndeleted, self.rowtype))
return ndeleted | Delete rows for which func(row) is true. Returns number of deleted rows. | Below is the the instruction that describes the task:
### Input:
Delete rows for which func(row) is true. Returns number of deleted rows.
### Response:
def deleteBy(self, func):
'Delete rows for which func(row) is true. Returns number of deleted rows.'
oldrows = copy(self.rows)
oldidx = self.cursorRowIndex
ndeleted = 0
row = None # row to re-place cursor after
while oldidx < len(oldrows):
if not func(oldrows[oldidx]):
row = self.rows[oldidx]
break
oldidx += 1
self.rows.clear()
for r in Progress(oldrows, 'deleting'):
if not func(r):
self.rows.append(r)
if r is row:
self.cursorRowIndex = len(self.rows)-1
else:
ndeleted += 1
status('deleted %s %s' % (ndeleted, self.rowtype))
return ndeleted |
def from_json(cls, data, genomes_data=None, genomes_deserialization_required=True, merge=False):
""" A JSON deserialization operation, that recovers a breakpoint graph from its JSON representation
as information about genomes, that are encoded in breakpoint graph might be available somewhere else, but not the
json object, there is an option to provide it and omit encoding information about genomes.
"""
result = cls()
merge = merge
vertices_dict = {}
genomes_dict = genomes_data if genomes_data is not None and not genomes_deserialization_required else None
if genomes_dict is None:
############################################################################################################
#
# if we need to recover genomes information from breakpoint graph json object
# we are happy to do that
#
############################################################################################################
genomes_dict = {}
try:
source = genomes_data if genomes_data is not None and genomes_deserialization_required else data[
"genomes"]
except KeyError as exc:
raise ValueError("Error during breakpoint graph deserialization. No \"genomes\" information found")
for g_dict in source:
############################################################################################################
#
# if explicitly specified in genome json object, it can be decoded using provided schema name,
# of course a decoding breakpoint graph object shall be aware of such scheme
# (it has to be specified in the `genomes_json_schemas` class wide dict)
#
############################################################################################################
schema_name = g_dict.get(BGGenome_JSON_SCHEMA_JSON_KEY, None)
schema_class = None if schema_name is None else cls.genomes_json_schemas.get(schema_name, None)
genomes_dict[g_dict["g_id"]] = BGGenome.from_json(data=g_dict, json_schema_class=schema_class)
if "vertices" not in data:
############################################################################################################
#
# breakpoint graph can not be decoded without having information about vertices explicitly
# as vertices are referenced in edges object, rather than explicitly provided
#
############################################################################################################
raise ValueError(
"Error during breakpoint graph deserialization. \"vertices\" key is not present in json object")
for vertex_dict in data["vertices"]:
############################################################################################################
#
# if explicitly specified in vertex json object, it can be decoded using provided schema name,
# of course a decoding breakpoint graph object shall be aware of such scheme
# (it has to be specified in the `vertices_json_schemas` class wide dict)
#
############################################################################################################
schema_name = vertex_dict.get(BGVertex_JSON_SCHEMA_JSON_KEY, None)
schema_class = None if schema_name is None else cls.vertices_json_schemas.get(schema_name, None)
try:
############################################################################################################
#
# we try to recover a specific vertex class based on its name.
# it does not overwrite the schema based behaviour
# but provides a correct default schema for a specific vertex type
#
############################################################################################################
vertex_class = BGVertex.get_vertex_class_from_vertex_name(vertex_dict["name"])
except KeyError:
vertex_class = BGVertex
vertices_dict[vertex_dict["v_id"]] = vertex_class.from_json(data=vertex_dict,
json_schema_class=schema_class)
for edge_dict in data["edges"]:
############################################################################################################
#
# if explicitly specified in edge json object, it can be decoded using provided schema name,
# of course a decoding breakpoint graph object shall be aware of such scheme
# (it has to be specified in the `edges_json_schemas` class wide dict)
#
############################################################################################################
schema_name = edge_dict.get(BGEdge_JSON_SCHEMA_JSON_KEY, None)
schema = None if schema_name is None else cls.edges_json_schemas.get(schema_name, None)
edge = BGEdge.from_json(data=edge_dict, json_schema_class=schema)
try:
edge.vertex1 = vertices_dict[edge.vertex1]
edge.vertex2 = vertices_dict[edge.vertex2]
except KeyError:
############################################################################################################
#
# as edge references a pair of vertices, we must be sure respective vertices were decoded
#
############################################################################################################
raise ValueError(
"Error during breakpoint graph deserialization. Deserialized edge references non-present vertex")
if len(edge.multicolor) == 0:
############################################################################################################
#
# edges with empty multicolor are not permitted in breakpoint graphs
#
############################################################################################################
raise ValueError(
"Error during breakpoint graph deserialization. Empty multicolor for deserialized edge")
try:
edge.multicolor = Multicolor(*[genomes_dict[g_id] for g_id in edge.multicolor])
except KeyError:
raise ValueError(
"Error during breakpoint graph deserialization. Deserialized edge reference non-present "
"genome in its multicolor")
result.__add_bgedge(edge, merge=merge)
return result | A JSON deserialization operation, that recovers a breakpoint graph from its JSON representation
as information about genomes, that are encoded in breakpoint graph might be available somewhere else, but not the
json object, there is an option to provide it and omit encoding information about genomes. | Below is the the instruction that describes the task:
### Input:
A JSON deserialization operation, that recovers a breakpoint graph from its JSON representation
as information about genomes, that are encoded in breakpoint graph might be available somewhere else, but not the
json object, there is an option to provide it and omit encoding information about genomes.
### Response:
def from_json(cls, data, genomes_data=None, genomes_deserialization_required=True, merge=False):
""" A JSON deserialization operation, that recovers a breakpoint graph from its JSON representation
as information about genomes, that are encoded in breakpoint graph might be available somewhere else, but not the
json object, there is an option to provide it and omit encoding information about genomes.
"""
result = cls()
merge = merge
vertices_dict = {}
genomes_dict = genomes_data if genomes_data is not None and not genomes_deserialization_required else None
if genomes_dict is None:
############################################################################################################
#
# if we need to recover genomes information from breakpoint graph json object
# we are happy to do that
#
############################################################################################################
genomes_dict = {}
try:
source = genomes_data if genomes_data is not None and genomes_deserialization_required else data[
"genomes"]
except KeyError as exc:
raise ValueError("Error during breakpoint graph deserialization. No \"genomes\" information found")
for g_dict in source:
############################################################################################################
#
# if explicitly specified in genome json object, it can be decoded using provided schema name,
# of course a decoding breakpoint graph object shall be aware of such scheme
# (it has to be specified in the `genomes_json_schemas` class wide dict)
#
############################################################################################################
schema_name = g_dict.get(BGGenome_JSON_SCHEMA_JSON_KEY, None)
schema_class = None if schema_name is None else cls.genomes_json_schemas.get(schema_name, None)
genomes_dict[g_dict["g_id"]] = BGGenome.from_json(data=g_dict, json_schema_class=schema_class)
if "vertices" not in data:
############################################################################################################
#
# breakpoint graph can not be decoded without having information about vertices explicitly
# as vertices are referenced in edges object, rather than explicitly provided
#
############################################################################################################
raise ValueError(
"Error during breakpoint graph deserialization. \"vertices\" key is not present in json object")
for vertex_dict in data["vertices"]:
############################################################################################################
#
# if explicitly specified in vertex json object, it can be decoded using provided schema name,
# of course a decoding breakpoint graph object shall be aware of such scheme
# (it has to be specified in the `vertices_json_schemas` class wide dict)
#
############################################################################################################
schema_name = vertex_dict.get(BGVertex_JSON_SCHEMA_JSON_KEY, None)
schema_class = None if schema_name is None else cls.vertices_json_schemas.get(schema_name, None)
try:
############################################################################################################
#
# we try to recover a specific vertex class based on its name.
# it does not overwrite the schema based behaviour
# but provides a correct default schema for a specific vertex type
#
############################################################################################################
vertex_class = BGVertex.get_vertex_class_from_vertex_name(vertex_dict["name"])
except KeyError:
vertex_class = BGVertex
vertices_dict[vertex_dict["v_id"]] = vertex_class.from_json(data=vertex_dict,
json_schema_class=schema_class)
for edge_dict in data["edges"]:
############################################################################################################
#
# if explicitly specified in edge json object, it can be decoded using provided schema name,
# of course a decoding breakpoint graph object shall be aware of such scheme
# (it has to be specified in the `edges_json_schemas` class wide dict)
#
############################################################################################################
schema_name = edge_dict.get(BGEdge_JSON_SCHEMA_JSON_KEY, None)
schema = None if schema_name is None else cls.edges_json_schemas.get(schema_name, None)
edge = BGEdge.from_json(data=edge_dict, json_schema_class=schema)
try:
edge.vertex1 = vertices_dict[edge.vertex1]
edge.vertex2 = vertices_dict[edge.vertex2]
except KeyError:
############################################################################################################
#
# as edge references a pair of vertices, we must be sure respective vertices were decoded
#
############################################################################################################
raise ValueError(
"Error during breakpoint graph deserialization. Deserialized edge references non-present vertex")
if len(edge.multicolor) == 0:
############################################################################################################
#
# edges with empty multicolor are not permitted in breakpoint graphs
#
############################################################################################################
raise ValueError(
"Error during breakpoint graph deserialization. Empty multicolor for deserialized edge")
try:
edge.multicolor = Multicolor(*[genomes_dict[g_id] for g_id in edge.multicolor])
except KeyError:
raise ValueError(
"Error during breakpoint graph deserialization. Deserialized edge reference non-present "
"genome in its multicolor")
result.__add_bgedge(edge, merge=merge)
return result |
def _assign_parent(self, ctx):
""" parent assignment, internal usage only
"""
def _assign(cls, _, obj):
if obj == None:
return
if cls.is_produced(obj):
if isinstance(obj, BaseObj):
obj._parent__ = self
else:
raise ValueError('Object is not instance of {0} but {1}'.format(cls.__swagger_ref_object__.__name__, obj.__class__.__name__))
# set self as childrent's parent
for name, (ct, ctx) in six.iteritems(ctx.__swagger_child__):
obj = getattr(self, name)
if obj == None:
continue
container_apply(ct, obj, functools.partial(_assign, ctx)) | parent assignment, internal usage only | Below is the the instruction that describes the task:
### Input:
parent assignment, internal usage only
### Response:
def _assign_parent(self, ctx):
""" parent assignment, internal usage only
"""
def _assign(cls, _, obj):
if obj == None:
return
if cls.is_produced(obj):
if isinstance(obj, BaseObj):
obj._parent__ = self
else:
raise ValueError('Object is not instance of {0} but {1}'.format(cls.__swagger_ref_object__.__name__, obj.__class__.__name__))
# set self as childrent's parent
for name, (ct, ctx) in six.iteritems(ctx.__swagger_child__):
obj = getattr(self, name)
if obj == None:
continue
container_apply(ct, obj, functools.partial(_assign, ctx)) |
def get_group(self, uuid=None):
"""Get group data based on uuid.
Args:
uuid (str): optional uuid. defaults to self.cuuid
Raises:
PyLmodUnexpectedData: No data was returned.
requests.RequestException: Exception connection error
Returns:
dict: group json
"""
if uuid is None:
uuid = self.uuid
group_data = self.get('group', params={'uuid': uuid})
return group_data | Get group data based on uuid.
Args:
uuid (str): optional uuid. defaults to self.cuuid
Raises:
PyLmodUnexpectedData: No data was returned.
requests.RequestException: Exception connection error
Returns:
dict: group json | Below is the the instruction that describes the task:
### Input:
Get group data based on uuid.
Args:
uuid (str): optional uuid. defaults to self.cuuid
Raises:
PyLmodUnexpectedData: No data was returned.
requests.RequestException: Exception connection error
Returns:
dict: group json
### Response:
def get_group(self, uuid=None):
"""Get group data based on uuid.
Args:
uuid (str): optional uuid. defaults to self.cuuid
Raises:
PyLmodUnexpectedData: No data was returned.
requests.RequestException: Exception connection error
Returns:
dict: group json
"""
if uuid is None:
uuid = self.uuid
group_data = self.get('group', params={'uuid': uuid})
return group_data |
def geocode(
self,
query,
exactly_one=True,
timeout=DEFAULT_SENTINEL,
location_bias=None,
language=False,
limit=None,
osm_tag=None
):
"""
Return a location point by address.
:param str query: The address or query you wish to geocode.
:param bool exactly_one: Return one result or a list of results, if
available.
:param int timeout: Time, in seconds, to wait for the geocoding service
to respond before raising a :class:`geopy.exc.GeocoderTimedOut`
exception. Set this only if you wish to override, on this call
only, the value set during the geocoder's initialization.
:param location_bias: The coordinates to used as location bias.
:param str language: Preferred language in which to return results.
:param int limit: Limit the number of returned results, defaults to no
limit.
.. versionadded:: 1.12.0
:param osm_tag: The expression to filter (include/exclude) by key and/
or value, str as ``'key:value'`` or list/set of str if multiple
filters are required as ``['key:!val', '!key', ':!value']``.
:type osm_tag: str or list or set
:rtype: ``None``, :class:`geopy.location.Location` or a list of them, if
``exactly_one=False``.
"""
params = {
'q': self.format_string % query
}
if limit:
params['limit'] = int(limit)
if exactly_one:
params['limit'] = 1
if language:
params['lang'] = language
if location_bias:
try:
lat, lon = self._coerce_point_to_string(location_bias).split(',')
params['lon'] = lon
params['lat'] = lat
except ValueError:
raise ValueError(("Location bias must be a"
" coordinate pair or Point"))
if osm_tag:
if isinstance(osm_tag, string_compare):
params['osm_tag'] = [osm_tag]
else:
if not isinstance(osm_tag, (list, set)):
raise ValueError(
"osm_tag must be a string expression or "
"a set/list of string expressions"
)
params['osm_tag'] = osm_tag
url = "?".join((self.api, urlencode(params, doseq=True)))
logger.debug("%s.geocode: %s", self.__class__.__name__, url)
return self._parse_json(
self._call_geocoder(url, timeout=timeout),
exactly_one
) | Return a location point by address.
:param str query: The address or query you wish to geocode.
:param bool exactly_one: Return one result or a list of results, if
available.
:param int timeout: Time, in seconds, to wait for the geocoding service
to respond before raising a :class:`geopy.exc.GeocoderTimedOut`
exception. Set this only if you wish to override, on this call
only, the value set during the geocoder's initialization.
:param location_bias: The coordinates to used as location bias.
:param str language: Preferred language in which to return results.
:param int limit: Limit the number of returned results, defaults to no
limit.
.. versionadded:: 1.12.0
:param osm_tag: The expression to filter (include/exclude) by key and/
or value, str as ``'key:value'`` or list/set of str if multiple
filters are required as ``['key:!val', '!key', ':!value']``.
:type osm_tag: str or list or set
:rtype: ``None``, :class:`geopy.location.Location` or a list of them, if
``exactly_one=False``. | Below is the the instruction that describes the task:
### Input:
Return a location point by address.
:param str query: The address or query you wish to geocode.
:param bool exactly_one: Return one result or a list of results, if
available.
:param int timeout: Time, in seconds, to wait for the geocoding service
to respond before raising a :class:`geopy.exc.GeocoderTimedOut`
exception. Set this only if you wish to override, on this call
only, the value set during the geocoder's initialization.
:param location_bias: The coordinates to used as location bias.
:param str language: Preferred language in which to return results.
:param int limit: Limit the number of returned results, defaults to no
limit.
.. versionadded:: 1.12.0
:param osm_tag: The expression to filter (include/exclude) by key and/
or value, str as ``'key:value'`` or list/set of str if multiple
filters are required as ``['key:!val', '!key', ':!value']``.
:type osm_tag: str or list or set
:rtype: ``None``, :class:`geopy.location.Location` or a list of them, if
``exactly_one=False``.
### Response:
def geocode(
self,
query,
exactly_one=True,
timeout=DEFAULT_SENTINEL,
location_bias=None,
language=False,
limit=None,
osm_tag=None
):
"""
Return a location point by address.
:param str query: The address or query you wish to geocode.
:param bool exactly_one: Return one result or a list of results, if
available.
:param int timeout: Time, in seconds, to wait for the geocoding service
to respond before raising a :class:`geopy.exc.GeocoderTimedOut`
exception. Set this only if you wish to override, on this call
only, the value set during the geocoder's initialization.
:param location_bias: The coordinates to used as location bias.
:param str language: Preferred language in which to return results.
:param int limit: Limit the number of returned results, defaults to no
limit.
.. versionadded:: 1.12.0
:param osm_tag: The expression to filter (include/exclude) by key and/
or value, str as ``'key:value'`` or list/set of str if multiple
filters are required as ``['key:!val', '!key', ':!value']``.
:type osm_tag: str or list or set
:rtype: ``None``, :class:`geopy.location.Location` or a list of them, if
``exactly_one=False``.
"""
params = {
'q': self.format_string % query
}
if limit:
params['limit'] = int(limit)
if exactly_one:
params['limit'] = 1
if language:
params['lang'] = language
if location_bias:
try:
lat, lon = self._coerce_point_to_string(location_bias).split(',')
params['lon'] = lon
params['lat'] = lat
except ValueError:
raise ValueError(("Location bias must be a"
" coordinate pair or Point"))
if osm_tag:
if isinstance(osm_tag, string_compare):
params['osm_tag'] = [osm_tag]
else:
if not isinstance(osm_tag, (list, set)):
raise ValueError(
"osm_tag must be a string expression or "
"a set/list of string expressions"
)
params['osm_tag'] = osm_tag
url = "?".join((self.api, urlencode(params, doseq=True)))
logger.debug("%s.geocode: %s", self.__class__.__name__, url)
return self._parse_json(
self._call_geocoder(url, timeout=timeout),
exactly_one
) |
def listen(self, topic, timeout=1, limit=1):
""" Listen to a topic and return a list of message payloads received
within the specified time. Requires an async Subscribe to have been called previously.
`topic` topic to listen to
`timeout` duration to listen
`limit` the max number of payloads that will be returned. Specify 0
for no limit
Examples:
Listen and get a list of all messages received within 5 seconds
| ${messages}= | Listen | test/test | timeout=5 | limit=0 |
Listen and get 1st message received within 60 seconds
| @{messages}= | Listen | test/test | timeout=60 | limit=1 |
| Length should be | ${messages} | 1 |
"""
if not self._subscribed:
logger.warn('Cannot listen when not subscribed to a topic')
return []
if topic not in self._messages:
logger.warn('Cannot listen when not subscribed to topic: %s' % topic)
return []
# If enough messages have already been gathered, return them
if limit != 0 and len(self._messages[topic]) >= limit:
messages = self._messages[topic][:] # Copy the list's contents
self._messages[topic] = []
return messages[-limit:]
seconds = convert_time(timeout)
limit = int(limit)
logger.info('Listening on topic: %s' % topic)
timer_start = time.time()
while time.time() < timer_start + seconds:
if limit == 0 or len(self._messages[topic]) < limit:
# If the loop is running in the background
# merely sleep here for a second or so and continue
# otherwise, do the loop ourselves
if self._background_mqttc:
time.sleep(1)
else:
self._mqttc.loop()
else:
# workaround for client to ack the publish. Otherwise,
# it seems that if client disconnects quickly, broker
# will not get the ack and publish the message again on
# next connect.
time.sleep(1)
break
messages = self._messages[topic][:] # Copy the list's contents
self._messages[topic] = []
return messages[-limit:] if limit != 0 else messages | Listen to a topic and return a list of message payloads received
within the specified time. Requires an async Subscribe to have been called previously.
`topic` topic to listen to
`timeout` duration to listen
`limit` the max number of payloads that will be returned. Specify 0
for no limit
Examples:
Listen and get a list of all messages received within 5 seconds
| ${messages}= | Listen | test/test | timeout=5 | limit=0 |
Listen and get 1st message received within 60 seconds
| @{messages}= | Listen | test/test | timeout=60 | limit=1 |
| Length should be | ${messages} | 1 | | Below is the the instruction that describes the task:
### Input:
Listen to a topic and return a list of message payloads received
within the specified time. Requires an async Subscribe to have been called previously.
`topic` topic to listen to
`timeout` duration to listen
`limit` the max number of payloads that will be returned. Specify 0
for no limit
Examples:
Listen and get a list of all messages received within 5 seconds
| ${messages}= | Listen | test/test | timeout=5 | limit=0 |
Listen and get 1st message received within 60 seconds
| @{messages}= | Listen | test/test | timeout=60 | limit=1 |
| Length should be | ${messages} | 1 |
### Response:
def listen(self, topic, timeout=1, limit=1):
""" Listen to a topic and return a list of message payloads received
within the specified time. Requires an async Subscribe to have been called previously.
`topic` topic to listen to
`timeout` duration to listen
`limit` the max number of payloads that will be returned. Specify 0
for no limit
Examples:
Listen and get a list of all messages received within 5 seconds
| ${messages}= | Listen | test/test | timeout=5 | limit=0 |
Listen and get 1st message received within 60 seconds
| @{messages}= | Listen | test/test | timeout=60 | limit=1 |
| Length should be | ${messages} | 1 |
"""
if not self._subscribed:
logger.warn('Cannot listen when not subscribed to a topic')
return []
if topic not in self._messages:
logger.warn('Cannot listen when not subscribed to topic: %s' % topic)
return []
# If enough messages have already been gathered, return them
if limit != 0 and len(self._messages[topic]) >= limit:
messages = self._messages[topic][:] # Copy the list's contents
self._messages[topic] = []
return messages[-limit:]
seconds = convert_time(timeout)
limit = int(limit)
logger.info('Listening on topic: %s' % topic)
timer_start = time.time()
while time.time() < timer_start + seconds:
if limit == 0 or len(self._messages[topic]) < limit:
# If the loop is running in the background
# merely sleep here for a second or so and continue
# otherwise, do the loop ourselves
if self._background_mqttc:
time.sleep(1)
else:
self._mqttc.loop()
else:
# workaround for client to ack the publish. Otherwise,
# it seems that if client disconnects quickly, broker
# will not get the ack and publish the message again on
# next connect.
time.sleep(1)
break
messages = self._messages[topic][:] # Copy the list's contents
self._messages[topic] = []
return messages[-limit:] if limit != 0 else messages |
def get_magnitude_of_effect_from_species(self, species, spin_state, motif):
"""
Get magnitude of Jahn-Teller effect from provided species, spin state and motife.
:param species: e.g. Fe2+
:param spin_state (str): "high" or "low"
:param motif (str): "oct" or "tet"
:return (str):
"""
magnitude = "none"
sp = get_el_sp(species)
# has to be Specie; we need to know the oxidation state
if isinstance(sp, Specie) and sp.element.is_transition_metal:
d_electrons = self._get_number_of_d_electrons(sp)
if motif in self.spin_configs:
if spin_state not in self.spin_configs[motif][d_electrons]:
spin_state = self.spin_configs[motif][d_electrons]['default']
spin_config = self.spin_configs[motif][d_electrons][spin_state]
magnitude = JahnTellerAnalyzer.get_magnitude_of_effect_from_spin_config(motif,
spin_config)
else:
warnings.warn("No data for this species.")
return magnitude | Get magnitude of Jahn-Teller effect from provided species, spin state and motife.
:param species: e.g. Fe2+
:param spin_state (str): "high" or "low"
:param motif (str): "oct" or "tet"
:return (str): | Below is the the instruction that describes the task:
### Input:
Get magnitude of Jahn-Teller effect from provided species, spin state and motife.
:param species: e.g. Fe2+
:param spin_state (str): "high" or "low"
:param motif (str): "oct" or "tet"
:return (str):
### Response:
def get_magnitude_of_effect_from_species(self, species, spin_state, motif):
"""
Get magnitude of Jahn-Teller effect from provided species, spin state and motife.
:param species: e.g. Fe2+
:param spin_state (str): "high" or "low"
:param motif (str): "oct" or "tet"
:return (str):
"""
magnitude = "none"
sp = get_el_sp(species)
# has to be Specie; we need to know the oxidation state
if isinstance(sp, Specie) and sp.element.is_transition_metal:
d_electrons = self._get_number_of_d_electrons(sp)
if motif in self.spin_configs:
if spin_state not in self.spin_configs[motif][d_electrons]:
spin_state = self.spin_configs[motif][d_electrons]['default']
spin_config = self.spin_configs[motif][d_electrons][spin_state]
magnitude = JahnTellerAnalyzer.get_magnitude_of_effect_from_spin_config(motif,
spin_config)
else:
warnings.warn("No data for this species.")
return magnitude |
def handle_data(self, data, new_file=False, flush=True):
'''Handling of the data.
Parameters
----------
data : list, tuple
Data tuple of the format (data (np.array), last_time (float), curr_time (float), status (int))
'''
for i, module_id in enumerate(self._selected_modules):
if data[i] is None:
continue
self._raw_data_files[module_id].append(data_iterable=data[i], scan_parameters=self._scan_parameters[module_id]._asdict(), new_file=new_file, flush=flush) | Handling of the data.
Parameters
----------
data : list, tuple
Data tuple of the format (data (np.array), last_time (float), curr_time (float), status (int)) | Below is the the instruction that describes the task:
### Input:
Handling of the data.
Parameters
----------
data : list, tuple
Data tuple of the format (data (np.array), last_time (float), curr_time (float), status (int))
### Response:
def handle_data(self, data, new_file=False, flush=True):
'''Handling of the data.
Parameters
----------
data : list, tuple
Data tuple of the format (data (np.array), last_time (float), curr_time (float), status (int))
'''
for i, module_id in enumerate(self._selected_modules):
if data[i] is None:
continue
self._raw_data_files[module_id].append(data_iterable=data[i], scan_parameters=self._scan_parameters[module_id]._asdict(), new_file=new_file, flush=flush) |
def setBreakpoints( self, breakpoints ):
"""
Sets the breakpoints for this edit to the inputed list of breakpoints.
:param breakpoints | [<int>, ..]
"""
self.clearBreakpoints()
for breakpoint in breakpoints:
self.addBreakpoint(breakpoint) | Sets the breakpoints for this edit to the inputed list of breakpoints.
:param breakpoints | [<int>, ..] | Below is the the instruction that describes the task:
### Input:
Sets the breakpoints for this edit to the inputed list of breakpoints.
:param breakpoints | [<int>, ..]
### Response:
def setBreakpoints( self, breakpoints ):
"""
Sets the breakpoints for this edit to the inputed list of breakpoints.
:param breakpoints | [<int>, ..]
"""
self.clearBreakpoints()
for breakpoint in breakpoints:
self.addBreakpoint(breakpoint) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.