code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def add_disk_encryption_passwords(self, ids, passwords, clear_on_suspend):
"""Adds a password used for hard disk encryption/decryption.
in ids of type str
List of identifiers for the passwords. Must match the identifier
used when the encrypted medium was created.
in pas... | Adds a password used for hard disk encryption/decryption.
in ids of type str
List of identifiers for the passwords. Must match the identifier
used when the encrypted medium was created.
in passwords of type str
List of passwords.
in clear_on_suspend of type... | Below is the the instruction that describes the task:
### Input:
Adds a password used for hard disk encryption/decryption.
in ids of type str
List of identifiers for the passwords. Must match the identifier
used when the encrypted medium was created.
in passwords of type st... |
def cli(ctx, env):
"""Print shell help text."""
env.out("Welcome to the SoftLayer shell.")
env.out("")
formatter = formatting.HelpFormatter()
commands = []
shell_commands = []
for name in cli_core.cli.list_commands(ctx):
command = cli_core.cli.get_command(ctx, name)
if comma... | Print shell help text. | Below is the the instruction that describes the task:
### Input:
Print shell help text.
### Response:
def cli(ctx, env):
"""Print shell help text."""
env.out("Welcome to the SoftLayer shell.")
env.out("")
formatter = formatting.HelpFormatter()
commands = []
shell_commands = []
for name... |
def find_repositories_with_locate(path):
"""Use locate to return a sequence of (directory, dotdir) pairs."""
command = [b'locate', b'-0']
for dotdir in DOTDIRS:
# Escaping the slash (using '\/' rather than '/') is an
# important signal to locate(1) that these glob patterns are
# supp... | Use locate to return a sequence of (directory, dotdir) pairs. | Below is the the instruction that describes the task:
### Input:
Use locate to return a sequence of (directory, dotdir) pairs.
### Response:
def find_repositories_with_locate(path):
"""Use locate to return a sequence of (directory, dotdir) pairs."""
command = [b'locate', b'-0']
for dotdir in DOTDIRS:
... |
def div(self, key, value=2):
"""Divides the specified key value by the specified value.
:param str|unicode key:
:param int value:
:rtype: bool
"""
return uwsgi.cache_mul(key, value, self.timeout, self.name) | Divides the specified key value by the specified value.
:param str|unicode key:
:param int value:
:rtype: bool | Below is the the instruction that describes the task:
### Input:
Divides the specified key value by the specified value.
:param str|unicode key:
:param int value:
:rtype: bool
### Response:
def div(self, key, value=2):
"""Divides the specified key value by the specified value.
... |
def post(self, path, data=None, json=None, headers=None, **kwargs):
"""
Sends a POST request to host/path.
:param path: String, resource path on server
:param data: Dictionary, bytes or file-like object to send in the body of the request
:param json: JSON formatted data to send ... | Sends a POST request to host/path.
:param path: String, resource path on server
:param data: Dictionary, bytes or file-like object to send in the body of the request
:param json: JSON formatted data to send in the body of the request
:param headers: Dictionary of HTTP headers to be sent... | Below is the the instruction that describes the task:
### Input:
Sends a POST request to host/path.
:param path: String, resource path on server
:param data: Dictionary, bytes or file-like object to send in the body of the request
:param json: JSON formatted data to send in the body of the ... |
def _get_server(self):
"""
Get server to use for request.
Also process inactive server list, re-add them after given interval.
"""
with self._lock:
inactive_server_count = len(self._inactive_servers)
for i in range(inactive_server_count):
t... | Get server to use for request.
Also process inactive server list, re-add them after given interval. | Below is the the instruction that describes the task:
### Input:
Get server to use for request.
Also process inactive server list, re-add them after given interval.
### Response:
def _get_server(self):
"""
Get server to use for request.
Also process inactive server list, re-add them... |
def pyobj_role(make_node, name, rawtext, text, lineno, inliner, options=None, content=None):
"""Include Python object value, rendering it to text using str.
Returns 2 part tuple containing list of nodes to insert into the
document and a list of system messages. Both are allowed to be
empty.
:para... | Include Python object value, rendering it to text using str.
Returns 2 part tuple containing list of nodes to insert into the
document and a list of system messages. Both are allowed to be
empty.
:param make_node: A callable which accepts (rawtext, app, prefixed_name, obj, parent, modname, options) a... | Below is the the instruction that describes the task:
### Input:
Include Python object value, rendering it to text using str.
Returns 2 part tuple containing list of nodes to insert into the
document and a list of system messages. Both are allowed to be
empty.
:param make_node: A callable which a... |
def read_csv(self, file: str, table: str = '_csv', libref: str = '', results: str = '',
opts: dict = None) -> 'SASdata':
"""
:param file: either the OS filesystem path of the file, or HTTP://... for a url accessible file
:param table: the name of the SAS Data Set to create
... | :param file: either the OS filesystem path of the file, or HTTP://... for a url accessible file
:param table: the name of the SAS Data Set to create
:param libref: the libref for the SAS Data Set being created. Defaults to WORK, or USER if assigned
:param results: format of results, SASsession.r... | Below is the the instruction that describes the task:
### Input:
:param file: either the OS filesystem path of the file, or HTTP://... for a url accessible file
:param table: the name of the SAS Data Set to create
:param libref: the libref for the SAS Data Set being created. Defaults to WORK, or USE... |
def get_sentence_xpath_tuples(filename_url_or_filelike,
xpath_to_text=TEXT_FINDER_XPATH):
"""
Given a url and xpath, this function will download, parse, then
iterate though queried text-nodes. From the resulting text-nodes,
extract a list of (text, exact-xpath) tuples.... | Given a url and xpath, this function will download, parse, then
iterate though queried text-nodes. From the resulting text-nodes,
extract a list of (text, exact-xpath) tuples. | Below is the the instruction that describes the task:
### Input:
Given a url and xpath, this function will download, parse, then
iterate though queried text-nodes. From the resulting text-nodes,
extract a list of (text, exact-xpath) tuples.
### Response:
def get_sentence_xpath_tuples(filename_url_or_file... |
def validate(self):
"""Ensure the Fold block is valid."""
if not isinstance(self.fold_scope_location, FoldScopeLocation):
raise TypeError(u'Expected a FoldScopeLocation for fold_scope_location, got: {} '
u'{}'.format(type(self.fold_scope_location), self.fold_scope... | Ensure the Fold block is valid. | Below is the the instruction that describes the task:
### Input:
Ensure the Fold block is valid.
### Response:
def validate(self):
"""Ensure the Fold block is valid."""
if not isinstance(self.fold_scope_location, FoldScopeLocation):
raise TypeError(u'Expected a FoldScopeLocation for fol... |
def close_session(self):
"""Close current session."""
if not self._session.closed:
if self._session._connector_owner:
self._session._connector.close()
self._session._connector = None | Close current session. | Below is the the instruction that describes the task:
### Input:
Close current session.
### Response:
def close_session(self):
"""Close current session."""
if not self._session.closed:
if self._session._connector_owner:
self._session._connector.close()
self._... |
def update_filenames(self):
"""Does nothing currently. May not need this method"""
self.sky_file = os.path.abspath(os.path.join(os.path.join(self.input_path, 'sky_files'),
'sky_' + self.sky_state + '_z' + str(
... | Does nothing currently. May not need this method | Below is the the instruction that describes the task:
### Input:
Does nothing currently. May not need this method
### Response:
def update_filenames(self):
"""Does nothing currently. May not need this method"""
self.sky_file = os.path.abspath(os.path.join(os.path.join(self.input_path, 'sky_files'... |
def detranslify(text):
"""Detranslify russian text"""
try:
res = translit.detranslify(text)
except Exception as err:
# because filter must die silently
res = default_value % {'error': err, 'value': text}
return res | Detranslify russian text | Below is the the instruction that describes the task:
### Input:
Detranslify russian text
### Response:
def detranslify(text):
"""Detranslify russian text"""
try:
res = translit.detranslify(text)
except Exception as err:
# because filter must die silently
res = default_value % {... |
def score(self):
"The total score for the words found, according to the rules."
return sum([self.scores[len(w)] for w in self.words()]) | The total score for the words found, according to the rules. | Below is the the instruction that describes the task:
### Input:
The total score for the words found, according to the rules.
### Response:
def score(self):
"The total score for the words found, according to the rules."
return sum([self.scores[len(w)] for w in self.words()]) |
def eval_option_value(self, option):
""" Evaluates an option
:param option: a string
:return: an object of type str, bool, int, float or list
"""
try:
value = eval(option, {}, {})
except (SyntaxError, NameError, TypeError):
return option
if... | Evaluates an option
:param option: a string
:return: an object of type str, bool, int, float or list | Below is the the instruction that describes the task:
### Input:
Evaluates an option
:param option: a string
:return: an object of type str, bool, int, float or list
### Response:
def eval_option_value(self, option):
""" Evaluates an option
:param option: a string
:return: a... |
def login(self, **kwargs):
"""登录"""
payload = {
'username': self.username,
'password': self.password,
}
headers = kwargs.setdefault('headers', {})
headers.setdefault(
'Referer',
'https://www.shanbay.com/web/account/login'
)
... | 登录 | Below is the the instruction that describes the task:
### Input:
登录
### Response:
def login(self, **kwargs):
"""登录"""
payload = {
'username': self.username,
'password': self.password,
}
headers = kwargs.setdefault('headers', {})
headers.setdefault(
... |
def object(self, object):
"""
Sets the object of this ServicePackageQuotaHistoryResponse.
Always set to 'service-package-quota-history'.
:param object: The object of this ServicePackageQuotaHistoryResponse.
:type: str
"""
if object is None:
raise Valu... | Sets the object of this ServicePackageQuotaHistoryResponse.
Always set to 'service-package-quota-history'.
:param object: The object of this ServicePackageQuotaHistoryResponse.
:type: str | Below is the the instruction that describes the task:
### Input:
Sets the object of this ServicePackageQuotaHistoryResponse.
Always set to 'service-package-quota-history'.
:param object: The object of this ServicePackageQuotaHistoryResponse.
:type: str
### Response:
def object(self, object... |
def _train_model(
self, train_data, loss_fn, valid_data=None, log_writer=None, restore_state={}
):
"""The internal training routine called by train_model() after setup
Args:
train_data: a tuple of Tensors (X,Y), a Dataset, or a DataLoader of
X (data) and Y (label... | The internal training routine called by train_model() after setup
Args:
train_data: a tuple of Tensors (X,Y), a Dataset, or a DataLoader of
X (data) and Y (labels) for the train split
loss_fn: the loss function to minimize (maps *data -> loss)
valid_data: a t... | Below is the the instruction that describes the task:
### Input:
The internal training routine called by train_model() after setup
Args:
train_data: a tuple of Tensors (X,Y), a Dataset, or a DataLoader of
X (data) and Y (labels) for the train split
loss_fn: the loss ... |
def get_object_reference(obj: Object) -> str:
"""Gets an object reference string from the obj instance.
This adds the object type to ALL_RESOURCES so that it gets documented and
returns a str which contains a sphinx reference to the documented object.
:param obj: The Object instance.
:returns: A s... | Gets an object reference string from the obj instance.
This adds the object type to ALL_RESOURCES so that it gets documented and
returns a str which contains a sphinx reference to the documented object.
:param obj: The Object instance.
:returns: A sphinx docs reference str. | Below is the the instruction that describes the task:
### Input:
Gets an object reference string from the obj instance.
This adds the object type to ALL_RESOURCES so that it gets documented and
returns a str which contains a sphinx reference to the documented object.
:param obj: The Object instance.
... |
def get_mouse_pos(self, window_pos=None):
"""Return a MousePos filled with the world position and surf it hit."""
window_pos = window_pos or pygame.mouse.get_pos()
# +0.5 to center the point on the middle of the pixel.
window_pt = point.Point(*window_pos) + 0.5
for surf in reversed(self._surfaces):
... | Return a MousePos filled with the world position and surf it hit. | Below is the the instruction that describes the task:
### Input:
Return a MousePos filled with the world position and surf it hit.
### Response:
def get_mouse_pos(self, window_pos=None):
"""Return a MousePos filled with the world position and surf it hit."""
window_pos = window_pos or pygame.mouse.get_pos(... |
def write_numeric_array(fd, header, array):
"""Write the numeric array"""
# make a memory file for writing array data
bd = BytesIO()
# write matrix header to memory file
write_var_header(bd, header)
if not isinstance(array, basestring) and header['dims'][0] > 1:
# list array data in co... | Write the numeric array | Below is the the instruction that describes the task:
### Input:
Write the numeric array
### Response:
def write_numeric_array(fd, header, array):
"""Write the numeric array"""
# make a memory file for writing array data
bd = BytesIO()
# write matrix header to memory file
write_var_header(bd, ... |
def require_at_least_one_query_parameter(*query_parameter_names):
"""
Ensure at least one of the specified query parameters are included in the request.
This decorator checks for the existence of at least one of the specified query
parameters and passes the values as function parameters to the decorate... | Ensure at least one of the specified query parameters are included in the request.
This decorator checks for the existence of at least one of the specified query
parameters and passes the values as function parameters to the decorated view.
If none of the specified query parameters are included in the requ... | Below is the the instruction that describes the task:
### Input:
Ensure at least one of the specified query parameters are included in the request.
This decorator checks for the existence of at least one of the specified query
parameters and passes the values as function parameters to the decorated view.
... |
def count_(self):
"""
Returns the number of rows of the main dataframe
"""
try:
num = len(self.df.index)
except Exception as e:
self.err(e, "Can not count data")
return
return num | Returns the number of rows of the main dataframe | Below is the the instruction that describes the task:
### Input:
Returns the number of rows of the main dataframe
### Response:
def count_(self):
"""
Returns the number of rows of the main dataframe
"""
try:
num = len(self.df.index)
except Exception as e:
... |
def attach_volume_to_device(self, volume_id, device_id):
"""Attaches the created Volume to a Device.
"""
try:
volume = self.manager.get_volume(volume_id)
volume.attach(device_id)
except packet.baseapi.Error as msg:
raise PacketManagerException(msg)
... | Attaches the created Volume to a Device. | Below is the the instruction that describes the task:
### Input:
Attaches the created Volume to a Device.
### Response:
def attach_volume_to_device(self, volume_id, device_id):
"""Attaches the created Volume to a Device.
"""
try:
volume = self.manager.get_volume(volume_id)
... |
def mock_attr(self, *args, **kwargs):
"""
Empty method to call to slurp up args and kwargs.
`args` get pushed onto the url path.
`kwargs` are converted to a query string and appended to the URL.
"""
self.path.extend(args)
self.qs.update(kwargs)
return sel... | Empty method to call to slurp up args and kwargs.
`args` get pushed onto the url path.
`kwargs` are converted to a query string and appended to the URL. | Below is the the instruction that describes the task:
### Input:
Empty method to call to slurp up args and kwargs.
`args` get pushed onto the url path.
`kwargs` are converted to a query string and appended to the URL.
### Response:
def mock_attr(self, *args, **kwargs):
"""
Empty me... |
def open_handle(self, dwDesiredAccess = win32.THREAD_ALL_ACCESS):
"""
Opens a new handle to the thread, closing the previous one.
The new handle is stored in the L{hThread} property.
@warn: Normally you should call L{get_handle} instead, since it's much
"smarter" and tries ... | Opens a new handle to the thread, closing the previous one.
The new handle is stored in the L{hThread} property.
@warn: Normally you should call L{get_handle} instead, since it's much
"smarter" and tries to reuse handles and merge access rights.
@type dwDesiredAccess: int
... | Below is the the instruction that describes the task:
### Input:
Opens a new handle to the thread, closing the previous one.
The new handle is stored in the L{hThread} property.
@warn: Normally you should call L{get_handle} instead, since it's much
"smarter" and tries to reuse handles ... |
async def nextset(self):
"""Get the next query set"""
conn = self._get_db()
current_result = self._result
if current_result is None or current_result is not conn._result:
return
if not current_result.has_next:
return
self._result = None
sel... | Get the next query set | Below is the the instruction that describes the task:
### Input:
Get the next query set
### Response:
async def nextset(self):
"""Get the next query set"""
conn = self._get_db()
current_result = self._result
if current_result is None or current_result is not conn._result:
... |
def _set_output_arguments(self):
"""Activate output arguments parsing"""
group = self.parser.add_argument_group('output arguments')
group.add_argument('-o', '--output', type=argparse.FileType('w'),
dest='outfile', default=sys.stdout,
help="o... | Activate output arguments parsing | Below is the the instruction that describes the task:
### Input:
Activate output arguments parsing
### Response:
def _set_output_arguments(self):
"""Activate output arguments parsing"""
group = self.parser.add_argument_group('output arguments')
group.add_argument('-o', '--output', type=arg... |
def savorSessionCookie(self, request):
"""
Make the session cookie last as long as the persistent session.
@type request: L{nevow.inevow.IRequest}
@param request: The HTTP request object for the guard login URL.
"""
cookieValue = request.getSession().uid
request.... | Make the session cookie last as long as the persistent session.
@type request: L{nevow.inevow.IRequest}
@param request: The HTTP request object for the guard login URL. | Below is the the instruction that describes the task:
### Input:
Make the session cookie last as long as the persistent session.
@type request: L{nevow.inevow.IRequest}
@param request: The HTTP request object for the guard login URL.
### Response:
def savorSessionCookie(self, request):
"""... |
def ContextTupleToDict(context):
"""Convert a tuple representing a context into a dict of (key, value) pairs
"""
d = {}
if not context:
return d
for k, v in zip(ExceptionWithContext.CONTEXT_PARTS, context):
if v != '' and v != None: # Don't ignore int(0), a valid row_num
d[k] = ... | Convert a tuple representing a context into a dict of (key, value) pairs | Below is the the instruction that describes the task:
### Input:
Convert a tuple representing a context into a dict of (key, value) pairs
### Response:
def ContextTupleToDict(context):
"""Convert a tuple representing a context into a dict of (key, value) pairs
"""
d = {}
if not context:
retur... |
def churn_rate(user, summary='default', **kwargs):
"""
Computes the frequency spent at every towers each week, and returns the
distribution of the cosine similarity between two consecutives week.
.. note:: The churn rate is always computed between pairs of weeks.
"""
if len(user.records) == 0:
... | Computes the frequency spent at every towers each week, and returns the
distribution of the cosine similarity between two consecutives week.
.. note:: The churn rate is always computed between pairs of weeks. | Below is the the instruction that describes the task:
### Input:
Computes the frequency spent at every towers each week, and returns the
distribution of the cosine similarity between two consecutives week.
.. note:: The churn rate is always computed between pairs of weeks.
### Response:
def churn_rate(use... |
def get_branch_info(self):
"""
Retrieve branch_info from Satellite Server
"""
branch_info = None
if os.path.exists(constants.cached_branch_info):
# use cached branch info file if less than 10 minutes old
# (failsafe, should be deleted at end of client run... | Retrieve branch_info from Satellite Server | Below is the the instruction that describes the task:
### Input:
Retrieve branch_info from Satellite Server
### Response:
def get_branch_info(self):
"""
Retrieve branch_info from Satellite Server
"""
branch_info = None
if os.path.exists(constants.cached_branch_info):
... |
def apply_perturbations(i, j, X, increase, theta, clip_min, clip_max):
"""
TensorFlow implementation for apply perturbations to input features based
on salency maps
:param i: index of first selected feature
:param j: index of second selected feature
:param X: a matrix containing our input features for our s... | TensorFlow implementation for apply perturbations to input features based
on salency maps
:param i: index of first selected feature
:param j: index of second selected feature
:param X: a matrix containing our input features for our sample
:param increase: boolean; true if we are increasing pixels, false other... | Below is the the instruction that describes the task:
### Input:
TensorFlow implementation for apply perturbations to input features based
on salency maps
:param i: index of first selected feature
:param j: index of second selected feature
:param X: a matrix containing our input features for our sample
:p... |
def _get_media(media_types):
"""Helper method to map the media types."""
get_mapped_media = (lambda x: maps.VIRTUAL_MEDIA_TYPES_MAP[x]
if x in maps.VIRTUAL_MEDIA_TYPES_MAP else None)
return list(map(get_mapped_media, media_types)) | Helper method to map the media types. | Below is the the instruction that describes the task:
### Input:
Helper method to map the media types.
### Response:
def _get_media(media_types):
"""Helper method to map the media types."""
get_mapped_media = (lambda x: maps.VIRTUAL_MEDIA_TYPES_MAP[x]
if x in maps.VIRTUAL_MEDIA_TYPE... |
def __get_zero_seq_indexes(self, message: str, following_zeros: int):
"""
:rtype: list[tuple of int]
"""
result = []
if following_zeros > len(message):
return result
zero_counter = 0
for i in range(0, len(message)):
if message[i] == "0":
... | :rtype: list[tuple of int] | Below is the the instruction that describes the task:
### Input:
:rtype: list[tuple of int]
### Response:
def __get_zero_seq_indexes(self, message: str, following_zeros: int):
"""
:rtype: list[tuple of int]
"""
result = []
if following_zeros > len(message):
retu... |
def inner(tensor0: BKTensor, tensor1: BKTensor) -> BKTensor:
"""Return the inner product between two tensors"""
# Note: Relying on fact that vdot flattens arrays
return np.vdot(tensor0, tensor1) | Return the inner product between two tensors | Below is the the instruction that describes the task:
### Input:
Return the inner product between two tensors
### Response:
def inner(tensor0: BKTensor, tensor1: BKTensor) -> BKTensor:
"""Return the inner product between two tensors"""
# Note: Relying on fact that vdot flattens arrays
return np.vdot(te... |
def get_volume_options(volumes):
"""
Generates volume options to run methods.
:param volumes: tuple or list of tuples in form target x source,target x source,target,mode.
:return: list of the form ["-v", "/source:/target", "-v", "/other/source:/destination:z", ...]
"""
i... | Generates volume options to run methods.
:param volumes: tuple or list of tuples in form target x source,target x source,target,mode.
:return: list of the form ["-v", "/source:/target", "-v", "/other/source:/destination:z", ...] | Below is the the instruction that describes the task:
### Input:
Generates volume options to run methods.
:param volumes: tuple or list of tuples in form target x source,target x source,target,mode.
:return: list of the form ["-v", "/source:/target", "-v", "/other/source:/destination:z", ...]
### R... |
def compute_elementary_effects(model_inputs, model_outputs, trajectory_size,
delta):
'''
Arguments
---------
model_inputs : matrix of inputs to the model under analysis.
x-by-r where x is the number of variables and
r is the number of rows (a function of x ... | Arguments
---------
model_inputs : matrix of inputs to the model under analysis.
x-by-r where x is the number of variables and
r is the number of rows (a function of x and num_trajectories)
model_outputs
an r-length vector of model outputs
trajectory_size
a scalar indicat... | Below is the the instruction that describes the task:
### Input:
Arguments
---------
model_inputs : matrix of inputs to the model under analysis.
x-by-r where x is the number of variables and
r is the number of rows (a function of x and num_trajectories)
model_outputs
an r-length... |
def mergeGraphs(targetGraph, addedGraph, incrementedNodeVal = 'count', incrementedEdgeVal = 'weight'):
"""A quick way of merging graphs, this is meant to be quick and is only intended for graphs generated by metaknowledge. This does not check anything and as such may cause unexpected results if the source and targe... | A quick way of merging graphs, this is meant to be quick and is only intended for graphs generated by metaknowledge. This does not check anything and as such may cause unexpected results if the source and target were not generated by the same method.
**mergeGraphs**() will **modify** _targetGraph_ in place by addi... | Below is the the instruction that describes the task:
### Input:
A quick way of merging graphs, this is meant to be quick and is only intended for graphs generated by metaknowledge. This does not check anything and as such may cause unexpected results if the source and target were not generated by the same method.
... |
def deliver_tx(self, raw_transaction):
"""Validate the transaction before mutating the state.
Args:
raw_tx: a raw string (in bytes) transaction.
"""
self.abort_if_abci_chain_is_not_synced()
logger.debug('deliver_tx: %s', raw_transaction)
transaction = self.... | Validate the transaction before mutating the state.
Args:
raw_tx: a raw string (in bytes) transaction. | Below is the the instruction that describes the task:
### Input:
Validate the transaction before mutating the state.
Args:
raw_tx: a raw string (in bytes) transaction.
### Response:
def deliver_tx(self, raw_transaction):
"""Validate the transaction before mutating the state.
A... |
def deepgetattr(obj, attr, default=AttributeError):
"""
Recurses through an attribute chain to get the ultimate value (obj/data/member/value)
from: http://pingfive.typepad.com/blog/2010/04/deep-getattr-python-function.html
>>> class Universe(object):
... def __init__(self, galaxy):
... ... | Recurses through an attribute chain to get the ultimate value (obj/data/member/value)
from: http://pingfive.typepad.com/blog/2010/04/deep-getattr-python-function.html
>>> class Universe(object):
... def __init__(self, galaxy):
... self.galaxy = galaxy
...
>>> class Galaxy(objec... | Below is the the instruction that describes the task:
### Input:
Recurses through an attribute chain to get the ultimate value (obj/data/member/value)
from: http://pingfive.typepad.com/blog/2010/04/deep-getattr-python-function.html
>>> class Universe(object):
... def __init__(self, galaxy):
...... |
def run_solr_text_on(solrInstance, category, q, qf, fields, optionals):
"""
Return the result of a solr query on the given solrInstance (Enum ESOLR), for a certain document_category (ESOLRDoc) and id
"""
if optionals == None:
optionals = ""
query = solrInstance.value + "select?q=" + q + "&qf... | Return the result of a solr query on the given solrInstance (Enum ESOLR), for a certain document_category (ESOLRDoc) and id | Below is the the instruction that describes the task:
### Input:
Return the result of a solr query on the given solrInstance (Enum ESOLR), for a certain document_category (ESOLRDoc) and id
### Response:
def run_solr_text_on(solrInstance, category, q, qf, fields, optionals):
"""
Return the result of a solr ... |
def radec2azel(ra_deg: float, dec_deg: float,
lat_deg: float, lon_deg: float,
time: datetime, usevallado: bool = False) -> Tuple[float, float]:
"""
sky coordinates (ra, dec) to viewing angle (az, el)
Parameters
----------
ra_deg : float or numpy.ndarray of float
... | sky coordinates (ra, dec) to viewing angle (az, el)
Parameters
----------
ra_deg : float or numpy.ndarray of float
ecliptic right ascension (degress)
dec_deg : float or numpy.ndarray of float
ecliptic declination (degrees)
lat_deg : float
observer latitude [-90, 90]
... | Below is the the instruction that describes the task:
### Input:
sky coordinates (ra, dec) to viewing angle (az, el)
Parameters
----------
ra_deg : float or numpy.ndarray of float
ecliptic right ascension (degress)
dec_deg : float or numpy.ndarray of float
ecliptic declination (de... |
def _simulate_coef_from_bootstraps(
self, n_draws, coef_bootstraps, cov_bootstraps):
"""Simulate coefficients using bootstrap samples."""
# Sample indices uniformly from {0, ..., n_bootstraps - 1}
# (Wood pg. 199 step 6)
random_bootstrap_indices = np.random.choice(
... | Simulate coefficients using bootstrap samples. | Below is the the instruction that describes the task:
### Input:
Simulate coefficients using bootstrap samples.
### Response:
def _simulate_coef_from_bootstraps(
self, n_draws, coef_bootstraps, cov_bootstraps):
"""Simulate coefficients using bootstrap samples."""
# Sample indices unifor... |
def run_shell_command(commands, **kwargs):
"""Run a shell command."""
p = subprocess.Popen(commands,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
**kwargs)
output, error = p.communicate()
return p.returncode, output, error | Run a shell command. | Below is the the instruction that describes the task:
### Input:
Run a shell command.
### Response:
def run_shell_command(commands, **kwargs):
"""Run a shell command."""
p = subprocess.Popen(commands,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
... |
def db_create(name,
user=None,
host=None,
port=None,
maintenance_db=None,
password=None,
tablespace=None,
encoding=None,
lc_collate=None,
lc_ctype=None,
owner=None,
t... | Adds a databases to the Postgres server.
CLI Example:
.. code-block:: bash
salt '*' postgres.db_create 'dbname'
salt '*' postgres.db_create 'dbname' template=template_postgis | Below is the the instruction that describes the task:
### Input:
Adds a databases to the Postgres server.
CLI Example:
.. code-block:: bash
salt '*' postgres.db_create 'dbname'
salt '*' postgres.db_create 'dbname' template=template_postgis
### Response:
def db_create(name,
... |
def addcomment(self, comment, private=False):
"""
Add the given comment to this bug. Set private to True to mark this
comment as private.
"""
# Note: fedora bodhi uses this function
vals = self.bugzilla.build_update(comment=comment,
... | Add the given comment to this bug. Set private to True to mark this
comment as private. | Below is the the instruction that describes the task:
### Input:
Add the given comment to this bug. Set private to True to mark this
comment as private.
### Response:
def addcomment(self, comment, private=False):
"""
Add the given comment to this bug. Set private to True to mark this
... |
def _safe_dump(data):
'''
this presenter magic makes yaml.safe_dump
work with the objects returned from
boto.describe_alarms()
'''
custom_dumper = __utils__['yaml.get_dumper']('SafeOrderedDumper')
def boto_listelement_presenter(dumper, data):
return dumper.represent_list(list(data))... | this presenter magic makes yaml.safe_dump
work with the objects returned from
boto.describe_alarms() | Below is the the instruction that describes the task:
### Input:
this presenter magic makes yaml.safe_dump
work with the objects returned from
boto.describe_alarms()
### Response:
def _safe_dump(data):
'''
this presenter magic makes yaml.safe_dump
work with the objects returned from
boto.de... |
def remove_tmp_prefix_from_filename(filename):
"""
Remove tmp prefix from filename.
"""
if not filename.startswith(dju_settings.DJU_IMG_UPLOAD_TMP_PREFIX):
raise RuntimeError(ERROR_MESSAGES['filename_hasnt_tmp_prefix'] % {'filename': filename})
return filename[len(dju_settings.DJU_IMG_UPLOAD... | Remove tmp prefix from filename. | Below is the the instruction that describes the task:
### Input:
Remove tmp prefix from filename.
### Response:
def remove_tmp_prefix_from_filename(filename):
"""
Remove tmp prefix from filename.
"""
if not filename.startswith(dju_settings.DJU_IMG_UPLOAD_TMP_PREFIX):
raise RuntimeError(ERRO... |
def from_ZNM(cls, Z, N, M, name=''):
"""
Creates a table from arrays Z, N and M
Example:
________
>>> Z = [82, 82, 83]
>>> N = [126, 127, 130]
>>> M = [-21.34, -18.0, -14.45]
>>> Table.from_ZNM(Z, N, M, name='Custom Table')
Z N
82 126 ... | Creates a table from arrays Z, N and M
Example:
________
>>> Z = [82, 82, 83]
>>> N = [126, 127, 130]
>>> M = [-21.34, -18.0, -14.45]
>>> Table.from_ZNM(Z, N, M, name='Custom Table')
Z N
82 126 -21.34
127 -18.00
83 130 -14.4... | Below is the the instruction that describes the task:
### Input:
Creates a table from arrays Z, N and M
Example:
________
>>> Z = [82, 82, 83]
>>> N = [126, 127, 130]
>>> M = [-21.34, -18.0, -14.45]
>>> Table.from_ZNM(Z, N, M, name='Custom Table')
Z N
... |
def p_plus_assignment(self, t):
'''plus_assignment : IDENT EQ PLUS'''
self.accu.add(Term('obs_vlabel', [self.name,"gen(\""+t[1]+"\")","1"])) | plus_assignment : IDENT EQ PLUS | Below is the the instruction that describes the task:
### Input:
plus_assignment : IDENT EQ PLUS
### Response:
def p_plus_assignment(self, t):
'''plus_assignment : IDENT EQ PLUS'''
self.accu.add(Term('obs_vlabel', [self.name,"gen(\""+t[1]+"\")","1"])) |
def url(self, pattern, method=None, type_cast=None):
"""Decorator for registering a path pattern.
Args:
pattern (str): Regex pattern to match a certain path
method (str, optional): Usually used to define one of GET, POST,
PUT, DELETE. You may use whatever fits yo... | Decorator for registering a path pattern.
Args:
pattern (str): Regex pattern to match a certain path
method (str, optional): Usually used to define one of GET, POST,
PUT, DELETE. You may use whatever fits your situation though.
Defaults to None.
... | Below is the the instruction that describes the task:
### Input:
Decorator for registering a path pattern.
Args:
pattern (str): Regex pattern to match a certain path
method (str, optional): Usually used to define one of GET, POST,
PUT, DELETE. You may use whatever fi... |
def load_table_from_config(input_dir, config):
"""Load table from table config dict
Args:
input_dir (path-like): directory containing input files
config (dict): mapping with keys 'name', 'path', and 'pd_read_kwargs'.
Returns:
pd.DataFrame
"""
path = pathlib.Path(input_dir).... | Load table from table config dict
Args:
input_dir (path-like): directory containing input files
config (dict): mapping with keys 'name', 'path', and 'pd_read_kwargs'.
Returns:
pd.DataFrame | Below is the the instruction that describes the task:
### Input:
Load table from table config dict
Args:
input_dir (path-like): directory containing input files
config (dict): mapping with keys 'name', 'path', and 'pd_read_kwargs'.
Returns:
pd.DataFrame
### Response:
def load_tabl... |
def _get_k(self):
'''
Accessing self.k indirectly allows for creating the kvstore table
if necessary.
'''
if not self.ready:
self.k.create() # create table if it does not exist.
self.ready = True
return self.k | Accessing self.k indirectly allows for creating the kvstore table
if necessary. | Below is the the instruction that describes the task:
### Input:
Accessing self.k indirectly allows for creating the kvstore table
if necessary.
### Response:
def _get_k(self):
'''
Accessing self.k indirectly allows for creating the kvstore table
if necessary.
'''
if... |
def has_project_permissions(user: 'User', project: 'Project', request_method: str) -> bool:
"""This logic is extracted here to be used also with Sanic api."""
# Superusers and the creator is allowed to do everything
if user.is_staff or user.is_superuser or project.user == user:
return True
# Ot... | This logic is extracted here to be used also with Sanic api. | Below is the the instruction that describes the task:
### Input:
This logic is extracted here to be used also with Sanic api.
### Response:
def has_project_permissions(user: 'User', project: 'Project', request_method: str) -> bool:
"""This logic is extracted here to be used also with Sanic api."""
# Superu... |
def divide(self, phi1, inplace=True):
"""
DiscreteFactor division by `phi1`.
Parameters
----------
phi1 : `DiscreteFactor` instance
The denominator for division.
inplace: boolean
If inplace=True it will modify the factor itself, else would return... | DiscreteFactor division by `phi1`.
Parameters
----------
phi1 : `DiscreteFactor` instance
The denominator for division.
inplace: boolean
If inplace=True it will modify the factor itself, else would return
a new factor.
Returns
------... | Below is the the instruction that describes the task:
### Input:
DiscreteFactor division by `phi1`.
Parameters
----------
phi1 : `DiscreteFactor` instance
The denominator for division.
inplace: boolean
If inplace=True it will modify the factor itself, else w... |
def get_archive(self, archive_name, default_version=None):
'''
Retrieve a data archive
Parameters
----------
archive_name: str
Name of the archive to retrieve
default_version: version
str or :py:class:`~distutils.StrictVersion` giving the defaul... | Retrieve a data archive
Parameters
----------
archive_name: str
Name of the archive to retrieve
default_version: version
str or :py:class:`~distutils.StrictVersion` giving the default
version number to be used on read operations
Returns
... | Below is the the instruction that describes the task:
### Input:
Retrieve a data archive
Parameters
----------
archive_name: str
Name of the archive to retrieve
default_version: version
str or :py:class:`~distutils.StrictVersion` giving the default
... |
def walk(self):
"""Walk proposal kernel"""
if self.verbose > 1:
print_('\t' + self._id + ' Running Walk proposal kernel')
# Mask for values to move
phi = self.phi
theta = self.walk_theta
u = random(len(phi))
z = (theta / (1 + theta)) * (theta * u *... | Walk proposal kernel | Below is the the instruction that describes the task:
### Input:
Walk proposal kernel
### Response:
def walk(self):
"""Walk proposal kernel"""
if self.verbose > 1:
print_('\t' + self._id + ' Running Walk proposal kernel')
# Mask for values to move
phi = self.phi
... |
def from_string(cls, string, relpath=None, encoding=None, is_sass=None):
"""Read Sass source from the contents of a string.
The origin is always None. `relpath` defaults to "string:...".
"""
if isinstance(string, six.text_type):
# Already decoded; we don't know what encodin... | Read Sass source from the contents of a string.
The origin is always None. `relpath` defaults to "string:...". | Below is the the instruction that describes the task:
### Input:
Read Sass source from the contents of a string.
The origin is always None. `relpath` defaults to "string:...".
### Response:
def from_string(cls, string, relpath=None, encoding=None, is_sass=None):
"""Read Sass source from the conte... |
def abbreviations(text):
"""Remove periods after an abbreviation from a list of known
abbrevations that can be spoken the same without that period. This
prevents having to handle tokenization of that period.
Note:
Could potentially remove the ending period of a sentence.
Note:
Abbr... | Remove periods after an abbreviation from a list of known
abbrevations that can be spoken the same without that period. This
prevents having to handle tokenization of that period.
Note:
Could potentially remove the ending period of a sentence.
Note:
Abbreviations that Google Translate ... | Below is the the instruction that describes the task:
### Input:
Remove periods after an abbreviation from a list of known
abbrevations that can be spoken the same without that period. This
prevents having to handle tokenization of that period.
Note:
Could potentially remove the ending period o... |
def isDiurnal(self):
""" Returns true if this chart is diurnal. """
sun = self.getObject(const.SUN)
mc = self.getAngle(const.MC)
# Get ecliptical positions and check if the
# sun is above the horizon.
lat = self.pos.lat
sunRA, sunDecl = utils.eqCoords(sun... | Returns true if this chart is diurnal. | Below is the the instruction that describes the task:
### Input:
Returns true if this chart is diurnal.
### Response:
def isDiurnal(self):
""" Returns true if this chart is diurnal. """
sun = self.getObject(const.SUN)
mc = self.getAngle(const.MC)
# Get ecliptical positions ... |
def service_highstate(requires=True):
'''
Return running and enabled services in a highstate structure. By default
also returns package dependencies for those services, which means that
package definitions must be created outside this function. To drop the
package dependencies, set ``requires`` to F... | Return running and enabled services in a highstate structure. By default
also returns package dependencies for those services, which means that
package definitions must be created outside this function. To drop the
package dependencies, set ``requires`` to False.
CLI Example:
salt myminion int... | Below is the the instruction that describes the task:
### Input:
Return running and enabled services in a highstate structure. By default
also returns package dependencies for those services, which means that
package definitions must be created outside this function. To drop the
package dependencies, se... |
def get_filters(cls, raw_filters, num_cols, columns_dict): # noqa
"""Given Superset filter data structure, returns pydruid Filter(s)"""
filters = None
for flt in raw_filters:
col = flt.get('col')
op = flt.get('op')
eq = flt.get('val')
if (
... | Given Superset filter data structure, returns pydruid Filter(s) | Below is the the instruction that describes the task:
### Input:
Given Superset filter data structure, returns pydruid Filter(s)
### Response:
def get_filters(cls, raw_filters, num_cols, columns_dict): # noqa
"""Given Superset filter data structure, returns pydruid Filter(s)"""
filters = None
... |
def get_model_from_path_string(root_model, path):
""" Return a model class for a related model
root_model is the class of the initial model
path is like foo__bar where bar is related to foo
"""
for path_section in path.split('__'):
if path_section:
try:
field, mod... | Return a model class for a related model
root_model is the class of the initial model
path is like foo__bar where bar is related to foo | Below is the the instruction that describes the task:
### Input:
Return a model class for a related model
root_model is the class of the initial model
path is like foo__bar where bar is related to foo
### Response:
def get_model_from_path_string(root_model, path):
""" Return a model class for a related... |
def calc_steady_state_dist(R):
"""Calculate the steady state dist of a 4 state markov transition matrix.
Parameters
----------
R : ndarray
Markov transition matrix
Returns
-------
p_ss : ndarray
Steady state probability distribution
"""
#Calc steady state d... | Calculate the steady state dist of a 4 state markov transition matrix.
Parameters
----------
R : ndarray
Markov transition matrix
Returns
-------
p_ss : ndarray
Steady state probability distribution | Below is the the instruction that describes the task:
### Input:
Calculate the steady state dist of a 4 state markov transition matrix.
Parameters
----------
R : ndarray
Markov transition matrix
Returns
-------
p_ss : ndarray
Steady state probability distribution
### Respon... |
def logger(name=None, save=False):
"""Init and configure logger."""
logger = logging.getLogger(name)
if save:
logformat = '%(asctime)s [%(levelname)s] [%(name)s] %(funcName)s: %(message)s (line %(lineno)d)'
log_file_path = 'fut.log' # TODO: define logpath
open(log_file_path, 'w').w... | Init and configure logger. | Below is the the instruction that describes the task:
### Input:
Init and configure logger.
### Response:
def logger(name=None, save=False):
"""Init and configure logger."""
logger = logging.getLogger(name)
if save:
logformat = '%(asctime)s [%(levelname)s] [%(name)s] %(funcName)s: %(message)s ... |
def find_usage(self):
"""
Determine the current usage for each limit of this service,
and update corresponding Limit via
:py:meth:`~.AwsLimit._add_current_usage`.
"""
logger.debug("Checking usage for service %s", self.service_name)
self.connect()
for lim i... | Determine the current usage for each limit of this service,
and update corresponding Limit via
:py:meth:`~.AwsLimit._add_current_usage`. | Below is the the instruction that describes the task:
### Input:
Determine the current usage for each limit of this service,
and update corresponding Limit via
:py:meth:`~.AwsLimit._add_current_usage`.
### Response:
def find_usage(self):
"""
Determine the current usage for each limi... |
def parse_raxml(handle):
"""Parse RAxML's summary output.
*handle* should be an open file handle containing the RAxML
output. It is parsed and a dictionary returned.
"""
s = ''.join(handle.readlines())
result = {}
try_set_fields(result, r'(?P<program>RAxML version [0-9.]+)', s)
try_set... | Parse RAxML's summary output.
*handle* should be an open file handle containing the RAxML
output. It is parsed and a dictionary returned. | Below is the the instruction that describes the task:
### Input:
Parse RAxML's summary output.
*handle* should be an open file handle containing the RAxML
output. It is parsed and a dictionary returned.
### Response:
def parse_raxml(handle):
"""Parse RAxML's summary output.
*handle* should be an... |
def current_changed(self, i):
"""Slot for when the current index changes.
Emits the :data:`AbstractLevel.new_root` signal.
:param index: the new current index
:type index: int
:returns: None
:rtype: None
:raises: None
"""
m = self.model()
... | Slot for when the current index changes.
Emits the :data:`AbstractLevel.new_root` signal.
:param index: the new current index
:type index: int
:returns: None
:rtype: None
:raises: None | Below is the the instruction that describes the task:
### Input:
Slot for when the current index changes.
Emits the :data:`AbstractLevel.new_root` signal.
:param index: the new current index
:type index: int
:returns: None
:rtype: None
:raises: None
### Response:
de... |
def line(self, serie, rescale=False):
"""Draw the line serie"""
serie_node = self.svg.serie(serie)
if rescale and self.secondary_series:
points = self._rescale(serie.points)
else:
points = serie.points
view_values = list(map(self.view, points))
if ... | Draw the line serie | Below is the the instruction that describes the task:
### Input:
Draw the line serie
### Response:
def line(self, serie, rescale=False):
"""Draw the line serie"""
serie_node = self.svg.serie(serie)
if rescale and self.secondary_series:
points = self._rescale(serie.points)
... |
def as_dict(self, cache=None, fetch=True):
"""Return torrent properties as a dictionary.
Set the cache flag to False to disable the cache. On the other hand,
set the fetch flag to False to avoid fetching data if it's not cached.
"""
if not self._fetched and fetch:
i... | Return torrent properties as a dictionary.
Set the cache flag to False to disable the cache. On the other hand,
set the fetch flag to False to avoid fetching data if it's not cached. | Below is the the instruction that describes the task:
### Input:
Return torrent properties as a dictionary.
Set the cache flag to False to disable the cache. On the other hand,
set the fetch flag to False to avoid fetching data if it's not cached.
### Response:
def as_dict(self, cache=None, fetch=... |
def create_ui(self):
'''
.. versionchanged:: 0.21.2
Load the builder configuration file using :func:`pkgutil.getdata`,
which supports loading from `.zip` archives (e.g., in an app
packaged with Py2Exe).
'''
builder = gtk.Builder()
# Read glade ... | .. versionchanged:: 0.21.2
Load the builder configuration file using :func:`pkgutil.getdata`,
which supports loading from `.zip` archives (e.g., in an app
packaged with Py2Exe). | Below is the the instruction that describes the task:
### Input:
.. versionchanged:: 0.21.2
Load the builder configuration file using :func:`pkgutil.getdata`,
which supports loading from `.zip` archives (e.g., in an app
packaged with Py2Exe).
### Response:
def create_ui(self):
... |
def which(cmd):
"""
Returns full path to a executable.
Args:
cmd (str): Executable command to search for.
Returns:
(str) Full path to command. None if it is not found.
Example::
full_path_to_python = which("python")
"""
def is_exe(fp):
return os.path.isfil... | Returns full path to a executable.
Args:
cmd (str): Executable command to search for.
Returns:
(str) Full path to command. None if it is not found.
Example::
full_path_to_python = which("python") | Below is the the instruction that describes the task:
### Input:
Returns full path to a executable.
Args:
cmd (str): Executable command to search for.
Returns:
(str) Full path to command. None if it is not found.
Example::
full_path_to_python = which("python")
### Response:
... |
def find_n50(contig_lengths_dict, genome_length_dict):
"""
Calculate the N50 for each strain. N50 is defined as the largest contig such that at least half of the total
genome size is contained in contigs equal to or larger than this contig
:param contig_lengths_dict: dictionary of strain name: reverse-s... | Calculate the N50 for each strain. N50 is defined as the largest contig such that at least half of the total
genome size is contained in contigs equal to or larger than this contig
:param contig_lengths_dict: dictionary of strain name: reverse-sorted list of all contig lengths
:param genome_length_dict: dic... | Below is the the instruction that describes the task:
### Input:
Calculate the N50 for each strain. N50 is defined as the largest contig such that at least half of the total
genome size is contained in contigs equal to or larger than this contig
:param contig_lengths_dict: dictionary of strain name: reverse... |
def transform(self, maps):
"""This function transforms from chirp mass and symmetric mass ratio to
component masses.
Parameters
----------
maps : a mapping object
Examples
--------
Convert a dict of numpy.array:
>>> import numpy
>>> from... | This function transforms from chirp mass and symmetric mass ratio to
component masses.
Parameters
----------
maps : a mapping object
Examples
--------
Convert a dict of numpy.array:
>>> import numpy
>>> from pycbc import transforms
>>> t... | Below is the the instruction that describes the task:
### Input:
This function transforms from chirp mass and symmetric mass ratio to
component masses.
Parameters
----------
maps : a mapping object
Examples
--------
Convert a dict of numpy.array:
>>... |
def splitterfields(data, commdct):
"""get splitter fields to diagram it"""
objkey = "Connector:Splitter".upper()
fieldlists = splittermixerfieldlists(data, commdct, objkey)
return extractfields(data, commdct, objkey, fieldlists) | get splitter fields to diagram it | Below is the the instruction that describes the task:
### Input:
get splitter fields to diagram it
### Response:
def splitterfields(data, commdct):
"""get splitter fields to diagram it"""
objkey = "Connector:Splitter".upper()
fieldlists = splittermixerfieldlists(data, commdct, objkey)
return extrac... |
def report(*arrays, **kwargs):
"""
Outputs a standalone HTML 'report card' for a
measurement (or several grouped measurements),
including relevant statistical information.
"""
name = kwargs.pop("name",None)
grouped = len(arrays) > 1
if grouped:
arr = N.concatenate(arrays)
... | Outputs a standalone HTML 'report card' for a
measurement (or several grouped measurements),
including relevant statistical information. | Below is the the instruction that describes the task:
### Input:
Outputs a standalone HTML 'report card' for a
measurement (or several grouped measurements),
including relevant statistical information.
### Response:
def report(*arrays, **kwargs):
"""
Outputs a standalone HTML 'report card' for a
... |
def get_timer(self, name=None):
'''Shortcut for getting a :class:`~statsd.timer.Timer` instance
:keyword name: See :func:`~statsd.client.Client.get_client`
:type name: str
'''
return self.get_client(name=name, class_=statsd.Timer) | Shortcut for getting a :class:`~statsd.timer.Timer` instance
:keyword name: See :func:`~statsd.client.Client.get_client`
:type name: str | Below is the the instruction that describes the task:
### Input:
Shortcut for getting a :class:`~statsd.timer.Timer` instance
:keyword name: See :func:`~statsd.client.Client.get_client`
:type name: str
### Response:
def get_timer(self, name=None):
'''Shortcut for getting a :class:`~statsd.... |
def write_to_conll_eval_file(prediction_file: TextIO,
gold_file: TextIO,
verb_index: Optional[int],
sentence: List[str],
prediction: List[str],
gold_labels: List[str]):
""... | Prints predicate argument predictions and gold labels for a single verbal
predicate in a sentence to two provided file references.
Parameters
----------
prediction_file : TextIO, required.
A file reference to print predictions to.
gold_file : TextIO, required.
A file reference to pr... | Below is the the instruction that describes the task:
### Input:
Prints predicate argument predictions and gold labels for a single verbal
predicate in a sentence to two provided file references.
Parameters
----------
prediction_file : TextIO, required.
A file reference to print predictions... |
def _extract_properties(config):
"""
Parse a line within a lease block
The line should basically match the expression:
>>> r"\s+(?P<key>(?:option|set)\s+\S+|\S+) (?P<value>[\s\S]+?);"
For easier seperation of the cases and faster parsing this is done using substrings etc..
:param config:
:re... | Parse a line within a lease block
The line should basically match the expression:
>>> r"\s+(?P<key>(?:option|set)\s+\S+|\S+) (?P<value>[\s\S]+?);"
For easier seperation of the cases and faster parsing this is done using substrings etc..
:param config:
:return: tuple of properties dict, options dict ... | Below is the the instruction that describes the task:
### Input:
Parse a line within a lease block
The line should basically match the expression:
>>> r"\s+(?P<key>(?:option|set)\s+\S+|\S+) (?P<value>[\s\S]+?);"
For easier seperation of the cases and faster parsing this is done using substrings etc..
... |
def find(self, name):
"""
Returns the Tag that matches the name.
:param name: the string representation of the tag
:type name: str
:return: the tag, None if not found
:rtype: Tag
"""
result = None
for t in self.array:
if str(t) == name... | Returns the Tag that matches the name.
:param name: the string representation of the tag
:type name: str
:return: the tag, None if not found
:rtype: Tag | Below is the the instruction that describes the task:
### Input:
Returns the Tag that matches the name.
:param name: the string representation of the tag
:type name: str
:return: the tag, None if not found
:rtype: Tag
### Response:
def find(self, name):
"""
Returns ... |
def find_kernel_specs(self):
"""Returns a dict mapping kernel names to resource directories."""
# let real installed kernels overwrite envs with the same name:
# this is the same order as the get_kernel_spec way, which also prefers
# kernels from the jupyter dir over env kernels.
... | Returns a dict mapping kernel names to resource directories. | Below is the the instruction that describes the task:
### Input:
Returns a dict mapping kernel names to resource directories.
### Response:
def find_kernel_specs(self):
"""Returns a dict mapping kernel names to resource directories."""
# let real installed kernels overwrite envs with the same name:... |
def import_module(name, package=None):
"""Import a module.
The 'package' argument is required when performing a relative import. It
specifies the package to use as the anchor point from which to resolve the
relative import to an absolute import.
"""
if name.startswith('.'):
if not pack... | Import a module.
The 'package' argument is required when performing a relative import. It
specifies the package to use as the anchor point from which to resolve the
relative import to an absolute import. | Below is the the instruction that describes the task:
### Input:
Import a module.
The 'package' argument is required when performing a relative import. It
specifies the package to use as the anchor point from which to resolve the
relative import to an absolute import.
### Response:
def import_module(n... |
def url(self):
"""return the full request url as an Url() instance"""
scheme = self.scheme
host = self.host
path = self.path
query = self.query
port = self.port
# normalize the port
host_domain, host_port = Url.split_hostname_from_port(host)
if ho... | return the full request url as an Url() instance | Below is the the instruction that describes the task:
### Input:
return the full request url as an Url() instance
### Response:
def url(self):
"""return the full request url as an Url() instance"""
scheme = self.scheme
host = self.host
path = self.path
query = self.query
... |
def converter_pm_log10(data):
"""Convert the given data to:
log10(subdata) for subdata > 0
log10(-subdata') for subdata' < 0
0 for subdata'' == 0
Parameters
----------
data: array
input data
Returns
-------
array_converted: array
converted data
... | Convert the given data to:
log10(subdata) for subdata > 0
log10(-subdata') for subdata' < 0
0 for subdata'' == 0
Parameters
----------
data: array
input data
Returns
-------
array_converted: array
converted data | Below is the the instruction that describes the task:
### Input:
Convert the given data to:
log10(subdata) for subdata > 0
log10(-subdata') for subdata' < 0
0 for subdata'' == 0
Parameters
----------
data: array
input data
Returns
-------
array_converted: a... |
def is_uniform_join_units(join_units):
"""
Check if the join units consist of blocks of uniform type that can
be concatenated using Block.concat_same_type instead of the generic
concatenate_join_units (which uses `_concat._concat_compat`).
"""
return (
# all blocks need to have the same... | Check if the join units consist of blocks of uniform type that can
be concatenated using Block.concat_same_type instead of the generic
concatenate_join_units (which uses `_concat._concat_compat`). | Below is the the instruction that describes the task:
### Input:
Check if the join units consist of blocks of uniform type that can
be concatenated using Block.concat_same_type instead of the generic
concatenate_join_units (which uses `_concat._concat_compat`).
### Response:
def is_uniform_join_units(join_... |
def get_mutation_rates(transcripts, mut_dict, ensembl):
""" determines mutation rates per functional category for transcripts
Args:
transcripts: list of transcript IDs for a gene
mut_dict: dictionary of local sequence context mutation rates
ensembl: EnsemblRequest object, to retriev... | determines mutation rates per functional category for transcripts
Args:
transcripts: list of transcript IDs for a gene
mut_dict: dictionary of local sequence context mutation rates
ensembl: EnsemblRequest object, to retrieve information from Ensembl.
Returns:
tuple of (... | Below is the the instruction that describes the task:
### Input:
determines mutation rates per functional category for transcripts
Args:
transcripts: list of transcript IDs for a gene
mut_dict: dictionary of local sequence context mutation rates
ensembl: EnsemblRequest object, to re... |
def run(self):
"""
Run the container.
Logic is as follows:
Generate container info (eventually from task definition)
Start container
Loop whilst not asked to stop and the container is running.
Get all logs from container between the last time I checked and now.... | Run the container.
Logic is as follows:
Generate container info (eventually from task definition)
Start container
Loop whilst not asked to stop and the container is running.
Get all logs from container between the last time I checked and now.
Convert logs into cloudwat... | Below is the the instruction that describes the task:
### Input:
Run the container.
Logic is as follows:
Generate container info (eventually from task definition)
Start container
Loop whilst not asked to stop and the container is running.
Get all logs from container betwee... |
def _acquire_lock(self, identifier, atime=30, ltime=5):
'''Acquire a lock for a given identifier.
If the lock cannot be obtained immediately, keep trying at random
intervals, up to 3 seconds, until `atime` has passed. Once the
lock has been obtained, continue to hold it for `ltime`.
... | Acquire a lock for a given identifier.
If the lock cannot be obtained immediately, keep trying at random
intervals, up to 3 seconds, until `atime` has passed. Once the
lock has been obtained, continue to hold it for `ltime`.
:param str identifier: lock token to write
:param in... | Below is the the instruction that describes the task:
### Input:
Acquire a lock for a given identifier.
If the lock cannot be obtained immediately, keep trying at random
intervals, up to 3 seconds, until `atime` has passed. Once the
lock has been obtained, continue to hold it for `ltime`.
... |
def set_active_scalar(self, name, preference='cell'):
"""Finds the scalar by name and appropriately sets it as active"""
_, field = get_scalar(self, name, preference=preference, info=True)
if field == POINT_DATA_FIELD:
self.GetPointData().SetActiveScalars(name)
elif field == ... | Finds the scalar by name and appropriately sets it as active | Below is the the instruction that describes the task:
### Input:
Finds the scalar by name and appropriately sets it as active
### Response:
def set_active_scalar(self, name, preference='cell'):
"""Finds the scalar by name and appropriately sets it as active"""
_, field = get_scalar(self, name, pref... |
def create(cls, name, members):
"""Creates a new enum type based on this one (cls) and adds newly
passed members to the newly created subclass of cls.
This method helps to create enums having the same member values as
values of other enum(s).
:param name: name of the newly crea... | Creates a new enum type based on this one (cls) and adds newly
passed members to the newly created subclass of cls.
This method helps to create enums having the same member values as
values of other enum(s).
:param name: name of the newly created type
:param members: 1) a dict ... | Below is the the instruction that describes the task:
### Input:
Creates a new enum type based on this one (cls) and adds newly
passed members to the newly created subclass of cls.
This method helps to create enums having the same member values as
values of other enum(s).
:param na... |
def long_description():
""" Collates project README and latest changes. """
changes = latest_changes()
changes[0] = "`Changes for v{}".format(changes[0][1:])
changes[1] = '-' * len(changes[0])
return "\n\n\n".join([
read_file('README.rst'),
'\n'.join(changes),
"`Full changelo... | Collates project README and latest changes. | Below is the the instruction that describes the task:
### Input:
Collates project README and latest changes.
### Response:
def long_description():
""" Collates project README and latest changes. """
changes = latest_changes()
changes[0] = "`Changes for v{}".format(changes[0][1:])
changes[1] = '-' *... |
def __set_basic_auth_string(self, username, password):
'''
Creates and sets the authentication string for (write-)accessing the
Handle Server. No return, the string is set as an attribute to
the client instance.
:param username: Username handle with index: index:prefix/s... | Creates and sets the authentication string for (write-)accessing the
Handle Server. No return, the string is set as an attribute to
the client instance.
:param username: Username handle with index: index:prefix/suffix.
:param password: The password contained in the index of the ... | Below is the the instruction that describes the task:
### Input:
Creates and sets the authentication string for (write-)accessing the
Handle Server. No return, the string is set as an attribute to
the client instance.
:param username: Username handle with index: index:prefix/suffix.... |
def magic_set(obj):
"""
Adds a function/method to an object. Uses the name of the first
argument as a hint about whether it is a method (``self``), class
method (``cls`` or ``klass``), or static method (anything else).
Works on both instances and classes.
>>> class color:
... def __init__(self, r, g, b):
... self.... | Adds a function/method to an object. Uses the name of the first
argument as a hint about whether it is a method (``self``), class
method (``cls`` or ``klass``), or static method (anything else).
Works on both instances and classes.
>>> class color:
... def __init__(self, r, g, b):
... self.r, self.g, self.b = r, g, b
... | Below is the the instruction that describes the task:
### Input:
Adds a function/method to an object. Uses the name of the first
argument as a hint about whether it is a method (``self``), class
method (``cls`` or ``klass``), or static method (anything else).
Works on both instances and classes.
>>> class color:
.... |
def get_ntp_peers(self):
"""Implementation of get_ntp_peers for IOS."""
ntp_stats = self.get_ntp_stats()
return {
ntp_peer.get("remote"): {}
for ntp_peer in ntp_stats
if ntp_peer.get("remote")
} | Implementation of get_ntp_peers for IOS. | Below is the the instruction that describes the task:
### Input:
Implementation of get_ntp_peers for IOS.
### Response:
def get_ntp_peers(self):
"""Implementation of get_ntp_peers for IOS."""
ntp_stats = self.get_ntp_stats()
return {
ntp_peer.get("remote"): {}
for n... |
def attendee(request, form, user_id=None):
''' Returns a list of all manifested attendees if no attendee is specified,
else displays the attendee manifest. '''
if user_id is None and form.cleaned_data["user"] is not None:
user_id = form.cleaned_data["user"]
if user_id is None:
return a... | Returns a list of all manifested attendees if no attendee is specified,
else displays the attendee manifest. | Below is the the instruction that describes the task:
### Input:
Returns a list of all manifested attendees if no attendee is specified,
else displays the attendee manifest.
### Response:
def attendee(request, form, user_id=None):
''' Returns a list of all manifested attendees if no attendee is specified,
... |
def _QueryHash(self, digest):
"""Queries the Viper Server for a specfic hash.
Args:
digest (str): hash to look up.
Returns:
dict[str, object]: JSON response or None on error.
"""
if not self._url:
self._url = '{0:s}://{1:s}:{2:d}/file/find'.format(
self._protocol, self.... | Queries the Viper Server for a specfic hash.
Args:
digest (str): hash to look up.
Returns:
dict[str, object]: JSON response or None on error. | Below is the the instruction that describes the task:
### Input:
Queries the Viper Server for a specfic hash.
Args:
digest (str): hash to look up.
Returns:
dict[str, object]: JSON response or None on error.
### Response:
def _QueryHash(self, digest):
"""Queries the Viper Server for a spec... |
def xAxisIsMajor(self):
'''
Returns True if the major axis is parallel to the X axis, boolean.
'''
return max(self.radius.x, self.radius.y) == self.radius.x | Returns True if the major axis is parallel to the X axis, boolean. | Below is the the instruction that describes the task:
### Input:
Returns True if the major axis is parallel to the X axis, boolean.
### Response:
def xAxisIsMajor(self):
'''
Returns True if the major axis is parallel to the X axis, boolean.
'''
return max(self.radius.x, self.radius.... |
def which(program, environ=None):
"""
Find out if an executable exists in the supplied PATH.
If so, the absolute path to the executable is returned.
If not, an exception is raised.
:type string
:param program: Executable to be checked for
:param dict
:param environ: Any additional ENV ... | Find out if an executable exists in the supplied PATH.
If so, the absolute path to the executable is returned.
If not, an exception is raised.
:type string
:param program: Executable to be checked for
:param dict
:param environ: Any additional ENV variables required, specifically PATH
:re... | Below is the the instruction that describes the task:
### Input:
Find out if an executable exists in the supplied PATH.
If so, the absolute path to the executable is returned.
If not, an exception is raised.
:type string
:param program: Executable to be checked for
:param dict
:param envir... |
def get_newest_app_version() -> Version:
"""
Download the version tag from remote.
:return: version from remote
:rtype: ~packaging.version.Version
"""
with urllib3.PoolManager(cert_reqs='CERT_REQUIRED', ca_certs=certifi.where()) as p_man:
pypi_json = p_man.urlopen('GET', static_data.PYP... | Download the version tag from remote.
:return: version from remote
:rtype: ~packaging.version.Version | Below is the the instruction that describes the task:
### Input:
Download the version tag from remote.
:return: version from remote
:rtype: ~packaging.version.Version
### Response:
def get_newest_app_version() -> Version:
"""
Download the version tag from remote.
:return: version from remote
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.