code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def in_use(self):
"""Check whether this device is in use, i.e. mounted or unlocked."""
if self.is_mounted or self.is_unlocked:
return True
if self.is_partition_table:
for device in self._daemon:
if device.partition_slave == self and device.in_use:
... | Check whether this device is in use, i.e. mounted or unlocked. | Below is the the instruction that describes the task:
### Input:
Check whether this device is in use, i.e. mounted or unlocked.
### Response:
def in_use(self):
"""Check whether this device is in use, i.e. mounted or unlocked."""
if self.is_mounted or self.is_unlocked:
return True
... |
def triple_apply(self, triple_apply_fn, mutated_fields, input_fields=None):
'''
Apply a transform function to each edge and its associated source and
target vertices in parallel. Each edge is visited once and in parallel.
Modification to vertex data is protected by lock. The effect on th... | Apply a transform function to each edge and its associated source and
target vertices in parallel. Each edge is visited once and in parallel.
Modification to vertex data is protected by lock. The effect on the
returned SGraph is equivalent to the following pseudocode:
>>> PARALLEL FOR (... | Below is the the instruction that describes the task:
### Input:
Apply a transform function to each edge and its associated source and
target vertices in parallel. Each edge is visited once and in parallel.
Modification to vertex data is protected by lock. The effect on the
returned SGraph i... |
def _normalize_coerce(self, mapping, schema):
""" {'oneof': [
{'type': 'callable'},
{'type': 'list',
'schema': {'oneof': [{'type': 'callable'},
{'type': 'string'}]}},
{'type': 'string'}
]} """
... | {'oneof': [
{'type': 'callable'},
{'type': 'list',
'schema': {'oneof': [{'type': 'callable'},
{'type': 'string'}]}},
{'type': 'string'}
]} | Below is the the instruction that describes the task:
### Input:
{'oneof': [
{'type': 'callable'},
{'type': 'list',
'schema': {'oneof': [{'type': 'callable'},
{'type': 'string'}]}},
{'type': 'string'}
... |
def to_table_data(self):
"""
:raises ValueError:
:raises pytablereader.error.ValidationError:
"""
self._validate_source_data()
header_list = []
for json_record in self._buffer:
for key in json_record:
if key not in header_list:
... | :raises ValueError:
:raises pytablereader.error.ValidationError: | Below is the the instruction that describes the task:
### Input:
:raises ValueError:
:raises pytablereader.error.ValidationError:
### Response:
def to_table_data(self):
"""
:raises ValueError:
:raises pytablereader.error.ValidationError:
"""
self._validate_source_da... |
def as_png_data_uri(matrix, version, scale=1, border=None, color='#000',
background='#fff', compresslevel=9, addad=True):
"""\
Converts the provided matrix into a PNG data URI.
:rtype: str
"""
buff = io.BytesIO()
write_png(matrix, version, buff, scale=scale, border=border, c... | \
Converts the provided matrix into a PNG data URI.
:rtype: str | Below is the the instruction that describes the task:
### Input:
\
Converts the provided matrix into a PNG data URI.
:rtype: str
### Response:
def as_png_data_uri(matrix, version, scale=1, border=None, color='#000',
background='#fff', compresslevel=9, addad=True):
"""\
Converts... |
def _generate_union_tag_state_funcs(self, union):
"""Emits the is<TAG_NAME> methods and tagName method for determining
tag state and retrieving human-readable value of tag state, respectively."""
for field in union.all_fields:
enum_field_name = fmt_enum_name(field.name, union)
... | Emits the is<TAG_NAME> methods and tagName method for determining
tag state and retrieving human-readable value of tag state, respectively. | Below is the the instruction that describes the task:
### Input:
Emits the is<TAG_NAME> methods and tagName method for determining
tag state and retrieving human-readable value of tag state, respectively.
### Response:
def _generate_union_tag_state_funcs(self, union):
"""Emits the is<TAG_NAME> meth... |
def compute_ecc_hash_from_string(string, ecc_manager, hasher, max_block_size, resilience_rate):
'''Generate a concatenated string of ecc stream of hash/ecc blocks, of constant encoding rate, given a string.
NOTE: resilience_rate here is constant, you need to supply only one rate, between 0.0 and 1.0. The encodi... | Generate a concatenated string of ecc stream of hash/ecc blocks, of constant encoding rate, given a string.
NOTE: resilience_rate here is constant, you need to supply only one rate, between 0.0 and 1.0. The encoding rate will then be constant, like in header_ecc.py. | Below is the the instruction that describes the task:
### Input:
Generate a concatenated string of ecc stream of hash/ecc blocks, of constant encoding rate, given a string.
NOTE: resilience_rate here is constant, you need to supply only one rate, between 0.0 and 1.0. The encoding rate will then be constant, lik... |
def shorten_aead(aead):
""" Produce pretty-printable version of long AEAD. """
head = aead.data[:4].encode('hex')
tail = aead.data[-4:].encode('hex')
return "%s...%s" % (head, tail) | Produce pretty-printable version of long AEAD. | Below is the the instruction that describes the task:
### Input:
Produce pretty-printable version of long AEAD.
### Response:
def shorten_aead(aead):
""" Produce pretty-printable version of long AEAD. """
head = aead.data[:4].encode('hex')
tail = aead.data[-4:].encode('hex')
return "%s...%s" % (hea... |
def _map(expr, func, rtype=None, resources=None, args=(), **kwargs):
"""
Call func on each element of this sequence.
:param func: lambda, function, :class:`odps.models.Function`,
or str which is the name of :class:`odps.models.Funtion`
:param rtype: if not provided, will be the dtype o... | Call func on each element of this sequence.
:param func: lambda, function, :class:`odps.models.Function`,
or str which is the name of :class:`odps.models.Funtion`
:param rtype: if not provided, will be the dtype of this sequence
:return: a new sequence
:Example:
>>> df.id.map(lam... | Below is the the instruction that describes the task:
### Input:
Call func on each element of this sequence.
:param func: lambda, function, :class:`odps.models.Function`,
or str which is the name of :class:`odps.models.Funtion`
:param rtype: if not provided, will be the dtype of this seque... |
def row(self, data):
"""Return a formatted row for the given data."""
for column in self.column_funcs:
if callable(column):
yield column(data)
else:
yield utils.lookup(data, *column) | Return a formatted row for the given data. | Below is the the instruction that describes the task:
### Input:
Return a formatted row for the given data.
### Response:
def row(self, data):
"""Return a formatted row for the given data."""
for column in self.column_funcs:
if callable(column):
yield column(data)
... |
def scale_degree_to_bitmap(scale_degree, modulo=False, length=BITMAP_LENGTH):
"""Create a bitmap representation of a scale degree.
Note that values in the bitmap may be negative, indicating that the
semitone is to be removed.
Parameters
----------
scale_degree : str
Spelling of a relat... | Create a bitmap representation of a scale degree.
Note that values in the bitmap may be negative, indicating that the
semitone is to be removed.
Parameters
----------
scale_degree : str
Spelling of a relative scale degree, e.g. 'b3', '7', '#5'
modulo : bool, default=True
If a s... | Below is the the instruction that describes the task:
### Input:
Create a bitmap representation of a scale degree.
Note that values in the bitmap may be negative, indicating that the
semitone is to be removed.
Parameters
----------
scale_degree : str
Spelling of a relative scale degree... |
def get_properties_obj(self):
"""Get the underlying C reference from this object.
:rtype: uamqp.c_uamqp.cProperties
"""
properties = c_uamqp.cProperties()
self._set_attr('message_id', properties)
self._set_attr('user_id', properties)
self._set_attr('to', properti... | Get the underlying C reference from this object.
:rtype: uamqp.c_uamqp.cProperties | Below is the the instruction that describes the task:
### Input:
Get the underlying C reference from this object.
:rtype: uamqp.c_uamqp.cProperties
### Response:
def get_properties_obj(self):
"""Get the underlying C reference from this object.
:rtype: uamqp.c_uamqp.cProperties
"""... |
def extract_author_keywords(skw_db, ckw_db, fulltext):
"""Find out human defined keywords in a text string.
Searches for the string "Keywords:" and its declinations and matches the
following words.
:param skw_db: list single kw object
:param ckw_db: list of composite kw objects
:param fulltext... | Find out human defined keywords in a text string.
Searches for the string "Keywords:" and its declinations and matches the
following words.
:param skw_db: list single kw object
:param ckw_db: list of composite kw objects
:param fulltext: utf-8 string
:return: dictionary of matches in a formt {... | Below is the the instruction that describes the task:
### Input:
Find out human defined keywords in a text string.
Searches for the string "Keywords:" and its declinations and matches the
following words.
:param skw_db: list single kw object
:param ckw_db: list of composite kw objects
:param f... |
def create_ipsec_site_connection(name,
ipsecpolicy,
ikepolicy,
vpnservice,
peer_cidrs,
peer_address,
peer_id,
... | Creates a new IPsecSiteConnection
CLI Example:
.. code-block:: bash
salt '*' neutron.show_ipsec_site_connection connection-name
ipsec-policy-name ikepolicy-name vpnservice-name
192.168.XXX.XXX/24 192.168.XXX.XXX 192.168.XXX.XXX secret
:param name: Set friendly nam... | Below is the the instruction that describes the task:
### Input:
Creates a new IPsecSiteConnection
CLI Example:
.. code-block:: bash
salt '*' neutron.show_ipsec_site_connection connection-name
ipsec-policy-name ikepolicy-name vpnservice-name
192.168.XXX.XXX/24 192.... |
def idd2grouplist(fhandle):
"""wrapper for iddtxt2grouplist"""
try:
txt = fhandle.read()
return iddtxt2grouplist(txt)
except AttributeError as e:
txt = open(fhandle, 'r').read()
return iddtxt2grouplist(txt) | wrapper for iddtxt2grouplist | Below is the the instruction that describes the task:
### Input:
wrapper for iddtxt2grouplist
### Response:
def idd2grouplist(fhandle):
"""wrapper for iddtxt2grouplist"""
try:
txt = fhandle.read()
return iddtxt2grouplist(txt)
except AttributeError as e:
txt = open(fhandle, 'r').... |
def resize(self, image_field, new_width=None, new_height=None):
"""
Resize an image to the 'best fit' width & height, maintaining
the scale of the image, so a 500x500 image sized to 300x400
will actually be scaled to 300x300.
Params:
image: ImageFieldFile to be r... | Resize an image to the 'best fit' width & height, maintaining
the scale of the image, so a 500x500 image sized to 300x400
will actually be scaled to 300x300.
Params:
image: ImageFieldFile to be resized (i.e. model.image_field)
new_width & new_height: desired maximums for... | Below is the the instruction that describes the task:
### Input:
Resize an image to the 'best fit' width & height, maintaining
the scale of the image, so a 500x500 image sized to 300x400
will actually be scaled to 300x300.
Params:
image: ImageFieldFile to be resized (i.e. mo... |
def quota(self, quota):
"""
Sets the quota of this ServicePackageQuota.
Available quota for the service package.
:param quota: The quota of this ServicePackageQuota.
:type: int
"""
if quota is None:
raise ValueError("Invalid value for `quota`, must no... | Sets the quota of this ServicePackageQuota.
Available quota for the service package.
:param quota: The quota of this ServicePackageQuota.
:type: int | Below is the the instruction that describes the task:
### Input:
Sets the quota of this ServicePackageQuota.
Available quota for the service package.
:param quota: The quota of this ServicePackageQuota.
:type: int
### Response:
def quota(self, quota):
"""
Sets the quota of ... |
def mavlink_packet(self, m):
'''handle mavlink packets'''
mtype = m.get_type()
if mtype not in self.counts:
self.counts[mtype] = 0
self.counts[mtype] += 1 | handle mavlink packets | Below is the the instruction that describes the task:
### Input:
handle mavlink packets
### Response:
def mavlink_packet(self, m):
'''handle mavlink packets'''
mtype = m.get_type()
if mtype not in self.counts:
self.counts[mtype] = 0
self.counts[mtype] += 1 |
def cross_lists(*sets):
"""Return the cross product of the arguments"""
wheels = [iter(_) for _ in sets]
digits = [next(it) for it in wheels]
while True:
yield digits[:]
for i in range(len(digits)-1, -1, -1):
try:
digits[i] = next(wheels[i])
br... | Return the cross product of the arguments | Below is the the instruction that describes the task:
### Input:
Return the cross product of the arguments
### Response:
def cross_lists(*sets):
"""Return the cross product of the arguments"""
wheels = [iter(_) for _ in sets]
digits = [next(it) for it in wheels]
while True:
yield digits[:]
... |
def submitted_projects(raw_df):
"""
Return all submitted projects.
"""
df = raw_df.astype({'PRONAC': str, 'CgcCpf': str})
submitted_projects = df.groupby('CgcCpf')[
'PRONAC'
].agg(['unique', 'nunique'])
submitted_projects.columns = ['pronac_list', 'num_pronacs']
return submitte... | Return all submitted projects. | Below is the the instruction that describes the task:
### Input:
Return all submitted projects.
### Response:
def submitted_projects(raw_df):
"""
Return all submitted projects.
"""
df = raw_df.astype({'PRONAC': str, 'CgcCpf': str})
submitted_projects = df.groupby('CgcCpf')[
'PRONAC'
... |
def ssml_break(self, strength=None, time=None, **kwargs):
"""
Create a <Break> element
:param strength: Set a pause based on strength
:param time: Set a pause to a specific length of time in seconds or milliseconds, available values: [number]s, [number]ms
:param kwargs: addition... | Create a <Break> element
:param strength: Set a pause based on strength
:param time: Set a pause to a specific length of time in seconds or milliseconds, available values: [number]s, [number]ms
:param kwargs: additional attributes
:returns: <Break> element | Below is the the instruction that describes the task:
### Input:
Create a <Break> element
:param strength: Set a pause based on strength
:param time: Set a pause to a specific length of time in seconds or milliseconds, available values: [number]s, [number]ms
:param kwargs: additional attrib... |
def start(self, user_func, refresh):
"""
Start the SNMP's protocol handler and the updater thread
user_func is a reference to an update function, ran every 'refresh' seconds.
"""
self.update=user_func
self.refresh=refresh
self.error=None
# First load
self.update()
self.commit()
# Start updater t... | Start the SNMP's protocol handler and the updater thread
user_func is a reference to an update function, ran every 'refresh' seconds. | Below is the the instruction that describes the task:
### Input:
Start the SNMP's protocol handler and the updater thread
user_func is a reference to an update function, ran every 'refresh' seconds.
### Response:
def start(self, user_func, refresh):
"""
Start the SNMP's protocol handler and the updater threa... |
def onCMapSave(self, event=None, col='int'):
"""save color table image"""
file_choices = 'PNG (*.png)|*.png'
ofile = 'Colormap.png'
dlg = wx.FileDialog(self, message='Save Colormap as...',
defaultDir=os.getcwd(),
defaultFile=ofile,
... | save color table image | Below is the the instruction that describes the task:
### Input:
save color table image
### Response:
def onCMapSave(self, event=None, col='int'):
"""save color table image"""
file_choices = 'PNG (*.png)|*.png'
ofile = 'Colormap.png'
dlg = wx.FileDialog(self, message='Save Colormap ... |
def wulff_gform_and_r(self, wulffshape, bulk_entry, r, from_sphere_area=False,
r_units="nanometers", e_units="keV", normalize=False,
scale_per_atom=False):
"""
Calculates the formation energy of the particle with arbitrary radius r.
Args:
... | Calculates the formation energy of the particle with arbitrary radius r.
Args:
wulffshape (WulffShape): Initial, unscaled WulffShape
bulk_entry (ComputedStructureEntry): Entry of the corresponding bulk.
r (float (Ang)): Arbitrary effective radius of the WulffShape
... | Below is the the instruction that describes the task:
### Input:
Calculates the formation energy of the particle with arbitrary radius r.
Args:
wulffshape (WulffShape): Initial, unscaled WulffShape
bulk_entry (ComputedStructureEntry): Entry of the corresponding bulk.
r (... |
def allow(cls, action, **kwargs):
"""Allow the given action need.
:param action: The action to allow.
:returns: A :class:`invenio_access.models.ActionNeedMixin` instance.
"""
return cls.create(action, exclude=False, **kwargs) | Allow the given action need.
:param action: The action to allow.
:returns: A :class:`invenio_access.models.ActionNeedMixin` instance. | Below is the the instruction that describes the task:
### Input:
Allow the given action need.
:param action: The action to allow.
:returns: A :class:`invenio_access.models.ActionNeedMixin` instance.
### Response:
def allow(cls, action, **kwargs):
"""Allow the given action need.
:p... |
def _pipeline_output(self, pipeline, chunks, name):
"""
Internal implementation of `pipeline_output`.
"""
today = normalize_date(self.get_datetime())
try:
data = self._pipeline_cache.get(name, today)
except KeyError:
# Calculate the next block.
... | Internal implementation of `pipeline_output`. | Below is the the instruction that describes the task:
### Input:
Internal implementation of `pipeline_output`.
### Response:
def _pipeline_output(self, pipeline, chunks, name):
"""
Internal implementation of `pipeline_output`.
"""
today = normalize_date(self.get_datetime())
... |
def _transformBy(self, matrix, **kwargs):
"""
Subclasses may override this method.
"""
for contour in self.contours:
contour.transformBy(matrix)
for component in self.components:
component.transformBy(matrix)
for anchor in self.anchors:
... | Subclasses may override this method. | Below is the the instruction that describes the task:
### Input:
Subclasses may override this method.
### Response:
def _transformBy(self, matrix, **kwargs):
"""
Subclasses may override this method.
"""
for contour in self.contours:
contour.transformBy(matrix)
fo... |
def quote_as2name(unquoted_name):
"""
Function converts as2 name from unquoted to quoted format
:param unquoted_name: the as2 name in unquoted format
:return: the as2 name in unquoted format
"""
if re.search(r'[\\" ]', unquoted_name, re.M):
return '"' + email.utils.quote(unquoted_name) ... | Function converts as2 name from unquoted to quoted format
:param unquoted_name: the as2 name in unquoted format
:return: the as2 name in unquoted format | Below is the the instruction that describes the task:
### Input:
Function converts as2 name from unquoted to quoted format
:param unquoted_name: the as2 name in unquoted format
:return: the as2 name in unquoted format
### Response:
def quote_as2name(unquoted_name):
"""
Function converts as2 name fr... |
def root(self, scope, names):
"""Find root of identifier, from scope
args:
scope (Scope): current scope
names (list): identifier name list (, separated identifiers)
returns:
list
"""
parent = scope.scopename
if parent:
paren... | Find root of identifier, from scope
args:
scope (Scope): current scope
names (list): identifier name list (, separated identifiers)
returns:
list | Below is the the instruction that describes the task:
### Input:
Find root of identifier, from scope
args:
scope (Scope): current scope
names (list): identifier name list (, separated identifiers)
returns:
list
### Response:
def root(self, scope, names):
... |
def from_srt(cls, file):
"""Reads captions from a file in SubRip format."""
parser = SRTParser().read(file)
return cls(file=file, captions=parser.captions) | Reads captions from a file in SubRip format. | Below is the the instruction that describes the task:
### Input:
Reads captions from a file in SubRip format.
### Response:
def from_srt(cls, file):
"""Reads captions from a file in SubRip format."""
parser = SRTParser().read(file)
return cls(file=file, captions=parser.captions) |
def get_protocol(handle: Handle, want_v2: bool) -> Protocol:
"""Make a Protocol instance for the given handle.
Each transport can have a preference for using a particular protocol version.
This preference is overridable through `TREZOR_PROTOCOL_V1` environment variable,
which forces the library to use ... | Make a Protocol instance for the given handle.
Each transport can have a preference for using a particular protocol version.
This preference is overridable through `TREZOR_PROTOCOL_V1` environment variable,
which forces the library to use V1 anyways.
As of 11/2018, no devices support V2, so we enforce... | Below is the the instruction that describes the task:
### Input:
Make a Protocol instance for the given handle.
Each transport can have a preference for using a particular protocol version.
This preference is overridable through `TREZOR_PROTOCOL_V1` environment variable,
which forces the library to use... |
def semicovariance(prices, benchmark=0, frequency=252):
"""
Estimate the semicovariance matrix, i.e the covariance given that
the returns are less than the benchmark.
.. semicov = E([min(r_i - B, 0)] . [min(r_j - B, 0)])
:param prices: adjusted closing prices of the asset, each row is a date
... | Estimate the semicovariance matrix, i.e the covariance given that
the returns are less than the benchmark.
.. semicov = E([min(r_i - B, 0)] . [min(r_j - B, 0)])
:param prices: adjusted closing prices of the asset, each row is a date
and each column is a ticker/id.
:type prices: pd.D... | Below is the the instruction that describes the task:
### Input:
Estimate the semicovariance matrix, i.e the covariance given that
the returns are less than the benchmark.
.. semicov = E([min(r_i - B, 0)] . [min(r_j - B, 0)])
:param prices: adjusted closing prices of the asset, each row is a date
... |
def set_cfg_value(config, section, option, value):
"""Set configuration value."""
if isinstance(value, list):
value = '\n'.join(value)
config[section][option] = value | Set configuration value. | Below is the the instruction that describes the task:
### Input:
Set configuration value.
### Response:
def set_cfg_value(config, section, option, value):
"""Set configuration value."""
if isinstance(value, list):
value = '\n'.join(value)
config[section][option] = value |
def replace_all(text, dic):
"""Takes a string and dictionary. replaces all occurrences of i with j"""
for i, j in dic.iteritems():
text = text.replace(i, j)
return text | Takes a string and dictionary. replaces all occurrences of i with j | Below is the the instruction that describes the task:
### Input:
Takes a string and dictionary. replaces all occurrences of i with j
### Response:
def replace_all(text, dic):
"""Takes a string and dictionary. replaces all occurrences of i with j"""
for i, j in dic.iteritems():
text = text.replace(... |
def register_endpoints(self, backend_names):
"""
See super class satosa.frontends.base.FrontendModule
:type backend_names: list[str]
:rtype: list[(str, ((satosa.context.Context, Any) -> satosa.response.Response, Any))]
"""
self.idp_config = self._build_idp_config_endpoint... | See super class satosa.frontends.base.FrontendModule
:type backend_names: list[str]
:rtype: list[(str, ((satosa.context.Context, Any) -> satosa.response.Response, Any))] | Below is the the instruction that describes the task:
### Input:
See super class satosa.frontends.base.FrontendModule
:type backend_names: list[str]
:rtype: list[(str, ((satosa.context.Context, Any) -> satosa.response.Response, Any))]
### Response:
def register_endpoints(self, backend_names):
... |
def pause_knocks(obj):
"""
Context manager to suspend sending knocks for the given model
:param obj: model instance
"""
if not hasattr(_thread_locals, 'knock_enabled'):
_thread_locals.knock_enabled = {}
obj.__class__._disconnect()
_thread_locals.knock_enabled[obj.__class__] = False
... | Context manager to suspend sending knocks for the given model
:param obj: model instance | Below is the the instruction that describes the task:
### Input:
Context manager to suspend sending knocks for the given model
:param obj: model instance
### Response:
def pause_knocks(obj):
"""
Context manager to suspend sending knocks for the given model
:param obj: model instance
"""
i... |
def remove_grad_hooks(module, input):
""" Remove gradient hooks to all of the parameters and monitored vars """
for hook in list(module.param_hooks.keys()):
module.param_hooks[hook].remove()
module.param_hooks.pop(hook)
for hook in list(module.var_hooks.keys()):
module.var_hooks[hook... | Remove gradient hooks to all of the parameters and monitored vars | Below is the the instruction that describes the task:
### Input:
Remove gradient hooks to all of the parameters and monitored vars
### Response:
def remove_grad_hooks(module, input):
""" Remove gradient hooks to all of the parameters and monitored vars """
for hook in list(module.param_hooks.keys()):
... |
def set_fetcher(self, fetcher_class):
"""Set the fetcher class.
:Parameters:
- `fetcher_class`: the fetcher class.
:Types:
- `fetcher_class`: `CacheFetcher` based class
"""
self._lock.acquire()
try:
self._fetcher = fetcher_class
... | Set the fetcher class.
:Parameters:
- `fetcher_class`: the fetcher class.
:Types:
- `fetcher_class`: `CacheFetcher` based class | Below is the the instruction that describes the task:
### Input:
Set the fetcher class.
:Parameters:
- `fetcher_class`: the fetcher class.
:Types:
- `fetcher_class`: `CacheFetcher` based class
### Response:
def set_fetcher(self, fetcher_class):
"""Set the fetcher cl... |
def _already_cutoff_filtered(in_file, filter_type):
"""Check if we have a pre-existing cutoff-based filter file from previous VQSR failure.
"""
filter_file = "%s-filter%s.vcf.gz" % (utils.splitext_plus(in_file)[0], filter_type)
return utils.file_exists(filter_file) | Check if we have a pre-existing cutoff-based filter file from previous VQSR failure. | Below is the the instruction that describes the task:
### Input:
Check if we have a pre-existing cutoff-based filter file from previous VQSR failure.
### Response:
def _already_cutoff_filtered(in_file, filter_type):
"""Check if we have a pre-existing cutoff-based filter file from previous VQSR failure.
"""... |
def setup_logging(verbosity=0):
"""Configure python `logging`. This is required before the `debug()`,
`info()`, etc. functions may be used.
If any other `codekit.*` modules, which are not a "package", have been
imported, and they have a `setup_logging()` function, that is called before
`logging` i... | Configure python `logging`. This is required before the `debug()`,
`info()`, etc. functions may be used.
If any other `codekit.*` modules, which are not a "package", have been
imported, and they have a `setup_logging()` function, that is called before
`logging` is configured. This gives other modules... | Below is the the instruction that describes the task:
### Input:
Configure python `logging`. This is required before the `debug()`,
`info()`, etc. functions may be used.
If any other `codekit.*` modules, which are not a "package", have been
imported, and they have a `setup_logging()` function, that is... |
def parse_value(self, value_string: str):
"""
Parses the amount string.
"""
self.value = Decimal(value_string)
return self.value | Parses the amount string. | Below is the the instruction that describes the task:
### Input:
Parses the amount string.
### Response:
def parse_value(self, value_string: str):
"""
Parses the amount string.
"""
self.value = Decimal(value_string)
return self.value |
def render_standalone_response(self, request, fragment, **kwargs): # pylint: disable=unused-argument
"""
Renders a standalone page as a response for the specified fragment.
"""
if fragment is None:
return HttpResponse(status=204)
html = self.render_to_standalone_htm... | Renders a standalone page as a response for the specified fragment. | Below is the the instruction that describes the task:
### Input:
Renders a standalone page as a response for the specified fragment.
### Response:
def render_standalone_response(self, request, fragment, **kwargs): # pylint: disable=unused-argument
"""
Renders a standalone page as a response for th... |
def delete_connection(self, name, reason=None):
"""
Closes an individual connection. Give an optional reason
:param name: The connection name
:type name: str
:param reason: An option reason why the connection was deleted
:type reason: str
"""
headers = {... | Closes an individual connection. Give an optional reason
:param name: The connection name
:type name: str
:param reason: An option reason why the connection was deleted
:type reason: str | Below is the the instruction that describes the task:
### Input:
Closes an individual connection. Give an optional reason
:param name: The connection name
:type name: str
:param reason: An option reason why the connection was deleted
:type reason: str
### Response:
def delete_conn... |
def configureCredentials(self, CAFilePath, KeyPath="", CertificatePath=""): # Should be good for MutualAuth and Websocket
"""
**Description**
Used to configure the rootCA, private key and certificate files. Should be called before connect. This is a public
facing API inherited by appli... | **Description**
Used to configure the rootCA, private key and certificate files. Should be called before connect. This is a public
facing API inherited by application level public clients.
**Syntax**
.. code:: python
myShadowClient.clearLastWill("PATH/TO/ROOT_CA", "PATH/TO/... | Below is the the instruction that describes the task:
### Input:
**Description**
Used to configure the rootCA, private key and certificate files. Should be called before connect. This is a public
facing API inherited by application level public clients.
**Syntax**
.. code:: python... |
def rsa_private_key_pkcs8_to_pkcs1(pkcs8_key):
"""Convert a PKCS8-encoded RSA private key to PKCS1."""
decoded_values = decoder.decode(pkcs8_key, asn1Spec=PKCS8PrivateKey())
try:
decoded_key = decoded_values[0]
except IndexError:
raise ValueError("Invalid private key encoding")
ret... | Convert a PKCS8-encoded RSA private key to PKCS1. | Below is the the instruction that describes the task:
### Input:
Convert a PKCS8-encoded RSA private key to PKCS1.
### Response:
def rsa_private_key_pkcs8_to_pkcs1(pkcs8_key):
"""Convert a PKCS8-encoded RSA private key to PKCS1."""
decoded_values = decoder.decode(pkcs8_key, asn1Spec=PKCS8PrivateKey())
... |
def stats_view(request, activity_id=None):
""" If a the GET parameter `year` is set, it uses stats from given year
with the following caveats:
- If it's the current year and start_date is set, start_date is ignored
- If it's the current year, stats will only show up to today - they w... | If a the GET parameter `year` is set, it uses stats from given year
with the following caveats:
- If it's the current year and start_date is set, start_date is ignored
- If it's the current year, stats will only show up to today - they won't
go into the future.
`all... | Below is the the instruction that describes the task:
### Input:
If a the GET parameter `year` is set, it uses stats from given year
with the following caveats:
- If it's the current year and start_date is set, start_date is ignored
- If it's the current year, stats will only show up... |
def format_configfield_nodes(field_name, field, field_id, state, lineno):
"""Create a section node that documents a ConfigField config field.
Parameters
----------
field_name : `str`
Name of the configuration field (the attribute name of on the config
class).
field : ``lsst.pex.conf... | Create a section node that documents a ConfigField config field.
Parameters
----------
field_name : `str`
Name of the configuration field (the attribute name of on the config
class).
field : ``lsst.pex.config.ConfigField``
A configuration field.
field_id : `str`
Uniq... | Below is the the instruction that describes the task:
### Input:
Create a section node that documents a ConfigField config field.
Parameters
----------
field_name : `str`
Name of the configuration field (the attribute name of on the config
class).
field : ``lsst.pex.config.ConfigFie... |
def cloudant(user, passwd, **kwargs):
"""
Provides a context manager to create a Cloudant session and
provide access to databases, docs etc.
:param str user: Username used to connect to Cloudant.
:param str passwd: Authentication token used to connect to Cloudant.
:param str account: The Clouda... | Provides a context manager to create a Cloudant session and
provide access to databases, docs etc.
:param str user: Username used to connect to Cloudant.
:param str passwd: Authentication token used to connect to Cloudant.
:param str account: The Cloudant account name. If the account parameter
... | Below is the the instruction that describes the task:
### Input:
Provides a context manager to create a Cloudant session and
provide access to databases, docs etc.
:param str user: Username used to connect to Cloudant.
:param str passwd: Authentication token used to connect to Cloudant.
:param str ... |
def random_discrete_dp(num_states, num_actions, beta=None,
k=None, scale=1, sparse=False, sa_pair=False,
random_state=None):
"""
Generate a DiscreteDP randomly. The reward values are drawn from the
normal distribution with mean 0 and standard deviation `scale`.
Parameters
... | Generate a DiscreteDP randomly. The reward values are drawn from the
normal distribution with mean 0 and standard deviation `scale`.
Parameters
----------
num_states : scalar(int)
Number of states.
num_actions : scalar(int)
Number of actions.
beta : scalar(float), optional(def... | Below is the the instruction that describes the task:
### Input:
Generate a DiscreteDP randomly. The reward values are drawn from the
normal distribution with mean 0 and standard deviation `scale`.
Parameters
----------
num_states : scalar(int)
Number of states.
num_actions : scalar(in... |
def parse_simplersp(self, tup_tree):
"""
Parse for SIMPLERSP Element.
::
<!ELEMENT SIMPLERSP (METHODRESPONSE | IMETHODRESPONSE)>
"""
self.check_node(tup_tree, 'SIMPLERSP')
child = self.one_child(tup_tree, ('METHODRESPONSE', 'IMETHODRESPONSE'))
r... | Parse for SIMPLERSP Element.
::
<!ELEMENT SIMPLERSP (METHODRESPONSE | IMETHODRESPONSE)> | Below is the the instruction that describes the task:
### Input:
Parse for SIMPLERSP Element.
::
<!ELEMENT SIMPLERSP (METHODRESPONSE | IMETHODRESPONSE)>
### Response:
def parse_simplersp(self, tup_tree):
"""
Parse for SIMPLERSP Element.
::
<!ELEMENT S... |
def lower_key(fn):
"""
:param fn: a key function
:return:
a function that wraps around the supplied key function to ensure
the returned key is in lowercase.
"""
def lower(key):
try:
return key.lower()
except AttributeError:
return key
retu... | :param fn: a key function
:return:
a function that wraps around the supplied key function to ensure
the returned key is in lowercase. | Below is the the instruction that describes the task:
### Input:
:param fn: a key function
:return:
a function that wraps around the supplied key function to ensure
the returned key is in lowercase.
### Response:
def lower_key(fn):
"""
:param fn: a key function
:return:
a ... |
def parse_name(parser):
# type: (Parser) -> Name
"""Converts a name lex token into a name parse node."""
token = expect(parser, TokenKind.NAME)
return ast.Name(value=token.value, loc=loc(parser, token.start)) | Converts a name lex token into a name parse node. | Below is the the instruction that describes the task:
### Input:
Converts a name lex token into a name parse node.
### Response:
def parse_name(parser):
# type: (Parser) -> Name
"""Converts a name lex token into a name parse node."""
token = expect(parser, TokenKind.NAME)
return ast.Name(value=toke... |
def set_default_masses(self):
"""Set self.masses based on self.numbers and periodic table."""
self.masses = np.array([periodic[n].mass for n in self.numbers]) | Set self.masses based on self.numbers and periodic table. | Below is the the instruction that describes the task:
### Input:
Set self.masses based on self.numbers and periodic table.
### Response:
def set_default_masses(self):
"""Set self.masses based on self.numbers and periodic table."""
self.masses = np.array([periodic[n].mass for n in self.numbers]) |
def FromDatetime(self, dt):
"""Converts datetime to Timestamp."""
td = dt - datetime(1970, 1, 1)
self.seconds = td.seconds + td.days * _SECONDS_PER_DAY
self.nanos = td.microseconds * _NANOS_PER_MICROSECOND | Converts datetime to Timestamp. | Below is the the instruction that describes the task:
### Input:
Converts datetime to Timestamp.
### Response:
def FromDatetime(self, dt):
"""Converts datetime to Timestamp."""
td = dt - datetime(1970, 1, 1)
self.seconds = td.seconds + td.days * _SECONDS_PER_DAY
self.nanos = td.microseconds * _NANO... |
def close(self):
""" Prompt the objects to output pdf code, and save to file. """
self.document._set_page_numbers()
# Places header, pages, page content first.
self._put_header()
self._put_pages()
self._put_resources()
# Information object
self._pu... | Prompt the objects to output pdf code, and save to file. | Below is the the instruction that describes the task:
### Input:
Prompt the objects to output pdf code, and save to file.
### Response:
def close(self):
""" Prompt the objects to output pdf code, and save to file. """
self.document._set_page_numbers()
# Places header, pages, page content... |
def doi_to_wos(wosclient, doi):
"""Convert DOI to WOS identifier."""
results = query(wosclient, 'DO="%s"' % doi, './REC/UID', count=1)
return results[0].lstrip('WOS:') if results else None | Convert DOI to WOS identifier. | Below is the the instruction that describes the task:
### Input:
Convert DOI to WOS identifier.
### Response:
def doi_to_wos(wosclient, doi):
"""Convert DOI to WOS identifier."""
results = query(wosclient, 'DO="%s"' % doi, './REC/UID', count=1)
return results[0].lstrip('WOS:') if results else None |
async def set_constraints(self, constraints):
"""Set machine constraints for this application.
:param dict constraints: Dict of machine constraints
"""
app_facade = client.ApplicationFacade.from_connection(self.connection)
log.debug(
'Setting constraints for %s: %s... | Set machine constraints for this application.
:param dict constraints: Dict of machine constraints | Below is the the instruction that describes the task:
### Input:
Set machine constraints for this application.
:param dict constraints: Dict of machine constraints
### Response:
async def set_constraints(self, constraints):
"""Set machine constraints for this application.
:param dict cons... |
def create_view(operations, operation):
"""
Implements ``CREATE VIEW``.
Args:
operations: instance of ``alembic.operations.base.Operations``
operation: instance of :class:`.ReversibleOp`
Returns:
``None``
"""
operations.execute("CREATE VIEW %s AS %s" % (
operati... | Implements ``CREATE VIEW``.
Args:
operations: instance of ``alembic.operations.base.Operations``
operation: instance of :class:`.ReversibleOp`
Returns:
``None`` | Below is the the instruction that describes the task:
### Input:
Implements ``CREATE VIEW``.
Args:
operations: instance of ``alembic.operations.base.Operations``
operation: instance of :class:`.ReversibleOp`
Returns:
``None``
### Response:
def create_view(operations, operation):
... |
def r_receive(self, filename):
""" Function which receives the data from Perseids
- Check the branch does not exist
- Make the branch if needed
- Receive PUT from Perseids
- Check if content exist
- Update/Create content
- Open Pull Reques... | Function which receives the data from Perseids
- Check the branch does not exist
- Make the branch if needed
- Receive PUT from Perseids
- Check if content exist
- Update/Create content
- Open Pull Request
- Return PR link to Perseids
... | Below is the the instruction that describes the task:
### Input:
Function which receives the data from Perseids
- Check the branch does not exist
- Make the branch if needed
- Receive PUT from Perseids
- Check if content exist
- Update/Create content
... |
def integer_based_slice(self, ts):
"""
Transform a :class:`TimeSlice` into integer indices that numpy can work
with
Args:
ts (slice, TimeSlice): the time slice to translate into integer
indices
"""
if isinstance(ts, slice):
try:
... | Transform a :class:`TimeSlice` into integer indices that numpy can work
with
Args:
ts (slice, TimeSlice): the time slice to translate into integer
indices | Below is the the instruction that describes the task:
### Input:
Transform a :class:`TimeSlice` into integer indices that numpy can work
with
Args:
ts (slice, TimeSlice): the time slice to translate into integer
indices
### Response:
def integer_based_slice(self, ts):
... |
def _get_and_execute(self):
"""
:return: True if it should continue running, False if it should end its execution.
"""
try:
work = self.queue.get(timeout=self.max_seconds_idle)
except queue.Empty:
# max_seconds_idle has been exhausted, exiting
... | :return: True if it should continue running, False if it should end its execution. | Below is the the instruction that describes the task:
### Input:
:return: True if it should continue running, False if it should end its execution.
### Response:
def _get_and_execute(self):
"""
:return: True if it should continue running, False if it should end its execution.
"""
tr... |
def pad_cells(table):
"""Pad each cell to the size of the largest cell in its column."""
col_sizes = [max(map(len, col)) for col in zip(*table)]
for row in table:
for cell_num, cell in enumerate(row):
row[cell_num] = pad_to(cell, col_sizes[cell_num])
return table | Pad each cell to the size of the largest cell in its column. | Below is the the instruction that describes the task:
### Input:
Pad each cell to the size of the largest cell in its column.
### Response:
def pad_cells(table):
"""Pad each cell to the size of the largest cell in its column."""
col_sizes = [max(map(len, col)) for col in zip(*table)]
for row in table:
... |
def _get_definition_from_module(definitions_module, symbol):
"""Given a python module fetch the declaration of a variable."""
path = definitions_module.__file__
path = path.replace('.pyc', '.py')
source = open(path, encoding='utf-8').readlines()
text = None
for line in source:
if symbol ... | Given a python module fetch the declaration of a variable. | Below is the the instruction that describes the task:
### Input:
Given a python module fetch the declaration of a variable.
### Response:
def _get_definition_from_module(definitions_module, symbol):
"""Given a python module fetch the declaration of a variable."""
path = definitions_module.__file__
path... |
def MGMT_PENDING_SET(self, sAddr='', xCommissionerSessionId=None, listPendingTimestamp=None, listActiveTimestamp=None, xDelayTimer=None,
xChannel=None, xPanId=None, xMasterKey=None, sMeshLocalPrefix=None, sNetworkName=None):
"""send MGMT_PENDING_SET command
Returns:
... | send MGMT_PENDING_SET command
Returns:
True: successful to send MGMT_PENDING_SET
False: fail to send MGMT_PENDING_SET | Below is the the instruction that describes the task:
### Input:
send MGMT_PENDING_SET command
Returns:
True: successful to send MGMT_PENDING_SET
False: fail to send MGMT_PENDING_SET
### Response:
def MGMT_PENDING_SET(self, sAddr='', xCommissionerSessionId=None, listPendingTimestam... |
def _concat_bgzip_fastq(finputs, out_dir, read, ldetail):
"""Concatenate multiple input fastq files, preparing a bgzipped output file.
"""
out_file = os.path.join(out_dir, "%s_%s.fastq.gz" % (ldetail["name"], read))
if not utils.file_exists(out_file):
with file_transaction(out_file) as tx_out_fi... | Concatenate multiple input fastq files, preparing a bgzipped output file. | Below is the the instruction that describes the task:
### Input:
Concatenate multiple input fastq files, preparing a bgzipped output file.
### Response:
def _concat_bgzip_fastq(finputs, out_dir, read, ldetail):
"""Concatenate multiple input fastq files, preparing a bgzipped output file.
"""
out_file = ... |
def currentAction( self ):
"""
Returns the action that is currently checked in the system.
:return <QAction> || None
"""
if ( not self._actionGroup ):
return None
for act in self._actionGroup.actions():
if ( act.isChecked(... | Returns the action that is currently checked in the system.
:return <QAction> || None | Below is the the instruction that describes the task:
### Input:
Returns the action that is currently checked in the system.
:return <QAction> || None
### Response:
def currentAction( self ):
"""
Returns the action that is currently checked in the system.
:retu... |
def add_member(self, contact_name, contactgroup_name):
"""Add a contact string to a contact member
if the contact group do not exist, create it
:param contact_name: contact name
:type contact_name: str
:param contactgroup_name: contact group name
:type contactgroup_name:... | Add a contact string to a contact member
if the contact group do not exist, create it
:param contact_name: contact name
:type contact_name: str
:param contactgroup_name: contact group name
:type contactgroup_name: str
:return: None | Below is the the instruction that describes the task:
### Input:
Add a contact string to a contact member
if the contact group do not exist, create it
:param contact_name: contact name
:type contact_name: str
:param contactgroup_name: contact group name
:type contactgroup_na... |
def create_record_set(self, rs_dict):
"""Accept a record_set dict. Return a Troposphere record_set object."""
record_set_md5 = get_record_set_md5(rs_dict["Name"], rs_dict["Type"])
rs = route53.RecordSetType.from_dict(record_set_md5, rs_dict)
rs = add_hosted_zone_id_if_missing(rs, self.ho... | Accept a record_set dict. Return a Troposphere record_set object. | Below is the the instruction that describes the task:
### Input:
Accept a record_set dict. Return a Troposphere record_set object.
### Response:
def create_record_set(self, rs_dict):
"""Accept a record_set dict. Return a Troposphere record_set object."""
record_set_md5 = get_record_set_md5(rs_dict[... |
def present(name, ip, clean=False): # pylint: disable=C0103
'''
Ensures that the named host is present with the given ip
name
The host to assign an ip to
ip
The ip addr(s) to apply to the host. Can be a single IP or a list of IP
addresses.
clean : False
Remove any... | Ensures that the named host is present with the given ip
name
The host to assign an ip to
ip
The ip addr(s) to apply to the host. Can be a single IP or a list of IP
addresses.
clean : False
Remove any entries which don't match those configured in the ``ip``
option.... | Below is the the instruction that describes the task:
### Input:
Ensures that the named host is present with the given ip
name
The host to assign an ip to
ip
The ip addr(s) to apply to the host. Can be a single IP or a list of IP
addresses.
clean : False
Remove any ent... |
def _perform_write(self, addr, data):
"""Perform a write using the machine controller."""
return self._machine_controller.write(addr, data, self._x, self._y, 0) | Perform a write using the machine controller. | Below is the the instruction that describes the task:
### Input:
Perform a write using the machine controller.
### Response:
def _perform_write(self, addr, data):
"""Perform a write using the machine controller."""
return self._machine_controller.write(addr, data, self._x, self._y, 0) |
def get_introspection_module(namespace):
"""Raises ImportError"""
if namespace in _introspection_modules:
return _introspection_modules[namespace]
from . import get_required_version
repository = GIRepository()
version = get_required_version(namespace)
try:
repository.require(... | Raises ImportError | Below is the the instruction that describes the task:
### Input:
Raises ImportError
### Response:
def get_introspection_module(namespace):
"""Raises ImportError"""
if namespace in _introspection_modules:
return _introspection_modules[namespace]
from . import get_required_version
reposito... |
def get_privacy_options(user):
"""Get a user's privacy options to pass as an initial value to a PrivacyOptionsForm."""
privacy_options = {}
for ptype in user.permissions:
for field in user.permissions[ptype]:
if ptype == "self":
privacy_options["{}-{}".format(field, pty... | Get a user's privacy options to pass as an initial value to a PrivacyOptionsForm. | Below is the the instruction that describes the task:
### Input:
Get a user's privacy options to pass as an initial value to a PrivacyOptionsForm.
### Response:
def get_privacy_options(user):
"""Get a user's privacy options to pass as an initial value to a PrivacyOptionsForm."""
privacy_options = {}
... |
def _output_results(
self):
"""
*output results*
**Key Arguments:**
# -
**Return:**
- None
.. todo::
- @review: when complete, clean _output_results method
- @review: when complete add logging
"""
sel... | *output results*
**Key Arguments:**
# -
**Return:**
- None
.. todo::
- @review: when complete, clean _output_results method
- @review: when complete add logging | Below is the the instruction that describes the task:
### Input:
*output results*
**Key Arguments:**
# -
**Return:**
- None
.. todo::
- @review: when complete, clean _output_results method
- @review: when complete add logging
### Response: ... |
def check_status(content, response):
"""
Check the response that is returned for known exceptions and errors.
:param response: Response that is returned from the call.
:raise:
MalformedRequestException if `response.status` is 400
UnauthorisedException if `response.statu... | Check the response that is returned for known exceptions and errors.
:param response: Response that is returned from the call.
:raise:
MalformedRequestException if `response.status` is 400
UnauthorisedException if `response.status` is 401
NotFoundException if `response.status`... | Below is the the instruction that describes the task:
### Input:
Check the response that is returned for known exceptions and errors.
:param response: Response that is returned from the call.
:raise:
MalformedRequestException if `response.status` is 400
UnauthorisedException if `re... |
def generate_one_of(self):
"""
Means that value have to be valid by only one of those definitions. It can't be valid
by two or more of them.
.. code-block:: python
{
'oneOf': [
{'type': 'number', 'multipleOf': 3},
{'ty... | Means that value have to be valid by only one of those definitions. It can't be valid
by two or more of them.
.. code-block:: python
{
'oneOf': [
{'type': 'number', 'multipleOf': 3},
{'type': 'number', 'multipleOf': 5},
... | Below is the the instruction that describes the task:
### Input:
Means that value have to be valid by only one of those definitions. It can't be valid
by two or more of them.
.. code-block:: python
{
'oneOf': [
{'type': 'number', 'multipleOf': 3},
... |
def page_string(str_to_page, pager_cmd):
"""
Page str_to_page via the pager.
"""
# By default, we expect the command to be `less -R`. If that is the
# pager_cmd, but they don't have less on their machine, odds are they're
# just using the default value. In this case the pager will fail, so we'll... | Page str_to_page via the pager. | Below is the the instruction that describes the task:
### Input:
Page str_to_page via the pager.
### Response:
def page_string(str_to_page, pager_cmd):
"""
Page str_to_page via the pager.
"""
# By default, we expect the command to be `less -R`. If that is the
# pager_cmd, but they don't have le... |
def _connect(self):
"""Connect to the MySQL database.
"""
try:
db = pymysql.connect(user=self.user, passwd=self.passwd,
host=self.host, port=self.port,
db=self.shdb, use_unicode=True)
return db, db.cursor(... | Connect to the MySQL database. | Below is the the instruction that describes the task:
### Input:
Connect to the MySQL database.
### Response:
def _connect(self):
"""Connect to the MySQL database.
"""
try:
db = pymysql.connect(user=self.user, passwd=self.passwd,
host=self.host,... |
def encode_hex(self, hex_str):
"""Converts a hexadecimal string (e.g. a MongoDB id) to a hashid.
:param hex_str The hexadecimal string to encodes
>>> Hashids.encode_hex('507f1f77bcf86cd799439011')
'y42LW46J9luq3Xq9XMly'
"""
numbers = (int('1' + hex_str[i:i+12], 16)
... | Converts a hexadecimal string (e.g. a MongoDB id) to a hashid.
:param hex_str The hexadecimal string to encodes
>>> Hashids.encode_hex('507f1f77bcf86cd799439011')
'y42LW46J9luq3Xq9XMly' | Below is the the instruction that describes the task:
### Input:
Converts a hexadecimal string (e.g. a MongoDB id) to a hashid.
:param hex_str The hexadecimal string to encodes
>>> Hashids.encode_hex('507f1f77bcf86cd799439011')
'y42LW46J9luq3Xq9XMly'
### Response:
def encode_hex(self, hex... |
def getctime(self, path=None, client_kwargs=None, header=None):
"""
Return the creation time of path.
Args:
path (str): File path or URL.
client_kwargs (dict): Client arguments.
header (dict): Object header.
Returns:
float: The number of ... | Return the creation time of path.
Args:
path (str): File path or URL.
client_kwargs (dict): Client arguments.
header (dict): Object header.
Returns:
float: The number of seconds since the epoch
(see the time module). | Below is the the instruction that describes the task:
### Input:
Return the creation time of path.
Args:
path (str): File path or URL.
client_kwargs (dict): Client arguments.
header (dict): Object header.
Returns:
float: The number of seconds since t... |
def delete(self, obj, matches=None, mt=None, lt=None, eq=None):
'''
Delete object from the database.
:param obj:
:param matches:
:param mt:
:param lt:
:param eq:
:return:
'''
deleted = False
objects = list()
for _obj in sel... | Delete object from the database.
:param obj:
:param matches:
:param mt:
:param lt:
:param eq:
:return: | Below is the the instruction that describes the task:
### Input:
Delete object from the database.
:param obj:
:param matches:
:param mt:
:param lt:
:param eq:
:return:
### Response:
def delete(self, obj, matches=None, mt=None, lt=None, eq=None):
'''
... |
def qrplatba(pdf,
IBAN, castka=None, mena='CZK', splatnost=None, msg=None, KS='0558', VS='', SS=None, IBAN2=None,
w=36, x=None, y=None, **payment_more):
"""This is the main method which generates the QR platba code.
pdf - object from: with PDF(<outputfilename>) as pdf:
(we use ... | This is the main method which generates the QR platba code.
pdf - object from: with PDF(<outputfilename>) as pdf:
(we use wfpdf (which is really minor wrapper),
we haven't not tested the calling with fpdf directly, but maybe it is easy)
IBAN..IBAN2 - ACC, AM, CC, DT, MSG, X-KS, X-VS, X-SS, ALT-A... | Below is the the instruction that describes the task:
### Input:
This is the main method which generates the QR platba code.
pdf - object from: with PDF(<outputfilename>) as pdf:
(we use wfpdf (which is really minor wrapper),
we haven't not tested the calling with fpdf directly, but maybe it is ... |
def register_magnitude_model(self, pid):
"""Set a given parameter model to the forward magnitude model
"""
if self.assignments['forward_model'] is None:
self.assignments['forward_model'] = [None, None]
self.assignments['forward_model'][0] = pid | Set a given parameter model to the forward magnitude model | Below is the the instruction that describes the task:
### Input:
Set a given parameter model to the forward magnitude model
### Response:
def register_magnitude_model(self, pid):
"""Set a given parameter model to the forward magnitude model
"""
if self.assignments['forward_model'] is None:
... |
def legacy_load_config(profile=None, endpoint=None, token=None, solver=None,
proxy=None, **kwargs):
"""Load configured URLs and token for the SAPI server.
.. warning:: Included only for backward compatibility. Please use
:func:`load_config` or the client factory
:meth:`~d... | Load configured URLs and token for the SAPI server.
.. warning:: Included only for backward compatibility. Please use
:func:`load_config` or the client factory
:meth:`~dwave.cloud.client.Client.from_config` instead.
This method tries to load a legacy configuration file from ``~/.dwrc``, select... | Below is the the instruction that describes the task:
### Input:
Load configured URLs and token for the SAPI server.
.. warning:: Included only for backward compatibility. Please use
:func:`load_config` or the client factory
:meth:`~dwave.cloud.client.Client.from_config` instead.
This meth... |
def fromSuccessResponse(cls, success_response):
"""Create a C{L{Response}} object from a successful OpenID
library response
(C{L{openid.consumer.consumer.SuccessResponse}}) response
message
@param success_response: A SuccessResponse from consumer.complete()
@type success... | Create a C{L{Response}} object from a successful OpenID
library response
(C{L{openid.consumer.consumer.SuccessResponse}}) response
message
@param success_response: A SuccessResponse from consumer.complete()
@type success_response: C{L{openid.consumer.consumer.SuccessResponse}}
... | Below is the the instruction that describes the task:
### Input:
Create a C{L{Response}} object from a successful OpenID
library response
(C{L{openid.consumer.consumer.SuccessResponse}}) response
message
@param success_response: A SuccessResponse from consumer.complete()
@ty... |
def remove_symbol_add_symbol(string_item, remove_symbol, add_symbol):
"""
Remove a symbol from a string, and replace it with a different one
Args:
string_item: String that you want to replace symbols in
remove_symbol: Symbol to remove
add_symbol: Symbol to add
Returns: returns a... | Remove a symbol from a string, and replace it with a different one
Args:
string_item: String that you want to replace symbols in
remove_symbol: Symbol to remove
add_symbol: Symbol to add
Returns: returns a string with symbols swapped | Below is the the instruction that describes the task:
### Input:
Remove a symbol from a string, and replace it with a different one
Args:
string_item: String that you want to replace symbols in
remove_symbol: Symbol to remove
add_symbol: Symbol to add
Returns: returns a string with ... |
def _build_package_finder(self, options, index_urls, session):
"""
Create a package finder appropriate to this install command.
This method is meant to be overridden by subclasses, not
called directly.
"""
return PackageFinder(
find_links=options.find_links,
... | Create a package finder appropriate to this install command.
This method is meant to be overridden by subclasses, not
called directly. | Below is the the instruction that describes the task:
### Input:
Create a package finder appropriate to this install command.
This method is meant to be overridden by subclasses, not
called directly.
### Response:
def _build_package_finder(self, options, index_urls, session):
"""
Cr... |
def featureclass_to_json(fc):
"""converts a feature class to JSON"""
if arcpyFound == False:
raise Exception("ArcPy is required to use this function")
desc = arcpy.Describe(fc)
if desc.dataType == "Table" or desc.dataType == "TableView":
return recordset_to_json(table=fc)
else:
... | converts a feature class to JSON | Below is the the instruction that describes the task:
### Input:
converts a feature class to JSON
### Response:
def featureclass_to_json(fc):
"""converts a feature class to JSON"""
if arcpyFound == False:
raise Exception("ArcPy is required to use this function")
desc = arcpy.Describe(fc)
if... |
def _merge_metadata(samples):
"""Merge all metadata into CSV file"""
samples = list(utils.flatten(samples))
out_dir = dd.get_work_dir(samples[0])
logger.info("summarize metadata")
out_file = os.path.join(out_dir, "metadata.csv")
sample_metrics = collections.defaultdict(dict)
for s in samples... | Merge all metadata into CSV file | Below is the the instruction that describes the task:
### Input:
Merge all metadata into CSV file
### Response:
def _merge_metadata(samples):
"""Merge all metadata into CSV file"""
samples = list(utils.flatten(samples))
out_dir = dd.get_work_dir(samples[0])
logger.info("summarize metadata")
out... |
def exp_schedule(k=20, lam=0.005, limit=100):
"One possible schedule function for simulated annealing"
return lambda t: if_(t < limit, k * math.exp(-lam * t), 0) | One possible schedule function for simulated annealing | Below is the the instruction that describes the task:
### Input:
One possible schedule function for simulated annealing
### Response:
def exp_schedule(k=20, lam=0.005, limit=100):
"One possible schedule function for simulated annealing"
return lambda t: if_(t < limit, k * math.exp(-lam * t), 0) |
def remove(name, keystore, passphrase):
'''
Removes a certificate from an existing keystore.
Returns True if remove was successful, otherwise False
:param name: alias for the certificate
:param keystore: The path to the keystore file to query
:param passphrase: The passphrase to use to decode t... | Removes a certificate from an existing keystore.
Returns True if remove was successful, otherwise False
:param name: alias for the certificate
:param keystore: The path to the keystore file to query
:param passphrase: The passphrase to use to decode the keystore
CLI Example:
.. code-block:: b... | Below is the the instruction that describes the task:
### Input:
Removes a certificate from an existing keystore.
Returns True if remove was successful, otherwise False
:param name: alias for the certificate
:param keystore: The path to the keystore file to query
:param passphrase: The passphrase t... |
def run(self, request_cb, notification_cb):
"""Run the event loop to receive requests and notifications from Nvim.
While the event loop is running, `request_cb` and `_notification_cb`
will be called whenever requests or notifications are respectively
available.
"""
self.... | Run the event loop to receive requests and notifications from Nvim.
While the event loop is running, `request_cb` and `_notification_cb`
will be called whenever requests or notifications are respectively
available. | Below is the the instruction that describes the task:
### Input:
Run the event loop to receive requests and notifications from Nvim.
While the event loop is running, `request_cb` and `_notification_cb`
will be called whenever requests or notifications are respectively
available.
### Respons... |
def unbind_key(pymux, variables):
"""
Remove key binding.
"""
key = variables['<key>']
needs_prefix = not variables['-n']
pymux.key_bindings_manager.remove_custom_binding(
key, needs_prefix=needs_prefix) | Remove key binding. | Below is the the instruction that describes the task:
### Input:
Remove key binding.
### Response:
def unbind_key(pymux, variables):
"""
Remove key binding.
"""
key = variables['<key>']
needs_prefix = not variables['-n']
pymux.key_bindings_manager.remove_custom_binding(
key, needs_... |
def from_json(self, json_text):
"""Deserialize a JSON object into this object. This method will
check that the JSON object has the required keys and will set each
of the keys in that JSON object as an instance attribute of this
object.
:param json_text: the JSON text or object ... | Deserialize a JSON object into this object. This method will
check that the JSON object has the required keys and will set each
of the keys in that JSON object as an instance attribute of this
object.
:param json_text: the JSON text or object to deserialize from
:type json_text... | Below is the the instruction that describes the task:
### Input:
Deserialize a JSON object into this object. This method will
check that the JSON object has the required keys and will set each
of the keys in that JSON object as an instance attribute of this
object.
:param json_text... |
def print_resolve_diff(self, other, heading=None):
"""Print the difference between the resolve of two contexts.
Args:
other (`ResolvedContext`): Context to compare to.
heading: One of:
- None: Do not display a heading;
- True: Display the filename... | Print the difference between the resolve of two contexts.
Args:
other (`ResolvedContext`): Context to compare to.
heading: One of:
- None: Do not display a heading;
- True: Display the filename of each context as a heading, if
both conte... | Below is the the instruction that describes the task:
### Input:
Print the difference between the resolve of two contexts.
Args:
other (`ResolvedContext`): Context to compare to.
heading: One of:
- None: Do not display a heading;
- True: Display the f... |
def push_message(self, to, messages, timeout=None):
"""Call push message API.
https://devdocs.line.me/en/#push-message
Send messages to users, groups, and rooms at any time.
:param str to: ID of the receiver
:param messages: Messages.
Max: 5
:type messages:... | Call push message API.
https://devdocs.line.me/en/#push-message
Send messages to users, groups, and rooms at any time.
:param str to: ID of the receiver
:param messages: Messages.
Max: 5
:type messages: T <= :py:class:`linebot.models.send_messages.SendMessage` |
... | Below is the the instruction that describes the task:
### Input:
Call push message API.
https://devdocs.line.me/en/#push-message
Send messages to users, groups, and rooms at any time.
:param str to: ID of the receiver
:param messages: Messages.
Max: 5
:type mes... |
def _get_data_from_filepath(self, filepath_or_buffer):
"""
The function read_json accepts three input types:
1. filepath (string-like)
2. file-like object (e.g. open file object, StringIO)
3. JSON string
This method turns (1) into (2) to simplify the rest of ... | The function read_json accepts three input types:
1. filepath (string-like)
2. file-like object (e.g. open file object, StringIO)
3. JSON string
This method turns (1) into (2) to simplify the rest of the processing.
It returns input types (2) and (3) unchanged. | Below is the the instruction that describes the task:
### Input:
The function read_json accepts three input types:
1. filepath (string-like)
2. file-like object (e.g. open file object, StringIO)
3. JSON string
This method turns (1) into (2) to simplify the rest of the pr... |
def make_banner(
text: typing.Optional[str] = None,
context: typing.Optional[Context] = None,
banner_template: typing.Optional[str] = None,
context_format: ContextFormat = "full",
) -> str:
"""Generates a full banner with version info, the given text, and a
formatted list of context variables.
... | Generates a full banner with version info, the given text, and a
formatted list of context variables. | Below is the the instruction that describes the task:
### Input:
Generates a full banner with version info, the given text, and a
formatted list of context variables.
### Response:
def make_banner(
text: typing.Optional[str] = None,
context: typing.Optional[Context] = None,
banner_template: typing.... |
def is_quantity(q):
'''
is_quantity(q) yields True if q is a pint quantity or a tuple (scalar, unit) and False
otherwise.
'''
if isinstance(q, tuple):
return len(q) == 2 and is_unit(q[1])
else:
cls = type(q)
return cls.__module__.startswith('pint.') and cls.__name__ == ... | is_quantity(q) yields True if q is a pint quantity or a tuple (scalar, unit) and False
otherwise. | Below is the the instruction that describes the task:
### Input:
is_quantity(q) yields True if q is a pint quantity or a tuple (scalar, unit) and False
otherwise.
### Response:
def is_quantity(q):
'''
is_quantity(q) yields True if q is a pint quantity or a tuple (scalar, unit) and False
otherwi... |
def create_api_network_ipv4(self):
"""Get an instance of Api Networkv4 services facade."""
return ApiNetworkIPv4(
self.networkapi_url,
self.user,
self.password,
self.user_ldap) | Get an instance of Api Networkv4 services facade. | Below is the the instruction that describes the task:
### Input:
Get an instance of Api Networkv4 services facade.
### Response:
def create_api_network_ipv4(self):
"""Get an instance of Api Networkv4 services facade."""
return ApiNetworkIPv4(
self.networkapi_url,
self.user,... |
def parseFASTACommandLineOptions(args):
"""
Examine parsed command-line options and return a Reads instance.
@param args: An argparse namespace, as returned by the argparse
C{parse_args} function.
@return: A C{Reads} subclass instance, depending on the type of FASTA file
given.
"""
... | Examine parsed command-line options and return a Reads instance.
@param args: An argparse namespace, as returned by the argparse
C{parse_args} function.
@return: A C{Reads} subclass instance, depending on the type of FASTA file
given. | Below is the the instruction that describes the task:
### Input:
Examine parsed command-line options and return a Reads instance.
@param args: An argparse namespace, as returned by the argparse
C{parse_args} function.
@return: A C{Reads} subclass instance, depending on the type of FASTA file
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.