code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def add_vts(self, task_name, targets, cache_key, valid, phase):
""" Add a single VersionedTargetSet entry to the report.
:param InvalidationCacheManager cache_manager:
:param CacheKey cache_key:
:param bool valid:
:param string phase:
"""
if task_name not in self._task_reports:
self.ad... | Add a single VersionedTargetSet entry to the report.
:param InvalidationCacheManager cache_manager:
:param CacheKey cache_key:
:param bool valid:
:param string phase: | Below is the the instruction that describes the task:
### Input:
Add a single VersionedTargetSet entry to the report.
:param InvalidationCacheManager cache_manager:
:param CacheKey cache_key:
:param bool valid:
:param string phase:
### Response:
def add_vts(self, task_name, targets, cache_key, vali... |
def node_setup(name, master, ticket):
'''
Setup the icinga2 node.
name
The domain name for which this certificate will be saved
master
Icinga2 master node for which this certificate will be saved
ticket
Authentication ticket generated on icinga2 master
'''
ret = {'... | Setup the icinga2 node.
name
The domain name for which this certificate will be saved
master
Icinga2 master node for which this certificate will be saved
ticket
Authentication ticket generated on icinga2 master | Below is the the instruction that describes the task:
### Input:
Setup the icinga2 node.
name
The domain name for which this certificate will be saved
master
Icinga2 master node for which this certificate will be saved
ticket
Authentication ticket generated on icinga2 master
#... |
def make_classes(base_class, module):
"""Create derived classes and put them into the same module as the base class.
This function is called at the end of each of the derived class modules, acs, census, civik and tiger.
It will create a set of new derived class in the module, one for each of the enries in... | Create derived classes and put them into the same module as the base class.
This function is called at the end of each of the derived class modules, acs, census, civik and tiger.
It will create a set of new derived class in the module, one for each of the enries in the `summary_levels`
dict. | Below is the the instruction that describes the task:
### Input:
Create derived classes and put them into the same module as the base class.
This function is called at the end of each of the derived class modules, acs, census, civik and tiger.
It will create a set of new derived class in the module, one fo... |
def _read_single_point_data(self):
"""
Parses final free energy information from single-point calculations.
"""
temp_dict = read_pattern(
self.text, {
"final_energy":
r"\s*SCF\s+energy in the final basis set\s+=\s*([\d\-\.]+)"
}... | Parses final free energy information from single-point calculations. | Below is the the instruction that describes the task:
### Input:
Parses final free energy information from single-point calculations.
### Response:
def _read_single_point_data(self):
"""
Parses final free energy information from single-point calculations.
"""
temp_dict = read_patter... |
def set_policy(table='filter', chain=None, policy=None, family='ipv4'):
'''
Set the current policy for the specified table/chain
CLI Example:
.. code-block:: bash
salt '*' iptables.set_policy filter INPUT ACCEPT
IPv6:
salt '*' iptables.set_policy filter INPUT ACCEPT family=ip... | Set the current policy for the specified table/chain
CLI Example:
.. code-block:: bash
salt '*' iptables.set_policy filter INPUT ACCEPT
IPv6:
salt '*' iptables.set_policy filter INPUT ACCEPT family=ipv6 | Below is the the instruction that describes the task:
### Input:
Set the current policy for the specified table/chain
CLI Example:
.. code-block:: bash
salt '*' iptables.set_policy filter INPUT ACCEPT
IPv6:
salt '*' iptables.set_policy filter INPUT ACCEPT family=ipv6
### Response... |
def unShare(sharedItem):
"""
Remove all instances of this item from public or shared view.
"""
sharedItem.store.query(Share, Share.sharedItem == sharedItem).deleteFromStore() | Remove all instances of this item from public or shared view. | Below is the the instruction that describes the task:
### Input:
Remove all instances of this item from public or shared view.
### Response:
def unShare(sharedItem):
"""
Remove all instances of this item from public or shared view.
"""
sharedItem.store.query(Share, Share.sharedItem == sharedItem).d... |
def create_login_profile(user_name, password, region=None, key=None,
keyid=None, profile=None):
'''
Creates a login profile for the specified user, give the user the
ability to access AWS services and the AWS Management Console.
.. versionadded:: 2015.8.0
CLI Example:
... | Creates a login profile for the specified user, give the user the
ability to access AWS services and the AWS Management Console.
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion boto_iam.create_login_profile user_name password | Below is the the instruction that describes the task:
### Input:
Creates a login profile for the specified user, give the user the
ability to access AWS services and the AWS Management Console.
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion boto_iam.create_log... |
def get_instance(self, payload):
"""
Build an instance of EventInstance
:param dict payload: Payload response from the API
:returns: twilio.rest.taskrouter.v1.workspace.event.EventInstance
:rtype: twilio.rest.taskrouter.v1.workspace.event.EventInstance
"""
retur... | Build an instance of EventInstance
:param dict payload: Payload response from the API
:returns: twilio.rest.taskrouter.v1.workspace.event.EventInstance
:rtype: twilio.rest.taskrouter.v1.workspace.event.EventInstance | Below is the the instruction that describes the task:
### Input:
Build an instance of EventInstance
:param dict payload: Payload response from the API
:returns: twilio.rest.taskrouter.v1.workspace.event.EventInstance
:rtype: twilio.rest.taskrouter.v1.workspace.event.EventInstance
### Respo... |
def write_file_list_cache(opts, data, list_cache, w_lock):
'''
Checks the cache file to see if there is a new enough file list cache, and
returns the match (if found, along with booleans used by the fileserver
backend to determine if the cache needs to be refreshed/written).
'''
serial = salt.pa... | Checks the cache file to see if there is a new enough file list cache, and
returns the match (if found, along with booleans used by the fileserver
backend to determine if the cache needs to be refreshed/written). | Below is the the instruction that describes the task:
### Input:
Checks the cache file to see if there is a new enough file list cache, and
returns the match (if found, along with booleans used by the fileserver
backend to determine if the cache needs to be refreshed/written).
### Response:
def write_file_... |
def convert_embedding(net, node, model, builder):
"""Convert an embedding layer from mxnet to coreml.
Parameters
----------
net: network
A mxnet network object.
node: layer
Node to convert.
model: model
An model for MXNet
builder: NeuralNetworkBuilder
A ne... | Convert an embedding layer from mxnet to coreml.
Parameters
----------
net: network
A mxnet network object.
node: layer
Node to convert.
model: model
An model for MXNet
builder: NeuralNetworkBuilder
A neural network builder object. | Below is the the instruction that describes the task:
### Input:
Convert an embedding layer from mxnet to coreml.
Parameters
----------
net: network
A mxnet network object.
node: layer
Node to convert.
model: model
An model for MXNet
builder: NeuralNetworkBuilder
... |
def _find_closest_trackpointaA(self,Or,Op,Oz,ar,ap,az,interp=True):
"""
NAME:
_find_closest_trackpointaA
PURPOSE:
find the closest point on the stream track to a given point in
frequency-angle coordinates
INPUT:
Or,Op,Oz,ar,ap,az - phase-space ... | NAME:
_find_closest_trackpointaA
PURPOSE:
find the closest point on the stream track to a given point in
frequency-angle coordinates
INPUT:
Or,Op,Oz,ar,ap,az - phase-space coordinates of the given point
interp= (True), if True, return the index of t... | Below is the the instruction that describes the task:
### Input:
NAME:
_find_closest_trackpointaA
PURPOSE:
find the closest point on the stream track to a given point in
frequency-angle coordinates
INPUT:
Or,Op,Oz,ar,ap,az - phase-space coordinates of the ... |
def send_command(self, command):
"""Send a command for FastAGI request:
:param command: Command to launch on FastAGI request. Ex: 'EXEC StartMusicOnHolds'
:type command: String
:Example:
::
@asyncio.coroutine
def call_waiting(request):
... | Send a command for FastAGI request:
:param command: Command to launch on FastAGI request. Ex: 'EXEC StartMusicOnHolds'
:type command: String
:Example:
::
@asyncio.coroutine
def call_waiting(request):
print(['AGI variables:', request.headers])
... | Below is the the instruction that describes the task:
### Input:
Send a command for FastAGI request:
:param command: Command to launch on FastAGI request. Ex: 'EXEC StartMusicOnHolds'
:type command: String
:Example:
::
@asyncio.coroutine
def call_waiting(r... |
def address(self, is_compressed=None):
"""
Return the public address representation of this key, if available.
"""
return self._network.address.for_p2pkh(self.hash160(is_compressed=is_compressed)) | Return the public address representation of this key, if available. | Below is the the instruction that describes the task:
### Input:
Return the public address representation of this key, if available.
### Response:
def address(self, is_compressed=None):
"""
Return the public address representation of this key, if available.
"""
return self._network.... |
def export_public_keys(env=None, sp=subprocess):
"""Export all GPG public keys."""
args = gpg_command(['--export'])
result = check_output(args=args, env=env, sp=sp)
if not result:
raise KeyError('No GPG public keys found at env: {!r}'.format(env))
return result | Export all GPG public keys. | Below is the the instruction that describes the task:
### Input:
Export all GPG public keys.
### Response:
def export_public_keys(env=None, sp=subprocess):
"""Export all GPG public keys."""
args = gpg_command(['--export'])
result = check_output(args=args, env=env, sp=sp)
if not result:
rais... |
def read(self, filename=None, read_detection_catalog=True):
"""
Read a Party from a file.
:type filename: str
:param filename:
File to read from - can be a list of files, and can contain
wildcards.
:type read_detection_catalog: bool
:param read_de... | Read a Party from a file.
:type filename: str
:param filename:
File to read from - can be a list of files, and can contain
wildcards.
:type read_detection_catalog: bool
:param read_detection_catalog:
Whether to read the detection catalog or not, if Fa... | Below is the the instruction that describes the task:
### Input:
Read a Party from a file.
:type filename: str
:param filename:
File to read from - can be a list of files, and can contain
wildcards.
:type read_detection_catalog: bool
:param read_detection_cat... |
def copy(cls, data):
"""Set the clipboard data ('Copy').
Parameters: data to set (string)
Optional: datatype if it's not a string
Returns: True / False on successful copy, Any exception raised (like
passes the NSPasteboardCommunicationError) should be caught
... | Set the clipboard data ('Copy').
Parameters: data to set (string)
Optional: datatype if it's not a string
Returns: True / False on successful copy, Any exception raised (like
passes the NSPasteboardCommunicationError) should be caught
by the caller. | Below is the the instruction that describes the task:
### Input:
Set the clipboard data ('Copy').
Parameters: data to set (string)
Optional: datatype if it's not a string
Returns: True / False on successful copy, Any exception raised (like
passes the NSPasteboardCommunicati... |
def encode(self):
"""This method encodes the data into a binary string using
the appropriate algorithm specified by the mode.
"""
if self.mode == tables.modes['alphanumeric']:
encoded = self.encode_alphanumeric()
elif self.mode == tables.modes['numeric']:
... | This method encodes the data into a binary string using
the appropriate algorithm specified by the mode. | Below is the the instruction that describes the task:
### Input:
This method encodes the data into a binary string using
the appropriate algorithm specified by the mode.
### Response:
def encode(self):
"""This method encodes the data into a binary string using
the appropriate algorithm spec... |
def get_rejected_variables(self, threshold=0.9):
"""Return a list of variable names being rejected for high
correlation with one of remaining variables.
Parameters:
----------
threshold : float
Correlation value which is above the threshold are rejected
... | Return a list of variable names being rejected for high
correlation with one of remaining variables.
Parameters:
----------
threshold : float
Correlation value which is above the threshold are rejected
Returns
-------
list
The lis... | Below is the the instruction that describes the task:
### Input:
Return a list of variable names being rejected for high
correlation with one of remaining variables.
Parameters:
----------
threshold : float
Correlation value which is above the threshold are rejected
... |
def __load_jco(self):
"""private method to set the jco attribute from a file or a matrix object
"""
if self.jco_arg is None:
return None
#raise Exception("linear_analysis.__load_jco(): jco_arg is None")
if isinstance(self.jco_arg, Matrix):
self.__jco =... | private method to set the jco attribute from a file or a matrix object | Below is the the instruction that describes the task:
### Input:
private method to set the jco attribute from a file or a matrix object
### Response:
def __load_jco(self):
"""private method to set the jco attribute from a file or a matrix object
"""
if self.jco_arg is None:
retu... |
def validate_generations_for_story_elements(
sender,
instance,
action,
target_node_type=None,
target_node=None,
pos=None,
*args,
**kwargs
):
'''
Unlike arc nodes, for which we just warn about structure, the story tree
allowed parent/child rules... | Unlike arc nodes, for which we just warn about structure, the story tree
allowed parent/child rules must be strictly enforced. | Below is the the instruction that describes the task:
### Input:
Unlike arc nodes, for which we just warn about structure, the story tree
allowed parent/child rules must be strictly enforced.
### Response:
def validate_generations_for_story_elements(
sender,
instance,
action,
ta... |
def restore(self):
"""
Restore the 'output/' directory structure based on the `dir_structure.json` file.
"""
# We get the structure we have to create/apply.
structure = self._get_structure()
# We get the list of key which is implicitly the list of directory to recreate.... | Restore the 'output/' directory structure based on the `dir_structure.json` file. | Below is the the instruction that describes the task:
### Input:
Restore the 'output/' directory structure based on the `dir_structure.json` file.
### Response:
def restore(self):
"""
Restore the 'output/' directory structure based on the `dir_structure.json` file.
"""
# We get the... |
def get_tripIs_within_range_by_dsut(self,
start_time_ut,
end_time_ut):
"""
Obtain a list of trip_Is that take place during a time interval.
The trip needs to be only partially overlapping with the given time interval... | Obtain a list of trip_Is that take place during a time interval.
The trip needs to be only partially overlapping with the given time interval.
The grouping by dsut (day_start_ut) is required as same trip_I could
take place on multiple days.
Parameters
----------
start_ti... | Below is the the instruction that describes the task:
### Input:
Obtain a list of trip_Is that take place during a time interval.
The trip needs to be only partially overlapping with the given time interval.
The grouping by dsut (day_start_ut) is required as same trip_I could
take place on m... |
def is_existing_up_to_date(destination, latest_version):
"""Returns False if there is no existing install or if the existing install
is out of date. Otherwise, returns True."""
version_path = os.path.join(
destination, 'google_appengine', 'VERSION')
if not os.path.exists(version_path):
... | Returns False if there is no existing install or if the existing install
is out of date. Otherwise, returns True. | Below is the the instruction that describes the task:
### Input:
Returns False if there is no existing install or if the existing install
is out of date. Otherwise, returns True.
### Response:
def is_existing_up_to_date(destination, latest_version):
"""Returns False if there is no existing install or if th... |
def get_protocol_sequence(self,sweep):
"""
given a sweep, return the protocol as condensed sequence.
This is better for comparing similarities and determining steps.
There should be no duplicate numbers.
"""
self.setsweep(sweep)
return list(self.protoSeqX),list(se... | given a sweep, return the protocol as condensed sequence.
This is better for comparing similarities and determining steps.
There should be no duplicate numbers. | Below is the the instruction that describes the task:
### Input:
given a sweep, return the protocol as condensed sequence.
This is better for comparing similarities and determining steps.
There should be no duplicate numbers.
### Response:
def get_protocol_sequence(self,sweep):
"""
... |
def at_depth(self, level):
"""
Locate the last config item at a specified depth
"""
return Zconfig(lib.zconfig_at_depth(self._as_parameter_, level), False) | Locate the last config item at a specified depth | Below is the the instruction that describes the task:
### Input:
Locate the last config item at a specified depth
### Response:
def at_depth(self, level):
"""
Locate the last config item at a specified depth
"""
return Zconfig(lib.zconfig_at_depth(self._as_parameter_, level), False) |
def delete_plate(self, name):
'''Deletes a plate.
Parameters
----------
name: str
name of the plate that should be deleted
See also
--------
:func:`tmserver.api.plate.delete_plate`
:class:`tmlib.models.plate.Plate`
'''
logger.... | Deletes a plate.
Parameters
----------
name: str
name of the plate that should be deleted
See also
--------
:func:`tmserver.api.plate.delete_plate`
:class:`tmlib.models.plate.Plate` | Below is the the instruction that describes the task:
### Input:
Deletes a plate.
Parameters
----------
name: str
name of the plate that should be deleted
See also
--------
:func:`tmserver.api.plate.delete_plate`
:class:`tmlib.models.plate.Plate`... |
def gen_multi_key(self, values, db='default'):
"""Takes a list of generations (not table keys) and returns a key."""
db = settings.DB_CACHE_KEYS[db]
if db and len(db) > 100:
db = db[0:68] + self.gen_key(db[68:])
return '%s_%s_multi_%s' % (self.prefix, db, self.gen_key(*values... | Takes a list of generations (not table keys) and returns a key. | Below is the the instruction that describes the task:
### Input:
Takes a list of generations (not table keys) and returns a key.
### Response:
def gen_multi_key(self, values, db='default'):
"""Takes a list of generations (not table keys) and returns a key."""
db = settings.DB_CACHE_KEYS[db]
... |
def command(state, args):
"""Unregister watching regexp for an anime."""
args = parser.parse_args(args[1:])
if args.complete:
query.files.delete_regexp_complete(state.db)
else:
if args.aid is None:
parser.print_help()
else:
aid = state.results.parse_aid(ar... | Unregister watching regexp for an anime. | Below is the the instruction that describes the task:
### Input:
Unregister watching regexp for an anime.
### Response:
def command(state, args):
"""Unregister watching regexp for an anime."""
args = parser.parse_args(args[1:])
if args.complete:
query.files.delete_regexp_complete(state.db)
... |
def ylim(self, low, high, index=1):
"""Set yaxis limits.
Parameters
----------
low : number
high : number
index : int, optional
Returns
-------
Chart
"""
self.layout['yaxis' + str(index)]['range'] = [low, high]
return sel... | Set yaxis limits.
Parameters
----------
low : number
high : number
index : int, optional
Returns
-------
Chart | Below is the the instruction that describes the task:
### Input:
Set yaxis limits.
Parameters
----------
low : number
high : number
index : int, optional
Returns
-------
Chart
### Response:
def ylim(self, low, high, index=1):
"""Set yaxis li... |
def _rename_hstore_required(self, old_table_name, new_table_name,
old_field, new_field, key):
"""Renames an existing REQUIRED CONSTRAINT for the specified
hstore key."""
old_name = self._required_constraint_name(
old_table_name, old_field, key)
... | Renames an existing REQUIRED CONSTRAINT for the specified
hstore key. | Below is the the instruction that describes the task:
### Input:
Renames an existing REQUIRED CONSTRAINT for the specified
hstore key.
### Response:
def _rename_hstore_required(self, old_table_name, new_table_name,
old_field, new_field, key):
"""Renames an existing R... |
def main():
"""Parse the command-line arguments and run the bot."""
parser = argparse.ArgumentParser(description = 'XMPP echo bot',
parents = [XMPPSettings.get_arg_parser()])
parser.add_argument('jid', metavar = 'JID',
help = 'The ... | Parse the command-line arguments and run the bot. | Below is the the instruction that describes the task:
### Input:
Parse the command-line arguments and run the bot.
### Response:
def main():
"""Parse the command-line arguments and run the bot."""
parser = argparse.ArgumentParser(description = 'XMPP echo bot',
parents = ... |
def by_id(cls, id, conn=None, google_user=None,
google_password=None):
""" Open a spreadsheet via its resource ID. This is more precise
than opening a document by title, and should be used with
preference. """
conn = Connection.connect(conn=conn, google_user=google_user,
... | Open a spreadsheet via its resource ID. This is more precise
than opening a document by title, and should be used with
preference. | Below is the the instruction that describes the task:
### Input:
Open a spreadsheet via its resource ID. This is more precise
than opening a document by title, and should be used with
preference.
### Response:
def by_id(cls, id, conn=None, google_user=None,
google_password=None):
... |
def _make_A_and_part_of_b_adjacent(self, ref_crds):
"""
Make A and part of b. See docstring of this class
for answer to "What are A and b?"
"""
rot = self._rotate_rows(ref_crds)
A = 2*(rot - ref_crds)
partial_b = (rot**2 - ref_crds**2).sum(1)
return A, par... | Make A and part of b. See docstring of this class
for answer to "What are A and b?" | Below is the the instruction that describes the task:
### Input:
Make A and part of b. See docstring of this class
for answer to "What are A and b?"
### Response:
def _make_A_and_part_of_b_adjacent(self, ref_crds):
"""
Make A and part of b. See docstring of this class
for answer to ... |
def process_route_spec_config(con, vpc_info, route_spec,
failed_ips, questionable_ips):
"""
Look through the route spec and update routes accordingly.
Idea: Make sure we have a route for each CIDR.
If we have a route to any of the IP addresses for a given CIDR then we are... | Look through the route spec and update routes accordingly.
Idea: Make sure we have a route for each CIDR.
If we have a route to any of the IP addresses for a given CIDR then we are
good. Otherwise, pick one (usually the first) IP and create a route to that
IP.
If a route points at a failed or que... | Below is the the instruction that describes the task:
### Input:
Look through the route spec and update routes accordingly.
Idea: Make sure we have a route for each CIDR.
If we have a route to any of the IP addresses for a given CIDR then we are
good. Otherwise, pick one (usually the first) IP and cre... |
def get(self, max=None, timeout=None, wait=None):
"""Deprecated. Use Queue.reserve() instead. Executes an HTTP request to get a message off of a queue.
Keyword arguments:
max -- The maximum number of messages to pull. Defaults to 1.
"""
response = self.reserve(max, timeout, wait... | Deprecated. Use Queue.reserve() instead. Executes an HTTP request to get a message off of a queue.
Keyword arguments:
max -- The maximum number of messages to pull. Defaults to 1. | Below is the the instruction that describes the task:
### Input:
Deprecated. Use Queue.reserve() instead. Executes an HTTP request to get a message off of a queue.
Keyword arguments:
max -- The maximum number of messages to pull. Defaults to 1.
### Response:
def get(self, max=None, timeout=None, w... |
def save_json_file(
file, val,
pretty=False, compact=True, sort=True, encoder=None
):
"""
Save data to json file
:param file: Writable object or path to file
:type file: FileIO | str | unicode
:param val: Value or struct to save
:type val: None | int | float | str | list | dict
... | Save data to json file
:param file: Writable object or path to file
:type file: FileIO | str | unicode
:param val: Value or struct to save
:type val: None | int | float | str | list | dict
:param pretty: Format data to be readable (default: False)
:type pretty: bool
:param compact: Format d... | Below is the the instruction that describes the task:
### Input:
Save data to json file
:param file: Writable object or path to file
:type file: FileIO | str | unicode
:param val: Value or struct to save
:type val: None | int | float | str | list | dict
:param pretty: Format data to be readable... |
def calculate_path(self, remote_relative_path, input_type):
""" Only for used by Pulsar client, should override for managers to
enforce security and make the directory if needed.
"""
directory, allow_nested_files = self._directory_for_file_type(input_type)
return self.path_helper... | Only for used by Pulsar client, should override for managers to
enforce security and make the directory if needed. | Below is the the instruction that describes the task:
### Input:
Only for used by Pulsar client, should override for managers to
enforce security and make the directory if needed.
### Response:
def calculate_path(self, remote_relative_path, input_type):
""" Only for used by Pulsar client, should ov... |
def list_users(self):
""" List all users.
"""
sql = "SELECT * FROM user ORDER BY username"
self._db_curs.execute(sql)
users = list()
for row in self._db_curs:
users.append(dict(row))
return users | List all users. | Below is the the instruction that describes the task:
### Input:
List all users.
### Response:
def list_users(self):
""" List all users.
"""
sql = "SELECT * FROM user ORDER BY username"
self._db_curs.execute(sql)
users = list()
for row in self._db_curs:
u... |
def update_members(self, members, append_lists=False, remove_members=False):
"""
Update group members with member list. Set append=True
to append to existing members, or append=False to overwrite.
:param list members: new members for group by href or Element
:type members: list[... | Update group members with member list. Set append=True
to append to existing members, or append=False to overwrite.
:param list members: new members for group by href or Element
:type members: list[str, Element]
:param bool append_lists: whether to append
:param bool remove_memb... | Below is the the instruction that describes the task:
### Input:
Update group members with member list. Set append=True
to append to existing members, or append=False to overwrite.
:param list members: new members for group by href or Element
:type members: list[str, Element]
:param... |
def set_stdev(self, col, row, stdev):
"""
Sets the standard deviation at this location (if valid location).
:param col: the 0-based column index
:type col: int
:param row: the 0-based row index
:type row: int
:param stdev: the standard deviation to set
:t... | Sets the standard deviation at this location (if valid location).
:param col: the 0-based column index
:type col: int
:param row: the 0-based row index
:type row: int
:param stdev: the standard deviation to set
:type stdev: float | Below is the the instruction that describes the task:
### Input:
Sets the standard deviation at this location (if valid location).
:param col: the 0-based column index
:type col: int
:param row: the 0-based row index
:type row: int
:param stdev: the standard deviation to set... |
def post(self, path, args, wait=False):
"""POST an HTTP request to a daemon
:param path: path to do the request
:type path: str
:param args: args to add in the request
:type args: dict
:param wait: True for a long timeout
:type wait: bool
:return: Content... | POST an HTTP request to a daemon
:param path: path to do the request
:type path: str
:param args: args to add in the request
:type args: dict
:param wait: True for a long timeout
:type wait: bool
:return: Content of the HTTP response if server returned 200
... | Below is the the instruction that describes the task:
### Input:
POST an HTTP request to a daemon
:param path: path to do the request
:type path: str
:param args: args to add in the request
:type args: dict
:param wait: True for a long timeout
:type wait: bool
... |
def get_global_count(self):
""" Return global count (used for naming of .json and .png files)
Returns
-------
int
Global count
"""
# Check current number of json files in results directory and dump current json in new file
path_to_json = se... | Return global count (used for naming of .json and .png files)
Returns
-------
int
Global count | Below is the the instruction that describes the task:
### Input:
Return global count (used for naming of .json and .png files)
Returns
-------
int
Global count
### Response:
def get_global_count(self):
""" Return global count (used for naming of .json and .png files)
... |
def _get_page_from_path(self, path):
"""
Fetches the FeinCMS Page object that the path points to.
Override this to deal with different types of object from Page.
"""
from feincms.module.page.models import Page
try:
return Page.objects.best_match_for_path(path... | Fetches the FeinCMS Page object that the path points to.
Override this to deal with different types of object from Page. | Below is the the instruction that describes the task:
### Input:
Fetches the FeinCMS Page object that the path points to.
Override this to deal with different types of object from Page.
### Response:
def _get_page_from_path(self, path):
"""
Fetches the FeinCMS Page object that the path poi... |
def restart_program(self):
"""Restart Alignak
Format of the line that triggers function call::
RESTART_PROGRAM
:return: None
"""
restart_cmd = self.commands.find_by_name('restart-alignak')
if not restart_cmd:
logger.error("Cannot restart Alignak : mi... | Restart Alignak
Format of the line that triggers function call::
RESTART_PROGRAM
:return: None | Below is the the instruction that describes the task:
### Input:
Restart Alignak
Format of the line that triggers function call::
RESTART_PROGRAM
:return: None
### Response:
def restart_program(self):
"""Restart Alignak
Format of the line that triggers function call::
... |
def wrap(item, args=None, krgs=None, **kwargs):
"""Wraps the given item content between horizontal lines. Item can be a
string or a function.
**Examples**:
::
qprompt.wrap("Hi, this will be wrapped.") # String item.
qprompt.wrap(myfunc, [arg1, arg2], {'krgk': krgv}) # Func item.
"... | Wraps the given item content between horizontal lines. Item can be a
string or a function.
**Examples**:
::
qprompt.wrap("Hi, this will be wrapped.") # String item.
qprompt.wrap(myfunc, [arg1, arg2], {'krgk': krgv}) # Func item. | Below is the the instruction that describes the task:
### Input:
Wraps the given item content between horizontal lines. Item can be a
string or a function.
**Examples**:
::
qprompt.wrap("Hi, this will be wrapped.") # String item.
qprompt.wrap(myfunc, [arg1, arg2], {'krgk': krgv}) # Fu... |
def static2dplot_timeaveraged(var, time):
""" If the static_taverage option is set in tplot, and is supplied with a time range, then the spectrogram
plot(s) for which it is set will have another window pop up, where the displayed y and z values are
averaged by the number of seconds between the specified tim... | If the static_taverage option is set in tplot, and is supplied with a time range, then the spectrogram
plot(s) for which it is set will have another window pop up, where the displayed y and z values are
averaged by the number of seconds between the specified time range. | Below is the the instruction that describes the task:
### Input:
If the static_taverage option is set in tplot, and is supplied with a time range, then the spectrogram
plot(s) for which it is set will have another window pop up, where the displayed y and z values are
averaged by the number of seconds betwee... |
def callable(self) -> Optional[str]:
"""Show the name of the current callable in the trace"""
if self.current_trace_frame_index != -1:
return self._get_callable_from_trace_tuple(
self.trace_tuples[self.current_trace_frame_index]
)[0]
return None | Show the name of the current callable in the trace | Below is the the instruction that describes the task:
### Input:
Show the name of the current callable in the trace
### Response:
def callable(self) -> Optional[str]:
"""Show the name of the current callable in the trace"""
if self.current_trace_frame_index != -1:
return self._get_calla... |
def rmse(self):
"""Get RMSE for regression model evaluation results.
Returns:
the RMSE float number.
Raises:
Exception if the CSV headers do not include 'target' or 'predicted', or BigQuery
does not return 'target' or 'predicted' column, or if target or predicted is not
number.
... | Get RMSE for regression model evaluation results.
Returns:
the RMSE float number.
Raises:
Exception if the CSV headers do not include 'target' or 'predicted', or BigQuery
does not return 'target' or 'predicted' column, or if target or predicted is not
number. | Below is the the instruction that describes the task:
### Input:
Get RMSE for regression model evaluation results.
Returns:
the RMSE float number.
Raises:
Exception if the CSV headers do not include 'target' or 'predicted', or BigQuery
does not return 'target' or 'predicted' column, or i... |
def clear_db():
"""Clear the entire db."""
cursor = '0'
while cursor != 0:
cursor, keys = DB.scan(cursor, match='*', count=5000)
if keys:
DB.delete(*keys) | Clear the entire db. | Below is the the instruction that describes the task:
### Input:
Clear the entire db.
### Response:
def clear_db():
"""Clear the entire db."""
cursor = '0'
while cursor != 0:
cursor, keys = DB.scan(cursor, match='*', count=5000)
if keys:
DB.delete(*keys) |
def get_coord_line_number(self,coord):
"""return the one-indexed line number given the coordinates"""
if coord[0] in self._coords:
if coord[1] in self._coords[coord[0]]:
return self._coords[coord[0]][coord[1]]
return None | return the one-indexed line number given the coordinates | Below is the the instruction that describes the task:
### Input:
return the one-indexed line number given the coordinates
### Response:
def get_coord_line_number(self,coord):
"""return the one-indexed line number given the coordinates"""
if coord[0] in self._coords:
if coord[1] in self._coords[coord[... |
def update_cache(from_currency, to_currency):
""" update from_currency to_currency pair in cache if
last update for that pair is over 30 minutes ago by request API info """
if check_update(from_currency, to_currency) is True:
ccache[from_currency][to_currency]['value'] = convert_using_api(from_currency, to_currenc... | update from_currency to_currency pair in cache if
last update for that pair is over 30 minutes ago by request API info | Below is the the instruction that describes the task:
### Input:
update from_currency to_currency pair in cache if
last update for that pair is over 30 minutes ago by request API info
### Response:
def update_cache(from_currency, to_currency):
""" update from_currency to_currency pair in cache if
last update fo... |
def create_object(self, name, experiment_id, model_id, argument_defs, arguments=None, properties=None):
"""Create a model run object with the given list of arguments. The
initial state of the object is RUNNING.
Raises ValueError if given arguments are invalid.
Parameters
------... | Create a model run object with the given list of arguments. The
initial state of the object is RUNNING.
Raises ValueError if given arguments are invalid.
Parameters
----------
name : string
User-provided name for the model run
experiment_id : string
... | Below is the the instruction that describes the task:
### Input:
Create a model run object with the given list of arguments. The
initial state of the object is RUNNING.
Raises ValueError if given arguments are invalid.
Parameters
----------
name : string
User-pr... |
def get_string_from_data(self, offset, data):
"""Get an ASCII string from within the data."""
# OC Patch
b = None
try:
b = data[offset]
except IndexError:
return ''
s = ''
while ord(b):
s += b
... | Get an ASCII string from within the data. | Below is the the instruction that describes the task:
### Input:
Get an ASCII string from within the data.
### Response:
def get_string_from_data(self, offset, data):
"""Get an ASCII string from within the data."""
# OC Patch
b = None
try:
b = data[offs... |
def get_assets_by_genus_type(self, asset_genus_type):
"""Gets an ``AssetList`` corresponding to the given asset genus ``Type`` which does not include assets of types derived from the specified ``Type``.
In plenary mode, the returned list contains all known assets or
an error results. Otherwise,... | Gets an ``AssetList`` corresponding to the given asset genus ``Type`` which does not include assets of types derived from the specified ``Type``.
In plenary mode, the returned list contains all known assets or
an error results. Otherwise, the returned list may contain only
those assets that are... | Below is the the instruction that describes the task:
### Input:
Gets an ``AssetList`` corresponding to the given asset genus ``Type`` which does not include assets of types derived from the specified ``Type``.
In plenary mode, the returned list contains all known assets or
an error results. Otherw... |
def drop(n, it, constructor=list):
"""
>>> first(10,drop(10,xrange(sys.maxint),iter))
[10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
"""
return constructor(itertools.islice(it,n,None)) | >>> first(10,drop(10,xrange(sys.maxint),iter))
[10, 11, 12, 13, 14, 15, 16, 17, 18, 19] | Below is the the instruction that describes the task:
### Input:
>>> first(10,drop(10,xrange(sys.maxint),iter))
[10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
### Response:
def drop(n, it, constructor=list):
"""
>>> first(10,drop(10,xrange(sys.maxint),iter))
[10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
"... |
def asdict(model, exclude=None, exclude_underscore=None, exclude_pk=None,
follow=None, include=None, only=None, method='asdict', **kwargs):
"""Get a dict from a model
Using the `method` parameter makes it possible to have multiple methods
that formats the result.
Additional keyword argument... | Get a dict from a model
Using the `method` parameter makes it possible to have multiple methods
that formats the result.
Additional keyword arguments will be passed to all relationships that are
followed. This can be used to pass on things like request or context.
:param follow: List or dict of r... | Below is the the instruction that describes the task:
### Input:
Get a dict from a model
Using the `method` parameter makes it possible to have multiple methods
that formats the result.
Additional keyword arguments will be passed to all relationships that are
followed. This can be used to pass on ... |
def map_borders(wls):
"""Compute borders of pixels for interpolation.
The border of the pixel is assumed to be midway of the wls
"""
midpt_wl = 0.5 * (wls[1:] + wls[:-1])
all_borders = np.zeros((wls.shape[0] + 1,))
all_borders[1:-1] = midpt_wl
all_borders[0] = 2 * wls[0] - midpt_wl[0]
a... | Compute borders of pixels for interpolation.
The border of the pixel is assumed to be midway of the wls | Below is the the instruction that describes the task:
### Input:
Compute borders of pixels for interpolation.
The border of the pixel is assumed to be midway of the wls
### Response:
def map_borders(wls):
"""Compute borders of pixels for interpolation.
The border of the pixel is assumed to be midway ... |
def disable_contactgroup_host_notifications(self, contactgroup):
"""Disable host notifications for a contactgroup
Format of the line that triggers function call::
DISABLE_CONTACTGROUP_HOST_NOTIFICATIONS;<contactgroup_name>
:param contactgroup: contactgroup to disable
:type cont... | Disable host notifications for a contactgroup
Format of the line that triggers function call::
DISABLE_CONTACTGROUP_HOST_NOTIFICATIONS;<contactgroup_name>
:param contactgroup: contactgroup to disable
:type contactgroup: alignak.objects.contactgroup.Contactgroup
:return: None | Below is the the instruction that describes the task:
### Input:
Disable host notifications for a contactgroup
Format of the line that triggers function call::
DISABLE_CONTACTGROUP_HOST_NOTIFICATIONS;<contactgroup_name>
:param contactgroup: contactgroup to disable
:type contactgrou... |
def get_movement_delta(self):
"""Get the amount the camera has moved since get_movement_delta was last called."""
pos = self.pan - self.previous_pos
self.previous_pos = Vector2(self.pan.X, self.pan.Y)
return pos | Get the amount the camera has moved since get_movement_delta was last called. | Below is the the instruction that describes the task:
### Input:
Get the amount the camera has moved since get_movement_delta was last called.
### Response:
def get_movement_delta(self):
"""Get the amount the camera has moved since get_movement_delta was last called."""
pos = self.pan - self.previo... |
def create_all_parent_directories(ase, dirs_created, timeout=None):
# type: (blobxfer.models.azure.StorageEntity, dict, int) -> None
"""Create all parent directories for a file
:param blobxfer.models.azure.StorageEntity ase: Azure StorageEntity
:param dict dirs_created: directories already created map
... | Create all parent directories for a file
:param blobxfer.models.azure.StorageEntity ase: Azure StorageEntity
:param dict dirs_created: directories already created map
:param int timeout: timeout | Below is the the instruction that describes the task:
### Input:
Create all parent directories for a file
:param blobxfer.models.azure.StorageEntity ase: Azure StorageEntity
:param dict dirs_created: directories already created map
:param int timeout: timeout
### Response:
def create_all_parent_directo... |
def normalize(tensor, mean, std, inplace=False):
"""Normalize a tensor image with mean and standard deviation.
.. note::
This transform acts out of place by default, i.e., it does not mutates the input tensor.
See :class:`~torchvision.transforms.Normalize` for more details.
Args:
tens... | Normalize a tensor image with mean and standard deviation.
.. note::
This transform acts out of place by default, i.e., it does not mutates the input tensor.
See :class:`~torchvision.transforms.Normalize` for more details.
Args:
tensor (Tensor): Tensor image of size (C, H, W) to be normal... | Below is the the instruction that describes the task:
### Input:
Normalize a tensor image with mean and standard deviation.
.. note::
This transform acts out of place by default, i.e., it does not mutates the input tensor.
See :class:`~torchvision.transforms.Normalize` for more details.
Args:... |
def revert(self, filename=None,
ignore_discard=False, ignore_expires=False):
"""Clear all cookies and reload cookies from a saved file.
Raises LoadError (or IOError) if reversion is not successful; the
object's state will not be altered if this happens.
"""
if fi... | Clear all cookies and reload cookies from a saved file.
Raises LoadError (or IOError) if reversion is not successful; the
object's state will not be altered if this happens. | Below is the the instruction that describes the task:
### Input:
Clear all cookies and reload cookies from a saved file.
Raises LoadError (or IOError) if reversion is not successful; the
object's state will not be altered if this happens.
### Response:
def revert(self, filename=None,
... |
def generate_hexagonal_lattice(maxv1, minv1, maxv2, minv2, mindist):
"""
This function generates a 2-dimensional lattice of points using a hexagonal
lattice.
Parameters
-----------
maxv1 : float
Largest value in the 1st dimension to cover
minv1 : float
Smallest value in the ... | This function generates a 2-dimensional lattice of points using a hexagonal
lattice.
Parameters
-----------
maxv1 : float
Largest value in the 1st dimension to cover
minv1 : float
Smallest value in the 1st dimension to cover
maxv2 : float
Largest value in the 2nd dimensi... | Below is the the instruction that describes the task:
### Input:
This function generates a 2-dimensional lattice of points using a hexagonal
lattice.
Parameters
-----------
maxv1 : float
Largest value in the 1st dimension to cover
minv1 : float
Smallest value in the 1st dimensio... |
def make_mapcube_source(name, Spatial_Filename, spectrum):
"""Construct and return a `fermipy.roi_model.MapCubeSource` object
"""
data = dict(Spatial_Filename=Spatial_Filename)
if spectrum is not None:
data.update(spectrum)
return roi_model.MapCubeSource(name, data) | Construct and return a `fermipy.roi_model.MapCubeSource` object | Below is the the instruction that describes the task:
### Input:
Construct and return a `fermipy.roi_model.MapCubeSource` object
### Response:
def make_mapcube_source(name, Spatial_Filename, spectrum):
"""Construct and return a `fermipy.roi_model.MapCubeSource` object
"""
data = dict(Spatial_Filename=S... |
def bind(self, func, etype):
'''
Wraps around container.bind().
'''
if func not in self._event_cbs:
wrapped = self._WrapCB(self, func)
self._event_cbs[func] = wrapped
else:
wrapped = self._event_cbs[func]
self.container.bind(wrapped, et... | Wraps around container.bind(). | Below is the the instruction that describes the task:
### Input:
Wraps around container.bind().
### Response:
def bind(self, func, etype):
'''
Wraps around container.bind().
'''
if func not in self._event_cbs:
wrapped = self._WrapCB(self, func)
self._event_cb... |
def load_monitoring_config_file(self, clean=True):
# pylint: disable=too-many-branches,too-many-statements, too-many-locals
"""Load main configuration file (alignak.cfg)::
* Read all files given in the -c parameters
* Read all .cfg files in cfg_dir
* Read all files in cfg_file
... | Load main configuration file (alignak.cfg)::
* Read all files given in the -c parameters
* Read all .cfg files in cfg_dir
* Read all files in cfg_file
* Create objects (Arbiter, Module)
* Set HTTP links info (ssl etc)
* Load its own modules
* Execute read_configu... | Below is the the instruction that describes the task:
### Input:
Load main configuration file (alignak.cfg)::
* Read all files given in the -c parameters
* Read all .cfg files in cfg_dir
* Read all files in cfg_file
* Create objects (Arbiter, Module)
* Set HTTP links info (s... |
def set_inhibit(self, inhibit):
"""Set inhibition state"""
if self._pid and inhibit != self._inhibited:
os.kill(self._pid, signal.SIGUSR1)
self._inhibited = inhibit | Set inhibition state | Below is the the instruction that describes the task:
### Input:
Set inhibition state
### Response:
def set_inhibit(self, inhibit):
"""Set inhibition state"""
if self._pid and inhibit != self._inhibited:
os.kill(self._pid, signal.SIGUSR1)
self._inhibited = inhibit |
def section(self, section_title):
""" Plain text section content
Args:
section_title (str): Name of the section to pull
Returns:
str: The content of the section
Note:
Returns **None** if section title is not found; only text \
... | Plain text section content
Args:
section_title (str): Name of the section to pull
Returns:
str: The content of the section
Note:
Returns **None** if section title is not found; only text \
between title and next section... | Below is the the instruction that describes the task:
### Input:
Plain text section content
Args:
section_title (str): Name of the section to pull
Returns:
str: The content of the section
Note:
Returns **None** if section title is ... |
def process(self, sched, coro):
"""Add the given coroutine in the scheduler."""
super(AddCoro, self).process(sched, coro)
self.result = sched.add(self.coro, self.args, self.kwargs, self.prio & priority.OP)
if self.prio & priority.CORO:
return self, coro
else:
... | Add the given coroutine in the scheduler. | Below is the the instruction that describes the task:
### Input:
Add the given coroutine in the scheduler.
### Response:
def process(self, sched, coro):
"""Add the given coroutine in the scheduler."""
super(AddCoro, self).process(sched, coro)
self.result = sched.add(self.coro, self.args,... |
async def _dump_container_size(
self, writer, container_len, container_type, params=None
):
"""
Dumps container size - per element streaming
:param writer:
:param container_len:
:param container_type:
:param params:
:return:
"""
if ... | Dumps container size - per element streaming
:param writer:
:param container_len:
:param container_type:
:param params:
:return: | Below is the the instruction that describes the task:
### Input:
Dumps container size - per element streaming
:param writer:
:param container_len:
:param container_type:
:param params:
:return:
### Response:
async def _dump_container_size(
self, writer, container... |
def vhel_to_vgsr(coordinate, vhel, vsun):
"""
Convert a velocity from a heliocentric radial velocity to
the Galactic standard of rest (GSR).
Parameters
----------
coordinate : :class:`~astropy.coordinates.SkyCoord`
An Astropy SkyCoord object or anything object that can be passed
... | Convert a velocity from a heliocentric radial velocity to
the Galactic standard of rest (GSR).
Parameters
----------
coordinate : :class:`~astropy.coordinates.SkyCoord`
An Astropy SkyCoord object or anything object that can be passed
to the SkyCoord initializer.
vhel : :class:`~astr... | Below is the the instruction that describes the task:
### Input:
Convert a velocity from a heliocentric radial velocity to
the Galactic standard of rest (GSR).
Parameters
----------
coordinate : :class:`~astropy.coordinates.SkyCoord`
An Astropy SkyCoord object or anything object that can be... |
def comply(self, path):
"""Issues a chown and chmod to the file paths specified."""
utils.ensure_permissions(path, self.user.pw_name, self.group.gr_name,
self.mode) | Issues a chown and chmod to the file paths specified. | Below is the the instruction that describes the task:
### Input:
Issues a chown and chmod to the file paths specified.
### Response:
def comply(self, path):
"""Issues a chown and chmod to the file paths specified."""
utils.ensure_permissions(path, self.user.pw_name, self.group.gr_name,
... |
def get_models(cls, index, as_class=False):
'''
Returns the list of models defined for this index.
:param index: index name.
:param as_class: set to True to return the model as a model object instead of as a string.
'''
try:
return cls._index_to_model[index] i... | Returns the list of models defined for this index.
:param index: index name.
:param as_class: set to True to return the model as a model object instead of as a string. | Below is the the instruction that describes the task:
### Input:
Returns the list of models defined for this index.
:param index: index name.
:param as_class: set to True to return the model as a model object instead of as a string.
### Response:
def get_models(cls, index, as_class=False):
... |
def find_users_by_email_and_group(email_prefix=None, group=None, cursor=None, page_size=30):
"""
Returns a command that retrieves users by its email_prefix, ordered by email and by Group.
If Group is None, only users without any group are going to be searched
It returns a max number of users defined by ... | Returns a command that retrieves users by its email_prefix, ordered by email and by Group.
If Group is None, only users without any group are going to be searched
It returns a max number of users defined by page_size arg. Next result can be retrieved using cursor, in
a next call. It is provided in cursor at... | Below is the the instruction that describes the task:
### Input:
Returns a command that retrieves users by its email_prefix, ordered by email and by Group.
If Group is None, only users without any group are going to be searched
It returns a max number of users defined by page_size arg. Next result can be re... |
def compare_dicts(i):
"""
Input: {
dict1 - dictionary 1
dict2 - dictionary 2
(ignore_case) - ignore case of letters
Note that if dict1 and dict2 has lists, the results will be as follows:
* dict1={"key":['a','b','c']}
... | Input: {
dict1 - dictionary 1
dict2 - dictionary 2
(ignore_case) - ignore case of letters
Note that if dict1 and dict2 has lists, the results will be as follows:
* dict1={"key":['a','b','c']}
dict2={"key":['a','b']}... | Below is the the instruction that describes the task:
### Input:
Input: {
dict1 - dictionary 1
dict2 - dictionary 2
(ignore_case) - ignore case of letters
Note that if dict1 and dict2 has lists, the results will be as follows:
... |
def get_qual_range(qual_str):
""" Get range of the Unicode encode range for a given string of characters.
The encoding is determined from the result of the :py:func:`ord` built-in.
Parameters
----------
qual_str : str
Arbitrary string.
Returns
-------
x : tuple
(Minimu... | Get range of the Unicode encode range for a given string of characters.
The encoding is determined from the result of the :py:func:`ord` built-in.
Parameters
----------
qual_str : str
Arbitrary string.
Returns
-------
x : tuple
(Minimum Unicode code, Maximum Unicode code). | Below is the the instruction that describes the task:
### Input:
Get range of the Unicode encode range for a given string of characters.
The encoding is determined from the result of the :py:func:`ord` built-in.
Parameters
----------
qual_str : str
Arbitrary string.
Returns
------... |
def get_r_df(self):
''' getter '''
if isinstance(self.__r_df, pd.DataFrame) is False and self.__r_df is not None:
raise TypeError("The type of `__r_df` must be `pd.DataFrame`.")
return self.__r_df | getter | Below is the the instruction that describes the task:
### Input:
getter
### Response:
def get_r_df(self):
''' getter '''
if isinstance(self.__r_df, pd.DataFrame) is False and self.__r_df is not None:
raise TypeError("The type of `__r_df` must be `pd.DataFrame`.")
return self.__r... |
def setattr(self, name, value):
"""Set an attribute to a new value for all Parameters.
For example, set grad_req to null if you don't need gradient w.r.t a
model's Parameters::
model.collect_params().setattr('grad_req', 'null')
or change the learning rate multiplier::
... | Set an attribute to a new value for all Parameters.
For example, set grad_req to null if you don't need gradient w.r.t a
model's Parameters::
model.collect_params().setattr('grad_req', 'null')
or change the learning rate multiplier::
model.collect_params().setattr('lr... | Below is the the instruction that describes the task:
### Input:
Set an attribute to a new value for all Parameters.
For example, set grad_req to null if you don't need gradient w.r.t a
model's Parameters::
model.collect_params().setattr('grad_req', 'null')
or change the learn... |
def _run_qmc(self, boot):
"""
Runs quartet max-cut QMC on the quartets qdump file.
"""
## build command
self._tmp = os.path.join(self.dirs, ".tmptre")
cmd = [ip.bins.qmc, "qrtt="+self.files.qdump, "otre="+self._tmp]
## run it
proc = subprocess.Popen(cmd,... | Runs quartet max-cut QMC on the quartets qdump file. | Below is the the instruction that describes the task:
### Input:
Runs quartet max-cut QMC on the quartets qdump file.
### Response:
def _run_qmc(self, boot):
"""
Runs quartet max-cut QMC on the quartets qdump file.
"""
## build command
self._tmp = os.path.join(self.dirs, ".... |
def display_name(self):
"""Readable name for the variant."""
if self.is_snv:
gene_ids = self.gene_symbols[:2]
return ', '.join(gene_ids)
else:
return "{this.cytoband_start} ({this.sv_len})".format(this=self) | Readable name for the variant. | Below is the the instruction that describes the task:
### Input:
Readable name for the variant.
### Response:
def display_name(self):
"""Readable name for the variant."""
if self.is_snv:
gene_ids = self.gene_symbols[:2]
return ', '.join(gene_ids)
else:
re... |
def calc_shape_statistics(self, stat_names):
"""
Calculate shape statistics using regionprops applied to the object mask.
Args:
stat_names: List of statistics to be extracted from those calculated by regionprops.
Returns:
Dictionary of shape statistics
... | Calculate shape statistics using regionprops applied to the object mask.
Args:
stat_names: List of statistics to be extracted from those calculated by regionprops.
Returns:
Dictionary of shape statistics | Below is the the instruction that describes the task:
### Input:
Calculate shape statistics using regionprops applied to the object mask.
Args:
stat_names: List of statistics to be extracted from those calculated by regionprops.
Returns:
Dictionary of shape statisti... |
def lookAtSpheroid(lat0: float, lon0: float, h0: float, az: float, tilt: float,
ell: Ellipsoid = None, deg: bool = True) -> Tuple[float, float, float]:
"""
Calculates line-of-sight intersection with Earth (or other ellipsoid) surface from above surface / orbit
Parameters
----------
... | Calculates line-of-sight intersection with Earth (or other ellipsoid) surface from above surface / orbit
Parameters
----------
lat0 : float
observer geodetic latitude
lon0 : float
observer geodetic longitude
h0 : float
observer altitude (meters) Must be non-negative ... | Below is the the instruction that describes the task:
### Input:
Calculates line-of-sight intersection with Earth (or other ellipsoid) surface from above surface / orbit
Parameters
----------
lat0 : float
observer geodetic latitude
lon0 : float
observer geodetic longitude
... |
def set_association_id(self, assoc_id=None):
"""
This will set the association ID based on the internal parts
of the association.
To be used in cases where an external association identifier
should be used.
:param assoc_id:
:return:
"""
if assoc... | This will set the association ID based on the internal parts
of the association.
To be used in cases where an external association identifier
should be used.
:param assoc_id:
:return: | Below is the the instruction that describes the task:
### Input:
This will set the association ID based on the internal parts
of the association.
To be used in cases where an external association identifier
should be used.
:param assoc_id:
:return:
### Response:
def set_as... |
def bookmark(snapshot, bookmark):
'''
Creates a bookmark of the given snapshot
.. note::
Bookmarks mark the point in time when the snapshot was created,
and can be used as the incremental source for a zfs send command.
This feature must be enabled to be used. See zpool-features(5)... | Creates a bookmark of the given snapshot
.. note::
Bookmarks mark the point in time when the snapshot was created,
and can be used as the incremental source for a zfs send command.
This feature must be enabled to be used. See zpool-features(5) for
details on ZFS feature flags and ... | Below is the the instruction that describes the task:
### Input:
Creates a bookmark of the given snapshot
.. note::
Bookmarks mark the point in time when the snapshot was created,
and can be used as the incremental source for a zfs send command.
This feature must be enabled to be used... |
def construct_auth (self):
"""Construct HTTP Basic authentication credentials if there
is user/password information available. Does not overwrite if
credentials have already been constructed."""
if self.auth:
return
_user, _password = self.get_user_password()
... | Construct HTTP Basic authentication credentials if there
is user/password information available. Does not overwrite if
credentials have already been constructed. | Below is the the instruction that describes the task:
### Input:
Construct HTTP Basic authentication credentials if there
is user/password information available. Does not overwrite if
credentials have already been constructed.
### Response:
def construct_auth (self):
"""Construct HTTP Basic... |
def workflow_set_stage_inputs(object_id, input_params={}, always_retry=True, **kwargs):
"""
Invokes the /workflow-xxxx/setStageInputs API method.
For more info, see: https://wiki.dnanexus.com/API-Specification-v1.0.0/Workflows-and-Analyses#API-method%3A-%2Fworkflow-xxxx%2FsetStageInputs
"""
return ... | Invokes the /workflow-xxxx/setStageInputs API method.
For more info, see: https://wiki.dnanexus.com/API-Specification-v1.0.0/Workflows-and-Analyses#API-method%3A-%2Fworkflow-xxxx%2FsetStageInputs | Below is the the instruction that describes the task:
### Input:
Invokes the /workflow-xxxx/setStageInputs API method.
For more info, see: https://wiki.dnanexus.com/API-Specification-v1.0.0/Workflows-and-Analyses#API-method%3A-%2Fworkflow-xxxx%2FsetStageInputs
### Response:
def workflow_set_stage_inputs(objec... |
def log_pdf(self, y, mu, weights=None):
"""
computes the log of the pdf or pmf of the values under the current distribution
Parameters
----------
y : array-like of length n
target values
mu : array-like of length n
expected values
weights ... | computes the log of the pdf or pmf of the values under the current distribution
Parameters
----------
y : array-like of length n
target values
mu : array-like of length n
expected values
weights : array-like shape (n,) or None, default: None
c... | Below is the the instruction that describes the task:
### Input:
computes the log of the pdf or pmf of the values under the current distribution
Parameters
----------
y : array-like of length n
target values
mu : array-like of length n
expected values
... |
def _init_ws(n_items, comparisons, prior_inv, tau, nu):
"""Initialize parameters in the weight space."""
prec = np.zeros((n_items, n_items))
xs = np.zeros(n_items)
for i, (a, b) in enumerate(comparisons):
prec[(a, a, b, b), (a, b, a, b)] += tau[i] * MAT_ONE_FLAT
xs[a] += nu[i]
x... | Initialize parameters in the weight space. | Below is the the instruction that describes the task:
### Input:
Initialize parameters in the weight space.
### Response:
def _init_ws(n_items, comparisons, prior_inv, tau, nu):
"""Initialize parameters in the weight space."""
prec = np.zeros((n_items, n_items))
xs = np.zeros(n_items)
for i, (a, b)... |
def flatten_list(list_):
"""
Banana banana
"""
res = []
for elem in list_:
if isinstance(elem, list):
res.extend(flatten_list(elem))
else:
res.append(elem)
return res | Banana banana | Below is the the instruction that describes the task:
### Input:
Banana banana
### Response:
def flatten_list(list_):
"""
Banana banana
"""
res = []
for elem in list_:
if isinstance(elem, list):
res.extend(flatten_list(elem))
else:
res.append(elem)
... |
def get_void_volume_surfarea(structure, rad_dict=None, chan_rad=0.3,
probe_rad=0.1):
"""
Computes the volume and surface area of isolated void using Zeo++.
Useful to compute the volume and surface area of vacant site.
Args:
structure: pymatgen Structure containing v... | Computes the volume and surface area of isolated void using Zeo++.
Useful to compute the volume and surface area of vacant site.
Args:
structure: pymatgen Structure containing vacancy
rad_dict(optional): Dictionary with short name of elements and their
radii.
chan_rad(option... | Below is the the instruction that describes the task:
### Input:
Computes the volume and surface area of isolated void using Zeo++.
Useful to compute the volume and surface area of vacant site.
Args:
structure: pymatgen Structure containing vacancy
rad_dict(optional): Dictionary with short ... |
def next_history(self, current): # (C-n)
u'''Move forward through the history list, fetching the next command. '''
if self.history_cursor < len(self.history) - 1:
self.history_cursor += 1
current.set_line(self.history[self.history_cursor].get_line_text()) | u'''Move forward through the history list, fetching the next command. | Below is the the instruction that describes the task:
### Input:
u'''Move forward through the history list, fetching the next command.
### Response:
def next_history(self, current): # (C-n)
u'''Move forward through the history list, fetching the next command. '''
if self.history_cursor < len(self... |
def truncate(self, n):
"""Erase [n] elements."""
# Current byte position - (n * data_size)
size = self.size - n * self.__strct.size
# Erase [size] bytes from file.tell()
self.__file.truncate(size) | Erase [n] elements. | Below is the the instruction that describes the task:
### Input:
Erase [n] elements.
### Response:
def truncate(self, n):
"""Erase [n] elements."""
# Current byte position - (n * data_size)
size = self.size - n * self.__strct.size
# Erase [size] bytes from file.tell()
self.... |
def parse_data(self, text, maxwidth, maxheight, template_dir, context,
urlize_all_links):
"""
Parses a block of text rendering links that occur on their own line
normally but rendering inline links using a special template dir
"""
block_parser = TextBlockParse... | Parses a block of text rendering links that occur on their own line
normally but rendering inline links using a special template dir | Below is the the instruction that describes the task:
### Input:
Parses a block of text rendering links that occur on their own line
normally but rendering inline links using a special template dir
### Response:
def parse_data(self, text, maxwidth, maxheight, template_dir, context,
urli... |
def convert_image_to_knitting_pattern(path, colors=("white", "black")):
"""Load a image file such as a png bitmap of jpeg file and convert it
to a :ref:`knitting pattern file <FileFormatSpecification>`.
:param list colors: a list of strings that should be used as
:ref:`colors <png-color>`.
:param... | Load a image file such as a png bitmap of jpeg file and convert it
to a :ref:`knitting pattern file <FileFormatSpecification>`.
:param list colors: a list of strings that should be used as
:ref:`colors <png-color>`.
:param str path: ignore this. It is fulfilled by the loeder.
Example:
.. co... | Below is the the instruction that describes the task:
### Input:
Load a image file such as a png bitmap of jpeg file and convert it
to a :ref:`knitting pattern file <FileFormatSpecification>`.
:param list colors: a list of strings that should be used as
:ref:`colors <png-color>`.
:param str path:... |
def get_queryset(self, *args, **kwargs):
"""
Ensures that this manager always returns nodes in tree order.
"""
qs = super(TreeManager, self).get_queryset(*args, **kwargs)
# Restrict operations to pages on the current site if needed
if settings.PAGES_HIDE_SITES and settin... | Ensures that this manager always returns nodes in tree order. | Below is the the instruction that describes the task:
### Input:
Ensures that this manager always returns nodes in tree order.
### Response:
def get_queryset(self, *args, **kwargs):
"""
Ensures that this manager always returns nodes in tree order.
"""
qs = super(TreeManager, self).g... |
def solid_angle(center, coords):
"""
Helper method to calculate the solid angle of a set of coords from the
center.
Args:
center (3x1 array): Center to measure solid angle from.
coords (Nx3 array): List of coords to determine solid angle.
Returns:
The solid angle.
"""
... | Helper method to calculate the solid angle of a set of coords from the
center.
Args:
center (3x1 array): Center to measure solid angle from.
coords (Nx3 array): List of coords to determine solid angle.
Returns:
The solid angle. | Below is the the instruction that describes the task:
### Input:
Helper method to calculate the solid angle of a set of coords from the
center.
Args:
center (3x1 array): Center to measure solid angle from.
coords (Nx3 array): List of coords to determine solid angle.
Returns:
Th... |
def content_upload(self, key, model, contentid, data, mimetype):
"""Store the given data as a result of a query for content id given the model.
This method maps to
https://github.com/exosite/docs/tree/master/provision#post---upload-content
Args:
key: The CIK or Token for th... | Store the given data as a result of a query for content id given the model.
This method maps to
https://github.com/exosite/docs/tree/master/provision#post---upload-content
Args:
key: The CIK or Token for the device
model:
contentid: The ID used to name the e... | Below is the the instruction that describes the task:
### Input:
Store the given data as a result of a query for content id given the model.
This method maps to
https://github.com/exosite/docs/tree/master/provision#post---upload-content
Args:
key: The CIK or Token for the devic... |
def create_pids(cls, record_uuid, pids):
"""Create persistent identifiers."""
for p in pids:
PersistentIdentifier.create(
pid_type=p.pid_type,
pid_value=p.pid_value,
pid_provider=p.provider.pid_provider if p.provider else None,
... | Create persistent identifiers. | Below is the the instruction that describes the task:
### Input:
Create persistent identifiers.
### Response:
def create_pids(cls, record_uuid, pids):
"""Create persistent identifiers."""
for p in pids:
PersistentIdentifier.create(
pid_type=p.pid_type,
pi... |
def create(self, source_type, name, resources, auth=None, parameters=None, validate=True):
""" Create a managed source
Uses API documented at http://dev.datasift.com/docs/api/rest-api/endpoints/sourcecreate
:param source_type: data source name e.g. facebook_page, googleplus, instagram,... | Create a managed source
Uses API documented at http://dev.datasift.com/docs/api/rest-api/endpoints/sourcecreate
:param source_type: data source name e.g. facebook_page, googleplus, instagram, yammer
:type source_type: str
:param name: name to use to identify the managed... | Below is the the instruction that describes the task:
### Input:
Create a managed source
Uses API documented at http://dev.datasift.com/docs/api/rest-api/endpoints/sourcecreate
:param source_type: data source name e.g. facebook_page, googleplus, instagram, yammer
:type source_t... |
def apply_region_configs(env_config):
"""Override default env configs with region specific configs and nest
all values under a region
Args:
env_config (dict): The environment specific config.
Return:
dict: Newly updated dictionary with region overrides applied.
"""
new_config =... | Override default env configs with region specific configs and nest
all values under a region
Args:
env_config (dict): The environment specific config.
Return:
dict: Newly updated dictionary with region overrides applied. | Below is the the instruction that describes the task:
### Input:
Override default env configs with region specific configs and nest
all values under a region
Args:
env_config (dict): The environment specific config.
Return:
dict: Newly updated dictionary with region overrides applied.
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.