code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def users_update(self, user_id, **kwargs):
"""Update an existing user."""
return self.__call_api_post('users.update', userId=user_id, data=kwargs) | Update an existing user. | Below is the the instruction that describes the task:
### Input:
Update an existing user.
### Response:
def users_update(self, user_id, **kwargs):
"""Update an existing user."""
return self.__call_api_post('users.update', userId=user_id, data=kwargs) |
def _cartesian_product(self, first_specs, second_specs):
"""
Takes the Cartesian product of the specifications. Result will
contain N specifications where N = len(first_specs) *
len(second_specs) and keys are merged.
Example: [{'a':1},{'b':2}] * [{'c':3},{'d':4}] =
[{'a':... | Takes the Cartesian product of the specifications. Result will
contain N specifications where N = len(first_specs) *
len(second_specs) and keys are merged.
Example: [{'a':1},{'b':2}] * [{'c':3},{'d':4}] =
[{'a':1,'c':3},{'a':1,'d':4},{'b':2,'c':3},{'b':2,'d':4}] | Below is the the instruction that describes the task:
### Input:
Takes the Cartesian product of the specifications. Result will
contain N specifications where N = len(first_specs) *
len(second_specs) and keys are merged.
Example: [{'a':1},{'b':2}] * [{'c':3},{'d':4}] =
[{'a':1,'c':3}... |
def _shouldConnect(self, node):
"""
Check whether this node should initiate a connection to another node
:param node: the other node
:type node: Node
"""
return isinstance(node, TCPNode) and node not in self._preventConnectNodes and (self._selfIsReadonlyNode or self._se... | Check whether this node should initiate a connection to another node
:param node: the other node
:type node: Node | Below is the the instruction that describes the task:
### Input:
Check whether this node should initiate a connection to another node
:param node: the other node
:type node: Node
### Response:
def _shouldConnect(self, node):
"""
Check whether this node should initiate a connection ... |
def __lazy_migration(self, master_id):
"""
Creates a revision for a master id that didn't previously have a
revision, this allows you to easily turn on revisioning for a
collection that didn't previously allow for it.
:param master_id:
:returns: list of objects
"... | Creates a revision for a master id that didn't previously have a
revision, this allows you to easily turn on revisioning for a
collection that didn't previously allow for it.
:param master_id:
:returns: list of objects | Below is the the instruction that describes the task:
### Input:
Creates a revision for a master id that didn't previously have a
revision, this allows you to easily turn on revisioning for a
collection that didn't previously allow for it.
:param master_id:
:returns: list of objects... |
def pow(self, *args, **kwargs):
""" pow(other, rho=0, inplace=True)
Raises by the power of an *other* number instance. The correlation coefficient *rho* can be
configured per uncertainty when passed as a dict. When *inplace* is *False*, a new instance
is returned.
"""
ret... | pow(other, rho=0, inplace=True)
Raises by the power of an *other* number instance. The correlation coefficient *rho* can be
configured per uncertainty when passed as a dict. When *inplace* is *False*, a new instance
is returned. | Below is the the instruction that describes the task:
### Input:
pow(other, rho=0, inplace=True)
Raises by the power of an *other* number instance. The correlation coefficient *rho* can be
configured per uncertainty when passed as a dict. When *inplace* is *False*, a new instance
is returned... |
def list_licenses(service_instance=None):
'''
Lists all licenses on a vCenter.
service_instance
Service instance (vim.ServiceInstance) of the vCenter/ESXi host.
Default is None.
.. code-block:: bash
salt '*' vsphere.list_licenses
'''
log.trace('Retrieving all licenses'... | Lists all licenses on a vCenter.
service_instance
Service instance (vim.ServiceInstance) of the vCenter/ESXi host.
Default is None.
.. code-block:: bash
salt '*' vsphere.list_licenses | Below is the the instruction that describes the task:
### Input:
Lists all licenses on a vCenter.
service_instance
Service instance (vim.ServiceInstance) of the vCenter/ESXi host.
Default is None.
.. code-block:: bash
salt '*' vsphere.list_licenses
### Response:
def list_licenses... |
def get_comments_by_book(self, book_id):
"""Gets the list of ``Comments`` associated with a ``Book``.
arg: book_id (osid.id.Id): ``Id`` of a ``Book``
return: (osid.commenting.CommentList) - list of related comments
raise: NotFound - ``book_id`` is not found
raise: NullArgum... | Gets the list of ``Comments`` associated with a ``Book``.
arg: book_id (osid.id.Id): ``Id`` of a ``Book``
return: (osid.commenting.CommentList) - list of related comments
raise: NotFound - ``book_id`` is not found
raise: NullArgument - ``book_id`` is ``null``
raise: Operat... | Below is the the instruction that describes the task:
### Input:
Gets the list of ``Comments`` associated with a ``Book``.
arg: book_id (osid.id.Id): ``Id`` of a ``Book``
return: (osid.commenting.CommentList) - list of related comments
raise: NotFound - ``book_id`` is not found
... |
def _slug_strip(value, separator='-'):
"""
Cleans up a slug by removing slug separator characters that occur at the
beginning or end of a slug.
If an alternate separator is used, it will also replace any instances of
the default '-' separator with the new separator.
"""
separator = separato... | Cleans up a slug by removing slug separator characters that occur at the
beginning or end of a slug.
If an alternate separator is used, it will also replace any instances of
the default '-' separator with the new separator. | Below is the the instruction that describes the task:
### Input:
Cleans up a slug by removing slug separator characters that occur at the
beginning or end of a slug.
If an alternate separator is used, it will also replace any instances of
the default '-' separator with the new separator.
### Response: ... |
def tags_to_dict(self, tags=dict, prev_query=dict, duplicated: str = "rename"):
"""Reverse search tags dictionary to values as keys.
Useful to populate filters comboboxes for example.
:param dict tags: tags dictionary from a search request
:param dict prev_query: query parameters return... | Reverse search tags dictionary to values as keys.
Useful to populate filters comboboxes for example.
:param dict tags: tags dictionary from a search request
:param dict prev_query: query parameters returned after a search request. Typically `search.get("query")`.
:param str duplicated: ... | Below is the the instruction that describes the task:
### Input:
Reverse search tags dictionary to values as keys.
Useful to populate filters comboboxes for example.
:param dict tags: tags dictionary from a search request
:param dict prev_query: query parameters returned after a search requ... |
def _set_process_list(self, v, load=False):
"""
Setter method for process_list, mapped from YANG variable /cpu_state/process_list (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_process_list is considered as a private
method. Backends looking to populate ... | Setter method for process_list, mapped from YANG variable /cpu_state/process_list (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_process_list is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_... | Below is the the instruction that describes the task:
### Input:
Setter method for process_list, mapped from YANG variable /cpu_state/process_list (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_process_list is considered as a private
method. Backends looking... |
def _iteratively_analyze_function_features(self, all_funcs_completed=False):
"""
Iteratively analyze function features until a fixed point is reached.
:return: the "changes" dict
:rtype: dict
"""
changes = {
'functions_do_not_return': set(),
'fu... | Iteratively analyze function features until a fixed point is reached.
:return: the "changes" dict
:rtype: dict | Below is the the instruction that describes the task:
### Input:
Iteratively analyze function features until a fixed point is reached.
:return: the "changes" dict
:rtype: dict
### Response:
def _iteratively_analyze_function_features(self, all_funcs_completed=False):
"""
Iterativel... |
def read_undone_from_datastore(self, shard_id=None, num_shards=None):
"""Reads undone work from the datastore.
If shard_id and num_shards are specified then this method will attempt
to read undone work for shard with id shard_id. If no undone work was found
then it will try to read shard (shard_id+1) a... | Reads undone work from the datastore.
If shard_id and num_shards are specified then this method will attempt
to read undone work for shard with id shard_id. If no undone work was found
then it will try to read shard (shard_id+1) and so on until either found
shard with undone work or all shards are read... | Below is the the instruction that describes the task:
### Input:
Reads undone work from the datastore.
If shard_id and num_shards are specified then this method will attempt
to read undone work for shard with id shard_id. If no undone work was found
then it will try to read shard (shard_id+1) and so on... |
def train_model_from_args(args: argparse.Namespace):
"""
Just converts from an ``argparse.Namespace`` object to string paths.
"""
train_model_from_file(args.param_path,
args.serialization_dir,
args.overrides,
args.file_friendl... | Just converts from an ``argparse.Namespace`` object to string paths. | Below is the the instruction that describes the task:
### Input:
Just converts from an ``argparse.Namespace`` object to string paths.
### Response:
def train_model_from_args(args: argparse.Namespace):
"""
Just converts from an ``argparse.Namespace`` object to string paths.
"""
train_model_from_file... |
def follow_log(self):
"""Reads a logfile continuously and updates internal graph if new step is found"""
# Server needs to be up and running before starting sending POST requests
time.sleep(5)
try:
if self.remote:
logger.debug('Logfile in remote host!')
... | Reads a logfile continuously and updates internal graph if new step is found | Below is the the instruction that describes the task:
### Input:
Reads a logfile continuously and updates internal graph if new step is found
### Response:
def follow_log(self):
"""Reads a logfile continuously and updates internal graph if new step is found"""
# Server needs to be up and running be... |
def connect(self, port=None):
''' Open a serial connection to the arm. '''
if port is None:
self.port = search_for_port('/dev/ttyUSB*', 'ROBOFORTH\r\n',
'ROBOFORTH')
else:
self.port = port
if self.port is None:
... | Open a serial connection to the arm. | Below is the the instruction that describes the task:
### Input:
Open a serial connection to the arm.
### Response:
def connect(self, port=None):
''' Open a serial connection to the arm. '''
if port is None:
self.port = search_for_port('/dev/ttyUSB*', 'ROBOFORTH\r\n',
... |
def items(self):
'''Return a copy of the dictionary's list of ``(key, value)`` pairs.'''
return [(self.keys[x], self.values[x]) for x in range(len(self.keys))] | Return a copy of the dictionary's list of ``(key, value)`` pairs. | Below is the the instruction that describes the task:
### Input:
Return a copy of the dictionary's list of ``(key, value)`` pairs.
### Response:
def items(self):
'''Return a copy of the dictionary's list of ``(key, value)`` pairs.'''
return [(self.keys[x], self.values[x]) for x in range(len(self.ke... |
def ProductsForm(category, products):
''' Produces an appropriate _ProductsForm subclass for the given render
type. '''
# Each Category.RENDER_TYPE value has a subclass here.
cat = inventory.Category
RENDER_TYPES = {
cat.RENDER_TYPE_QUANTITY: _QuantityBoxProductsForm,
cat.RENDER_TYP... | Produces an appropriate _ProductsForm subclass for the given render
type. | Below is the the instruction that describes the task:
### Input:
Produces an appropriate _ProductsForm subclass for the given render
type.
### Response:
def ProductsForm(category, products):
''' Produces an appropriate _ProductsForm subclass for the given render
type. '''
# Each Category.RENDER_TY... |
def discover_single_case(self, module, case_attributes):
"""Find and load a single TestCase or TestCase method from a module.
Parameters
----------
module : module
The imported Python module containing the TestCase to be
loaded.
case_attributes : list
... | Find and load a single TestCase or TestCase method from a module.
Parameters
----------
module : module
The imported Python module containing the TestCase to be
loaded.
case_attributes : list
A list (length 1 or 2) of str. The first component must be... | Below is the the instruction that describes the task:
### Input:
Find and load a single TestCase or TestCase method from a module.
Parameters
----------
module : module
The imported Python module containing the TestCase to be
loaded.
case_attributes : list
... |
def is_tensor_on_canonical_device(self, tensor_name):
"""Whether the tensor is on the first (canonical) device.
Tensors not assigned to a device are assumed to be on all devices, including
the canonical device.
Args:
tensor_name: a string, name of a tensor in the graph.
Returns:
a boo... | Whether the tensor is on the first (canonical) device.
Tensors not assigned to a device are assumed to be on all devices, including
the canonical device.
Args:
tensor_name: a string, name of a tensor in the graph.
Returns:
a boolean indicating whether the tensor is on the first device. | Below is the the instruction that describes the task:
### Input:
Whether the tensor is on the first (canonical) device.
Tensors not assigned to a device are assumed to be on all devices, including
the canonical device.
Args:
tensor_name: a string, name of a tensor in the graph.
Returns:
... |
def real(self, stock_codes, prefix=False):
"""return specific stocks real quotation
:param stock_codes: stock code or list of stock code,
when prefix is True, stock code must start with sh/sz
:param prefix: if prefix i True, stock_codes must contain sh/sz market
flag.... | return specific stocks real quotation
:param stock_codes: stock code or list of stock code,
when prefix is True, stock code must start with sh/sz
:param prefix: if prefix i True, stock_codes must contain sh/sz market
flag. If prefix is False, index quotation can't return
... | Below is the the instruction that describes the task:
### Input:
return specific stocks real quotation
:param stock_codes: stock code or list of stock code,
when prefix is True, stock code must start with sh/sz
:param prefix: if prefix i True, stock_codes must contain sh/sz market
... |
def register_channel(im0, im1, scale=None, ch0angle=None,
chanapproxangle=None):
"""Register the images assuming they are channels
Parameters:
-----------
im0: 2d array
The first image
im1: 2d array
The second image
scale: number, optional
The scale ... | Register the images assuming they are channels
Parameters:
-----------
im0: 2d array
The first image
im1: 2d array
The second image
scale: number, optional
The scale difference if known
ch0angle: number, optional
The angle of the channel in the first image if kno... | Below is the the instruction that describes the task:
### Input:
Register the images assuming they are channels
Parameters:
-----------
im0: 2d array
The first image
im1: 2d array
The second image
scale: number, optional
The scale difference if known
ch0angle: number... |
def Eg(self, **kwargs):
'''
Returns the bandgap, Eg, in eV at a given
temperature, T, in K (default=300.).
'''
return min(self.Eg_Gamma(**kwargs),
self.Eg_L(**kwargs),
self.Eg_X(**kwargs)) | Returns the bandgap, Eg, in eV at a given
temperature, T, in K (default=300.). | Below is the the instruction that describes the task:
### Input:
Returns the bandgap, Eg, in eV at a given
temperature, T, in K (default=300.).
### Response:
def Eg(self, **kwargs):
'''
Returns the bandgap, Eg, in eV at a given
temperature, T, in K (default=300.).
'''
... |
def get(self, sid):
"""
Constructs a ShortCodeContext
:param sid: The unique string that identifies the resource
:returns: twilio.rest.proxy.v1.service.short_code.ShortCodeContext
:rtype: twilio.rest.proxy.v1.service.short_code.ShortCodeContext
"""
return ShortC... | Constructs a ShortCodeContext
:param sid: The unique string that identifies the resource
:returns: twilio.rest.proxy.v1.service.short_code.ShortCodeContext
:rtype: twilio.rest.proxy.v1.service.short_code.ShortCodeContext | Below is the the instruction that describes the task:
### Input:
Constructs a ShortCodeContext
:param sid: The unique string that identifies the resource
:returns: twilio.rest.proxy.v1.service.short_code.ShortCodeContext
:rtype: twilio.rest.proxy.v1.service.short_code.ShortCodeContext
### ... |
def data_validation(self, in_nc):
"""Check the necessary dimensions and variables in the
input netcdf data"""
data_nc = Dataset(in_nc)
for dim in self.dims_oi:
if dim not in data_nc.dimensions.keys():
data_nc.close()
raise Exception(self.error_... | Check the necessary dimensions and variables in the
input netcdf data | Below is the the instruction that describes the task:
### Input:
Check the necessary dimensions and variables in the
input netcdf data
### Response:
def data_validation(self, in_nc):
"""Check the necessary dimensions and variables in the
input netcdf data"""
data_nc = Dataset(in_nc)... |
def calc_anchors(preregistration_map, model, model_hemi,
scale=1, sigma=Ellipsis, radius_weight=0, field_sign_weight=0,
invert_rh_field_sign=False):
'''
calc_anchors is a calculator that creates a set of anchor instructions for a registration.
Required afferent parameters:... | calc_anchors is a calculator that creates a set of anchor instructions for a registration.
Required afferent parameters:
@ invert_rh_field_sign May be set to True (default is False) to indicate that the right
hemisphere's field signs will be incorrect relative to the model; this generally should be
... | Below is the the instruction that describes the task:
### Input:
calc_anchors is a calculator that creates a set of anchor instructions for a registration.
Required afferent parameters:
@ invert_rh_field_sign May be set to True (default is False) to indicate that the right
hemisphere's field sign... |
def stream(self, item, *, device_id=None, quality='hi', session_token=None):
"""Get MP3 stream of a podcast episode, library song, station_song, or store song.
Note:
Streaming requires a ``device_id`` from a valid, linked mobile device.
Parameters:
item (str): A podcast episode, library song, station_song... | Get MP3 stream of a podcast episode, library song, station_song, or store song.
Note:
Streaming requires a ``device_id`` from a valid, linked mobile device.
Parameters:
item (str): A podcast episode, library song, station_song, or store song.
A Google Music subscription is required to stream store songs... | Below is the the instruction that describes the task:
### Input:
Get MP3 stream of a podcast episode, library song, station_song, or store song.
Note:
Streaming requires a ``device_id`` from a valid, linked mobile device.
Parameters:
item (str): A podcast episode, library song, station_song, or store so... |
def _clear_inspect(self):
"""Clears inspect attributes when re-executing a pipeline"""
self.trace_info = defaultdict(list)
self.process_tags = {}
self.process_stats = {}
self.samples = []
self.stored_ids = []
self.stored_log_ids = []
self.time_start = Non... | Clears inspect attributes when re-executing a pipeline | Below is the the instruction that describes the task:
### Input:
Clears inspect attributes when re-executing a pipeline
### Response:
def _clear_inspect(self):
"""Clears inspect attributes when re-executing a pipeline"""
self.trace_info = defaultdict(list)
self.process_tags = {}
se... |
def _arm_track_read_lr_from_stack(self, irsb, function): # pylint:disable=unused-argument
"""
At the end of a basic block, simulate the very last instruction to see if the return address is read from the
stack and written in PC. If so, the jumpkind of this IRSB will be set to Ijk_Ret. For detai... | At the end of a basic block, simulate the very last instruction to see if the return address is read from the
stack and written in PC. If so, the jumpkind of this IRSB will be set to Ijk_Ret. For detailed explanations,
please see the documentation of _arm_track_lr_on_stack().
:param pyvex.IRSB ... | Below is the the instruction that describes the task:
### Input:
At the end of a basic block, simulate the very last instruction to see if the return address is read from the
stack and written in PC. If so, the jumpkind of this IRSB will be set to Ijk_Ret. For detailed explanations,
please see the d... |
def _init_security(self):
"""
Initialize a secure connection to the server.
"""
if not self._starttls():
raise SecurityError("Could not start TLS connection")
# _ssh_handshake() will throw an exception upon failure
self._ssl_handshake()
if not self._au... | Initialize a secure connection to the server. | Below is the the instruction that describes the task:
### Input:
Initialize a secure connection to the server.
### Response:
def _init_security(self):
"""
Initialize a secure connection to the server.
"""
if not self._starttls():
raise SecurityError("Could not start TLS ... |
def jinja2_output_as_string(impact_report, component_key):
"""Get a given jinja2 component output as string.
Useful for composing complex document.
:param impact_report: Impact Report that contains the component key.
:type impact_report: safe.report.impact_report.ImpactReport
:param component_key... | Get a given jinja2 component output as string.
Useful for composing complex document.
:param impact_report: Impact Report that contains the component key.
:type impact_report: safe.report.impact_report.ImpactReport
:param component_key: The key of the component to get the output from.
:type compo... | Below is the the instruction that describes the task:
### Input:
Get a given jinja2 component output as string.
Useful for composing complex document.
:param impact_report: Impact Report that contains the component key.
:type impact_report: safe.report.impact_report.ImpactReport
:param component_... |
def split_by_rand_pct(self, valid_pct:float=0.2, seed:int=None)->'ItemLists':
"Split the items randomly by putting `valid_pct` in the validation set, optional `seed` can be passed."
if valid_pct==0.: return self.split_none()
if seed is not None: np.random.seed(seed)
rand_idx = np.random.... | Split the items randomly by putting `valid_pct` in the validation set, optional `seed` can be passed. | Below is the the instruction that describes the task:
### Input:
Split the items randomly by putting `valid_pct` in the validation set, optional `seed` can be passed.
### Response:
def split_by_rand_pct(self, valid_pct:float=0.2, seed:int=None)->'ItemLists':
"Split the items randomly by putting `valid_pct`... |
def create_self_signed_cert():
"""Creates a self-signed certificate key pair."""
config_dir = Path(BaseDirectory.xdg_config_home) / 'xenon-grpc'
config_dir.mkdir(parents=True, exist_ok=True)
key_prefix = gethostname()
crt_file = config_dir / ('%s.crt' % key_prefix)
key_file = config_dir / ('%s.... | Creates a self-signed certificate key pair. | Below is the the instruction that describes the task:
### Input:
Creates a self-signed certificate key pair.
### Response:
def create_self_signed_cert():
"""Creates a self-signed certificate key pair."""
config_dir = Path(BaseDirectory.xdg_config_home) / 'xenon-grpc'
config_dir.mkdir(parents=True, exis... |
def Dependencies(tools):
"""
Takes in a list of tools that are being updated and returns any tools that
depend on linking to them
"""
dependencies = []
if tools:
path_dirs = PathDirs()
man = Template(join(path_dirs.meta_dir, 'plugin_manifest.cfg'))
for section in man.sect... | Takes in a list of tools that are being updated and returns any tools that
depend on linking to them | Below is the the instruction that describes the task:
### Input:
Takes in a list of tools that are being updated and returns any tools that
depend on linking to them
### Response:
def Dependencies(tools):
"""
Takes in a list of tools that are being updated and returns any tools that
depend on linki... |
def download_to_file(self, file_obj, client=None, start=None, end=None):
"""Download the contents of this blob into a file-like object.
.. note::
If the server-set property, :attr:`media_link`, is not yet
initialized, makes an additional API request to load it.
Downloadi... | Download the contents of this blob into a file-like object.
.. note::
If the server-set property, :attr:`media_link`, is not yet
initialized, makes an additional API request to load it.
Downloading a file that has been encrypted with a `customer-supplied`_
encryption key... | Below is the the instruction that describes the task:
### Input:
Download the contents of this blob into a file-like object.
.. note::
If the server-set property, :attr:`media_link`, is not yet
initialized, makes an additional API request to load it.
Downloading a file that ... |
def medias(self, timeframe=None):
"""Return a generator that yields only the refered post.
Yields:
dict: a media dictionary obtained from the given post.
Raises:
StopIteration: if the post does not fit the timeframe.
"""
info = self.info
if time... | Return a generator that yields only the refered post.
Yields:
dict: a media dictionary obtained from the given post.
Raises:
StopIteration: if the post does not fit the timeframe. | Below is the the instruction that describes the task:
### Input:
Return a generator that yields only the refered post.
Yields:
dict: a media dictionary obtained from the given post.
Raises:
StopIteration: if the post does not fit the timeframe.
### Response:
def medias(sel... |
def incr(self, key, value):
"""
Increment a key, if it exists, returns it's actual value, if it don't, return 0.
:param key: Key's name
:type key: six.string_types
:param value: Number to be incremented
:type value: int
:return: Actual value of the key on server
... | Increment a key, if it exists, returns it's actual value, if it don't, return 0.
:param key: Key's name
:type key: six.string_types
:param value: Number to be incremented
:type value: int
:return: Actual value of the key on server
:rtype: int | Below is the the instruction that describes the task:
### Input:
Increment a key, if it exists, returns it's actual value, if it don't, return 0.
:param key: Key's name
:type key: six.string_types
:param value: Number to be incremented
:type value: int
:return: Actual value ... |
def alter_partitions_with_environment_context(self, db_name, tbl_name, new_parts, environment_context):
"""
Parameters:
- db_name
- tbl_name
- new_parts
- environment_context
"""
self.send_alter_partitions_with_environment_context(db_name, tbl_name, new_parts, environment_context)
... | Parameters:
- db_name
- tbl_name
- new_parts
- environment_context | Below is the the instruction that describes the task:
### Input:
Parameters:
- db_name
- tbl_name
- new_parts
- environment_context
### Response:
def alter_partitions_with_environment_context(self, db_name, tbl_name, new_parts, environment_context):
"""
Parameters:
- db_name
-... |
def _migrate_pgpm_version(self, cur, version_pgpm_db, version_pgpm_script, migrate_or_leave):
"""
Enact migration script from one version of pgpm to another (newer)
:param cur:
:param migrate_or_leave: True if migrating, False if exiting
:return:
"""
migrations_f... | Enact migration script from one version of pgpm to another (newer)
:param cur:
:param migrate_or_leave: True if migrating, False if exiting
:return: | Below is the the instruction that describes the task:
### Input:
Enact migration script from one version of pgpm to another (newer)
:param cur:
:param migrate_or_leave: True if migrating, False if exiting
:return:
### Response:
def _migrate_pgpm_version(self, cur, version_pgpm_db, version_p... |
def _field_sort_name(cls, name):
"""Get a sort key for a field name that determines the order
fields should be written in.
Fields names are kept unchanged, unless they are instances of
:class:`DateItemField`, in which case `year`, `month`, and `day`
are replaced by `date0`, `dat... | Get a sort key for a field name that determines the order
fields should be written in.
Fields names are kept unchanged, unless they are instances of
:class:`DateItemField`, in which case `year`, `month`, and `day`
are replaced by `date0`, `date1`, and `date2`, respectively, to
m... | Below is the the instruction that describes the task:
### Input:
Get a sort key for a field name that determines the order
fields should be written in.
Fields names are kept unchanged, unless they are instances of
:class:`DateItemField`, in which case `year`, `month`, and `day`
are ... |
def finalize(self):
""" finalize any open file handles """
if self.rc_file:
self.rc_file.close()
if self.env_file:
self.env_file.close() | finalize any open file handles | Below is the the instruction that describes the task:
### Input:
finalize any open file handles
### Response:
def finalize(self):
""" finalize any open file handles """
if self.rc_file:
self.rc_file.close()
if self.env_file:
self.env_file.close() |
def get_dimensions_units(names):
"""Create dictionary of unit dimensions."""
dimensions_uni = {}
for name in names:
key = get_key_from_dimensions(names[name].dimensions)
dimensions_uni[key] = names[name]
plain_dimensions = [{'base': name, 'power': 1}]
key = get_key_from_dim... | Create dictionary of unit dimensions. | Below is the the instruction that describes the task:
### Input:
Create dictionary of unit dimensions.
### Response:
def get_dimensions_units(names):
"""Create dictionary of unit dimensions."""
dimensions_uni = {}
for name in names:
key = get_key_from_dimensions(names[name].dimensions)
... |
def _extract_shifted_mean_gauss(image, mask = slice(None), offset = None, sigma = 1, voxelspacing = None):
"""
Internal, single-image version of `shifted_mean_gauss`.
"""
# set voxel spacing
if voxelspacing is None:
voxelspacing = [1.] * image.ndim
# set offset
if offset is None:... | Internal, single-image version of `shifted_mean_gauss`. | Below is the the instruction that describes the task:
### Input:
Internal, single-image version of `shifted_mean_gauss`.
### Response:
def _extract_shifted_mean_gauss(image, mask = slice(None), offset = None, sigma = 1, voxelspacing = None):
"""
Internal, single-image version of `shifted_mean_gauss`.
"... |
def comments_nb_counts():
"""Get number of comments for the record `recid`."""
recid = request.view_args.get('recid')
if recid is None:
return
elif recid == 0:
return 0
else:
return CmtRECORDCOMMENT.count(*[
CmtRECORDCOMMENT.id_bibrec == recid,
CmtREC... | Get number of comments for the record `recid`. | Below is the the instruction that describes the task:
### Input:
Get number of comments for the record `recid`.
### Response:
def comments_nb_counts():
"""Get number of comments for the record `recid`."""
recid = request.view_args.get('recid')
if recid is None:
return
elif recid == 0:
... |
def from_file(cls, filename: str, run_number: int, continue_training: bool = False, seed: int = None,
device: str = 'cuda', params=None):
""" Create model config from file """
with open(filename, 'r') as fp:
model_config_contents = Parser.parse(fp)
project_config_p... | Create model config from file | Below is the the instruction that describes the task:
### Input:
Create model config from file
### Response:
def from_file(cls, filename: str, run_number: int, continue_training: bool = False, seed: int = None,
device: str = 'cuda', params=None):
""" Create model config from file """
... |
def wrap(self, image):
"""
Wraps a nested python sequence or PIL/pillow Image.
"""
if hasattr(image, 'size') and hasattr(image, 'convert'):
# Treat image as PIL/pillow Image object
self.width, self.height = image.size
array_type = ctypes.c_ubyte * 4 * ... | Wraps a nested python sequence or PIL/pillow Image. | Below is the the instruction that describes the task:
### Input:
Wraps a nested python sequence or PIL/pillow Image.
### Response:
def wrap(self, image):
"""
Wraps a nested python sequence or PIL/pillow Image.
"""
if hasattr(image, 'size') and hasattr(image, 'convert'):
... |
def shoelace_for_area(nodes):
r"""Compute an auxiliary "shoelace" sum used to compute area.
.. note::
This is a helper for :func:`_compute_area`.
Defining :math:`\left[i, j\right] = x_i y_j - y_i x_j` as a shoelace
term illuminates the name of this helper. On a degree one curve, this
funct... | r"""Compute an auxiliary "shoelace" sum used to compute area.
.. note::
This is a helper for :func:`_compute_area`.
Defining :math:`\left[i, j\right] = x_i y_j - y_i x_j` as a shoelace
term illuminates the name of this helper. On a degree one curve, this
function will return
.. math::
... | Below is the the instruction that describes the task:
### Input:
r"""Compute an auxiliary "shoelace" sum used to compute area.
.. note::
This is a helper for :func:`_compute_area`.
Defining :math:`\left[i, j\right] = x_i y_j - y_i x_j` as a shoelace
term illuminates the name of this helper. On... |
def toplevel_packages():
""" Get package list, without sub-packages.
"""
packages = set(easy.options.setup.packages)
for pkg in list(packages):
packages -= set(p for p in packages if str(p).startswith(pkg + '.'))
return list(sorted(packages)) | Get package list, without sub-packages. | Below is the the instruction that describes the task:
### Input:
Get package list, without sub-packages.
### Response:
def toplevel_packages():
""" Get package list, without sub-packages.
"""
packages = set(easy.options.setup.packages)
for pkg in list(packages):
packages -= set(p for p in p... |
def process_presence_events(self, event_data, token, opts):
'''
Check if any minions have connected or dropped.
Send a message to the client if they have.
'''
tag = event_data['tag']
event_info = event_data['data']
minions_detected = event_info['present']
... | Check if any minions have connected or dropped.
Send a message to the client if they have. | Below is the the instruction that describes the task:
### Input:
Check if any minions have connected or dropped.
Send a message to the client if they have.
### Response:
def process_presence_events(self, event_data, token, opts):
'''
Check if any minions have connected or dropped.
S... |
def is_equal_or_child_uri(parentUri, childUri):
"""Return True, if childUri is a child of parentUri or maps to the same resource.
Similar to <util.is_child_uri>_ , but this method also returns True, if parent
equals child. ('/a/b' is considered identical with '/a/b/').
"""
return (
parentU... | Return True, if childUri is a child of parentUri or maps to the same resource.
Similar to <util.is_child_uri>_ , but this method also returns True, if parent
equals child. ('/a/b' is considered identical with '/a/b/'). | Below is the the instruction that describes the task:
### Input:
Return True, if childUri is a child of parentUri or maps to the same resource.
Similar to <util.is_child_uri>_ , but this method also returns True, if parent
equals child. ('/a/b' is considered identical with '/a/b/').
### Response:
def is_... |
def get_facet_keys_as_list(self,field):
'''
:param str field: Name of facet field to retrieve keys from.
Similar to get_facet_values_as_list but returns the list of keys as a list instead.
Example::
>>> r.get_facet_keys_as_list('facet_test')
['Lorem', 'ipsum', '... | :param str field: Name of facet field to retrieve keys from.
Similar to get_facet_values_as_list but returns the list of keys as a list instead.
Example::
>>> r.get_facet_keys_as_list('facet_test')
['Lorem', 'ipsum', 'amet,', 'dolor', 'sit'] | Below is the the instruction that describes the task:
### Input:
:param str field: Name of facet field to retrieve keys from.
Similar to get_facet_values_as_list but returns the list of keys as a list instead.
Example::
>>> r.get_facet_keys_as_list('facet_test')
['Lorem', '... |
def extract_objects(self, fname, type_filter=None):
'''Extract objects from a source file
Args:
fname(str): Name of file to read from
type_filter (class, optional): Object class to filter results
Returns:
List of objects extracted from the file.
'''
objects = []
if fname in se... | Extract objects from a source file
Args:
fname(str): Name of file to read from
type_filter (class, optional): Object class to filter results
Returns:
List of objects extracted from the file. | Below is the the instruction that describes the task:
### Input:
Extract objects from a source file
Args:
fname(str): Name of file to read from
type_filter (class, optional): Object class to filter results
Returns:
List of objects extracted from the file.
### Response:
def extract_object... |
def _key_name(self): # type: () -> str
"""Return the key referring to this object
The default value is the lower case version of the class name
:rtype: str
"""
if self._key is not None:
return self._key
return self.__class__.__name__.lower() | Return the key referring to this object
The default value is the lower case version of the class name
:rtype: str | Below is the the instruction that describes the task:
### Input:
Return the key referring to this object
The default value is the lower case version of the class name
:rtype: str
### Response:
def _key_name(self): # type: () -> str
"""Return the key referring to this object
The ... |
def nearest_vertices(self, x, y, k=1, max_distance=np.inf ):
"""
Query the cKDtree for the nearest neighbours and Euclidean
distance from x,y points.
Returns 0, 0 if a cKDtree has not been constructed
(switch tree=True if you need this routine)
Parameters
------... | Query the cKDtree for the nearest neighbours and Euclidean
distance from x,y points.
Returns 0, 0 if a cKDtree has not been constructed
(switch tree=True if you need this routine)
Parameters
----------
x : 1D array of Cartesian x coordinates
y : 1D array of Ca... | Below is the the instruction that describes the task:
### Input:
Query the cKDtree for the nearest neighbours and Euclidean
distance from x,y points.
Returns 0, 0 if a cKDtree has not been constructed
(switch tree=True if you need this routine)
Parameters
----------
... |
def replace_nan( trainingset, replace_with = None ): # if replace_with = None, replaces with mean value
"""
Replace instanced of "not a number" with either the mean of the signal feature
or a specific value assigned by `replace_nan_with`
"""
training_data = np.array( [instance.features for instance ... | Replace instanced of "not a number" with either the mean of the signal feature
or a specific value assigned by `replace_nan_with` | Below is the the instruction that describes the task:
### Input:
Replace instanced of "not a number" with either the mean of the signal feature
or a specific value assigned by `replace_nan_with`
### Response:
def replace_nan( trainingset, replace_with = None ): # if replace_with = None, replaces with mean valu... |
def encodeBinaryData(dataArray, bitEncoding, compression):
"""Function to encode a ``numpy.array`` into a mzML byte array. This is the
inverse function of :func:`decodeBinaryData`.
:param dataArray: #TODO: docstring
:param bitEncoding: #TODO: docstring
:param compression: #TODO: docstring
:ret... | Function to encode a ``numpy.array`` into a mzML byte array. This is the
inverse function of :func:`decodeBinaryData`.
:param dataArray: #TODO: docstring
:param bitEncoding: #TODO: docstring
:param compression: #TODO: docstring
:returns: #TODO: docstring | Below is the the instruction that describes the task:
### Input:
Function to encode a ``numpy.array`` into a mzML byte array. This is the
inverse function of :func:`decodeBinaryData`.
:param dataArray: #TODO: docstring
:param bitEncoding: #TODO: docstring
:param compression: #TODO: docstring
:... |
def read(source, channels, start=None, end=None, scaled=None, type=None,
series_class=TimeSeries):
# pylint: disable=redefined-builtin
"""Read a dict of series from one or more GWF files
Parameters
----------
source : `str`, `list`
Source of data, any of the following:
- `... | Read a dict of series from one or more GWF files
Parameters
----------
source : `str`, `list`
Source of data, any of the following:
- `str` path of single data file,
- `str` path of cache file,
- `list` of paths.
channels : `~gwpy.detector.ChannelList`, `list`
... | Below is the the instruction that describes the task:
### Input:
Read a dict of series from one or more GWF files
Parameters
----------
source : `str`, `list`
Source of data, any of the following:
- `str` path of single data file,
- `str` path of cache file,
- `list` of... |
def distance_restraint_force(self, atoms, distances, strengths):
"""
Parameters
----------
atoms : tuple of tuple of int or str
Pair of atom indices to be restrained, with shape (n, 2),
like ((a1, a2), (a3, a4)). Items can be str compatible with MDTraj DSL.
... | Parameters
----------
atoms : tuple of tuple of int or str
Pair of atom indices to be restrained, with shape (n, 2),
like ((a1, a2), (a3, a4)). Items can be str compatible with MDTraj DSL.
distances : tuple of float
Equilibrium distances for each pair
... | Below is the the instruction that describes the task:
### Input:
Parameters
----------
atoms : tuple of tuple of int or str
Pair of atom indices to be restrained, with shape (n, 2),
like ((a1, a2), (a3, a4)). Items can be str compatible with MDTraj DSL.
distances : tu... |
def _add_hash(cls, attrs):
"""
Add a hash method to *cls*.
"""
cls.__hash__ = _make_hash(attrs, frozen=False, cache_hash=False)
return cls | Add a hash method to *cls*. | Below is the the instruction that describes the task:
### Input:
Add a hash method to *cls*.
### Response:
def _add_hash(cls, attrs):
"""
Add a hash method to *cls*.
"""
cls.__hash__ = _make_hash(attrs, frozen=False, cache_hash=False)
return cls |
def from_dict(data, ctx):
"""
Instantiate a new ClientConfigureTransaction from a dict (generally
from loading a JSON response). The data used to instantiate the
ClientConfigureTransaction is a shallow copy of the dict passed in,
with any complex child types instantiated appropri... | Instantiate a new ClientConfigureTransaction from a dict (generally
from loading a JSON response). The data used to instantiate the
ClientConfigureTransaction is a shallow copy of the dict passed in,
with any complex child types instantiated appropriately. | Below is the the instruction that describes the task:
### Input:
Instantiate a new ClientConfigureTransaction from a dict (generally
from loading a JSON response). The data used to instantiate the
ClientConfigureTransaction is a shallow copy of the dict passed in,
with any complex child type... |
def show_cimreferences(server_name, server, org_vm):
"""
Show info about the CIM_ReferencedProfile instances.
Goal. Clearly show what the various refs look like by using profile
names for the antecedent and dependent rather than instances.
"""
try:
ref_insts = server.conn.EnumerateInstan... | Show info about the CIM_ReferencedProfile instances.
Goal. Clearly show what the various refs look like by using profile
names for the antecedent and dependent rather than instances. | Below is the the instruction that describes the task:
### Input:
Show info about the CIM_ReferencedProfile instances.
Goal. Clearly show what the various refs look like by using profile
names for the antecedent and dependent rather than instances.
### Response:
def show_cimreferences(server_name, server, o... |
def row_is_filtered(self, row_subs, filters):
'''returns True if row should NOT be included according to filters'''
for filtername in filters:
filtervalue = filters[filtername]
if filtername in row_subs:
row_subs_value = row_subs[filtername]
if str... | returns True if row should NOT be included according to filters | Below is the the instruction that describes the task:
### Input:
returns True if row should NOT be included according to filters
### Response:
def row_is_filtered(self, row_subs, filters):
'''returns True if row should NOT be included according to filters'''
for filtername in filters:
f... |
def remove_cache(self, namespace, key=None):
"""Remove all cached values for the specified namespace,
optionally specifying a key"""
if key is None:
self.cursor.execute('DELETE FROM gauged_cache '
'WHERE namespace = %s', (namespace,))
else:
... | Remove all cached values for the specified namespace,
optionally specifying a key | Below is the the instruction that describes the task:
### Input:
Remove all cached values for the specified namespace,
optionally specifying a key
### Response:
def remove_cache(self, namespace, key=None):
"""Remove all cached values for the specified namespace,
optionally specifying a key"... |
def _wrap_command(cmds, cls, strict=True):
"""Wrap a setup command
Parameters
----------
cmds: list(str)
The names of the other commands to run prior to the command.
strict: boolean, optional
Whether to raise errors when a pre-command fails.
"""
class WrappedCommand(cls):
... | Wrap a setup command
Parameters
----------
cmds: list(str)
The names of the other commands to run prior to the command.
strict: boolean, optional
Whether to raise errors when a pre-command fails. | Below is the the instruction that describes the task:
### Input:
Wrap a setup command
Parameters
----------
cmds: list(str)
The names of the other commands to run prior to the command.
strict: boolean, optional
Whether to raise errors when a pre-command fails.
### Response:
def _wr... |
def setup(self, address, rack=0, slot=1, port=102):
"""Connects to a Siemens S7 PLC.
Connects to a Siemens S7 using the Snap7 library.
See [the snap7 documentation](http://snap7.sourceforge.net/) for
supported models and more details.
It's not currently possible to query the de... | Connects to a Siemens S7 PLC.
Connects to a Siemens S7 using the Snap7 library.
See [the snap7 documentation](http://snap7.sourceforge.net/) for
supported models and more details.
It's not currently possible to query the device for available pins,
so `available_pins()` returns ... | Below is the the instruction that describes the task:
### Input:
Connects to a Siemens S7 PLC.
Connects to a Siemens S7 using the Snap7 library.
See [the snap7 documentation](http://snap7.sourceforge.net/) for
supported models and more details.
It's not currently possible to query ... |
def _process_string(self, char):
""" Process a character as part of a string token.
"""
if char in self.QUOTES:
# end of quoted string:
# 1) quote must match original quote
# 2) not escaped quote (e.g. "hey there" vs "hey there\")
# 3) a... | Process a character as part of a string token. | Below is the the instruction that describes the task:
### Input:
Process a character as part of a string token.
### Response:
def _process_string(self, char):
""" Process a character as part of a string token.
"""
if char in self.QUOTES:
# end of quoted string:
... |
def load_data(fname, **kwargs):
"""Load example data"""
fname = get_file(fname)
if fname.suffix == ".lzma":
return load_tar_lzma_data(fname)
elif fname.suffix == ".zip":
return load_zip_data(fname, **kwargs) | Load example data | Below is the the instruction that describes the task:
### Input:
Load example data
### Response:
def load_data(fname, **kwargs):
"""Load example data"""
fname = get_file(fname)
if fname.suffix == ".lzma":
return load_tar_lzma_data(fname)
elif fname.suffix == ".zip":
return load_zip_... |
def cli(log_level):
"""Manage tmux sessions.
Pass the "--help" argument to any command to see detailed help.
See detailed documentation and examples at:
http://tmuxp.readthedocs.io/en/latest/"""
try:
has_minimum_version()
except TmuxCommandNotFound:
click.echo('tmux not found. t... | Manage tmux sessions.
Pass the "--help" argument to any command to see detailed help.
See detailed documentation and examples at:
http://tmuxp.readthedocs.io/en/latest/ | Below is the the instruction that describes the task:
### Input:
Manage tmux sessions.
Pass the "--help" argument to any command to see detailed help.
See detailed documentation and examples at:
http://tmuxp.readthedocs.io/en/latest/
### Response:
def cli(log_level):
"""Manage tmux sessions.
... |
def read_sps(path):
"""Read a LibSVM file line-by-line.
Args:
path (str): A path to the LibSVM file to read.
Yields:
data (list) and target (int).
"""
for line in open(path):
# parse x
xs = line.rstrip().split(' ')
yield xs[1:], int(xs[0]) | Read a LibSVM file line-by-line.
Args:
path (str): A path to the LibSVM file to read.
Yields:
data (list) and target (int). | Below is the the instruction that describes the task:
### Input:
Read a LibSVM file line-by-line.
Args:
path (str): A path to the LibSVM file to read.
Yields:
data (list) and target (int).
### Response:
def read_sps(path):
"""Read a LibSVM file line-by-line.
Args:
path (s... |
def quadratic(a, b, c=None):
""" x^2 + ax + b = 0 (or ax^2 + bx + c = 0)
By substituting x = y-t and t = a/2, the equation reduces to
y^2 + (b-t^2) = 0
which has easy solution
y = +/- sqrt(t^2-b)
"""
if c: # (ax^2 + bx + c = 0)
a, b = b / float(a), c / float(a)
t = a ... | x^2 + ax + b = 0 (or ax^2 + bx + c = 0)
By substituting x = y-t and t = a/2, the equation reduces to
y^2 + (b-t^2) = 0
which has easy solution
y = +/- sqrt(t^2-b) | Below is the the instruction that describes the task:
### Input:
x^2 + ax + b = 0 (or ax^2 + bx + c = 0)
By substituting x = y-t and t = a/2, the equation reduces to
y^2 + (b-t^2) = 0
which has easy solution
y = +/- sqrt(t^2-b)
### Response:
def quadratic(a, b, c=None):
""" x^2 + ax + ... |
def activate_comfort(self):
"""Activates the comfort temperature."""
value = struct.pack('B', PROP_COMFORT)
self._conn.make_request(PROP_WRITE_HANDLE, value) | Activates the comfort temperature. | Below is the the instruction that describes the task:
### Input:
Activates the comfort temperature.
### Response:
def activate_comfort(self):
"""Activates the comfort temperature."""
value = struct.pack('B', PROP_COMFORT)
self._conn.make_request(PROP_WRITE_HANDLE, value) |
def check(self, dsm, simplicity_factor=2, **kwargs):
"""
Check economy of mechanism.
As first abstraction, number of dependencies between two modules
< 2 * the number of modules
(dependencies to the framework are NOT considered).
Args:
dsm (:class:`DesignStr... | Check economy of mechanism.
As first abstraction, number of dependencies between two modules
< 2 * the number of modules
(dependencies to the framework are NOT considered).
Args:
dsm (:class:`DesignStructureMatrix`): the DSM to check.
simplicity_factor (int): si... | Below is the the instruction that describes the task:
### Input:
Check economy of mechanism.
As first abstraction, number of dependencies between two modules
< 2 * the number of modules
(dependencies to the framework are NOT considered).
Args:
dsm (:class:`DesignStructu... |
def _terminate_service(self):
"""Force termination of running service.
Disconnect queues, end queue feeder threads.
Wait for service process to clear, drop all references."""
with self.__lock:
if self._service:
self._service.terminate()
if self._pi... | Force termination of running service.
Disconnect queues, end queue feeder threads.
Wait for service process to clear, drop all references. | Below is the the instruction that describes the task:
### Input:
Force termination of running service.
Disconnect queues, end queue feeder threads.
Wait for service process to clear, drop all references.
### Response:
def _terminate_service(self):
"""Force termination of running service.
... |
def save_file(self):
"""Saves the notebook to a file"""
with open(self.write_file, 'w') as out_nb:
json.dump(self.work_notebook, out_nb, indent=2) | Saves the notebook to a file | Below is the the instruction that describes the task:
### Input:
Saves the notebook to a file
### Response:
def save_file(self):
"""Saves the notebook to a file"""
with open(self.write_file, 'w') as out_nb:
json.dump(self.work_notebook, out_nb, indent=2) |
def Exists(path):
'''
:rtype: bool
:returns:
True if the path already exists (either a file or a directory)
.. seealso:: FTP LIMITATIONS at this module's doc for performance issues information
'''
from six.moves.urllib.parse import urlparse
path_url = urlparse(path)
# Handle lo... | :rtype: bool
:returns:
True if the path already exists (either a file or a directory)
.. seealso:: FTP LIMITATIONS at this module's doc for performance issues information | Below is the the instruction that describes the task:
### Input:
:rtype: bool
:returns:
True if the path already exists (either a file or a directory)
.. seealso:: FTP LIMITATIONS at this module's doc for performance issues information
### Response:
def Exists(path):
'''
:rtype: bool
:... |
def h2i(self, pkt, seconds):
"""Convert the number of seconds since 1-Jan-70 UTC to the packed
representation."""
if seconds is None:
seconds = 0
tmp_short = (seconds >> 32) & 0xFFFF
tmp_int = seconds & 0xFFFFFFFF
return struct.pack("!HI", tmp_short, tmp... | Convert the number of seconds since 1-Jan-70 UTC to the packed
representation. | Below is the the instruction that describes the task:
### Input:
Convert the number of seconds since 1-Jan-70 UTC to the packed
representation.
### Response:
def h2i(self, pkt, seconds):
"""Convert the number of seconds since 1-Jan-70 UTC to the packed
representation."""
if s... |
def plot_optimum_prediction_fraction_correct_cutoffs_over_range(self, analysis_set, min_stability_classication_x_cutoff, max_stability_classication_x_cutoff, suppress_plot = False, analysis_file_prefix = None, verbose = True):
'''Plots the optimum cutoff for the predictions to maximize the fraction correct metr... | Plots the optimum cutoff for the predictions to maximize the fraction correct metric over a range of experimental cutoffs.
Returns the average scalar corresponding to the best value of fraction correct over a range of cutoff values for the experimental cutoffs. | Below is the the instruction that describes the task:
### Input:
Plots the optimum cutoff for the predictions to maximize the fraction correct metric over a range of experimental cutoffs.
Returns the average scalar corresponding to the best value of fraction correct over a range of cutoff values for the ... |
def set_denotation(onnx_model, input_name, denotation, target_opset, dimension_denotation=None):
'''
Set input type denotation and dimension denotation.
Type denotation is a feature in ONNX 1.2.1 that let's the model specify the content of a tensor (e.g. IMAGE or AUDIO).
This information can be used by... | Set input type denotation and dimension denotation.
Type denotation is a feature in ONNX 1.2.1 that let's the model specify the content of a tensor (e.g. IMAGE or AUDIO).
This information can be used by the backend. One example where it is useful is in images: Whenever data is bound to
a tensor with type d... | Below is the the instruction that describes the task:
### Input:
Set input type denotation and dimension denotation.
Type denotation is a feature in ONNX 1.2.1 that let's the model specify the content of a tensor (e.g. IMAGE or AUDIO).
This information can be used by the backend. One example where it is us... |
def to_gltf(self, scene):
"""
Export a transforms as the 'nodes' section of a GLTF dict.
Flattens tree.
Returns
--------
gltf : dict
with keys:
'nodes': list of dicts
"""
# geometry is an OrderedDict
# {geometry key : i... | Export a transforms as the 'nodes' section of a GLTF dict.
Flattens tree.
Returns
--------
gltf : dict
with keys:
'nodes': list of dicts | Below is the the instruction that describes the task:
### Input:
Export a transforms as the 'nodes' section of a GLTF dict.
Flattens tree.
Returns
--------
gltf : dict
with keys:
'nodes': list of dicts
### Response:
def to_gltf(self, scene):
"""
... |
def create_supervised_tbptt_trainer(
model,
optimizer,
loss_fn,
tbtt_step,
dim=0,
device=None,
non_blocking=False,
prepare_batch=_prepare_batch
):
"""Create a trainer for truncated backprop through time supervised models.
Training recurrent model on long sequences is computation... | Create a trainer for truncated backprop through time supervised models.
Training recurrent model on long sequences is computationally intensive as
it requires to process the whole sequence before getting a gradient.
However, when the training loss is computed over many outputs
(`X to many <https://karp... | Below is the the instruction that describes the task:
### Input:
Create a trainer for truncated backprop through time supervised models.
Training recurrent model on long sequences is computationally intensive as
it requires to process the whole sequence before getting a gradient.
However, when the trai... |
def read_next_maf( file, species_to_lengths=None, parse_e_rows=False ):
"""
Read the next MAF block from `file` and return as an `Alignment`
instance. If `parse_i_rows` is true, empty components will be created
when e rows are encountered.
"""
alignment = Alignment(species_to_lengths=species_t... | Read the next MAF block from `file` and return as an `Alignment`
instance. If `parse_i_rows` is true, empty components will be created
when e rows are encountered. | Below is the the instruction that describes the task:
### Input:
Read the next MAF block from `file` and return as an `Alignment`
instance. If `parse_i_rows` is true, empty components will be created
when e rows are encountered.
### Response:
def read_next_maf( file, species_to_lengths=None, parse_e_rows... |
def mark(self, lineno, count=1):
"""Mark a given source line as executed count times.
Multiple calls to mark for the same lineno add up.
"""
self.sourcelines[lineno] = self.sourcelines.get(lineno, 0) + count | Mark a given source line as executed count times.
Multiple calls to mark for the same lineno add up. | Below is the the instruction that describes the task:
### Input:
Mark a given source line as executed count times.
Multiple calls to mark for the same lineno add up.
### Response:
def mark(self, lineno, count=1):
"""Mark a given source line as executed count times.
Multiple calls to mark ... |
def disconnect(self):
"""
Disconnects from Telegram.
If the event loop is already running, this method returns a
coroutine that you should await on your own code; otherwise
the loop is ran until said coroutine completes.
"""
if self._loop.is_running():
... | Disconnects from Telegram.
If the event loop is already running, this method returns a
coroutine that you should await on your own code; otherwise
the loop is ran until said coroutine completes. | Below is the the instruction that describes the task:
### Input:
Disconnects from Telegram.
If the event loop is already running, this method returns a
coroutine that you should await on your own code; otherwise
the loop is ran until said coroutine completes.
### Response:
def disconnect(s... |
def _handle_wikilink(self, token):
"""Handle a case where a wikilink is at the head of the tokens."""
title = None
self._push()
while self._tokens:
token = self._tokens.pop()
if isinstance(token, tokens.WikilinkSeparator):
title = self._pop()
... | Handle a case where a wikilink is at the head of the tokens. | Below is the the instruction that describes the task:
### Input:
Handle a case where a wikilink is at the head of the tokens.
### Response:
def _handle_wikilink(self, token):
"""Handle a case where a wikilink is at the head of the tokens."""
title = None
self._push()
while self._tok... |
def somatic(args):
"""
%prog somatic ref.fasta *.bam > somatic.sh
Useful to identify somatic mutations in each sample compared to all other
samples. Script using SPEEDSEQ-somatic will be written to stdout.
"""
p = OptionParser(somatic.__doc__)
opts, args = p.parse_args(args)
if len(arg... | %prog somatic ref.fasta *.bam > somatic.sh
Useful to identify somatic mutations in each sample compared to all other
samples. Script using SPEEDSEQ-somatic will be written to stdout. | Below is the the instruction that describes the task:
### Input:
%prog somatic ref.fasta *.bam > somatic.sh
Useful to identify somatic mutations in each sample compared to all other
samples. Script using SPEEDSEQ-somatic will be written to stdout.
### Response:
def somatic(args):
"""
%prog somatic... |
def goal_show(self, goal_id, **kwargs):
"https://developer.zendesk.com/rest_api/docs/chat/goals#get-goal"
api_path = "/api/v2/goals/{goal_id}"
api_path = api_path.format(goal_id=goal_id)
return self.call(api_path, **kwargs) | https://developer.zendesk.com/rest_api/docs/chat/goals#get-goal | Below is the the instruction that describes the task:
### Input:
https://developer.zendesk.com/rest_api/docs/chat/goals#get-goal
### Response:
def goal_show(self, goal_id, **kwargs):
"https://developer.zendesk.com/rest_api/docs/chat/goals#get-goal"
api_path = "/api/v2/goals/{goal_id}"
api_p... |
def get_color_func(self, word):
"""Returns a single_color_func associated with the word"""
try:
color_func = next(
color_func for (color_func, words) in self.color_func_to_words
if word in words)
except StopIteration:
color_func = self.defa... | Returns a single_color_func associated with the word | Below is the the instruction that describes the task:
### Input:
Returns a single_color_func associated with the word
### Response:
def get_color_func(self, word):
"""Returns a single_color_func associated with the word"""
try:
color_func = next(
color_func for (color_fu... |
def GetAttribute(self, identifier):
"""Retrieves a specific attribute.
Args:
identifier (str): identifier of the attribute within the volume.
Returns:
VolumeAttribute: volume attribute or None if not available.
"""
if not self._is_parsed:
self._Parse()
self._is_parsed = Tru... | Retrieves a specific attribute.
Args:
identifier (str): identifier of the attribute within the volume.
Returns:
VolumeAttribute: volume attribute or None if not available. | Below is the the instruction that describes the task:
### Input:
Retrieves a specific attribute.
Args:
identifier (str): identifier of the attribute within the volume.
Returns:
VolumeAttribute: volume attribute or None if not available.
### Response:
def GetAttribute(self, identifier):
""... |
def preprocess(self, images, augmenter, parents):
"""
A function to be called before the augmentation of images starts (per augmenter).
Returns
-------
(N,H,W,C) ndarray or (N,H,W) ndarray or list of (H,W,C) ndarray or list of (H,W) ndarray
The input images, optional... | A function to be called before the augmentation of images starts (per augmenter).
Returns
-------
(N,H,W,C) ndarray or (N,H,W) ndarray or list of (H,W,C) ndarray or list of (H,W) ndarray
The input images, optionally modified. | Below is the the instruction that describes the task:
### Input:
A function to be called before the augmentation of images starts (per augmenter).
Returns
-------
(N,H,W,C) ndarray or (N,H,W) ndarray or list of (H,W,C) ndarray or list of (H,W) ndarray
The input images, optionall... |
def send(self, smtp=None, **kw):
"""
Sends message.
:param smtp: When set, parameters from this dictionary overwrite
options from config. See `emails.Message.send` for more information.
:param kwargs: Parameters for `emails.Message.send`
:return: Response ... | Sends message.
:param smtp: When set, parameters from this dictionary overwrite
options from config. See `emails.Message.send` for more information.
:param kwargs: Parameters for `emails.Message.send`
:return: Response objects from emails backend.
For def... | Below is the the instruction that describes the task:
### Input:
Sends message.
:param smtp: When set, parameters from this dictionary overwrite
options from config. See `emails.Message.send` for more information.
:param kwargs: Parameters for `emails.Message.send`
:r... |
def to_unicode(s):
"""Return the object as unicode (only matters for Python 2.x).
If s is already Unicode, return s as is.
Otherwise, assume that s is UTF-8 encoded, and convert to Unicode.
:param (basestring) s: a str, unicode or other basestring object
:return (unicode): the object as unicode
... | Return the object as unicode (only matters for Python 2.x).
If s is already Unicode, return s as is.
Otherwise, assume that s is UTF-8 encoded, and convert to Unicode.
:param (basestring) s: a str, unicode or other basestring object
:return (unicode): the object as unicode | Below is the the instruction that describes the task:
### Input:
Return the object as unicode (only matters for Python 2.x).
If s is already Unicode, return s as is.
Otherwise, assume that s is UTF-8 encoded, and convert to Unicode.
:param (basestring) s: a str, unicode or other basestring object
... |
def community_post_comment_show(self, post_id, id, **kwargs):
"https://developer.zendesk.com/rest_api/docs/help_center/post_comments#show-comment"
api_path = "/api/v2/community/posts/{post_id}/comments/{id}.json"
api_path = api_path.format(post_id=post_id, id=id)
return self.call(api_pat... | https://developer.zendesk.com/rest_api/docs/help_center/post_comments#show-comment | Below is the the instruction that describes the task:
### Input:
https://developer.zendesk.com/rest_api/docs/help_center/post_comments#show-comment
### Response:
def community_post_comment_show(self, post_id, id, **kwargs):
"https://developer.zendesk.com/rest_api/docs/help_center/post_comments#show-comment... |
def evaluate(self, values):
''' Evaluates the expression to an integer
values is a dictionnary that associates n-bit variables to integer
values. Every symbolic variables used in the expression must be
represented.
For instance, let x and y 4-bit variables, and e = x+y:
... | Evaluates the expression to an integer
values is a dictionnary that associates n-bit variables to integer
values. Every symbolic variables used in the expression must be
represented.
For instance, let x and y 4-bit variables, and e = x+y:
>>> mba = MBA(4)
>>> x = mba.... | Below is the the instruction that describes the task:
### Input:
Evaluates the expression to an integer
values is a dictionnary that associates n-bit variables to integer
values. Every symbolic variables used in the expression must be
represented.
For instance, let x and y 4-bit v... |
def stdev(requestContext, seriesList, points, windowTolerance=0.1):
"""
Takes one metric or a wildcard seriesList followed by an integer N.
Draw the Standard Deviation of all metrics passed for the past N
datapoints. If the ratio of null points in the window is greater than
windowTolerance, skip the... | Takes one metric or a wildcard seriesList followed by an integer N.
Draw the Standard Deviation of all metrics passed for the past N
datapoints. If the ratio of null points in the window is greater than
windowTolerance, skip the calculation. The default for windowTolerance is
0.1 (up to 10% of points in... | Below is the the instruction that describes the task:
### Input:
Takes one metric or a wildcard seriesList followed by an integer N.
Draw the Standard Deviation of all metrics passed for the past N
datapoints. If the ratio of null points in the window is greater than
windowTolerance, skip the calculatio... |
def rmdir(self, target_directory, allow_symlink=False):
"""Remove a leaf Fake directory.
Args:
target_directory: (str) Name of directory to remove.
allow_symlink: (bool) if `target_directory` is a symlink,
the function just returns, otherwise it raises (Posix onl... | Remove a leaf Fake directory.
Args:
target_directory: (str) Name of directory to remove.
allow_symlink: (bool) if `target_directory` is a symlink,
the function just returns, otherwise it raises (Posix only)
Raises:
OSError: if target_directory does n... | Below is the the instruction that describes the task:
### Input:
Remove a leaf Fake directory.
Args:
target_directory: (str) Name of directory to remove.
allow_symlink: (bool) if `target_directory` is a symlink,
the function just returns, otherwise it raises (Posix o... |
def _find_valid_name(self, initial_name):
'''Finds a non-colliding name by optional postfixing'''
return vaex.utils.find_valid_name(initial_name, used=self.get_column_names(hidden=True)) | Finds a non-colliding name by optional postfixing | Below is the the instruction that describes the task:
### Input:
Finds a non-colliding name by optional postfixing
### Response:
def _find_valid_name(self, initial_name):
'''Finds a non-colliding name by optional postfixing'''
return vaex.utils.find_valid_name(initial_name, used=self.get_column_nam... |
def _get_register_specs(bit_labels):
"""Get the number and size of unique registers from bit_labels list.
Args:
bit_labels (list): this list is of the form::
[['reg1', 0], ['reg1', 1], ['reg2', 0]]
which indicates a register named "reg1" of size 2
and a register na... | Get the number and size of unique registers from bit_labels list.
Args:
bit_labels (list): this list is of the form::
[['reg1', 0], ['reg1', 1], ['reg2', 0]]
which indicates a register named "reg1" of size 2
and a register named "reg2" of size 1. This is the
... | Below is the the instruction that describes the task:
### Input:
Get the number and size of unique registers from bit_labels list.
Args:
bit_labels (list): this list is of the form::
[['reg1', 0], ['reg1', 1], ['reg2', 0]]
which indicates a register named "reg1" of size 2
... |
def extend(dset, array, **attrs):
"""
Extend an extensible dataset with an array of a compatible dtype.
:param dset: an h5py dataset
:param array: an array of length L
:returns: the total length of the dataset (i.e. initial length + L)
"""
length = len(dset)
if len(array) == 0:
... | Extend an extensible dataset with an array of a compatible dtype.
:param dset: an h5py dataset
:param array: an array of length L
:returns: the total length of the dataset (i.e. initial length + L) | Below is the the instruction that describes the task:
### Input:
Extend an extensible dataset with an array of a compatible dtype.
:param dset: an h5py dataset
:param array: an array of length L
:returns: the total length of the dataset (i.e. initial length + L)
### Response:
def extend(dset, array, *... |
def _message(self, beacon_config, invert_hello=False):
""" Overridden :meth:`.WBeaconGouverneurMessenger._message` method. Appends encoded host group names
to requests and responses.
:param beacon_config: beacon configuration
:return: bytes
"""
m = WBeaconGouverneurMessenger._message(self, beacon_config, i... | Overridden :meth:`.WBeaconGouverneurMessenger._message` method. Appends encoded host group names
to requests and responses.
:param beacon_config: beacon configuration
:return: bytes | Below is the the instruction that describes the task:
### Input:
Overridden :meth:`.WBeaconGouverneurMessenger._message` method. Appends encoded host group names
to requests and responses.
:param beacon_config: beacon configuration
:return: bytes
### Response:
def _message(self, beacon_config, invert_hello=... |
def writeFile(filename, data):
"""
Writes data to a file
"""
with open(filename, 'wb') as f:
f.write(data.encode('utf-8')) | Writes data to a file | Below is the the instruction that describes the task:
### Input:
Writes data to a file
### Response:
def writeFile(filename, data):
"""
Writes data to a file
"""
with open(filename, 'wb') as f:
f.write(data.encode('utf-8')) |
def main(host, port, timeout, itimeout, qsize, backlog, maxtry, bsize, verbose, logfile=None, logcfgfile=None, cfgfile=None):
"""Simple python implementation of a socks5 proxy server. """
dict_cfg = {}
if cfgfile:
dict_cfg = app_config.get_config_by_file(cfgfile)
def get_param(key, param, defa... | Simple python implementation of a socks5 proxy server. | Below is the the instruction that describes the task:
### Input:
Simple python implementation of a socks5 proxy server.
### Response:
def main(host, port, timeout, itimeout, qsize, backlog, maxtry, bsize, verbose, logfile=None, logcfgfile=None, cfgfile=None):
"""Simple python implementation of a socks5 proxy s... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.