code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def list_postkantons_by_gemeente(self, gemeente):
'''
List all `postkantons` in a :class:`Gemeente`
:param gemeente: The :class:`Gemeente` for which the \
`potkantons` are wanted.
:rtype: A :class:`list` of :class:`Postkanton`
'''
try:
id = gemeen... | List all `postkantons` in a :class:`Gemeente`
:param gemeente: The :class:`Gemeente` for which the \
`potkantons` are wanted.
:rtype: A :class:`list` of :class:`Postkanton` | Below is the the instruction that describes the task:
### Input:
List all `postkantons` in a :class:`Gemeente`
:param gemeente: The :class:`Gemeente` for which the \
`potkantons` are wanted.
:rtype: A :class:`list` of :class:`Postkanton`
### Response:
def list_postkantons_by_gemeente(s... |
def strip(notebook):
"""Remove outputs from a notebook."""
for cell in notebook.cells:
if cell.cell_type == 'code':
cell.outputs = []
cell.execution_count = None | Remove outputs from a notebook. | Below is the the instruction that describes the task:
### Input:
Remove outputs from a notebook.
### Response:
def strip(notebook):
"""Remove outputs from a notebook."""
for cell in notebook.cells:
if cell.cell_type == 'code':
cell.outputs = []
cell.execution_count = None |
def _build(self, ids):
"""Lookup embeddings.
Looks up an embedding vector for each value in `ids`. All ids must be within
[0, vocab_size), else an `InvalidArgumentError` is raised at runtime.
Args:
ids: Tensor of dtype int64.
Returns:
Tensor of tf.shape(ids) + [embedding_dim] and dtyp... | Lookup embeddings.
Looks up an embedding vector for each value in `ids`. All ids must be within
[0, vocab_size), else an `InvalidArgumentError` is raised at runtime.
Args:
ids: Tensor of dtype int64.
Returns:
Tensor of tf.shape(ids) + [embedding_dim] and dtype float32. | Below is the the instruction that describes the task:
### Input:
Lookup embeddings.
Looks up an embedding vector for each value in `ids`. All ids must be within
[0, vocab_size), else an `InvalidArgumentError` is raised at runtime.
Args:
ids: Tensor of dtype int64.
Returns:
Tensor of t... |
def _trigger(self, obj, old, value, hint=None, setter=None):
''' Unconditionally send a change event notification for the property.
Args:
obj (HasProps)
The object the property is being set on.
old (obj) :
The previous value of the property
... | Unconditionally send a change event notification for the property.
Args:
obj (HasProps)
The object the property is being set on.
old (obj) :
The previous value of the property
new (obj) :
The new value of the property
... | Below is the the instruction that describes the task:
### Input:
Unconditionally send a change event notification for the property.
Args:
obj (HasProps)
The object the property is being set on.
old (obj) :
The previous value of the property
... |
def crop_indices(image, lowerind, upperind):
"""
Create a proper ANTsImage sub-image by indexing the image with indices.
This is similar to but different from array sub-setting in that
the resulting sub-image can be decropped back into its place without
having to store its original index location... | Create a proper ANTsImage sub-image by indexing the image with indices.
This is similar to but different from array sub-setting in that
the resulting sub-image can be decropped back into its place without
having to store its original index locations explicitly.
ANTsR function: `cropIndices`
... | Below is the the instruction that describes the task:
### Input:
Create a proper ANTsImage sub-image by indexing the image with indices.
This is similar to but different from array sub-setting in that
the resulting sub-image can be decropped back into its place without
having to store its original in... |
def list_all_orders(cls, **kwargs):
"""List Orders
Return a list of Orders
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.list_all_orders(async=True)
>>> result = thread.get()
... | List Orders
Return a list of Orders
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.list_all_orders(async=True)
>>> result = thread.get()
:param async bool
:param int page: pa... | Below is the the instruction that describes the task:
### Input:
List Orders
Return a list of Orders
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.list_all_orders(async=True)
>>> result ... |
def sign_execute_cancellation(cancellation_params, key_pair):
"""
Function to sign the parameters required to execute a cancellation request on the Switcheo Exchange.
Execution of this function is as follows::
sign_execute_cancellation(cancellation_params=signable_params, key_pair=key_pair)
Th... | Function to sign the parameters required to execute a cancellation request on the Switcheo Exchange.
Execution of this function is as follows::
sign_execute_cancellation(cancellation_params=signable_params, key_pair=key_pair)
The expected return result for this function is as follows::
{
... | Below is the the instruction that describes the task:
### Input:
Function to sign the parameters required to execute a cancellation request on the Switcheo Exchange.
Execution of this function is as follows::
sign_execute_cancellation(cancellation_params=signable_params, key_pair=key_pair)
The exp... |
def show_firmware_version_output_show_firmware_version_firmware_full_version(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
show_firmware_version = ET.Element("show_firmware_version")
config = show_firmware_version
output = ET.SubElement(show_fi... | Auto Generated Code | Below is the the instruction that describes the task:
### Input:
Auto Generated Code
### Response:
def show_firmware_version_output_show_firmware_version_firmware_full_version(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
show_firmware_version = ET.Elemen... |
def predict_cumulative_hazard_function(self, X, alpha=None):
"""Predict cumulative hazard function.
Only available if :meth:`fit` has been called with `fit_baseline_model = True`.
The cumulative hazard function for an individual
with feature vector :math:`x_\\alpha` is defined as
... | Predict cumulative hazard function.
Only available if :meth:`fit` has been called with `fit_baseline_model = True`.
The cumulative hazard function for an individual
with feature vector :math:`x_\\alpha` is defined as
.. math::
H(t \\mid x_\\alpha) = \\exp(x_\\alpha^\\top ... | Below is the the instruction that describes the task:
### Input:
Predict cumulative hazard function.
Only available if :meth:`fit` has been called with `fit_baseline_model = True`.
The cumulative hazard function for an individual
with feature vector :math:`x_\\alpha` is defined as
... |
def get_distance_scaling_term(self, C, rhyp):
"""
Returns the distance scaling term (equation 1)
"""
rval = rhyp + C['bh']
return C['b5'] * np.log(rval) + C['b6'] * rval | Returns the distance scaling term (equation 1) | Below is the the instruction that describes the task:
### Input:
Returns the distance scaling term (equation 1)
### Response:
def get_distance_scaling_term(self, C, rhyp):
"""
Returns the distance scaling term (equation 1)
"""
rval = rhyp + C['bh']
return C['b5'] * np.log(rv... |
def dock_json_get_plugin_conf(self, plugin_type, plugin_name):
"""
Return the configuration for a plugin.
Raises KeyError if there are no plugins of that type.
Raises IndexError if the named plugin is not listed.
"""
match = [x for x in self.dock_json[plugin_type] if x.g... | Return the configuration for a plugin.
Raises KeyError if there are no plugins of that type.
Raises IndexError if the named plugin is not listed. | Below is the the instruction that describes the task:
### Input:
Return the configuration for a plugin.
Raises KeyError if there are no plugins of that type.
Raises IndexError if the named plugin is not listed.
### Response:
def dock_json_get_plugin_conf(self, plugin_type, plugin_name):
""... |
def findPrev( self ):
"""
Looks for the previous occurance of the current search text.
"""
text = self.uiFindTXT.text()
view = self.currentWebView()
options = QWebPage.FindWrapsAroundDocument
options |= QWebPage.FindBackward
if... | Looks for the previous occurance of the current search text. | Below is the the instruction that describes the task:
### Input:
Looks for the previous occurance of the current search text.
### Response:
def findPrev( self ):
"""
Looks for the previous occurance of the current search text.
"""
text = self.uiFindTXT.text()
view = sel... |
def make_driver(device_name, **kwargs):
"""Creates an instance of CAN driver.
The right driver class will be selected automatically based on the device_name.
:param device_name: This parameter is used to select driver class. E.g. "/dev/ttyACM0", "COM9", "can0".
:param kwargs: Passed directly to the cons... | Creates an instance of CAN driver.
The right driver class will be selected automatically based on the device_name.
:param device_name: This parameter is used to select driver class. E.g. "/dev/ttyACM0", "COM9", "can0".
:param kwargs: Passed directly to the constructor. | Below is the the instruction that describes the task:
### Input:
Creates an instance of CAN driver.
The right driver class will be selected automatically based on the device_name.
:param device_name: This parameter is used to select driver class. E.g. "/dev/ttyACM0", "COM9", "can0".
:param kwargs: Passe... |
def submit(self, buf, *, checked=False):
"""Submit reassembled payload.
Positional arguments:
* buf -- dict, buffer dict of reassembled packets
Keyword arguments:
* bufid -- tuple, buffer identifier
Returns:
* list -- reassembled packets
""... | Submit reassembled payload.
Positional arguments:
* buf -- dict, buffer dict of reassembled packets
Keyword arguments:
* bufid -- tuple, buffer identifier
Returns:
* list -- reassembled packets | Below is the the instruction that describes the task:
### Input:
Submit reassembled payload.
Positional arguments:
* buf -- dict, buffer dict of reassembled packets
Keyword arguments:
* bufid -- tuple, buffer identifier
Returns:
* list -- reassembled pa... |
def depth_soil_specific_heat(self, value=None):
"""Corresponds to IDD Field `depth_soil_specific_heat`
Args:
value (float): value for IDD Field `depth_soil_specific_heat`
Unit: J/kg-K,
if `value` is None it will not be checked against the
spec... | Corresponds to IDD Field `depth_soil_specific_heat`
Args:
value (float): value for IDD Field `depth_soil_specific_heat`
Unit: J/kg-K,
if `value` is None it will not be checked against the
specification and is assumed to be a missing value
Rai... | Below is the the instruction that describes the task:
### Input:
Corresponds to IDD Field `depth_soil_specific_heat`
Args:
value (float): value for IDD Field `depth_soil_specific_heat`
Unit: J/kg-K,
if `value` is None it will not be checked against the
... |
def _get_file_size(self):
"""
Fetches file size by reading the Content-Length header
for the resource.
:return: File size.
"""
file_size = retry(self._retry_count)(_get_content_length)(
self._session, self.url, self._timeout
)
file_size = int(f... | Fetches file size by reading the Content-Length header
for the resource.
:return: File size. | Below is the the instruction that describes the task:
### Input:
Fetches file size by reading the Content-Length header
for the resource.
:return: File size.
### Response:
def _get_file_size(self):
"""
Fetches file size by reading the Content-Length header
for the resource.
... |
def middleware(self, middleware_or_request):
"""
Decorate and register middleware to be called before a request.
Can either be called as *@app.middleware* or
*@app.middleware('request')*
:param: middleware_or_request: Optional parameter to use for
identifying which t... | Decorate and register middleware to be called before a request.
Can either be called as *@app.middleware* or
*@app.middleware('request')*
:param: middleware_or_request: Optional parameter to use for
identifying which type of middleware is being registered. | Below is the the instruction that describes the task:
### Input:
Decorate and register middleware to be called before a request.
Can either be called as *@app.middleware* or
*@app.middleware('request')*
:param: middleware_or_request: Optional parameter to use for
identifying whi... |
def usage(self, node_id=None, metric=None, params=None):
"""
The cluster nodes usage API allows to retrieve information on the usage
of features for each node.
`<http://www.elastic.co/guide/en/elasticsearch/reference/master/cluster-nodes-usage.html>`_
:arg node_id: A comma-separ... | The cluster nodes usage API allows to retrieve information on the usage
of features for each node.
`<http://www.elastic.co/guide/en/elasticsearch/reference/master/cluster-nodes-usage.html>`_
:arg node_id: A comma-separated list of node IDs or names to limit the
returned information;... | Below is the the instruction that describes the task:
### Input:
The cluster nodes usage API allows to retrieve information on the usage
of features for each node.
`<http://www.elastic.co/guide/en/elasticsearch/reference/master/cluster-nodes-usage.html>`_
:arg node_id: A comma-separated lis... |
def dijkstra(G, start, weight='weight'):
"""
Compute shortest path length between satrt
and all other reachable nodes for a weight graph.
return -> ({vertex: weight form start, }, {vertex: predeseccor, })
"""
if start not in G.vertices:
raise GraphInsertError("Vertex %s doesn't ex... | Compute shortest path length between satrt
and all other reachable nodes for a weight graph.
return -> ({vertex: weight form start, }, {vertex: predeseccor, }) | Below is the the instruction that describes the task:
### Input:
Compute shortest path length between satrt
and all other reachable nodes for a weight graph.
return -> ({vertex: weight form start, }, {vertex: predeseccor, })
### Response:
def dijkstra(G, start, weight='weight'):
"""
Compute sho... |
def quantile(self, q=0.5, interpolation='linear'):
"""
Return group values at the given quantile, a la numpy.percentile.
Parameters
----------
q : float or array-like, default 0.5 (50% quantile)
Value(s) between 0 and 1 providing the quantile(s) to compute.
i... | Return group values at the given quantile, a la numpy.percentile.
Parameters
----------
q : float or array-like, default 0.5 (50% quantile)
Value(s) between 0 and 1 providing the quantile(s) to compute.
interpolation : {'linear', 'lower', 'higher', 'midpoint', 'nearest'}
... | Below is the the instruction that describes the task:
### Input:
Return group values at the given quantile, a la numpy.percentile.
Parameters
----------
q : float or array-like, default 0.5 (50% quantile)
Value(s) between 0 and 1 providing the quantile(s) to compute.
int... |
def build_downstream(self, process_descriptions, task, all_tasks,
task_pipeline,
count_forks, total_tasks, forks):
"""Builds the downstream pipeline of the current process
Checks for the downstream processes to the current process and
adds them ... | Builds the downstream pipeline of the current process
Checks for the downstream processes to the current process and
adds them to the current pipeline fragment.
Parameters
----------
process_descriptions : dict
Information of processes input, output and if is forkab... | Below is the the instruction that describes the task:
### Input:
Builds the downstream pipeline of the current process
Checks for the downstream processes to the current process and
adds them to the current pipeline fragment.
Parameters
----------
process_descriptions : dic... |
def opponent_rank(self):
"""
Returns a ``string`` of the opponent's rank when the game was played
and None if the team was unranked.
"""
rank = re.findall(r'\d+', self._opponent_name)
if len(rank) > 0:
return int(rank[0])
return None | Returns a ``string`` of the opponent's rank when the game was played
and None if the team was unranked. | Below is the the instruction that describes the task:
### Input:
Returns a ``string`` of the opponent's rank when the game was played
and None if the team was unranked.
### Response:
def opponent_rank(self):
"""
Returns a ``string`` of the opponent's rank when the game was played
an... |
def fnames(self, names):
"""Ensure constant size of fnames"""
names = list(names[:len(self._fnames)])
self._fnames = names + self._fnames[len(names):] | Ensure constant size of fnames | Below is the the instruction that describes the task:
### Input:
Ensure constant size of fnames
### Response:
def fnames(self, names):
"""Ensure constant size of fnames"""
names = list(names[:len(self._fnames)])
self._fnames = names + self._fnames[len(names):] |
def dstat(inarr, taxdict, mindict=1, nboots=1000, name=0):
""" private function to perform a single D-stat test"""
#if isinstance(inarr, str):
# with open(inarr, 'r') as infile:
# inarr = infile.read().strip().split("|\n")
# ## get data as an array from loci file
# ## if loci-list th... | private function to perform a single D-stat test | Below is the the instruction that describes the task:
### Input:
private function to perform a single D-stat test
### Response:
def dstat(inarr, taxdict, mindict=1, nboots=1000, name=0):
""" private function to perform a single D-stat test"""
#if isinstance(inarr, str):
# with open(inarr, 'r') as i... |
def fold(
fun: Callable, state: Any, xs: Iterable):
"""
Traverse an iterable object while performing stateful computations
with the elements. It returns a :py:class:`PromisedObject` containing
the result of the stateful computations.
For a general definition of folding see:
https://en.w... | Traverse an iterable object while performing stateful computations
with the elements. It returns a :py:class:`PromisedObject` containing
the result of the stateful computations.
For a general definition of folding see:
https://en.wikipedia.org/wiki/Fold_(higher-order_function)
:param fun: stateful... | Below is the the instruction that describes the task:
### Input:
Traverse an iterable object while performing stateful computations
with the elements. It returns a :py:class:`PromisedObject` containing
the result of the stateful computations.
For a general definition of folding see:
https://en.wiki... |
def get_jid(jid):
'''
Return the information returned when the specified job id was executed
'''
with _get_serv(ret=None, commit=True) as cur:
sql = '''SELECT id, full_ret FROM salt_returns
WHERE jid = %s'''
cur.execute(sql, (jid,))
data = cur.fetchall()
... | Return the information returned when the specified job id was executed | Below is the the instruction that describes the task:
### Input:
Return the information returned when the specified job id was executed
### Response:
def get_jid(jid):
'''
Return the information returned when the specified job id was executed
'''
with _get_serv(ret=None, commit=True) as cur:
... |
def to_file(self, filename):
"""
Saves object to a file in YAML format.
Args:
filename (str): Filename.
"""
d = {"mass_info": self.mass_info,
"nonbond_coeffs": self.nonbond_coeffs,
"topo_coeffs": self.topo_coeffs}
yaml = YAML(typ="s... | Saves object to a file in YAML format.
Args:
filename (str): Filename. | Below is the the instruction that describes the task:
### Input:
Saves object to a file in YAML format.
Args:
filename (str): Filename.
### Response:
def to_file(self, filename):
"""
Saves object to a file in YAML format.
Args:
filename (str): Filename.
... |
def CompleteTransaction(self, dumpXml=None):
"""
Completes a transaction.
This method completes a transaction by sending the final configuration (modification queries stored in configMap) to UCS and
returns the result.
"""
from Ucs import ConfigMap, Pair
from UcsBase import Manage... | Completes a transaction.
This method completes a transaction by sending the final configuration (modification queries stored in configMap) to UCS and
returns the result. | Below is the the instruction that describes the task:
### Input:
Completes a transaction.
This method completes a transaction by sending the final configuration (modification queries stored in configMap) to UCS and
returns the result.
### Response:
def CompleteTransaction(self, dumpXml=None):
""... |
def user(self, id):
"""
Retrieve public information about a user.
Args:
id (str): user identifier to lookup
Returns:
SkypeUser: resulting user object
"""
json = self.skype.conn("POST", "{0}/batch/profiles".format(SkypeConnection.API_PROFILE),
... | Retrieve public information about a user.
Args:
id (str): user identifier to lookup
Returns:
SkypeUser: resulting user object | Below is the the instruction that describes the task:
### Input:
Retrieve public information about a user.
Args:
id (str): user identifier to lookup
Returns:
SkypeUser: resulting user object
### Response:
def user(self, id):
"""
Retrieve public information ... |
def _send_ffd(self, pid, aplx_data, address):
"""Send flood-fill data packets."""
block = 0
pos = 0
aplx_size = len(aplx_data)
while pos < aplx_size:
# Get the next block of data, send and progress the block
# counter and the address
data = ap... | Send flood-fill data packets. | Below is the the instruction that describes the task:
### Input:
Send flood-fill data packets.
### Response:
def _send_ffd(self, pid, aplx_data, address):
"""Send flood-fill data packets."""
block = 0
pos = 0
aplx_size = len(aplx_data)
while pos < aplx_size:
# G... |
def close(self):
"""
Close all pooled connections and disable the pool.
"""
# Disable access to the pool
old_pool, self.pool = self.pool, None
try:
while True:
conn = old_pool.get(block=False)
if conn:
conn.... | Close all pooled connections and disable the pool. | Below is the the instruction that describes the task:
### Input:
Close all pooled connections and disable the pool.
### Response:
def close(self):
"""
Close all pooled connections and disable the pool.
"""
# Disable access to the pool
old_pool, self.pool = self.pool, None
... |
def setup_ui(self, ):
"""Create all necessary ui elements for the tool
:returns: None
:rtype: None
:raises: None
"""
log.debug("Setting up the ui")
self.setup_prjs_page()
self.setup_prj_page()
self.setup_seq_page()
self.setup_shot_page()
... | Create all necessary ui elements for the tool
:returns: None
:rtype: None
:raises: None | Below is the the instruction that describes the task:
### Input:
Create all necessary ui elements for the tool
:returns: None
:rtype: None
:raises: None
### Response:
def setup_ui(self, ):
"""Create all necessary ui elements for the tool
:returns: None
:rtype: None... |
def rolldim(P, n=1):
"""
Roll the axes.
Args:
P (Poly) : Input polynomial.
n (int) : The axis that after rolling becomes the 0th axis.
Returns:
(Poly) : Polynomial with new axis configuration.
Examples:
>>> x,y,z = variable(3)
>>> P = x*x*x + y*y + z
... | Roll the axes.
Args:
P (Poly) : Input polynomial.
n (int) : The axis that after rolling becomes the 0th axis.
Returns:
(Poly) : Polynomial with new axis configuration.
Examples:
>>> x,y,z = variable(3)
>>> P = x*x*x + y*y + z
>>> print(P)
q0^3+q1^2+... | Below is the the instruction that describes the task:
### Input:
Roll the axes.
Args:
P (Poly) : Input polynomial.
n (int) : The axis that after rolling becomes the 0th axis.
Returns:
(Poly) : Polynomial with new axis configuration.
Examples:
>>> x,y,z = variable(3)
... |
def search(self, terms):
"""
Seraches the documents for the inputed terms.
:param terms
:return [{'url': <str>, 'title': <str>', 'strength': <int>}]
"""
# load the search information
if not self._searchurls:
base = se... | Seraches the documents for the inputed terms.
:param terms
:return [{'url': <str>, 'title': <str>', 'strength': <int>}] | Below is the the instruction that describes the task:
### Input:
Seraches the documents for the inputed terms.
:param terms
:return [{'url': <str>, 'title': <str>', 'strength': <int>}]
### Response:
def search(self, terms):
"""
Seraches the documents f... |
def remove_multizone(self, group_uuid):
""" Stop managing a group """
group_uuid = str(group_uuid)
group = self._groups.pop(group_uuid, None)
# Inform all group members that they are no longer members
if group is not None:
group['listener']._mz.reset_members() # noqa... | Stop managing a group | Below is the the instruction that describes the task:
### Input:
Stop managing a group
### Response:
def remove_multizone(self, group_uuid):
""" Stop managing a group """
group_uuid = str(group_uuid)
group = self._groups.pop(group_uuid, None)
# Inform all group members that they are... |
def safe_call(func, *args, **kwargs):
"""
Call `func(*args, **kwargs)` but NEVER raise an exception.
Useful in situations such as inside exception handlers where calls to
`logging.error` try to send email, but the SMTP server isn't always
availalbe and you don't want your exception handler blowing ... | Call `func(*args, **kwargs)` but NEVER raise an exception.
Useful in situations such as inside exception handlers where calls to
`logging.error` try to send email, but the SMTP server isn't always
availalbe and you don't want your exception handler blowing up. | Below is the the instruction that describes the task:
### Input:
Call `func(*args, **kwargs)` but NEVER raise an exception.
Useful in situations such as inside exception handlers where calls to
`logging.error` try to send email, but the SMTP server isn't always
availalbe and you don't want your excepti... |
def detokenize(s):
""" Detokenize a string by removing spaces before punctuation."""
print(s)
s = re.sub("\s+([;:,\.\?!])", "\\1", s)
s = re.sub("\s+(n't)", "\\1", s)
return s | Detokenize a string by removing spaces before punctuation. | Below is the the instruction that describes the task:
### Input:
Detokenize a string by removing spaces before punctuation.
### Response:
def detokenize(s):
""" Detokenize a string by removing spaces before punctuation."""
print(s)
s = re.sub("\s+([;:,\.\?!])", "\\1", s)
s = re.sub("\s+(n't)", "\\1... |
def apply_fit_filters(self, choosers, alternatives):
"""
Filter `choosers` and `alternatives` for fitting.
Parameters
----------
choosers : pandas.DataFrame
Table describing the agents making choices, e.g. households.
alternatives : pandas.DataFrame
... | Filter `choosers` and `alternatives` for fitting.
Parameters
----------
choosers : pandas.DataFrame
Table describing the agents making choices, e.g. households.
alternatives : pandas.DataFrame
Table describing the things from which agents are choosing,
... | Below is the the instruction that describes the task:
### Input:
Filter `choosers` and `alternatives` for fitting.
Parameters
----------
choosers : pandas.DataFrame
Table describing the agents making choices, e.g. households.
alternatives : pandas.DataFrame
T... |
def startLogin():
"""
If we are not logged in, this generates the redirect URL to the OIDC
provider and returns the redirect response
:return: A redirect response to the OIDC provider
"""
flask.session["state"] = oic.oauth2.rndstr(SECRET_KEY_LENGTH)
flask.session["nonce"] = oic.oauth2.rndstr... | If we are not logged in, this generates the redirect URL to the OIDC
provider and returns the redirect response
:return: A redirect response to the OIDC provider | Below is the the instruction that describes the task:
### Input:
If we are not logged in, this generates the redirect URL to the OIDC
provider and returns the redirect response
:return: A redirect response to the OIDC provider
### Response:
def startLogin():
"""
If we are not logged in, this genera... |
def get_messages(self, new=True):
"""
Return all messages sent to this user, formatted as a notification.
:param new: False for all notifications, True for only non-viewed
notifications.
"""
url = (self._imgur._base_url + "/3/account/{0}/notifications/"
... | Return all messages sent to this user, formatted as a notification.
:param new: False for all notifications, True for only non-viewed
notifications. | Below is the the instruction that describes the task:
### Input:
Return all messages sent to this user, formatted as a notification.
:param new: False for all notifications, True for only non-viewed
notifications.
### Response:
def get_messages(self, new=True):
"""
Return all m... |
def _format_executable(lines, element, spacer=""):
"""Performs formatting specific to a Subroutine or Function code
element for relevant docstrings.
"""
rlines = []
rlines.append(element.signature)
_format_summary(rlines, element)
rlines.append("")
rlines.append("PARAMETERS")
for p ... | Performs formatting specific to a Subroutine or Function code
element for relevant docstrings. | Below is the the instruction that describes the task:
### Input:
Performs formatting specific to a Subroutine or Function code
element for relevant docstrings.
### Response:
def _format_executable(lines, element, spacer=""):
"""Performs formatting specific to a Subroutine or Function code
element for r... |
def wait_for_request(pbclient, request_id,
timeout=0, initial_wait=5, scaleup=10):
'''
Waits for a request to finish until timeout.
timeout==0 is interpreted as infinite wait time.
Returns a tuple (return code, request status, message) where return code
0 : request successful
... | Waits for a request to finish until timeout.
timeout==0 is interpreted as infinite wait time.
Returns a tuple (return code, request status, message) where return code
0 : request successful
1 : request failed
-1 : timeout exceeded
The wait_period is increased every scaleup steps to adjust for ... | Below is the the instruction that describes the task:
### Input:
Waits for a request to finish until timeout.
timeout==0 is interpreted as infinite wait time.
Returns a tuple (return code, request status, message) where return code
0 : request successful
1 : request failed
-1 : timeout exceede... |
def merge_translations(localization_bundle_path):
""" Merges the new translation with the old one.
The translated files are saved as '.translated' file, and are merged with old translated file.
Args:
localization_bundle_path (str): The path to the localization bundle.
"""
logging.info("Me... | Merges the new translation with the old one.
The translated files are saved as '.translated' file, and are merged with old translated file.
Args:
localization_bundle_path (str): The path to the localization bundle. | Below is the the instruction that describes the task:
### Input:
Merges the new translation with the old one.
The translated files are saved as '.translated' file, and are merged with old translated file.
Args:
localization_bundle_path (str): The path to the localization bundle.
### Response:
def... |
def verification_start(
self,
client,
mode=None,
verification_speed=None,
row_doubling="off",
phone_number=None,
):
"""
Start a verification. Uses POST to /verifications interface.
:Args:
* *client*: (str) Client's Name
... | Start a verification. Uses POST to /verifications interface.
:Args:
* *client*: (str) Client's Name
* *mode*: (str) Verification Mode. Allowed values: "audiopin", "audiopass"
* *verification_speed*: (int) Allowed values: 0, 25, 50, 75, 100
* *row_doubling*: (str... | Below is the the instruction that describes the task:
### Input:
Start a verification. Uses POST to /verifications interface.
:Args:
* *client*: (str) Client's Name
* *mode*: (str) Verification Mode. Allowed values: "audiopin", "audiopass"
* *verification_speed*: (int) ... |
def capture(self, *args, **kwargs):
"""
Takes the same arguments as the super function in :py:class:`Client`
and extracts the keyword argument callback which will be called on
asynchronous sending of the request
:return: a 32-length string identifying this event
"""
... | Takes the same arguments as the super function in :py:class:`Client`
and extracts the keyword argument callback which will be called on
asynchronous sending of the request
:return: a 32-length string identifying this event | Below is the the instruction that describes the task:
### Input:
Takes the same arguments as the super function in :py:class:`Client`
and extracts the keyword argument callback which will be called on
asynchronous sending of the request
:return: a 32-length string identifying this event
###... |
def read_file(self, id_file):
"""
Read and parse id data from id_file which must be an iterable
yielding Unicode strings formatted as in '/etc/subuid' or
'/etc/subgid'.
"""
lineno = 0
for line in id_file:
lineno += 1
id_data = line.split('... | Read and parse id data from id_file which must be an iterable
yielding Unicode strings formatted as in '/etc/subuid' or
'/etc/subgid'. | Below is the the instruction that describes the task:
### Input:
Read and parse id data from id_file which must be an iterable
yielding Unicode strings formatted as in '/etc/subuid' or
'/etc/subgid'.
### Response:
def read_file(self, id_file):
"""
Read and parse id data from id_file... |
def _assemble_and_send_request(self):
"""
Fires off the Fedex request.
@warning: NEVER CALL THIS METHOD DIRECTLY. CALL send_request(),
WHICH RESIDES ON FedexBaseService AND IS INHERITED.
"""
# We get an exception like this when specifying an IntegratorId:
... | Fires off the Fedex request.
@warning: NEVER CALL THIS METHOD DIRECTLY. CALL send_request(),
WHICH RESIDES ON FedexBaseService AND IS INHERITED. | Below is the the instruction that describes the task:
### Input:
Fires off the Fedex request.
@warning: NEVER CALL THIS METHOD DIRECTLY. CALL send_request(),
WHICH RESIDES ON FedexBaseService AND IS INHERITED.
### Response:
def _assemble_and_send_request(self):
"""
Fir... |
def chop_sequence(sequence, limit_length):
"""Input sequence is divided on smaller non-overlapping sequences with set length. """
return [sequence[i:i + limit_length] for i in range(0, len(sequence), limit_length)] | Input sequence is divided on smaller non-overlapping sequences with set length. | Below is the the instruction that describes the task:
### Input:
Input sequence is divided on smaller non-overlapping sequences with set length.
### Response:
def chop_sequence(sequence, limit_length):
"""Input sequence is divided on smaller non-overlapping sequences with set length. """
return [s... |
def sphericalToCartesian(r, phi, theta):
"""
Convert spherical to Cartesian coordinates. The input can be scalars or 1-dimensional numpy arrays.
Note that the angle coordinates follow the astronomical convention of using elevation (declination,
latitude) rather than its complement (pi/2-elevation), where the la... | Convert spherical to Cartesian coordinates. The input can be scalars or 1-dimensional numpy arrays.
Note that the angle coordinates follow the astronomical convention of using elevation (declination,
latitude) rather than its complement (pi/2-elevation), where the latter is commonly used in the
mathematical treat... | Below is the the instruction that describes the task:
### Input:
Convert spherical to Cartesian coordinates. The input can be scalars or 1-dimensional numpy arrays.
Note that the angle coordinates follow the astronomical convention of using elevation (declination,
latitude) rather than its complement (pi/2-elev... |
def get_file(self,pattern):
'''
returns a flag array of the data loaded from a given file pattern
:parameter pattern: pattern to match in the file list.
'''
flag=[fnmatch.fnmatch(l,pattern) for l in self.filelist]
id=self.fid_list.compress(flag)
... | returns a flag array of the data loaded from a given file pattern
:parameter pattern: pattern to match in the file list. | Below is the the instruction that describes the task:
### Input:
returns a flag array of the data loaded from a given file pattern
:parameter pattern: pattern to match in the file list.
### Response:
def get_file(self,pattern):
'''
returns a flag array of the data loaded from a... |
def query(self):
"""A QueryDict object holding the query parameters (QUERY_STRING)."""
if self._query is None:
query_string = self.environ.get('QUERY_STRING')
self._query = QueryDict([
(k.decode('utf-8'), v.decode('utf-8'))
for k, v in urlparse.par... | A QueryDict object holding the query parameters (QUERY_STRING). | Below is the the instruction that describes the task:
### Input:
A QueryDict object holding the query parameters (QUERY_STRING).
### Response:
def query(self):
"""A QueryDict object holding the query parameters (QUERY_STRING)."""
if self._query is None:
query_string = self.environ.get('... |
def get_arguments(self):
"""
Extracts the specific arguments of this CLI
"""
ApiCli.get_arguments(self)
if self.args.pluginName is not None:
self.pluginName = self.args.pluginName
self.path = "v1/plugins/{0}/components".format(self.pluginName) | Extracts the specific arguments of this CLI | Below is the the instruction that describes the task:
### Input:
Extracts the specific arguments of this CLI
### Response:
def get_arguments(self):
"""
Extracts the specific arguments of this CLI
"""
ApiCli.get_arguments(self)
if self.args.pluginName is not None:
... |
def open(name):
""""
name: str or file or file-like or pathlib.Path
File to be opened
"""
with builtins.open(name, mode='r') as fd:
data = json.load(fd)
return loads(data) | name: str or file or file-like or pathlib.Path
File to be opened | Below is the the instruction that describes the task:
### Input:
name: str or file or file-like or pathlib.Path
File to be opened
### Response:
def open(name):
""""
name: str or file or file-like or pathlib.Path
File to be opened
"""
with builtins.open(name, mode='r') as fd:
... |
def register_secret_batch(
self,
secrets: List[Secret],
):
"""Register a batch of secrets. Check if they are already registered at
the given block identifier."""
secrets_to_register = list()
secrethashes_to_register = list()
secrethashes_not_sent = lis... | Register a batch of secrets. Check if they are already registered at
the given block identifier. | Below is the the instruction that describes the task:
### Input:
Register a batch of secrets. Check if they are already registered at
the given block identifier.
### Response:
def register_secret_batch(
self,
secrets: List[Secret],
):
"""Register a batch of secrets. Chec... |
def _centroids(self, verts):
r'''
Function to calculate the centroid as the mean of a set of vertices.
Used for pore and throat.
'''
value = sp.zeros([len(verts), 3])
for i, i_verts in enumerate(verts):
value[i] = np.mean(i_verts, axis=0)
return value | r'''
Function to calculate the centroid as the mean of a set of vertices.
Used for pore and throat. | Below is the the instruction that describes the task:
### Input:
r'''
Function to calculate the centroid as the mean of a set of vertices.
Used for pore and throat.
### Response:
def _centroids(self, verts):
r'''
Function to calculate the centroid as the mean of a set of vertices.
... |
def _get_parameter_conversion_entry(parameter_config):
"""Get information needed to convert the given parameter to its API type.
Args:
parameter_config: The dictionary containing information specific to the
parameter in question. This is retrieved from request.parameters in the
method config.
Re... | Get information needed to convert the given parameter to its API type.
Args:
parameter_config: The dictionary containing information specific to the
parameter in question. This is retrieved from request.parameters in the
method config.
Returns:
The entry from _PARAM_CONVERSION_MAP with functio... | Below is the the instruction that describes the task:
### Input:
Get information needed to convert the given parameter to its API type.
Args:
parameter_config: The dictionary containing information specific to the
parameter in question. This is retrieved from request.parameters in the
method conf... |
def _mergeDictionaries(*args):
''' merge dictionaries of dictionaries recursively, with elements from
dictionaries earlier in the argument sequence taking precedence
'''
# to support merging of OrderedDicts, copy the result type from the first
# argument:
result = type(args[0])()
for k, ... | merge dictionaries of dictionaries recursively, with elements from
dictionaries earlier in the argument sequence taking precedence | Below is the the instruction that describes the task:
### Input:
merge dictionaries of dictionaries recursively, with elements from
dictionaries earlier in the argument sequence taking precedence
### Response:
def _mergeDictionaries(*args):
''' merge dictionaries of dictionaries recursively, with eleme... |
def __start_waiting_for_events(self):
'''
This waits until the whole chain of callback methods triggered by
"trigger_connection_to_rabbit_etc()" has finished, and then starts
waiting for publications.
This is done by starting the ioloop.
Note: In the pika usage example,... | This waits until the whole chain of callback methods triggered by
"trigger_connection_to_rabbit_etc()" has finished, and then starts
waiting for publications.
This is done by starting the ioloop.
Note: In the pika usage example, these things are both called inside the run()
met... | Below is the the instruction that describes the task:
### Input:
This waits until the whole chain of callback methods triggered by
"trigger_connection_to_rabbit_etc()" has finished, and then starts
waiting for publications.
This is done by starting the ioloop.
Note: In the pika usa... |
def link(src, path):
'''
.. versionadded:: 2014.1.0
Create a hard link to a file
CLI Example:
.. code-block:: bash
salt '*' file.link /path/to/file /path/to/link
'''
src = os.path.expanduser(src)
if not os.path.isabs(src):
raise SaltInvocationError('File path must be... | .. versionadded:: 2014.1.0
Create a hard link to a file
CLI Example:
.. code-block:: bash
salt '*' file.link /path/to/file /path/to/link | Below is the the instruction that describes the task:
### Input:
.. versionadded:: 2014.1.0
Create a hard link to a file
CLI Example:
.. code-block:: bash
salt '*' file.link /path/to/file /path/to/link
### Response:
def link(src, path):
'''
.. versionadded:: 2014.1.0
Create a h... |
def show_taghistory():
"""Show history of all known repo/tags for image"""
if not nav:
sys.exit(1)
ecode = 0
try:
result = nav.get_taghistory()
if result:
anchore_utils.print_result(config, result)
except:
anchore_print_err("operation failed")
... | Show history of all known repo/tags for image | Below is the the instruction that describes the task:
### Input:
Show history of all known repo/tags for image
### Response:
def show_taghistory():
"""Show history of all known repo/tags for image"""
if not nav:
sys.exit(1)
ecode = 0
try:
result = nav.get_taghistory()
if ... |
def complexes(self, strands, max_size, ordered=False, pairs=False,
mfe=False, cutoff=0.001, degenerate=False, temp=37.0,
pseudo=False, material=None, dangles='some', sodium=1.0,
magnesium=0.0):
'''
:param strands: Strands on which to run energy. Stra... | :param strands: Strands on which to run energy. Strands must be either
coral.DNA or coral.RNA).
:type strands: list of coral.DNA or coral.RNA
:param max_size: Maximum complex size to consider (maximum number of
strand species in complex).
:type max... | Below is the the instruction that describes the task:
### Input:
:param strands: Strands on which to run energy. Strands must be either
coral.DNA or coral.RNA).
:type strands: list of coral.DNA or coral.RNA
:param max_size: Maximum complex size to consider (maximum number of
... |
def asJSON(self):
""" returns a geometry as JSON """
value = self._json
if value is None:
value = json.dumps(self.asDictionary,
default=_date_handler)
self._json = value
return self._json | returns a geometry as JSON | Below is the the instruction that describes the task:
### Input:
returns a geometry as JSON
### Response:
def asJSON(self):
""" returns a geometry as JSON """
value = self._json
if value is None:
value = json.dumps(self.asDictionary,
default=_date_... |
def update_iptables(self):
"""Update iptables based on information in the rule_info."""
# Read the iptables
iptables_cmds = ['iptables-save', '-c']
all_rules = dsl.execute(iptables_cmds, root_helper=self._root_helper,
log_output=False)
# For each... | Update iptables based on information in the rule_info. | Below is the the instruction that describes the task:
### Input:
Update iptables based on information in the rule_info.
### Response:
def update_iptables(self):
"""Update iptables based on information in the rule_info."""
# Read the iptables
iptables_cmds = ['iptables-save', '-c']
... |
def render_as_text(self, limit=None):
"""Return a string with the traceback."""
lines = traceback.format_exception(self.exc_type, self.exc_value,
self.frames[0], limit=limit)
return ''.join(lines).rstrip() | Return a string with the traceback. | Below is the the instruction that describes the task:
### Input:
Return a string with the traceback.
### Response:
def render_as_text(self, limit=None):
"""Return a string with the traceback."""
lines = traceback.format_exception(self.exc_type, self.exc_value,
... |
def get_rst_spans(rst_graph):
"""
Returns a list of 5-tuples describing each RST span (i.e. the nucleus
or satellite of a relation) in the document. (This function is meant for
people who prefer to work with R / DataFrames / CSV files instead of
graphs.)
Parameters
----------
docgraph :... | Returns a list of 5-tuples describing each RST span (i.e. the nucleus
or satellite of a relation) in the document. (This function is meant for
people who prefer to work with R / DataFrames / CSV files instead of
graphs.)
Parameters
----------
docgraph : DiscourseDocumentGraph
a document... | Below is the the instruction that describes the task:
### Input:
Returns a list of 5-tuples describing each RST span (i.e. the nucleus
or satellite of a relation) in the document. (This function is meant for
people who prefer to work with R / DataFrames / CSV files instead of
graphs.)
Parameters
... |
def reordi(iorder, ndim, array):
"""
Re-order the elements of an integer array according to
a given order vector.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/reordi_c.html
:param iorder: Order vector to be used to re-order array.
:type iorder: Array of ints
:param ndim: Dimensi... | Re-order the elements of an integer array according to
a given order vector.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/reordi_c.html
:param iorder: Order vector to be used to re-order array.
:type iorder: Array of ints
:param ndim: Dimension of array.
:type ndim: int
:param a... | Below is the the instruction that describes the task:
### Input:
Re-order the elements of an integer array according to
a given order vector.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/reordi_c.html
:param iorder: Order vector to be used to re-order array.
:type iorder: Array of ints
... |
def is_foreign_key(line):
"""
:param line: a line from the table definition
:return: true if the line appears to be a foreign key definition
"""
arrow_position = line.find('->')
return arrow_position >= 0 and not any(c in line[:arrow_position] for c in '"#\'') | :param line: a line from the table definition
:return: true if the line appears to be a foreign key definition | Below is the the instruction that describes the task:
### Input:
:param line: a line from the table definition
:return: true if the line appears to be a foreign key definition
### Response:
def is_foreign_key(line):
"""
:param line: a line from the table definition
:return: true if the line appears... |
def include_all_subfiles(*args):
"""Slurps up all files in a directory (non recursive) for data_files section
Note:
Not recursive, only includes flat files
Returns:
list: list of all non-directories in a file
"""
file_list = []
for path_included in args:
local_path = p... | Slurps up all files in a directory (non recursive) for data_files section
Note:
Not recursive, only includes flat files
Returns:
list: list of all non-directories in a file | Below is the the instruction that describes the task:
### Input:
Slurps up all files in a directory (non recursive) for data_files section
Note:
Not recursive, only includes flat files
Returns:
list: list of all non-directories in a file
### Response:
def include_all_subfiles(*args):
... |
def _normalized(self, data):
"""
Does a normalization of sorts on image type data so that values
that should be integers are converted from strings
"""
int_keys = ('frames', 'width', 'height', 'size')
for key in int_keys:
if key not in data:
c... | Does a normalization of sorts on image type data so that values
that should be integers are converted from strings | Below is the the instruction that describes the task:
### Input:
Does a normalization of sorts on image type data so that values
that should be integers are converted from strings
### Response:
def _normalized(self, data):
"""
Does a normalization of sorts on image type data so that values
... |
def aggregate_multi_graph(sub_network):
"""Aggregate branches between same buses and replace with a single
branch with aggregated properties (e.g. s_nom is summed, length is
averaged).
"""
network = sub_network.network
count = 0
seen = []
graph = sub_network.graph()
for u,v in graph.edges... | Aggregate branches between same buses and replace with a single
branch with aggregated properties (e.g. s_nom is summed, length is
averaged). | Below is the the instruction that describes the task:
### Input:
Aggregate branches between same buses and replace with a single
branch with aggregated properties (e.g. s_nom is summed, length is
averaged).
### Response:
def aggregate_multi_graph(sub_network):
"""Aggregate branches between same buses and repla... |
def invalidate_objects_cf(self):
"""Split the invalidation request in groups of 1000 objects"""
if not self.AWS_CLOUDFRONT_DISTRIBUTION:
raise CommandError(
'An object invalidation was requested but the variable '
'AWS_CLOUDFRONT_DISTRIBUTION is not present in... | Split the invalidation request in groups of 1000 objects | Below is the the instruction that describes the task:
### Input:
Split the invalidation request in groups of 1000 objects
### Response:
def invalidate_objects_cf(self):
"""Split the invalidation request in groups of 1000 objects"""
if not self.AWS_CLOUDFRONT_DISTRIBUTION:
raise CommandE... |
def auth_with_token(self, token, tenant_id=None, tenant_name=None):
"""
If a valid token is already known, this call will use it to generate
the service catalog.
"""
# Implementation note:
# Rackspace auth uses one tenant ID for the object_store services and
# ano... | If a valid token is already known, this call will use it to generate
the service catalog. | Below is the the instruction that describes the task:
### Input:
If a valid token is already known, this call will use it to generate
the service catalog.
### Response:
def auth_with_token(self, token, tenant_id=None, tenant_name=None):
"""
If a valid token is already known, this call will ... |
def resize_bytes(self, size):
""" Resize the buffer (in-place, deferred operation)
Parameters
----------
size : integer
New buffer size in bytes
Notes
-----
This clears any pending operations.
"""
Buffer.resize_bytes(self, size)
... | Resize the buffer (in-place, deferred operation)
Parameters
----------
size : integer
New buffer size in bytes
Notes
-----
This clears any pending operations. | Below is the the instruction that describes the task:
### Input:
Resize the buffer (in-place, deferred operation)
Parameters
----------
size : integer
New buffer size in bytes
Notes
-----
This clears any pending operations.
### Response:
def resize_byte... |
def wait(self, poll_interval=1, timeout=None, full_data=False):
""" Wait for this job to finish. """
end_time = None
if timeout:
end_time = time.time() + timeout
while end_time is None or time.time() < end_time:
job_data = self.collection.find_one({
... | Wait for this job to finish. | Below is the the instruction that describes the task:
### Input:
Wait for this job to finish.
### Response:
def wait(self, poll_interval=1, timeout=None, full_data=False):
""" Wait for this job to finish. """
end_time = None
if timeout:
end_time = time.time() + timeout
... |
def run(bam_file, data, fastqc_out):
"""Run fastqc, generating report in specified directory and parsing metrics.
Downsamples to 10 million reads to avoid excessive processing times with large
files, unless we're running a Standard/smallRNA-seq/QC pipeline.
Handles fastqc 0.11+, which use a single HTM... | Run fastqc, generating report in specified directory and parsing metrics.
Downsamples to 10 million reads to avoid excessive processing times with large
files, unless we're running a Standard/smallRNA-seq/QC pipeline.
Handles fastqc 0.11+, which use a single HTML file and older versions that use
a dir... | Below is the the instruction that describes the task:
### Input:
Run fastqc, generating report in specified directory and parsing metrics.
Downsamples to 10 million reads to avoid excessive processing times with large
files, unless we're running a Standard/smallRNA-seq/QC pipeline.
Handles fastqc 0.11... |
def distributed_wait(modulo=None, wait=None, operation_name='operation'):
''' Distribute operations by waiting based on modulo_distribution
If modulo and or wait are not set, check config_get for those values.
If config values are not set, default to modulo=3 and wait=30.
:param modulo: int The modulo... | Distribute operations by waiting based on modulo_distribution
If modulo and or wait are not set, check config_get for those values.
If config values are not set, default to modulo=3 and wait=30.
:param modulo: int The modulo number creates the group distribution
:param wait: int The constant time wait... | Below is the the instruction that describes the task:
### Input:
Distribute operations by waiting based on modulo_distribution
If modulo and or wait are not set, check config_get for those values.
If config values are not set, default to modulo=3 and wait=30.
:param modulo: int The modulo number creat... |
def validate_key(self, key):
"""
Validate the provided reset key.
Returns:
The validated key.
Raises:
serializers.ValidationError:
If the provided key does not exist.
"""
if not models.PasswordResetToken.valid_tokens.filter(key=ke... | Validate the provided reset key.
Returns:
The validated key.
Raises:
serializers.ValidationError:
If the provided key does not exist. | Below is the the instruction that describes the task:
### Input:
Validate the provided reset key.
Returns:
The validated key.
Raises:
serializers.ValidationError:
If the provided key does not exist.
### Response:
def validate_key(self, key):
"""
... |
def nested_join(array, o_str= '{', c_str= '}'):
'''
Builds a string out of a given nested list.
Args :
array : An array retruned by pyparsing nestedExpr.
o_str : Opening str.
c_str : Closing str.
'''
result = ''
for x in array :
if typ... | Builds a string out of a given nested list.
Args :
array : An array retruned by pyparsing nestedExpr.
o_str : Opening str.
c_str : Closing str. | Below is the the instruction that describes the task:
### Input:
Builds a string out of a given nested list.
Args :
array : An array retruned by pyparsing nestedExpr.
o_str : Opening str.
c_str : Closing str.
### Response:
def nested_join(array, o_str= '{', c_st... |
def get_colorized_contents(contents, color_config):
"""Colorize the contents based on the color_config."""
colorizer = color.EgColorizer(color_config)
result = colorizer.colorize_text(contents)
return result | Colorize the contents based on the color_config. | Below is the the instruction that describes the task:
### Input:
Colorize the contents based on the color_config.
### Response:
def get_colorized_contents(contents, color_config):
"""Colorize the contents based on the color_config."""
colorizer = color.EgColorizer(color_config)
result = colorizer.color... |
def loadModelData(self,name):
"""
Loads the model data of the given name.
The model file must always be a .json file.
"""
path = self.resourceNameToPath(name,".json")
try:
data = json.load(open(path,"r"))
except Exception:
# Tempor... | Loads the model data of the given name.
The model file must always be a .json file. | Below is the the instruction that describes the task:
### Input:
Loads the model data of the given name.
The model file must always be a .json file.
### Response:
def loadModelData(self,name):
"""
Loads the model data of the given name.
The model file must always b... |
def finish_init(environment, start_web, create_sysadmin, log_syslog=False,
do_install=True, quiet=False, site_url=None, interactive=False,
init_db=True):
"""
Common parts of create and init: Install, init db, start site, sysadmin
"""
if not init_db:
start_web = Fa... | Common parts of create and init: Install, init db, start site, sysadmin | Below is the the instruction that describes the task:
### Input:
Common parts of create and init: Install, init db, start site, sysadmin
### Response:
def finish_init(environment, start_web, create_sysadmin, log_syslog=False,
do_install=True, quiet=False, site_url=None, interactive=False,
... |
def create_spot(self,
price,
instance_type='default',
tags=None,
root_device_type='ebs',
size='default',
vol_type='gp2',
delete_on_termination=False,
timeout=No... | Create one or more EC2 spot instances.
:param root_device_type:
:param size:
:param vol_type:
:param delete_on_termination:
:param timeout:
:param price: Max price to pay for spot instance per hour.
:type price: float
:param instance_type: A section name ... | Below is the the instruction that describes the task:
### Input:
Create one or more EC2 spot instances.
:param root_device_type:
:param size:
:param vol_type:
:param delete_on_termination:
:param timeout:
:param price: Max price to pay for spot instance per hour.
... |
def Polygon(center=(0.,0.,0.), radius=1, normal=(0,0,1), n_sides=6):
"""
Createa a polygonal disk with a hole in the center. The disk has zero
height. The user can specify the inner and outer radius of the disk, and
the radial and circumferential resolution of the polygonal representation.
Paramete... | Createa a polygonal disk with a hole in the center. The disk has zero
height. The user can specify the inner and outer radius of the disk, and
the radial and circumferential resolution of the polygonal representation.
Parameters
----------
center : np.ndarray or list
Center in [x, y, z]. mi... | Below is the the instruction that describes the task:
### Input:
Createa a polygonal disk with a hole in the center. The disk has zero
height. The user can specify the inner and outer radius of the disk, and
the radial and circumferential resolution of the polygonal representation.
Parameters
-----... |
def find_repositories_by_walking_and_following_symlinks(path):
"""Walk a tree and return a sequence of (directory, dotdir) pairs."""
repos = []
# This is for detecting symlink loops and escaping them. This is similar to
# http://stackoverflow.com/questions/36977259/avoiding-infinite-recursion-with-os-w... | Walk a tree and return a sequence of (directory, dotdir) pairs. | Below is the the instruction that describes the task:
### Input:
Walk a tree and return a sequence of (directory, dotdir) pairs.
### Response:
def find_repositories_by_walking_and_following_symlinks(path):
"""Walk a tree and return a sequence of (directory, dotdir) pairs."""
repos = []
# This is for d... |
def hybrid_forward(self, F, inputs, states=None, mask=None):
# pylint: disable=arguments-differ
# pylint: disable=unused-argument
"""Defines the forward computation for cache cell. Arguments can be either
:py:class:`NDArray` or :py:class:`Symbol`.
Parameters
----------
... | Defines the forward computation for cache cell. Arguments can be either
:py:class:`NDArray` or :py:class:`Symbol`.
Parameters
----------
inputs : NDArray
The input data layout='TNC'.
states : Tuple[List[List[NDArray]]]
The states. including:
s... | Below is the the instruction that describes the task:
### Input:
Defines the forward computation for cache cell. Arguments can be either
:py:class:`NDArray` or :py:class:`Symbol`.
Parameters
----------
inputs : NDArray
The input data layout='TNC'.
states : Tuple[... |
def is_compatible(self, obj):
"""Check if characters can be combined into a textline
We consider characters compatible if:
- the Unicode mapping is known, and both have the same render mode
- the Unicode mapping is unknown but both are part of the same font
"""
b... | Check if characters can be combined into a textline
We consider characters compatible if:
- the Unicode mapping is known, and both have the same render mode
- the Unicode mapping is unknown but both are part of the same font | Below is the the instruction that describes the task:
### Input:
Check if characters can be combined into a textline
We consider characters compatible if:
- the Unicode mapping is known, and both have the same render mode
- the Unicode mapping is unknown but both are part of the sam... |
def admin_url(model, url, object_id=None):
"""
Returns the URL for the given model and admin url name.
"""
opts = model._meta
url = "admin:%s_%s_%s" % (opts.app_label, opts.object_name.lower(), url)
args = ()
if object_id is not None:
args = (object_id,)
return reverse(url, args=... | Returns the URL for the given model and admin url name. | Below is the the instruction that describes the task:
### Input:
Returns the URL for the given model and admin url name.
### Response:
def admin_url(model, url, object_id=None):
"""
Returns the URL for the given model and admin url name.
"""
opts = model._meta
url = "admin:%s_%s_%s" % (opts.app... |
def p_postfix_expr(self, p):
"""postfix_expr : left_hand_side_expr
| left_hand_side_expr PLUSPLUS
| left_hand_side_expr MINUSMINUS
"""
if len(p) == 2:
p[0] = p[1]
else:
p[0] = ast.UnaryOp(op=p[2], value=p[1], postfix... | postfix_expr : left_hand_side_expr
| left_hand_side_expr PLUSPLUS
| left_hand_side_expr MINUSMINUS | Below is the the instruction that describes the task:
### Input:
postfix_expr : left_hand_side_expr
| left_hand_side_expr PLUSPLUS
| left_hand_side_expr MINUSMINUS
### Response:
def p_postfix_expr(self, p):
"""postfix_expr : left_hand_side_expr
... |
def _transform_snapshot(raw_snapshot: str) -> str:
"""
The transformation step does the following:
1. Add `allocated_fee` to all initiator tasks
2. Adds `mediation_fee` to all channels
3. Populates tokennetworkaddresses_to_paymentnetworkaddresses in chain state
"""
snapshot = json.loads(raw_... | The transformation step does the following:
1. Add `allocated_fee` to all initiator tasks
2. Adds `mediation_fee` to all channels
3. Populates tokennetworkaddresses_to_paymentnetworkaddresses in chain state | Below is the the instruction that describes the task:
### Input:
The transformation step does the following:
1. Add `allocated_fee` to all initiator tasks
2. Adds `mediation_fee` to all channels
3. Populates tokennetworkaddresses_to_paymentnetworkaddresses in chain state
### Response:
def _transform_sn... |
def _join_signals(self):
r"""Join N 1D signals into one N-dimensional signal."""
joined = dict()
for name in self.signals:
name_base = name.rsplit('_', 1)[0]
names = joined.get(name_base, list())
names.append(name)
joined[name_base] = names
... | r"""Join N 1D signals into one N-dimensional signal. | Below is the the instruction that describes the task:
### Input:
r"""Join N 1D signals into one N-dimensional signal.
### Response:
def _join_signals(self):
r"""Join N 1D signals into one N-dimensional signal."""
joined = dict()
for name in self.signals:
name_base = name.rsplit(... |
def transpose(self, *axes):
"""
Transpose just the values of a BoltArraySpark, returning a
new BoltArraySpark.
Parameters
----------
axes : tuple
New proposed axes.
"""
new = argpack(axes)
old = range(self.ndim)
istransposeabl... | Transpose just the values of a BoltArraySpark, returning a
new BoltArraySpark.
Parameters
----------
axes : tuple
New proposed axes. | Below is the the instruction that describes the task:
### Input:
Transpose just the values of a BoltArraySpark, returning a
new BoltArraySpark.
Parameters
----------
axes : tuple
New proposed axes.
### Response:
def transpose(self, *axes):
"""
Transpose... |
def verify_key_in_shelve(file_name, save_key, file_location):
"""
Function to check for a key in a shelve
Args:
file_name: Shelve storage file name
save_key: The name of the key the item is stored in
file_location: The location of the file, derive from the os module
Returns: ret... | Function to check for a key in a shelve
Args:
file_name: Shelve storage file name
save_key: The name of the key the item is stored in
file_location: The location of the file, derive from the os module
Returns: returns true or false | Below is the the instruction that describes the task:
### Input:
Function to check for a key in a shelve
Args:
file_name: Shelve storage file name
save_key: The name of the key the item is stored in
file_location: The location of the file, derive from the os module
Returns: returns ... |
def _set_area_range(self, v, load=False):
"""
Setter method for area_range, mapped from YANG variable /rbridge_id/ipv6/router/ospf/area/area_range (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_area_range is considered as a private
method. Backends looking to... | Setter method for area_range, mapped from YANG variable /rbridge_id/ipv6/router/ospf/area/area_range (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_area_range is considered as a private
method. Backends looking to populate this variable should
do so via calling t... | Below is the the instruction that describes the task:
### Input:
Setter method for area_range, mapped from YANG variable /rbridge_id/ipv6/router/ospf/area/area_range (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_area_range is considered as a private
method. Back... |
def update(self, pk, data, **kwargs):
"""
Updates the object by primary_key:
.. code-block:: python
DBSession.sacrud(Users).update(1, {'name': 'Petya'})
DBSession.sacrud(Users).update('1', {'name': 'Petya'})
DBSession.sacrud(User2Groups).update({'user_id': 4... | Updates the object by primary_key:
.. code-block:: python
DBSession.sacrud(Users).update(1, {'name': 'Petya'})
DBSession.sacrud(Users).update('1', {'name': 'Petya'})
DBSession.sacrud(User2Groups).update({'user_id': 4, 'group_id': 2},
... | Below is the the instruction that describes the task:
### Input:
Updates the object by primary_key:
.. code-block:: python
DBSession.sacrud(Users).update(1, {'name': 'Petya'})
DBSession.sacrud(Users).update('1', {'name': 'Petya'})
DBSession.sacrud(User2Groups).update({'... |
def create_pipeline_field(self, pipeline_key, name, field_type, **kwargs):
'''Creates a pipeline field with the provided attributes.
Args:
pipeline_key specifying the pipeline to add the field to
name required name string
field_type required type string [TEXT_INPUT, DATE or PERSON]
kwargs {}
ret... | Creates a pipeline field with the provided attributes.
Args:
pipeline_key specifying the pipeline to add the field to
name required name string
field_type required type string [TEXT_INPUT, DATE or PERSON]
kwargs {}
return (status code, field dict) | Below is the the instruction that describes the task:
### Input:
Creates a pipeline field with the provided attributes.
Args:
pipeline_key specifying the pipeline to add the field to
name required name string
field_type required type string [TEXT_INPUT, DATE or PERSON]
kwargs {}
return (stat... |
def get_composition_search_session_for_repository(self, repository_id, proxy):
"""Gets a composition search session for the given repository.
arg: repository_id (osid.id.Id): the Id of the repository
arg proxy (osid.proxy.Proxy): a proxy
return: (osid.repository.CompositionSearch... | Gets a composition search session for the given repository.
arg: repository_id (osid.id.Id): the Id of the repository
arg proxy (osid.proxy.Proxy): a proxy
return: (osid.repository.CompositionSearchSession) - a
CompositionSearchSession
raise: NotFound - repositor... | Below is the the instruction that describes the task:
### Input:
Gets a composition search session for the given repository.
arg: repository_id (osid.id.Id): the Id of the repository
arg proxy (osid.proxy.Proxy): a proxy
return: (osid.repository.CompositionSearchSession) - a
... |
def _query_label(self, loc):
"""Query the label for the item with index `loc`. Preferentially
queries the label from the cache, but if not yet cached, queries the
oracle.
Returns
-------
int
the true label "0" or "1".
"""
# Try to get label fr... | Query the label for the item with index `loc`. Preferentially
queries the label from the cache, but if not yet cached, queries the
oracle.
Returns
-------
int
the true label "0" or "1". | Below is the the instruction that describes the task:
### Input:
Query the label for the item with index `loc`. Preferentially
queries the label from the cache, but if not yet cached, queries the
oracle.
Returns
-------
int
the true label "0" or "1".
### Response... |
def subCell2DSlices(arr, shape, d01=None, p01=None):
'''Generator to access evenly sized sub-cells in a 2d array
Args:
shape (tuple): number of sub-cells in y,x e.g. (10,15)
d01 (tuple, optional): cell size in y and x
p01 (tuple, optional): position of top left edge
Returns:
... | Generator to access evenly sized sub-cells in a 2d array
Args:
shape (tuple): number of sub-cells in y,x e.g. (10,15)
d01 (tuple, optional): cell size in y and x
p01 (tuple, optional): position of top left edge
Returns:
int: 1st index
int: 2nd index
slice... | Below is the the instruction that describes the task:
### Input:
Generator to access evenly sized sub-cells in a 2d array
Args:
shape (tuple): number of sub-cells in y,x e.g. (10,15)
d01 (tuple, optional): cell size in y and x
p01 (tuple, optional): position of top left edge
Re... |
def invitations():
"""List and manage received invitations.
"""
with Session() as session:
try:
result = session.VFolder.invitations()
invitations = result.get('invitations', [])
if len(invitations) < 1:
print('No invitations.')
ret... | List and manage received invitations. | Below is the the instruction that describes the task:
### Input:
List and manage received invitations.
### Response:
def invitations():
"""List and manage received invitations.
"""
with Session() as session:
try:
result = session.VFolder.invitations()
invitations = resul... |
def update(name,
password=None,
fullname=None,
description=None,
home=None,
homedrive=None,
logonscript=None,
profile=None,
expiration_date=None,
expired=None,
account_disabled=None,
unlock_account=N... | Updates settings for the windows user. Name is the only required parameter.
Settings will only be changed if the parameter is passed a value.
.. versionadded:: 2015.8.0
Args:
name (str): The user name to update.
password (str, optional): New user password in plain text.
fullname ... | Below is the the instruction that describes the task:
### Input:
Updates settings for the windows user. Name is the only required parameter.
Settings will only be changed if the parameter is passed a value.
.. versionadded:: 2015.8.0
Args:
name (str): The user name to update.
password... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.