code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def stop(self, timeout=None):
"""
Stop the producer (async mode). Blocks until async thread completes.
"""
if timeout is not None:
log.warning('timeout argument to stop() is deprecated - '
'it will be removed in future release')
if not self.as... | Stop the producer (async mode). Blocks until async thread completes. | Below is the the instruction that describes the task:
### Input:
Stop the producer (async mode). Blocks until async thread completes.
### Response:
def stop(self, timeout=None):
"""
Stop the producer (async mode). Blocks until async thread completes.
"""
if timeout is not None:
... |
def get_planes(im, squeeze=True):
r"""
Extracts three planar images from the volumetric image, one for each
principle axis. The planes are taken from the middle of the domain.
Parameters
----------
im : ND-array
The volumetric image from which the 3 planar images are to be obtained
... | r"""
Extracts three planar images from the volumetric image, one for each
principle axis. The planes are taken from the middle of the domain.
Parameters
----------
im : ND-array
The volumetric image from which the 3 planar images are to be obtained
squeeze : boolean, optional
... | Below is the the instruction that describes the task:
### Input:
r"""
Extracts three planar images from the volumetric image, one for each
principle axis. The planes are taken from the middle of the domain.
Parameters
----------
im : ND-array
The volumetric image from which the 3 plana... |
def ends_with(self, suffix):
"""Asserts that val is string or iterable and ends with suffix."""
if suffix is None:
raise TypeError('given suffix arg must not be none')
if isinstance(self.val, str_types):
if not isinstance(suffix, str_types):
raise TypeErro... | Asserts that val is string or iterable and ends with suffix. | Below is the the instruction that describes the task:
### Input:
Asserts that val is string or iterable and ends with suffix.
### Response:
def ends_with(self, suffix):
"""Asserts that val is string or iterable and ends with suffix."""
if suffix is None:
raise TypeError('given suffix ar... |
def __skaters(self, tab):
"""
Constructs dictionary of players on the ice in the provided table at time of play.
:param tab: RTSS table of the skaters and goalie on at the time of the play
:rtype: dictionary, key = player number, value = [position, name]
"""
res ... | Constructs dictionary of players on the ice in the provided table at time of play.
:param tab: RTSS table of the skaters and goalie on at the time of the play
:rtype: dictionary, key = player number, value = [position, name] | Below is the the instruction that describes the task:
### Input:
Constructs dictionary of players on the ice in the provided table at time of play.
:param tab: RTSS table of the skaters and goalie on at the time of the play
:rtype: dictionary, key = player number, value = [position, name]
### Respon... |
def from_bytes(cls, mybytes, byteorder='big', signed=False):
"""
Return the integer represented by the given array of bytes.
The mybytes argument must either support the buffer protocol or be an
iterable object producing bytes. Bytes and bytearray are examples of
built-in objec... | Return the integer represented by the given array of bytes.
The mybytes argument must either support the buffer protocol or be an
iterable object producing bytes. Bytes and bytearray are examples of
built-in objects that support the buffer protocol.
The byteorder argument determines t... | Below is the the instruction that describes the task:
### Input:
Return the integer represented by the given array of bytes.
The mybytes argument must either support the buffer protocol or be an
iterable object producing bytes. Bytes and bytearray are examples of
built-in objects that supp... |
def purge_node(self, node_id, remove_definition=False, sandbox=None):
"""
Purges a node (collection of streams)
:param node_id: The node identifier
:param remove_definition: Whether to remove the stream definition as well
:param sandbox: The sandbox
:return: None
... | Purges a node (collection of streams)
:param node_id: The node identifier
:param remove_definition: Whether to remove the stream definition as well
:param sandbox: The sandbox
:return: None | Below is the the instruction that describes the task:
### Input:
Purges a node (collection of streams)
:param node_id: The node identifier
:param remove_definition: Whether to remove the stream definition as well
:param sandbox: The sandbox
:return: None
### Response:
def purge_nod... |
def com_google_fonts_check_name_no_copyright_on_description(ttFont):
"""Description strings in the name table must not contain copyright info."""
failed = False
for name in ttFont['name'].names:
if 'opyright' in name.string.decode(name.getEncoding())\
and name.nameID == NameID.DESCRIPTION:
failed... | Description strings in the name table must not contain copyright info. | Below is the the instruction that describes the task:
### Input:
Description strings in the name table must not contain copyright info.
### Response:
def com_google_fonts_check_name_no_copyright_on_description(ttFont):
"""Description strings in the name table must not contain copyright info."""
failed = False
... |
def new_dataset(data, identifier=None):
"""Initialize a new RT-DC dataset
Parameters
----------
data:
can be one of the following:
- dict
- .tdms file
- .rtdc file
- subclass of `RTDCBase`
(will create a hierarchy child)
identifier: str
A u... | Initialize a new RT-DC dataset
Parameters
----------
data:
can be one of the following:
- dict
- .tdms file
- .rtdc file
- subclass of `RTDCBase`
(will create a hierarchy child)
identifier: str
A unique identifier for this dataset. If set to `N... | Below is the the instruction that describes the task:
### Input:
Initialize a new RT-DC dataset
Parameters
----------
data:
can be one of the following:
- dict
- .tdms file
- .rtdc file
- subclass of `RTDCBase`
(will create a hierarchy child)
ident... |
def from_string(self, value):
"""Convert string to enum value."""
if not isinstance(value, basestring):
raise ValueError('expected string value: ' + str(type(value)))
self.test_value(value)
return value | Convert string to enum value. | Below is the the instruction that describes the task:
### Input:
Convert string to enum value.
### Response:
def from_string(self, value):
"""Convert string to enum value."""
if not isinstance(value, basestring):
raise ValueError('expected string value: ' + str(type(value)))
sel... |
def html_page_for_render_items(bundle, docs_json, render_items, title, template=None, template_variables={}):
''' Render an HTML page from a template and Bokeh render items.
Args:
bundle (tuple):
a tuple containing (bokehjs, bokehcss)
docs_json (JSON-like):
Serialized B... | Render an HTML page from a template and Bokeh render items.
Args:
bundle (tuple):
a tuple containing (bokehjs, bokehcss)
docs_json (JSON-like):
Serialized Bokeh Document
render_items (RenderItems)
Specific items to render from the document and where
... | Below is the the instruction that describes the task:
### Input:
Render an HTML page from a template and Bokeh render items.
Args:
bundle (tuple):
a tuple containing (bokehjs, bokehcss)
docs_json (JSON-like):
Serialized Bokeh Document
render_items (RenderItems)... |
def p_block(self, p):
'block : BEGIN block_statements END'
p[0] = Block(p[2], lineno=p.lineno(1))
p.set_lineno(0, p.lineno(1)) | block : BEGIN block_statements END | Below is the the instruction that describes the task:
### Input:
block : BEGIN block_statements END
### Response:
def p_block(self, p):
'block : BEGIN block_statements END'
p[0] = Block(p[2], lineno=p.lineno(1))
p.set_lineno(0, p.lineno(1)) |
def edit_pool(self, auth, spec, attr):
""" Update pool given by `spec` with attributes `attr`.
* `auth` [BaseAuth]
AAA options.
* `spec` [pool_spec]
Specifies what pool to edit.
* `attr` [pool_attr]
Attributes to update and the... | Update pool given by `spec` with attributes `attr`.
* `auth` [BaseAuth]
AAA options.
* `spec` [pool_spec]
Specifies what pool to edit.
* `attr` [pool_attr]
Attributes to update and their new values.
This is the documentati... | Below is the the instruction that describes the task:
### Input:
Update pool given by `spec` with attributes `attr`.
* `auth` [BaseAuth]
AAA options.
* `spec` [pool_spec]
Specifies what pool to edit.
* `attr` [pool_attr]
Attributes... |
def get_hierarchy_traversal_session(self, proxy):
"""Gets the ``OsidSession`` associated with the hierarchy traversal service.
arg: proxy (osid.proxy.Proxy): a proxy
return: (osid.hierarchy.HierarchyTraversalSession) - a
``HierarchyTraversalSession``
raise: NullArgum... | Gets the ``OsidSession`` associated with the hierarchy traversal service.
arg: proxy (osid.proxy.Proxy): a proxy
return: (osid.hierarchy.HierarchyTraversalSession) - a
``HierarchyTraversalSession``
raise: NullArgument - ``proxy`` is ``null``
raise: OperationFailed -... | Below is the the instruction that describes the task:
### Input:
Gets the ``OsidSession`` associated with the hierarchy traversal service.
arg: proxy (osid.proxy.Proxy): a proxy
return: (osid.hierarchy.HierarchyTraversalSession) - a
``HierarchyTraversalSession``
raise: N... |
def _list_fields(self):
"""
Get the current settings of the model. The keys depend on the type of
model.
Returns
-------
out : list
A list of fields that can be queried using the ``get`` method.
"""
response = self.__proxy__.list_fields()
... | Get the current settings of the model. The keys depend on the type of
model.
Returns
-------
out : list
A list of fields that can be queried using the ``get`` method. | Below is the the instruction that describes the task:
### Input:
Get the current settings of the model. The keys depend on the type of
model.
Returns
-------
out : list
A list of fields that can be queried using the ``get`` method.
### Response:
def _list_fields(self):
... |
def purge_db(self):
"""
Clear all matching our user_id.
"""
with self.engine.begin() as db:
purge_user(db, self.user_id) | Clear all matching our user_id. | Below is the the instruction that describes the task:
### Input:
Clear all matching our user_id.
### Response:
def purge_db(self):
"""
Clear all matching our user_id.
"""
with self.engine.begin() as db:
purge_user(db, self.user_id) |
def cal_pst(self, v):
"""
calculate static pressure at 300 K.
:param v: unit-cell volume in A^3
:return: static pressure at t_ref (=300 K) in GPa
"""
params = self._set_params(self.params_st)
return func_st[self.eqn_st](v, *params) | calculate static pressure at 300 K.
:param v: unit-cell volume in A^3
:return: static pressure at t_ref (=300 K) in GPa | Below is the the instruction that describes the task:
### Input:
calculate static pressure at 300 K.
:param v: unit-cell volume in A^3
:return: static pressure at t_ref (=300 K) in GPa
### Response:
def cal_pst(self, v):
"""
calculate static pressure at 300 K.
:param v: un... |
def page_size(self) -> int:
"""
A property that returns how large a page is, calculated from the paginator properties.
If this exceeds `max_page_size`, an exception is raised upon instantiation.
"""
page_count = self.page_count
return self.paginator.max_size + len(f'\nPa... | A property that returns how large a page is, calculated from the paginator properties.
If this exceeds `max_page_size`, an exception is raised upon instantiation. | Below is the the instruction that describes the task:
### Input:
A property that returns how large a page is, calculated from the paginator properties.
If this exceeds `max_page_size`, an exception is raised upon instantiation.
### Response:
def page_size(self) -> int:
"""
A property that ... |
def pass_condition(b, test, a):
"""
Generic test function used by Scout2 / AWS recipes
.
:param b: Value to be tested against
:param test: Name of the test case to run
:param a: Value t... | Generic test function used by Scout2 / AWS recipes
.
:param b: Value to be tested against
:param test: Name of the test case to run
:param a: Value to be tested
:return: ... | Below is the the instruction that describes the task:
### Input:
Generic test function used by Scout2 / AWS recipes
.
:param b: Value to be tested against
:param test: Name of the test case to run
:param a: ... |
def _leave_handler(self, event):
"""Callback for :obj:`<Leave>` event on marker, to set normal options"""
iid = self.current_iid
if iid is None or self.active == iid:
return
self.update_state(iid, "normal") | Callback for :obj:`<Leave>` event on marker, to set normal options | Below is the the instruction that describes the task:
### Input:
Callback for :obj:`<Leave>` event on marker, to set normal options
### Response:
def _leave_handler(self, event):
"""Callback for :obj:`<Leave>` event on marker, to set normal options"""
iid = self.current_iid
if iid is None o... |
def http_basic_auth(request):
"""
Extracts the credentials of a client using HTTP Basic Auth.
Expects the ``client_id`` to be the username and the ``client_secret`` to
be the password part of the Authorization header.
:param request: The incoming request
:type request: oauth2.web.Request
... | Extracts the credentials of a client using HTTP Basic Auth.
Expects the ``client_id`` to be the username and the ``client_secret`` to
be the password part of the Authorization header.
:param request: The incoming request
:type request: oauth2.web.Request
:return: A tuple in the format of (<CLIENT... | Below is the the instruction that describes the task:
### Input:
Extracts the credentials of a client using HTTP Basic Auth.
Expects the ``client_id`` to be the username and the ``client_secret`` to
be the password part of the Authorization header.
:param request: The incoming request
:type reques... |
def set_layer(self, layer=None, keywords=None):
"""Set layer and update UI accordingly.
:param layer: A QgsVectorLayer.
:type layer: QgsVectorLayer
:param keywords: Keywords for the layer.
:type keywords: dict, None
"""
if self.field_mapping_widget is not None:
... | Set layer and update UI accordingly.
:param layer: A QgsVectorLayer.
:type layer: QgsVectorLayer
:param keywords: Keywords for the layer.
:type keywords: dict, None | Below is the the instruction that describes the task:
### Input:
Set layer and update UI accordingly.
:param layer: A QgsVectorLayer.
:type layer: QgsVectorLayer
:param keywords: Keywords for the layer.
:type keywords: dict, None
### Response:
def set_layer(self, layer=None, keywo... |
def db_for_write(self, model, **hints):
"""
If the app has its own database, use it for writes
"""
if model._meta.app_label in self._apps:
return getattr(model, '_db_alias', model._meta.app_label)
return None | If the app has its own database, use it for writes | Below is the the instruction that describes the task:
### Input:
If the app has its own database, use it for writes
### Response:
def db_for_write(self, model, **hints):
"""
If the app has its own database, use it for writes
"""
if model._meta.app_label in self._apps:
re... |
def parse_file_entities(filename, entities=None, config=None,
include_unmatched=False):
""" Parse the passed filename for entity/value pairs.
Args:
filename (str): The filename to parse for entity values
entities (list): An optional list of Entity instances to use in
... | Parse the passed filename for entity/value pairs.
Args:
filename (str): The filename to parse for entity values
entities (list): An optional list of Entity instances to use in
extraction. If passed, the config argument is ignored.
config (str, Config, list): One or more Config o... | Below is the the instruction that describes the task:
### Input:
Parse the passed filename for entity/value pairs.
Args:
filename (str): The filename to parse for entity values
entities (list): An optional list of Entity instances to use in
extraction. If passed, the config argument... |
def imagetransformer_b12l_4h_uncond_dr03_tpu():
"""TPU related small model."""
hparams = imagetransformer_b12l_4h_b256_uncond_dr03_tpu()
hparams.learning_rate = 0.2
hparams.learning_rate_warmup_steps = 4000
hparams.layer_preprocess_sequence = "none"
hparams.layer_postprocess_sequence = "dan"
hparams.layer... | TPU related small model. | Below is the the instruction that describes the task:
### Input:
TPU related small model.
### Response:
def imagetransformer_b12l_4h_uncond_dr03_tpu():
"""TPU related small model."""
hparams = imagetransformer_b12l_4h_b256_uncond_dr03_tpu()
hparams.learning_rate = 0.2
hparams.learning_rate_warmup_steps = 4... |
def isfile(self, path, follow_symlinks=True):
"""Determine if path identifies a regular file.
Args:
path: Path to filesystem object.
Returns:
`True` if path points to a regular file (following symlinks).
Raises:
TypeError: if path is None.
"... | Determine if path identifies a regular file.
Args:
path: Path to filesystem object.
Returns:
`True` if path points to a regular file (following symlinks).
Raises:
TypeError: if path is None. | Below is the the instruction that describes the task:
### Input:
Determine if path identifies a regular file.
Args:
path: Path to filesystem object.
Returns:
`True` if path points to a regular file (following symlinks).
Raises:
TypeError: if path is Non... |
def _palette_cmd(self, event):
"""Respond to user click on a palette item."""
label = event.widget
label.master.focus_set()
label.master.configure(relief="sunken")
r, g, b = self.winfo_rgb(label.cget("background"))
r = round2(r * 255 / 65535)
g = round2(g * 255 / ... | Respond to user click on a palette item. | Below is the the instruction that describes the task:
### Input:
Respond to user click on a palette item.
### Response:
def _palette_cmd(self, event):
"""Respond to user click on a palette item."""
label = event.widget
label.master.focus_set()
label.master.configure(relief="sunken")... |
def get(self, requirement):
"""Find packages matching ``requirement``.
:param requirement: Requirement to match against repository packages.
:type requirement: `str` or :class:`.Requirement`
:returns: :func:`list` of matching :class:`.Package` objects.
"""
if isinstance... | Find packages matching ``requirement``.
:param requirement: Requirement to match against repository packages.
:type requirement: `str` or :class:`.Requirement`
:returns: :func:`list` of matching :class:`.Package` objects. | Below is the the instruction that describes the task:
### Input:
Find packages matching ``requirement``.
:param requirement: Requirement to match against repository packages.
:type requirement: `str` or :class:`.Requirement`
:returns: :func:`list` of matching :class:`.Package` objects.
### ... |
def copy_attrs(obj1, obj2, attrs):
"""
Allows copy a list of attributes from object2 to object1.
Useful for copy ccs attributes to fragment
"""
for attr in attrs:
value = getattr(obj2, attr) if hasattr(obj2, attr) else None
if value is None and isinstance(obj2, dict) and attr in ob... | Allows copy a list of attributes from object2 to object1.
Useful for copy ccs attributes to fragment | Below is the the instruction that describes the task:
### Input:
Allows copy a list of attributes from object2 to object1.
Useful for copy ccs attributes to fragment
### Response:
def copy_attrs(obj1, obj2, attrs):
"""
Allows copy a list of attributes from object2 to object1.
Useful for copy ccs at... |
def sound_touch_stop(self, call_params):
"""REST Remove soundtouch audio effects on a Call
"""
path = '/' + self.api_version + '/SoundTouchStop/'
method = 'POST'
return self.request(path, method, call_params) | REST Remove soundtouch audio effects on a Call | Below is the the instruction that describes the task:
### Input:
REST Remove soundtouch audio effects on a Call
### Response:
def sound_touch_stop(self, call_params):
"""REST Remove soundtouch audio effects on a Call
"""
path = '/' + self.api_version + '/SoundTouchStop/'
method = 'P... |
def multpasswordbox(msg="Fill in values for the fields."
, title=" "
, fields=tuple()
,values=tuple()
):
r"""
Same interface as multenterbox. But in multpassword box,
the last of the fields is assumed to be a password, and
is masked with asterisks.
Example
=======
Here is ... | r"""
Same interface as multenterbox. But in multpassword box,
the last of the fields is assumed to be a password, and
is masked with asterisks.
Example
=======
Here is some example code, that shows how values returned from
multpasswordbox can be checked for validity before they are accept... | Below is the the instruction that describes the task:
### Input:
r"""
Same interface as multenterbox. But in multpassword box,
the last of the fields is assumed to be a password, and
is masked with asterisks.
Example
=======
Here is some example code, that shows how values returned from
... |
def state_get(self, block_id, addresses):
'''Returns a list of address/data pairs (str, bytes)'''
block = self._get_blocks([block_id.hex()])[0]
block_header = BlockHeader()
block_header.ParseFromString(block.header)
try:
state_view = self._state_view_factory.create_v... | Returns a list of address/data pairs (str, bytes) | Below is the the instruction that describes the task:
### Input:
Returns a list of address/data pairs (str, bytes)
### Response:
def state_get(self, block_id, addresses):
'''Returns a list of address/data pairs (str, bytes)'''
block = self._get_blocks([block_id.hex()])[0]
block_header = Blo... |
def get(self, key, sort_key):
""" Get an element in dictionary """
key = self.prefixed('{}:{}'.format(key, sort_key))
self.logger.debug('Storage - get {}'.format(key))
if key not in self.cache.keys():
return None
return self.cache[key] | Get an element in dictionary | Below is the the instruction that describes the task:
### Input:
Get an element in dictionary
### Response:
def get(self, key, sort_key):
""" Get an element in dictionary """
key = self.prefixed('{}:{}'.format(key, sort_key))
self.logger.debug('Storage - get {}'.format(key))
if key ... |
def hide_routemap_holder_route_map_content_match_vrf(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
hide_routemap_holder = ET.SubElement(config, "hide-routemap-holder", xmlns="urn:brocade.com:mgmt:brocade-ip-policy")
route_map = ET.SubElement(hide_route... | Auto Generated Code | Below is the the instruction that describes the task:
### Input:
Auto Generated Code
### Response:
def hide_routemap_holder_route_map_content_match_vrf(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
hide_routemap_holder = ET.SubElement(config, "hide-routem... |
def _ensure_valid_index(self, value):
"""
Ensure that if we don't have an index, that we can create one from the
passed value.
"""
# GH5632, make sure that we are a Series convertible
if not len(self.index) and is_list_like(value):
try:
value =... | Ensure that if we don't have an index, that we can create one from the
passed value. | Below is the the instruction that describes the task:
### Input:
Ensure that if we don't have an index, that we can create one from the
passed value.
### Response:
def _ensure_valid_index(self, value):
"""
Ensure that if we don't have an index, that we can create one from the
passed... |
def validate(self, input):
"""
Validate the given input value against this L{Field} definition.
@param input: An input value supposedly serializable by this L{Field}.
@raises ValidationError: If the value is not serializable or fails to
be validated by the additional valida... | Validate the given input value against this L{Field} definition.
@param input: An input value supposedly serializable by this L{Field}.
@raises ValidationError: If the value is not serializable or fails to
be validated by the additional validator. | Below is the the instruction that describes the task:
### Input:
Validate the given input value against this L{Field} definition.
@param input: An input value supposedly serializable by this L{Field}.
@raises ValidationError: If the value is not serializable or fails to
be validated by... |
def get_cached(location, **kwargs):
"""
Simple wrapper that adds Django caching support to 'geocoder.get()'.
"""
result = cache.get(location)
# Result is not cached or wrong
if not result or not result.ok:
result = geocoder.get(location, **kwargs)
if result.ok:
cache... | Simple wrapper that adds Django caching support to 'geocoder.get()'. | Below is the the instruction that describes the task:
### Input:
Simple wrapper that adds Django caching support to 'geocoder.get()'.
### Response:
def get_cached(location, **kwargs):
"""
Simple wrapper that adds Django caching support to 'geocoder.get()'.
"""
result = cache.get(location)
# Re... |
def compute_fitness_cdf(chromosomes, ga):
"""
Return a list of fitness-weighted cumulative probabilities for a set of chromosomes.
chromosomes: chromosomes to use for fitness-based calculations
ga: ``algorithms.BaseGeneticAlgorithm`` used to obtain fitness values using its ``eval_fitness`` method... | Return a list of fitness-weighted cumulative probabilities for a set of chromosomes.
chromosomes: chromosomes to use for fitness-based calculations
ga: ``algorithms.BaseGeneticAlgorithm`` used to obtain fitness values using its ``eval_fitness`` method
return: list of fitness-weighted cumulative... | Below is the the instruction that describes the task:
### Input:
Return a list of fitness-weighted cumulative probabilities for a set of chromosomes.
chromosomes: chromosomes to use for fitness-based calculations
ga: ``algorithms.BaseGeneticAlgorithm`` used to obtain fitness values using its ``eval_f... |
def check_thickness(s):
"""
Check and parse thickness specs as either a single [s] or a list of [s,s,s,...]
"""
s = check_1d(s, "thickness")
if any(map(lambda d: d <= 0, s)):
raise Exception('Thickness cannot be 0 or negative')
return s | Check and parse thickness specs as either a single [s] or a list of [s,s,s,...] | Below is the the instruction that describes the task:
### Input:
Check and parse thickness specs as either a single [s] or a list of [s,s,s,...]
### Response:
def check_thickness(s):
"""
Check and parse thickness specs as either a single [s] or a list of [s,s,s,...]
"""
s = check_1d(s, "thickness"... |
def ListFiles(directory):
'''
Lists the files in the given directory
:type directory: unicode | unicode
:param directory:
A directory or URL
:rtype: list(unicode) | list(unicode)
:returns:
List of filenames/directories found in the given directory.
Returns None if the g... | Lists the files in the given directory
:type directory: unicode | unicode
:param directory:
A directory or URL
:rtype: list(unicode) | list(unicode)
:returns:
List of filenames/directories found in the given directory.
Returns None if the given directory does not exists.
... | Below is the the instruction that describes the task:
### Input:
Lists the files in the given directory
:type directory: unicode | unicode
:param directory:
A directory or URL
:rtype: list(unicode) | list(unicode)
:returns:
List of filenames/directories found in the given directory... |
def access_storage_rm(name, yes, **kwargs):
"""
Remove ACL for the specified collection.
If none is specified - removes ACL for all collections.
"""
if name is None:
if not yes:
click.confirm('Are you sure you want to remove all ACL?', abort=True)
ctx = Context(**kwargs)
... | Remove ACL for the specified collection.
If none is specified - removes ACL for all collections. | Below is the the instruction that describes the task:
### Input:
Remove ACL for the specified collection.
If none is specified - removes ACL for all collections.
### Response:
def access_storage_rm(name, yes, **kwargs):
"""
Remove ACL for the specified collection.
If none is specified - removes A... |
def template_shebang(template, renderers, default, blacklist, whitelist, input_data):
'''
Check the template shebang line and return the list of renderers specified
in the pipe.
Example shebang lines::
#!yaml_jinja
#!yaml_mako
#!mako|yaml
#!jinja|yaml
#!jinja|mako|yaml
... | Check the template shebang line and return the list of renderers specified
in the pipe.
Example shebang lines::
#!yaml_jinja
#!yaml_mako
#!mako|yaml
#!jinja|yaml
#!jinja|mako|yaml
#!mako|yaml|stateconf
#!jinja|yaml|stateconf
#!mako|yaml_odict
#!mako|yaml_o... | Below is the the instruction that describes the task:
### Input:
Check the template shebang line and return the list of renderers specified
in the pipe.
Example shebang lines::
#!yaml_jinja
#!yaml_mako
#!mako|yaml
#!jinja|yaml
#!jinja|mako|yaml
#!mako|yaml|stateconf
... |
def _get_simple_dtype_and_shape(self, colnum, rows=None):
"""
When reading a single column, we want the basic data
type and the shape of the array.
for scalar columns, shape is just nrows, otherwise
it is (nrows, dim1, dim2)
Note if rows= is sent and only a single row i... | When reading a single column, we want the basic data
type and the shape of the array.
for scalar columns, shape is just nrows, otherwise
it is (nrows, dim1, dim2)
Note if rows= is sent and only a single row is requested,
the shape will be (dim2,dim2) | Below is the the instruction that describes the task:
### Input:
When reading a single column, we want the basic data
type and the shape of the array.
for scalar columns, shape is just nrows, otherwise
it is (nrows, dim1, dim2)
Note if rows= is sent and only a single row is request... |
def log_likelihood(C, T):
r"""Log-likelihood of the count matrix given a transition matrix.
Parameters
----------
C : (M, M) ndarray or scipy.sparse matrix
Count matrix
T : (M, M) ndarray orscipy.sparse matrix
Transition matrix
Returns
-------
logL : float
Log-l... | r"""Log-likelihood of the count matrix given a transition matrix.
Parameters
----------
C : (M, M) ndarray or scipy.sparse matrix
Count matrix
T : (M, M) ndarray orscipy.sparse matrix
Transition matrix
Returns
-------
logL : float
Log-likelihood of the count matrix
... | Below is the the instruction that describes the task:
### Input:
r"""Log-likelihood of the count matrix given a transition matrix.
Parameters
----------
C : (M, M) ndarray or scipy.sparse matrix
Count matrix
T : (M, M) ndarray orscipy.sparse matrix
Transition matrix
Returns
... |
def update(self, fallback_actions=values.unset):
"""
Update the AssistantFallbackActionsInstance
:param dict fallback_actions: The fallback_actions
:returns: Updated AssistantFallbackActionsInstance
:rtype: twilio.rest.preview.understand.assistant.assistant_fallback_actions.Ass... | Update the AssistantFallbackActionsInstance
:param dict fallback_actions: The fallback_actions
:returns: Updated AssistantFallbackActionsInstance
:rtype: twilio.rest.preview.understand.assistant.assistant_fallback_actions.AssistantFallbackActionsInstance | Below is the the instruction that describes the task:
### Input:
Update the AssistantFallbackActionsInstance
:param dict fallback_actions: The fallback_actions
:returns: Updated AssistantFallbackActionsInstance
:rtype: twilio.rest.preview.understand.assistant.assistant_fallback_actions.Ass... |
def remove_password(entry, username=None):
"""
Removes the password for the specific user in the user's keychain.
:param entry: The entry in the keychain. This is a caller specific key.
:param username: The username whose password is to be removed. Default is the current user.
"""
if use... | Removes the password for the specific user in the user's keychain.
:param entry: The entry in the keychain. This is a caller specific key.
:param username: The username whose password is to be removed. Default is the current user. | Below is the the instruction that describes the task:
### Input:
Removes the password for the specific user in the user's keychain.
:param entry: The entry in the keychain. This is a caller specific key.
:param username: The username whose password is to be removed. Default is the current user.
### Res... |
def remove_root_repository(self, repository_id):
"""Removes a root repository.
arg: repository_id (osid.id.Id): the ``Id`` of a repository
raise: NotFound - ``repository_id`` not a root
raise: NullArgument - ``repository_id`` is ``null``
raise: OperationFailed - unable to ... | Removes a root repository.
arg: repository_id (osid.id.Id): the ``Id`` of a repository
raise: NotFound - ``repository_id`` not a root
raise: NullArgument - ``repository_id`` is ``null``
raise: OperationFailed - unable to complete request
raise: PermissionDenied - authoriz... | Below is the the instruction that describes the task:
### Input:
Removes a root repository.
arg: repository_id (osid.id.Id): the ``Id`` of a repository
raise: NotFound - ``repository_id`` not a root
raise: NullArgument - ``repository_id`` is ``null``
raise: OperationFailed - u... |
def user_context(self, worker_ctx, exc_info):
""" Merge any user context to include in the sentry payload.
Extracts user identifiers from the worker context data by matching
context keys with
"""
user = {}
for key in worker_ctx.context_data:
for matcher in se... | Merge any user context to include in the sentry payload.
Extracts user identifiers from the worker context data by matching
context keys with | Below is the the instruction that describes the task:
### Input:
Merge any user context to include in the sentry payload.
Extracts user identifiers from the worker context data by matching
context keys with
### Response:
def user_context(self, worker_ctx, exc_info):
""" Merge any user cont... |
def _get_entry(self, entry, entry_tree):
'''Helper function for retrieving a particular entry from the prefix trees'''
for e in entry_tree[entry.filename]:
if entry == e:
return e | Helper function for retrieving a particular entry from the prefix trees | Below is the the instruction that describes the task:
### Input:
Helper function for retrieving a particular entry from the prefix trees
### Response:
def _get_entry(self, entry, entry_tree):
'''Helper function for retrieving a particular entry from the prefix trees'''
for e in entry_tree[entry.fil... |
def add_idle(self, callback, *args, **kwds):
"""Add an idle callback.
An idle callback can return True, False or None. These mean:
- None: remove the callback (don't reschedule)
- False: the callback did no work; reschedule later
- True: the callback did some work; reschedule soon
If the cal... | Add an idle callback.
An idle callback can return True, False or None. These mean:
- None: remove the callback (don't reschedule)
- False: the callback did no work; reschedule later
- True: the callback did some work; reschedule soon
If the callback raises an exception, the traceback is logged a... | Below is the the instruction that describes the task:
### Input:
Add an idle callback.
An idle callback can return True, False or None. These mean:
- None: remove the callback (don't reschedule)
- False: the callback did no work; reschedule later
- True: the callback did some work; reschedule soo... |
def fit(self, x, y):
"""
:param x: 2D np.ndarray (n_instances, n_features) should be categorical data, must be of type int
:param y: 1D np.ndarray (n_instances, ) labels
:return:
"""
verbose = self.verbose
# Create temporary files
data_file = tempfile.Name... | :param x: 2D np.ndarray (n_instances, n_features) should be categorical data, must be of type int
:param y: 1D np.ndarray (n_instances, ) labels
:return: | Below is the the instruction that describes the task:
### Input:
:param x: 2D np.ndarray (n_instances, n_features) should be categorical data, must be of type int
:param y: 1D np.ndarray (n_instances, ) labels
:return:
### Response:
def fit(self, x, y):
"""
:param x: 2D np.ndarray (... |
def parse_config(self, config_file):
"""
Given a configuration file, read in and interpret the results
:param config_file:
:return:
"""
with open(config_file, 'r') as f:
config = json.load(f)
self.params = config
if self.params['proxy']['prox... | Given a configuration file, read in and interpret the results
:param config_file:
:return: | Below is the the instruction that describes the task:
### Input:
Given a configuration file, read in and interpret the results
:param config_file:
:return:
### Response:
def parse_config(self, config_file):
"""
Given a configuration file, read in and interpret the results
... |
def fields(self, value):
"""sets the fields variable"""
if type(value) is list:
self._fields = value
else:
raise TypeError("Input must be a list") | sets the fields variable | Below is the the instruction that describes the task:
### Input:
sets the fields variable
### Response:
def fields(self, value):
"""sets the fields variable"""
if type(value) is list:
self._fields = value
else:
raise TypeError("Input must be a list") |
def gen_otu_dict(nex_obj, nexson_version=None):
"""Takes a NexSON object and returns a dict of
otu_id -> otu_obj
"""
if nexson_version is None:
nexson_version = detect_nexson_version(nex_obj)
if _is_by_id_hbf(nexson_version):
otus = nex_obj['nexml']['otusById']
if len(otus) >... | Takes a NexSON object and returns a dict of
otu_id -> otu_obj | Below is the the instruction that describes the task:
### Input:
Takes a NexSON object and returns a dict of
otu_id -> otu_obj
### Response:
def gen_otu_dict(nex_obj, nexson_version=None):
"""Takes a NexSON object and returns a dict of
otu_id -> otu_obj
"""
if nexson_version is None:
ne... |
def flushmany(self):
"""Send a potentially huge number of pending signals over the message bus.
This method assumes that the number of pending signals might
be huge, so that they might not fit into memory. However,
`SignalBus.flushmany` is not very smart in handling concurrent
s... | Send a potentially huge number of pending signals over the message bus.
This method assumes that the number of pending signals might
be huge, so that they might not fit into memory. However,
`SignalBus.flushmany` is not very smart in handling concurrent
senders. It is mostly useful when... | Below is the the instruction that describes the task:
### Input:
Send a potentially huge number of pending signals over the message bus.
This method assumes that the number of pending signals might
be huge, so that they might not fit into memory. However,
`SignalBus.flushmany` is not very s... |
def recommend_k_items_slow(self, test, top_k=10, remove_seen=True):
"""Recommend top K items for all users which are in the test set.
Args:
test: test Spark dataframe
top_k: top n items to return
remove_seen: remove items test users have already seen in the past from... | Recommend top K items for all users which are in the test set.
Args:
test: test Spark dataframe
top_k: top n items to return
remove_seen: remove items test users have already seen in the past from the recommended set. | Below is the the instruction that describes the task:
### Input:
Recommend top K items for all users which are in the test set.
Args:
test: test Spark dataframe
top_k: top n items to return
remove_seen: remove items test users have already seen in the past from the recom... |
def data(self, data, part=False, dataset=''):
"""Parse data and update links.
Parameters
----------
data
Data to parse.
part : `bool`, optional
True if data is partial (default: `False`).
dataset : `str`, optional
Dataset key prefix (d... | Parse data and update links.
Parameters
----------
data
Data to parse.
part : `bool`, optional
True if data is partial (default: `False`).
dataset : `str`, optional
Dataset key prefix (default: ''). | Below is the the instruction that describes the task:
### Input:
Parse data and update links.
Parameters
----------
data
Data to parse.
part : `bool`, optional
True if data is partial (default: `False`).
dataset : `str`, optional
Dataset k... |
def merge(self, evaluation_context: 'EvaluationContext') -> None:
"""
Merges the provided evaluation context to the current evaluation context.
:param evaluation_context: Evaluation context to merge.
"""
self.global_context.merge(evaluation_context.global_context)
self.lo... | Merges the provided evaluation context to the current evaluation context.
:param evaluation_context: Evaluation context to merge. | Below is the the instruction that describes the task:
### Input:
Merges the provided evaluation context to the current evaluation context.
:param evaluation_context: Evaluation context to merge.
### Response:
def merge(self, evaluation_context: 'EvaluationContext') -> None:
"""
Merges the p... |
def hide_cursor(stream=sys.stdout):
"""
Hide the console cursor on the given stream
:param stream: The name of the stream to get the handle for
:return: None
:rtype: None
"""
handle = get_stream_handle(stream=stream)
if os.name == "nt":
from ctypes import windll
cursor... | Hide the console cursor on the given stream
:param stream: The name of the stream to get the handle for
:return: None
:rtype: None | Below is the the instruction that describes the task:
### Input:
Hide the console cursor on the given stream
:param stream: The name of the stream to get the handle for
:return: None
:rtype: None
### Response:
def hide_cursor(stream=sys.stdout):
"""
Hide the console cursor on the given stream
... |
def post_upgrade_checks(self, upgrades):
"""Run post-upgrade checks after applying all pending upgrades.
Post checks may be used to emit warnings encountered when applying an
upgrade, but post-checks can also be used to advice the user to run
re-indexing or similar long running processe... | Run post-upgrade checks after applying all pending upgrades.
Post checks may be used to emit warnings encountered when applying an
upgrade, but post-checks can also be used to advice the user to run
re-indexing or similar long running processes.
Post-checks may query for user-input, bu... | Below is the the instruction that describes the task:
### Input:
Run post-upgrade checks after applying all pending upgrades.
Post checks may be used to emit warnings encountered when applying an
upgrade, but post-checks can also be used to advice the user to run
re-indexing or similar long... |
def _apply_mask(
data: np.ndarray,
encoded_fill_values: list,
decoded_fill_value: Any,
dtype: Any,
) -> np.ndarray:
"""Mask all matching values in a NumPy arrays."""
data = np.asarray(data, dtype=dtype)
condition = False
for fv in encoded_fill_values:
condition |= data == fv
... | Mask all matching values in a NumPy arrays. | Below is the the instruction that describes the task:
### Input:
Mask all matching values in a NumPy arrays.
### Response:
def _apply_mask(
data: np.ndarray,
encoded_fill_values: list,
decoded_fill_value: Any,
dtype: Any,
) -> np.ndarray:
"""Mask all matching values in a NumPy arrays."""
da... |
def verify_element_present(self, locator, msg=None):
"""
Soft assert for whether and element is present in the current window/frame
:params locator: the locator of the element to search for
:params msg: (Optional) msg explaining the difference
"""
try:
self.a... | Soft assert for whether and element is present in the current window/frame
:params locator: the locator of the element to search for
:params msg: (Optional) msg explaining the difference | Below is the the instruction that describes the task:
### Input:
Soft assert for whether and element is present in the current window/frame
:params locator: the locator of the element to search for
:params msg: (Optional) msg explaining the difference
### Response:
def verify_element_present(self,... |
def function_type(self):
"""returns function type. See :class:`type_t` hierarchy"""
return cpptypes.free_function_type_t(
return_type=self.return_type,
arguments_types=[
arg.decl_type for arg in self.arguments]) | returns function type. See :class:`type_t` hierarchy | Below is the the instruction that describes the task:
### Input:
returns function type. See :class:`type_t` hierarchy
### Response:
def function_type(self):
"""returns function type. See :class:`type_t` hierarchy"""
return cpptypes.free_function_type_t(
return_type=self.return_type,
... |
def used_in_func(statement: str, filename: str = '<string>',
mode: str = 'exec'):
'''Parse a Python statement and analyze the symbols used. The result
will be used to determine what variables a step depends upon.'''
try:
return get_used_in_func(ast.parse(statement, filename, mode))
... | Parse a Python statement and analyze the symbols used. The result
will be used to determine what variables a step depends upon. | Below is the the instruction that describes the task:
### Input:
Parse a Python statement and analyze the symbols used. The result
will be used to determine what variables a step depends upon.
### Response:
def used_in_func(statement: str, filename: str = '<string>',
mode: str = 'exec'):
'... |
def setdefault(obj: JsonObj, k: str, value: Union[Dict, JsonTypes]) -> JsonObjTypes:
""" Dictionary setdefault reoutine """
return obj._setdefault(k, value) | Dictionary setdefault reoutine | Below is the the instruction that describes the task:
### Input:
Dictionary setdefault reoutine
### Response:
def setdefault(obj: JsonObj, k: str, value: Union[Dict, JsonTypes]) -> JsonObjTypes:
""" Dictionary setdefault reoutine """
return obj._setdefault(k, value) |
def get_msg(self, block=True, timeout=None):
"Gets a message if there is one that is ready."
return self._in_queue.get(block, timeout) | Gets a message if there is one that is ready. | Below is the the instruction that describes the task:
### Input:
Gets a message if there is one that is ready.
### Response:
def get_msg(self, block=True, timeout=None):
"Gets a message if there is one that is ready."
return self._in_queue.get(block, timeout) |
def str(self, value, tolerant=False, limit=1000, seen=frozenset()):
"""Transform value into a representation suitable for substitution."""
if value is None:
if tolerant:
return ""
raise ValueError("value is None")
if isinstance(value, (bool, numbers.Numb... | Transform value into a representation suitable for substitution. | Below is the the instruction that describes the task:
### Input:
Transform value into a representation suitable for substitution.
### Response:
def str(self, value, tolerant=False, limit=1000, seen=frozenset()):
"""Transform value into a representation suitable for substitution."""
if value is None... |
def _warn_unsafe_options(cls, args):
'''Print warnings about any enabled hazardous options.
This function will print messages complaining about:
* ``--save-headers``
* ``--no-iri``
* ``--output-document``
* ``--ignore-fatal-errors``
'''
enabled_options =... | Print warnings about any enabled hazardous options.
This function will print messages complaining about:
* ``--save-headers``
* ``--no-iri``
* ``--output-document``
* ``--ignore-fatal-errors`` | Below is the the instruction that describes the task:
### Input:
Print warnings about any enabled hazardous options.
This function will print messages complaining about:
* ``--save-headers``
* ``--no-iri``
* ``--output-document``
* ``--ignore-fatal-errors``
### Response:
d... |
def ReadUsers(self, database_link, options=None):
"""Reads all users in a database.
:params str database_link:
The link to the database.
:params dict options:
The request options for the request.
:return:
Query iterable of Users.
:rtype:
... | Reads all users in a database.
:params str database_link:
The link to the database.
:params dict options:
The request options for the request.
:return:
Query iterable of Users.
:rtype:
query_iterable.QueryIterable | Below is the the instruction that describes the task:
### Input:
Reads all users in a database.
:params str database_link:
The link to the database.
:params dict options:
The request options for the request.
:return:
Query iterable of Users.
:rtyp... |
def understand(self):
"""
:returns: Version understand of preview
:rtype: twilio.rest.preview.understand.Understand
"""
if self._understand is None:
self._understand = Understand(self)
return self._understand | :returns: Version understand of preview
:rtype: twilio.rest.preview.understand.Understand | Below is the the instruction that describes the task:
### Input:
:returns: Version understand of preview
:rtype: twilio.rest.preview.understand.Understand
### Response:
def understand(self):
"""
:returns: Version understand of preview
:rtype: twilio.rest.preview.understand.Understan... |
def expect_exact(self, pattern_list, timeout=-1, searchwindowsize=-1,
async_=False, **kw):
'''This is similar to expect(), but uses plain string matching instead
of compiled regular expressions in 'pattern_list'. The 'pattern_list'
may be a string; a list or other sequence ... | This is similar to expect(), but uses plain string matching instead
of compiled regular expressions in 'pattern_list'. The 'pattern_list'
may be a string; a list or other sequence of strings; or TIMEOUT and
EOF.
This call might be faster than expect() for two reasons: string
sea... | Below is the the instruction that describes the task:
### Input:
This is similar to expect(), but uses plain string matching instead
of compiled regular expressions in 'pattern_list'. The 'pattern_list'
may be a string; a list or other sequence of strings; or TIMEOUT and
EOF.
This c... |
def ssa(scatterer, h_pol=True):
"""Single-scattering albedo for the current setup, with polarization.
Args:
scatterer: a Scatterer instance.
h_pol: If True (default), use horizontal polarization.
If False, use vertical polarization.
Returns:
The single-scattering albedo... | Single-scattering albedo for the current setup, with polarization.
Args:
scatterer: a Scatterer instance.
h_pol: If True (default), use horizontal polarization.
If False, use vertical polarization.
Returns:
The single-scattering albedo. | Below is the the instruction that describes the task:
### Input:
Single-scattering albedo for the current setup, with polarization.
Args:
scatterer: a Scatterer instance.
h_pol: If True (default), use horizontal polarization.
If False, use vertical polarization.
Returns:
... |
def dump_resource_to_zipfile(resource, zipfile, content_type=None):
"""
Convenience function. See
:meth:`everest.resources.io.ConnectedResourcesSerializer.to_zipfile` for
details.
The given context type defaults to CSV.
"""
if content_type is None:
content_type = CsvMime
srl = C... | Convenience function. See
:meth:`everest.resources.io.ConnectedResourcesSerializer.to_zipfile` for
details.
The given context type defaults to CSV. | Below is the the instruction that describes the task:
### Input:
Convenience function. See
:meth:`everest.resources.io.ConnectedResourcesSerializer.to_zipfile` for
details.
The given context type defaults to CSV.
### Response:
def dump_resource_to_zipfile(resource, zipfile, content_type=None):
"""... |
def _get_float(data, position, dummy0, dummy1, dummy2):
"""Decode a BSON double to python float."""
end = position + 8
return _UNPACK_FLOAT(data[position:end])[0], end | Decode a BSON double to python float. | Below is the the instruction that describes the task:
### Input:
Decode a BSON double to python float.
### Response:
def _get_float(data, position, dummy0, dummy1, dummy2):
"""Decode a BSON double to python float."""
end = position + 8
return _UNPACK_FLOAT(data[position:end])[0], end |
def getallobjlists(idf, refname):
"""get all object-list fields for refname
return a list:
[('OBJKEY', refname, fieldindexlist), ...] where
fieldindexlist = index of the field where the object-list = refname
"""
dtls = idf.model.dtls
objlists = []
for i, fieldidds in enumerate(idf.idd_in... | get all object-list fields for refname
return a list:
[('OBJKEY', refname, fieldindexlist), ...] where
fieldindexlist = index of the field where the object-list = refname | Below is the the instruction that describes the task:
### Input:
get all object-list fields for refname
return a list:
[('OBJKEY', refname, fieldindexlist), ...] where
fieldindexlist = index of the field where the object-list = refname
### Response:
def getallobjlists(idf, refname):
"""get all obje... |
def position_i(self):
"""
The integral constant for the position PID.
"""
self._position_i, value = self.get_attr_int(self._position_i, 'hold_pid/Ki')
return value | The integral constant for the position PID. | Below is the the instruction that describes the task:
### Input:
The integral constant for the position PID.
### Response:
def position_i(self):
"""
The integral constant for the position PID.
"""
self._position_i, value = self.get_attr_int(self._position_i, 'hold_pid/Ki')
r... |
def view(ctx, schema, uuid, object_filter):
"""Show stored objects"""
database = ctx.obj['db']
if schema is None:
log('No schema given. Read the help', lvl=warn)
return
model = database.objectmodels[schema]
if uuid:
obj = model.find({'uuid': uuid})
elif object_filter:... | Show stored objects | Below is the the instruction that describes the task:
### Input:
Show stored objects
### Response:
def view(ctx, schema, uuid, object_filter):
"""Show stored objects"""
database = ctx.obj['db']
if schema is None:
log('No schema given. Read the help', lvl=warn)
return
model = data... |
def draw_lines():
"""
Draws a line between a set of random values
"""
r = numpy.random.randn(200)
fig = pyplot.figure()
ax = fig.add_subplot(111)
ax.plot(r)
ax.grid(True)
pyplot.savefig(lines_filename) | Draws a line between a set of random values | Below is the the instruction that describes the task:
### Input:
Draws a line between a set of random values
### Response:
def draw_lines():
"""
Draws a line between a set of random values
"""
r = numpy.random.randn(200)
fig = pyplot.figure()
ax = fig.add_subplot(111)
ax.plot(r)
ax... |
def row_append(self, row_key, value_list):
"""
append a new row to a DataRange
:param row_key: a string
:param value_list: a list
"""
if row_key in self._row_keys:
raise KeyError('Key %s already exists in row keys.' % row_key)
if not len(value_list) =... | append a new row to a DataRange
:param row_key: a string
:param value_list: a list | Below is the the instruction that describes the task:
### Input:
append a new row to a DataRange
:param row_key: a string
:param value_list: a list
### Response:
def row_append(self, row_key, value_list):
"""
append a new row to a DataRange
:param row_key: a string
... |
def apply_styles(self, cmdmap):
"""
Apply the set of commands defined in cmdmap. for example, apply_styles({'FONTSIZE': 12, 'BACKGROUND': white})
:param cmdmap: dict of commands mapped to the command arguments
:return: self
"""
is_list_like = lambda arg: isinstance(arg, (... | Apply the set of commands defined in cmdmap. for example, apply_styles({'FONTSIZE': 12, 'BACKGROUND': white})
:param cmdmap: dict of commands mapped to the command arguments
:return: self | Below is the the instruction that describes the task:
### Input:
Apply the set of commands defined in cmdmap. for example, apply_styles({'FONTSIZE': 12, 'BACKGROUND': white})
:param cmdmap: dict of commands mapped to the command arguments
:return: self
### Response:
def apply_styles(self, cmdmap):
... |
def txt_to_obj(cls, file_path=None, text='', columns=None,
remove_empty_rows=True, key_on=None,
row_columns=None, deliminator='\t', eval_cells=True):
"""
This will convert text file or text to a seaborn table
and return it
:param file_path: str of th... | This will convert text file or text to a seaborn table
and return it
:param file_path: str of the path to the file
:param text: str of the csv text
:param columns: list of str of columns to use
:param row_columns: list of str of columns in data but not to use
:param remov... | Below is the the instruction that describes the task:
### Input:
This will convert text file or text to a seaborn table
and return it
:param file_path: str of the path to the file
:param text: str of the csv text
:param columns: list of str of columns to use
:param row_column... |
def _poly_eval_0(self, u, ids):
"""Evaluate internal polynomial."""
return u * (u * (self._a[ids] * u + self._b[ids]) + self._c[ids]) + self._d[ids] | Evaluate internal polynomial. | Below is the the instruction that describes the task:
### Input:
Evaluate internal polynomial.
### Response:
def _poly_eval_0(self, u, ids):
"""Evaluate internal polynomial."""
return u * (u * (self._a[ids] * u + self._b[ids]) + self._c[ids]) + self._d[ids] |
def add_spatial_unit_condition(self, droppable_id, container_id, spatial_unit, match=True):
"""stub"""
if not isinstance(spatial_unit, abc_mapping_primitives.SpatialUnit):
raise InvalidArgument('spatial_unit is not a SpatialUnit')
self.my_osid_object_form._my_map['spatialUnitConditi... | stub | Below is the the instruction that describes the task:
### Input:
stub
### Response:
def add_spatial_unit_condition(self, droppable_id, container_id, spatial_unit, match=True):
"""stub"""
if not isinstance(spatial_unit, abc_mapping_primitives.SpatialUnit):
raise InvalidArgument('spatial_... |
def _from_dict(cls, _dict):
"""Initialize a LogQueryResponseResult object from a json dictionary."""
args = {}
if 'environment_id' in _dict:
args['environment_id'] = _dict.get('environment_id')
if 'customer_id' in _dict:
args['customer_id'] = _dict.get('customer_i... | Initialize a LogQueryResponseResult object from a json dictionary. | Below is the the instruction that describes the task:
### Input:
Initialize a LogQueryResponseResult object from a json dictionary.
### Response:
def _from_dict(cls, _dict):
"""Initialize a LogQueryResponseResult object from a json dictionary."""
args = {}
if 'environment_id' in _dict:
... |
def seqannotation(self, seqrecord, allele, loc):
"""
Gets the Annotation from the found sequence
:return: The Annotation from the found sequence
:rtype: Annotation
"""
#seqrecord = self.seqrecord(allele, loc)
complete_annotation = get_features(seqrecord)
... | Gets the Annotation from the found sequence
:return: The Annotation from the found sequence
:rtype: Annotation | Below is the the instruction that describes the task:
### Input:
Gets the Annotation from the found sequence
:return: The Annotation from the found sequence
:rtype: Annotation
### Response:
def seqannotation(self, seqrecord, allele, loc):
"""
Gets the Annotation from the found sequ... |
def _run_genotype_gvcfs_genomicsdb(genomics_db, region, out_file, data):
"""GenotypeGVCFs from a merged GenomicsDB input: GATK4.
ropts += [str(x) for x in resources.get("options", [])]
No core scaling -- not yet supported in GATK4.
"""
if not utils.file_exists(out_file):
with file_t... | GenotypeGVCFs from a merged GenomicsDB input: GATK4.
ropts += [str(x) for x in resources.get("options", [])]
No core scaling -- not yet supported in GATK4. | Below is the the instruction that describes the task:
### Input:
GenotypeGVCFs from a merged GenomicsDB input: GATK4.
ropts += [str(x) for x in resources.get("options", [])]
No core scaling -- not yet supported in GATK4.
### Response:
def _run_genotype_gvcfs_genomicsdb(genomics_db, region, out_fil... |
def candle_lighting(self):
"""Return the time for candle lighting, or None if not applicable."""
today = HDate(gdate=self.date, diaspora=self.location.diaspora)
tomorrow = HDate(gdate=self.date + dt.timedelta(days=1),
diaspora=self.location.diaspora)
# If today... | Return the time for candle lighting, or None if not applicable. | Below is the the instruction that describes the task:
### Input:
Return the time for candle lighting, or None if not applicable.
### Response:
def candle_lighting(self):
"""Return the time for candle lighting, or None if not applicable."""
today = HDate(gdate=self.date, diaspora=self.location.diasp... |
def vector(p1, p2):
'''compute vector between two 3D points
Args:
p1, p2: indexable objects with
indices 0, 1, 2 corresponding to 3D cartesian coordinates.
Returns:
3-vector from p1 - p2
'''
return np.subtract(p1[COLS.XYZ], p2[COLS.XYZ]) | compute vector between two 3D points
Args:
p1, p2: indexable objects with
indices 0, 1, 2 corresponding to 3D cartesian coordinates.
Returns:
3-vector from p1 - p2 | Below is the the instruction that describes the task:
### Input:
compute vector between two 3D points
Args:
p1, p2: indexable objects with
indices 0, 1, 2 corresponding to 3D cartesian coordinates.
Returns:
3-vector from p1 - p2
### Response:
def vector(p1, p2):
'''compute vec... |
def run_query(self, cmd="", **kwargs):
"""
Remote Popen (actually execute the Spark-sql query)
:param cmd: command to remotely execute
:param kwargs: extra arguments to Popen (see subprocess.Popen)
"""
spark_sql_cmd = self._prepare_command(cmd)
self._sp = subproc... | Remote Popen (actually execute the Spark-sql query)
:param cmd: command to remotely execute
:param kwargs: extra arguments to Popen (see subprocess.Popen) | Below is the the instruction that describes the task:
### Input:
Remote Popen (actually execute the Spark-sql query)
:param cmd: command to remotely execute
:param kwargs: extra arguments to Popen (see subprocess.Popen)
### Response:
def run_query(self, cmd="", **kwargs):
"""
Remot... |
def from_config(cls, cp, **kwargs):
r"""Initializes an instance of this class from the given config file.
Parameters
----------
cp : WorkflowConfigParser
Config file parser to read.
\**kwargs :
All additional keyword arguments are passed to the class. Any... | r"""Initializes an instance of this class from the given config file.
Parameters
----------
cp : WorkflowConfigParser
Config file parser to read.
\**kwargs :
All additional keyword arguments are passed to the class. Any
provided keyword will over ride... | Below is the the instruction that describes the task:
### Input:
r"""Initializes an instance of this class from the given config file.
Parameters
----------
cp : WorkflowConfigParser
Config file parser to read.
\**kwargs :
All additional keyword arguments are... |
def register(self, mimetype):
"""Register a function to handle a particular mimetype."""
def dec(func):
self._reg[mimetype] = func
return func
return dec | Register a function to handle a particular mimetype. | Below is the the instruction that describes the task:
### Input:
Register a function to handle a particular mimetype.
### Response:
def register(self, mimetype):
"""Register a function to handle a particular mimetype."""
def dec(func):
self._reg[mimetype] = func
return func
... |
def reject_milestone_request(session, milestone_request_id):
"""
Reject a milestone request
"""
params_data = {
'action': 'reject',
}
# POST /api/projects/0.1/milestone_requests/{milestone_request_id}/?action=
# reject
endpoint = 'milestone_requests/{}'.format(milestone_request_i... | Reject a milestone request | Below is the the instruction that describes the task:
### Input:
Reject a milestone request
### Response:
def reject_milestone_request(session, milestone_request_id):
"""
Reject a milestone request
"""
params_data = {
'action': 'reject',
}
# POST /api/projects/0.1/milestone_requests... |
def call(self, command, *args):
""" Execute local OR remote command and show response """
if not command:
return
# Look for local methods first
try:
res = self.registered[command]['function'](self, *args)
return Response('local', res, None)
... | Execute local OR remote command and show response | Below is the the instruction that describes the task:
### Input:
Execute local OR remote command and show response
### Response:
def call(self, command, *args):
""" Execute local OR remote command and show response """
if not command:
return
# Look for local methods first
... |
def validate(filename, verbose=False):
"""
Validate file and return JSON result as dictionary.
"filename" can be a file name or an HTTP URL.
Return "" if the validator does not return valid JSON.
Raise OSError if curl command returns an error status.
"""
# is_css = filename.endswith(".css")... | Validate file and return JSON result as dictionary.
"filename" can be a file name or an HTTP URL.
Return "" if the validator does not return valid JSON.
Raise OSError if curl command returns an error status. | Below is the the instruction that describes the task:
### Input:
Validate file and return JSON result as dictionary.
"filename" can be a file name or an HTTP URL.
Return "" if the validator does not return valid JSON.
Raise OSError if curl command returns an error status.
### Response:
def validate(fi... |
def do_string(self, parent=None, ident=0):
"""
Handles a TC_STRING opcode
:param parent:
:param ident: Log indentation level
:return: A string
"""
log_debug("[string]", ident)
ba = JavaString(self._readString())
self._add_reference(ba, ident)
... | Handles a TC_STRING opcode
:param parent:
:param ident: Log indentation level
:return: A string | Below is the the instruction that describes the task:
### Input:
Handles a TC_STRING opcode
:param parent:
:param ident: Log indentation level
:return: A string
### Response:
def do_string(self, parent=None, ident=0):
"""
Handles a TC_STRING opcode
:param parent:
... |
def build(self, stmts=None, set_check_var=True, invert=False):
"""Construct code for performing the match then executing stmts."""
out = ""
if set_check_var:
out += self.check_var + " = False\n"
out += self.out()
if stmts is not None:
out += "if " + ("not ... | Construct code for performing the match then executing stmts. | Below is the the instruction that describes the task:
### Input:
Construct code for performing the match then executing stmts.
### Response:
def build(self, stmts=None, set_check_var=True, invert=False):
"""Construct code for performing the match then executing stmts."""
out = ""
if set_che... |
async def deserialize(data: dict):
"""
Create the object from a previously serialized object.
:param data: The output of the "serialize" call
Example:
source_id = 'foobar123'
schema_name = 'Schema Name'
payment_handle = 0
credential_def1 = await Credentia... | Create the object from a previously serialized object.
:param data: The output of the "serialize" call
Example:
source_id = 'foobar123'
schema_name = 'Schema Name'
payment_handle = 0
credential_def1 = await CredentialDef.create(source_id, name, schema_id, payment_handle)... | Below is the the instruction that describes the task:
### Input:
Create the object from a previously serialized object.
:param data: The output of the "serialize" call
Example:
source_id = 'foobar123'
schema_name = 'Schema Name'
payment_handle = 0
credential_def1 = a... |
def _assert_lt(self, cost):
"""
The method enforces an upper bound on the cost of the MaxSAT
solution. This is done by encoding the sum of all soft clause
selectors with the use the iterative totalizer encoding, i.e.
:class:`.ITotalizer`. Note that the sum is crea... | The method enforces an upper bound on the cost of the MaxSAT
solution. This is done by encoding the sum of all soft clause
selectors with the use the iterative totalizer encoding, i.e.
:class:`.ITotalizer`. Note that the sum is created once, at the
beginning. Each of the ... | Below is the the instruction that describes the task:
### Input:
The method enforces an upper bound on the cost of the MaxSAT
solution. This is done by encoding the sum of all soft clause
selectors with the use the iterative totalizer encoding, i.e.
:class:`.ITotalizer`. Note tha... |
def parallelize(self, seconds_to_wait=2):
"""Start a parallel thread for receiving messages.
If :meth:`start` was no called before, start will be called in the
thread.
The thread calls :meth:`receive_message` until the :attr:`state`
:meth:`~AYABInterface.communication.states.Sta... | Start a parallel thread for receiving messages.
If :meth:`start` was no called before, start will be called in the
thread.
The thread calls :meth:`receive_message` until the :attr:`state`
:meth:`~AYABInterface.communication.states.State.is_connection_closed`.
:param float secon... | Below is the the instruction that describes the task:
### Input:
Start a parallel thread for receiving messages.
If :meth:`start` was no called before, start will be called in the
thread.
The thread calls :meth:`receive_message` until the :attr:`state`
:meth:`~AYABInterface.communic... |
def get_conn(opts, profile):
'''
Return a client object for accessing consul
'''
opts_pillar = opts.get('pillar', {})
opts_master = opts_pillar.get('master', {})
opts_merged = {}
opts_merged.update(opts_master)
opts_merged.update(opts_pillar)
opts_merged.update(opts)
if profil... | Return a client object for accessing consul | Below is the the instruction that describes the task:
### Input:
Return a client object for accessing consul
### Response:
def get_conn(opts, profile):
'''
Return a client object for accessing consul
'''
opts_pillar = opts.get('pillar', {})
opts_master = opts_pillar.get('master', {})
opts... |
def cloud_init(names, host=None, quiet=False, **kwargs):
'''
Wrapper for using lxc.init in saltcloud compatibility mode
names
Name of the containers, supports a single name or a comma delimited
list of names.
host
Minion to start the container on. Required.
path
pa... | Wrapper for using lxc.init in saltcloud compatibility mode
names
Name of the containers, supports a single name or a comma delimited
list of names.
host
Minion to start the container on. Required.
path
path to the container parent
default: /var/lib/lxc (system defa... | Below is the the instruction that describes the task:
### Input:
Wrapper for using lxc.init in saltcloud compatibility mode
names
Name of the containers, supports a single name or a comma delimited
list of names.
host
Minion to start the container on. Required.
path
pa... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.