code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def get_queryset(self):
""" extend parent class queryset by filtering nodes of the specified layer """
self.get_layer()
return super(LayerNodeListMixin, self).get_queryset().filter(layer_id=self.layer.id) | extend parent class queryset by filtering nodes of the specified layer | Below is the the instruction that describes the task:
### Input:
extend parent class queryset by filtering nodes of the specified layer
### Response:
def get_queryset(self):
""" extend parent class queryset by filtering nodes of the specified layer """
self.get_layer()
return super(LayerNod... |
def execute(self, action):
"""
Executes a single step in the UE4 game. This step may be comprised of one or more actual game ticks for all of
which the same given
action- and axis-inputs (or action number in case of discretized actions) are repeated.
UE4 distinguishes between act... | Executes a single step in the UE4 game. This step may be comprised of one or more actual game ticks for all of
which the same given
action- and axis-inputs (or action number in case of discretized actions) are repeated.
UE4 distinguishes between action-mappings, which are boolean actions (e.g. j... | Below is the the instruction that describes the task:
### Input:
Executes a single step in the UE4 game. This step may be comprised of one or more actual game ticks for all of
which the same given
action- and axis-inputs (or action number in case of discretized actions) are repeated.
UE4 dis... |
def finish(self, chunk=None):
"""Tornado `finish` handler"""
self._log_disconnect()
super(BaseHandler, self).finish(chunk) | Tornado `finish` handler | Below is the the instruction that describes the task:
### Input:
Tornado `finish` handler
### Response:
def finish(self, chunk=None):
"""Tornado `finish` handler"""
self._log_disconnect()
super(BaseHandler, self).finish(chunk) |
def teardown_request(self, func: Callable) -> Callable:
"""Add a teardown request function to the Blueprint.
This is designed to be used as a decorator, and has the same arguments
as :meth:`~quart.Quart.teardown_request`. It applies only to requests that
are routed to an endpoint in thi... | Add a teardown request function to the Blueprint.
This is designed to be used as a decorator, and has the same arguments
as :meth:`~quart.Quart.teardown_request`. It applies only to requests that
are routed to an endpoint in this blueprint. An example usage,
.. code-block:: python
... | Below is the the instruction that describes the task:
### Input:
Add a teardown request function to the Blueprint.
This is designed to be used as a decorator, and has the same arguments
as :meth:`~quart.Quart.teardown_request`. It applies only to requests that
are routed to an endpoint in t... |
def isBlockComment(self, block, column):
"""Check if character at column is a block comment
"""
dataObject = block.userData()
data = dataObject.data if dataObject is not None else None
return self._syntax.isBlockComment(data, column) | Check if character at column is a block comment | Below is the the instruction that describes the task:
### Input:
Check if character at column is a block comment
### Response:
def isBlockComment(self, block, column):
"""Check if character at column is a block comment
"""
dataObject = block.userData()
data = dataObject.data if data... |
def describe_table(cls,
db: DATABASE_SUPPORTER_FWD_REF,
table: str) -> List[List[Any]]:
"""Returns details on a specific table."""
raise RuntimeError(_MSG_NO_FLAVOUR) | Returns details on a specific table. | Below is the the instruction that describes the task:
### Input:
Returns details on a specific table.
### Response:
def describe_table(cls,
db: DATABASE_SUPPORTER_FWD_REF,
table: str) -> List[List[Any]]:
"""Returns details on a specific table."""
raise ... |
def _to_dict(self):
"""Return a json dictionary representing this model."""
_dict = {}
if hasattr(self, 'input') and self.input is not None:
_dict['input'] = self.input._to_dict()
if hasattr(self, 'intents') and self.intents is not None:
_dict['intents'] = [x._to_... | Return a json dictionary representing this model. | Below is the the instruction that describes the task:
### Input:
Return a json dictionary representing this model.
### Response:
def _to_dict(self):
"""Return a json dictionary representing this model."""
_dict = {}
if hasattr(self, 'input') and self.input is not None:
_dict['in... |
def dcc_chat(self, mask, host=None, port=None):
"""Open a DCC CHAT whith mask. If host/port are specified then connect
to a server. Else create a server"""
return self.dcc.create(
'chat', mask, host=host, port=port).ready | Open a DCC CHAT whith mask. If host/port are specified then connect
to a server. Else create a server | Below is the the instruction that describes the task:
### Input:
Open a DCC CHAT whith mask. If host/port are specified then connect
to a server. Else create a server
### Response:
def dcc_chat(self, mask, host=None, port=None):
"""Open a DCC CHAT whith mask. If host/port are specified then connect... |
def _JsonDecodeKey(d):
"""Json decode a ndb.Key object."""
k_c = d['key_string']
if isinstance(k_c, (list, tuple)):
return ndb.Key(flat=k_c)
return ndb.Key(urlsafe=d['key_string']) | Json decode a ndb.Key object. | Below is the the instruction that describes the task:
### Input:
Json decode a ndb.Key object.
### Response:
def _JsonDecodeKey(d):
"""Json decode a ndb.Key object."""
k_c = d['key_string']
if isinstance(k_c, (list, tuple)):
return ndb.Key(flat=k_c)
return ndb.Key(urlsafe=d['key_string']) |
def update_weights(self, x, y):
"""Weight updates as described in the Földiák's paper."""
m = self._inputSize
n = self._outputSize
W = self._W
Q = self._Q
t = self._t
alpha = self._alpha
beta = self._beta
gamma = self._gamma
... | Weight updates as described in the Földiák's paper. | Below is the the instruction that describes the task:
### Input:
Weight updates as described in the Földiák's paper.
### Response:
def update_weights(self, x, y):
"""Weight updates as described in the Földiák's paper."""
m = self._inputSize
n = self._outputSize
W = self.... |
def service_update(auth=None, **kwargs):
'''
Update a service
CLI Example:
.. code-block:: bash
salt '*' keystoneng.service_update name=cinder type=volumev2
salt '*' keystoneng.service_update name=cinder description='new description'
salt '*' keystoneng.service_update name=ab4... | Update a service
CLI Example:
.. code-block:: bash
salt '*' keystoneng.service_update name=cinder type=volumev2
salt '*' keystoneng.service_update name=cinder description='new description'
salt '*' keystoneng.service_update name=ab4d35e269f147b3ae2d849f77f5c88f enabled=False | Below is the the instruction that describes the task:
### Input:
Update a service
CLI Example:
.. code-block:: bash
salt '*' keystoneng.service_update name=cinder type=volumev2
salt '*' keystoneng.service_update name=cinder description='new description'
salt '*' keystoneng.service... |
def get_live_weather(lat, lon, writer):
"""Gets the live weather via lat and long"""
requrl = FORECAST_BASE_URL+forecast_api_token+'/'+str(lat)+','+str(lon)
req = requests.get(requrl)
if req.status_code == requests.codes.ok:
weather = req.json()
if not weather['currently']:
c... | Gets the live weather via lat and long | Below is the the instruction that describes the task:
### Input:
Gets the live weather via lat and long
### Response:
def get_live_weather(lat, lon, writer):
"""Gets the live weather via lat and long"""
requrl = FORECAST_BASE_URL+forecast_api_token+'/'+str(lat)+','+str(lon)
req = requests.get(requrl)
... |
def get_compiled_serving(dk_api, kitchen, recipe_name, variation_name):
"""
returns a string.
:param dk_api: -- api object
:param kitchen: string
:param recipe_name: string -- kitchen name, string
:param variation_name: string -- name of the recipe variation_name to be u... | returns a string.
:param dk_api: -- api object
:param kitchen: string
:param recipe_name: string -- kitchen name, string
:param variation_name: string -- name of the recipe variation_name to be used
:rtype: DKReturnCode | Below is the the instruction that describes the task:
### Input:
returns a string.
:param dk_api: -- api object
:param kitchen: string
:param recipe_name: string -- kitchen name, string
:param variation_name: string -- name of the recipe variation_name to be used
:rtype: DKR... |
def get_file(self, url, path_or_file=None, headers=None, filename=None):
''' Get a file from a url and save it as `filename`
Args:
url (str): URL to send the request to
path_or_file (str or file): A writable File-like object or a path to save the file to.
filename ... | Get a file from a url and save it as `filename`
Args:
url (str): URL to send the request to
path_or_file (str or file): A writable File-like object or a path to save the file to.
filename (str): [DEPRECATED] File name to save the file as, this can be either
... | Below is the the instruction that describes the task:
### Input:
Get a file from a url and save it as `filename`
Args:
url (str): URL to send the request to
path_or_file (str or file): A writable File-like object or a path to save the file to.
filename (str): [DEPRECAT... |
def get_okeeffe_distance_prediction(el1, el2):
"""
Returns an estimate of the bond valence parameter (bond length) using
the derived parameters from 'Atoms Sizes and Bond Lengths in Molecules
and Crystals' (O'Keeffe & Brese, 1991). The estimate is based on two
experimental parameters: r and c. The v... | Returns an estimate of the bond valence parameter (bond length) using
the derived parameters from 'Atoms Sizes and Bond Lengths in Molecules
and Crystals' (O'Keeffe & Brese, 1991). The estimate is based on two
experimental parameters: r and c. The value for r is based off radius,
while c is (usually) t... | Below is the the instruction that describes the task:
### Input:
Returns an estimate of the bond valence parameter (bond length) using
the derived parameters from 'Atoms Sizes and Bond Lengths in Molecules
and Crystals' (O'Keeffe & Brese, 1991). The estimate is based on two
experimental parameters: r an... |
def victim(self, name, owner=None, **kwargs):
"""
Create the Victim TI object.
Args:
owner:
name:
**kwargs:
Return:
"""
return Victim(self.tcex, name, owner=owner, **kwargs) | Create the Victim TI object.
Args:
owner:
name:
**kwargs:
Return: | Below is the the instruction that describes the task:
### Input:
Create the Victim TI object.
Args:
owner:
name:
**kwargs:
Return:
### Response:
def victim(self, name, owner=None, **kwargs):
"""
Create the Victim TI object.
Args:
... |
def bytes_dict_cast(dict_, include_keys=True, include_vals=True, **kwargs):
"""
Converts any string-like items in input dict to bytes-like values, with
respect to python version
Parameters
----------
dict_ : dict
any string-like objects contained in the dict will be converted to bytes
... | Converts any string-like items in input dict to bytes-like values, with
respect to python version
Parameters
----------
dict_ : dict
any string-like objects contained in the dict will be converted to bytes
include_keys : bool, default=True
if True, cast keys to bytes, else ignore
... | Below is the the instruction that describes the task:
### Input:
Converts any string-like items in input dict to bytes-like values, with
respect to python version
Parameters
----------
dict_ : dict
any string-like objects contained in the dict will be converted to bytes
include_keys : b... |
def replace_month_abbr_with_num(date_str, lang=DEFAULT_DATE_LANG):
"""Replace month strings occurrences with month number."""
num, abbr = get_month_from_date_str(date_str, lang)
return re.sub(abbr, str(num), date_str, flags=re.IGNORECASE) | Replace month strings occurrences with month number. | Below is the the instruction that describes the task:
### Input:
Replace month strings occurrences with month number.
### Response:
def replace_month_abbr_with_num(date_str, lang=DEFAULT_DATE_LANG):
"""Replace month strings occurrences with month number."""
num, abbr = get_month_from_date_str(date_str, lan... |
def is_simplicial(G, n):
"""Determines whether a node n in G is simplicial.
Parameters
----------
G : NetworkX graph
The graph on which to check whether node n is simplicial.
n : node
A node in graph G.
Returns
-------
is_simplicial : bool
True if its neighbors ... | Determines whether a node n in G is simplicial.
Parameters
----------
G : NetworkX graph
The graph on which to check whether node n is simplicial.
n : node
A node in graph G.
Returns
-------
is_simplicial : bool
True if its neighbors form a clique.
Examples
... | Below is the the instruction that describes the task:
### Input:
Determines whether a node n in G is simplicial.
Parameters
----------
G : NetworkX graph
The graph on which to check whether node n is simplicial.
n : node
A node in graph G.
Returns
-------
is_simplicial ... |
def find_postaggs_for(postagg_names, metrics_dict):
"""Return a list of metrics that are post aggregations"""
postagg_metrics = [
metrics_dict[name] for name in postagg_names
if metrics_dict[name].metric_type == POST_AGG_TYPE
]
# Remove post aggregations that were... | Return a list of metrics that are post aggregations | Below is the the instruction that describes the task:
### Input:
Return a list of metrics that are post aggregations
### Response:
def find_postaggs_for(postagg_names, metrics_dict):
"""Return a list of metrics that are post aggregations"""
postagg_metrics = [
metrics_dict[name] for nam... |
def server_error(request, template_name='500.html'):
"""
500 error handler.
Templates: :template:`500.html`
Context: None
"""
response = render_in_page(request, template_name)
if response:
return response
try:
template = loader.get_template(template_name)
except T... | 500 error handler.
Templates: :template:`500.html`
Context: None | Below is the the instruction that describes the task:
### Input:
500 error handler.
Templates: :template:`500.html`
Context: None
### Response:
def server_error(request, template_name='500.html'):
"""
500 error handler.
Templates: :template:`500.html`
Context: None
"""
response =... |
def batch_workflow_cancel(self, batch_workflow_id):
"""Cancels GBDX batch workflow.
Args:
batch workflow_id (str): Batch workflow id.
Returns:
Batch Workflow status (str).
"""
self.logger.debug('Cancel batch workflow: ' + batch_workflow_id)
u... | Cancels GBDX batch workflow.
Args:
batch workflow_id (str): Batch workflow id.
Returns:
Batch Workflow status (str). | Below is the the instruction that describes the task:
### Input:
Cancels GBDX batch workflow.
Args:
batch workflow_id (str): Batch workflow id.
Returns:
Batch Workflow status (str).
### Response:
def batch_workflow_cancel(self, batch_workflow_id):
"""Cancels GB... |
def check_file(self, fs, info):
# type: (FS, Info) -> bool
"""Check if a filename should be included.
Override to exclude files from the walk.
Arguments:
fs (FS): A filesystem instance.
info (Info): A resource info object.
Returns:
bool: `Tr... | Check if a filename should be included.
Override to exclude files from the walk.
Arguments:
fs (FS): A filesystem instance.
info (Info): A resource info object.
Returns:
bool: `True` if the file should be included. | Below is the the instruction that describes the task:
### Input:
Check if a filename should be included.
Override to exclude files from the walk.
Arguments:
fs (FS): A filesystem instance.
info (Info): A resource info object.
Returns:
bool: `True` if th... |
def rename_annotations(self, annotations) -> None:
"""Renames the aliases for the specified annotations:
.annotate(myfield=F('somestuf__myfield'))
.rename_annotations(myfield='field')
Arguments:
annotations:
The annotations to rename. Mapping the
... | Renames the aliases for the specified annotations:
.annotate(myfield=F('somestuf__myfield'))
.rename_annotations(myfield='field')
Arguments:
annotations:
The annotations to rename. Mapping the
old name to the new name. | Below is the the instruction that describes the task:
### Input:
Renames the aliases for the specified annotations:
.annotate(myfield=F('somestuf__myfield'))
.rename_annotations(myfield='field')
Arguments:
annotations:
The annotations to rename. Mapping ... |
def get_array_ndim(self, key):
"""Return array's ndim"""
data = self.model.get_data()
return data[key].ndim | Return array's ndim | Below is the the instruction that describes the task:
### Input:
Return array's ndim
### Response:
def get_array_ndim(self, key):
"""Return array's ndim"""
data = self.model.get_data()
return data[key].ndim |
def compare_datetimes(d1, d2):
""" Compares two datetimes safely, whether they are timezone-naive or timezone-aware.
If either datetime is naive it is converted to an aware datetime assuming UTC.
Args:
d1: first datetime.
d2: second datetime.
Returns:
-1 if d1 < d2, 0 if they are the same, or +1 ... | Compares two datetimes safely, whether they are timezone-naive or timezone-aware.
If either datetime is naive it is converted to an aware datetime assuming UTC.
Args:
d1: first datetime.
d2: second datetime.
Returns:
-1 if d1 < d2, 0 if they are the same, or +1 is d1 > d2. | Below is the the instruction that describes the task:
### Input:
Compares two datetimes safely, whether they are timezone-naive or timezone-aware.
If either datetime is naive it is converted to an aware datetime assuming UTC.
Args:
d1: first datetime.
d2: second datetime.
Returns:
-1 if d1 < d2... |
def main(argv=None):
"""Run the main CLI entry point."""
parser = build_argparser()
args = parser.parse_args(argv)
logging.basicConfig(level=args.loglevel, format="%(message)s")
check_args(parser, args)
if args.extract:
marfile = os.path.abspath(args.extract)
if args.chdir:
... | Run the main CLI entry point. | Below is the the instruction that describes the task:
### Input:
Run the main CLI entry point.
### Response:
def main(argv=None):
"""Run the main CLI entry point."""
parser = build_argparser()
args = parser.parse_args(argv)
logging.basicConfig(level=args.loglevel, format="%(message)s")
check... |
def from_where(cls, where):
""" Factory method for creating the top-level expression """
if where.conjunction:
return Conjunction.from_clause(where)
else:
return cls.from_clause(where[0]) | Factory method for creating the top-level expression | Below is the the instruction that describes the task:
### Input:
Factory method for creating the top-level expression
### Response:
def from_where(cls, where):
""" Factory method for creating the top-level expression """
if where.conjunction:
return Conjunction.from_clause(where)
... |
def get_activity(self):
"""Check account concurrency limits."""
method = 'GET'
endpoint = '/rest/v1/{}/activity'.format(self.client.sauce_username)
return self.client.request(method, endpoint) | Check account concurrency limits. | Below is the the instruction that describes the task:
### Input:
Check account concurrency limits.
### Response:
def get_activity(self):
"""Check account concurrency limits."""
method = 'GET'
endpoint = '/rest/v1/{}/activity'.format(self.client.sauce_username)
return self.client.req... |
def _chk_docopt_exit(self, args, exp_letters):
"""Check if docopt exit was for an unknown argument."""
if args is None:
args = sys.argv[1:]
keys_all = self.exp_keys.union(self.exp_elems)
if exp_letters:
keys_all |= exp_letters
unknown_args = self._chk_docu... | Check if docopt exit was for an unknown argument. | Below is the the instruction that describes the task:
### Input:
Check if docopt exit was for an unknown argument.
### Response:
def _chk_docopt_exit(self, args, exp_letters):
"""Check if docopt exit was for an unknown argument."""
if args is None:
args = sys.argv[1:]
keys_all =... |
def check_fastq(self, input_files, output_files, paired_end):
"""
Returns a follow sanity-check function to be run after a fastq conversion.
Run following a command that will produce the fastq files.
This function will make sure any input files have the same number of reads as the
... | Returns a follow sanity-check function to be run after a fastq conversion.
Run following a command that will produce the fastq files.
This function will make sure any input files have the same number of reads as the
output files. | Below is the the instruction that describes the task:
### Input:
Returns a follow sanity-check function to be run after a fastq conversion.
Run following a command that will produce the fastq files.
This function will make sure any input files have the same number of reads as the
output fil... |
def group_and_sort_nodes(self):
"""
Groups and then sorts the nodes according to the criteria passed into
the Plot constructor.
"""
if self.node_grouping and not self.node_order:
if self.group_order == "alphabetically":
self.nodes = [
... | Groups and then sorts the nodes according to the criteria passed into
the Plot constructor. | Below is the the instruction that describes the task:
### Input:
Groups and then sorts the nodes according to the criteria passed into
the Plot constructor.
### Response:
def group_and_sort_nodes(self):
"""
Groups and then sorts the nodes according to the criteria passed into
the Pl... |
def read_list_edges(filename, directed=True, **kwargs):
"""Read a file (containing list of edges) and convert it into a directed
or undirected networkx graph.
:param filename: file to read or DataFrame containing the data
:type filename: str or pandas.DataFrame
:param directed: Return directed grap... | Read a file (containing list of edges) and convert it into a directed
or undirected networkx graph.
:param filename: file to read or DataFrame containing the data
:type filename: str or pandas.DataFrame
:param directed: Return directed graph
:type directed: bool
:param kwargs: extra parameters ... | Below is the the instruction that describes the task:
### Input:
Read a file (containing list of edges) and convert it into a directed
or undirected networkx graph.
:param filename: file to read or DataFrame containing the data
:type filename: str or pandas.DataFrame
:param directed: Return directe... |
def load_outputs(self):
"""Load output module(s)"""
for output in sorted(logdissect.output.__formats__):
self.output_modules[output] = \
__import__('logdissect.output.' + output, globals(), \
locals(), [logdissect]).OutputModule(args=self.output_args) | Load output module(s) | Below is the the instruction that describes the task:
### Input:
Load output module(s)
### Response:
def load_outputs(self):
"""Load output module(s)"""
for output in sorted(logdissect.output.__formats__):
self.output_modules[output] = \
__import__('logdissect.output.' +... |
def _modify(self, **patch):
'''Modify only draft or legacy policies
Published policies cannot be modified
:raises: OperationNotSupportedOnPublishedPolicy
'''
legacy = patch.pop('legacy', False)
tmos_ver = self._meta_data['bigip']._meta_data['tmos_version']
self.... | Modify only draft or legacy policies
Published policies cannot be modified
:raises: OperationNotSupportedOnPublishedPolicy | Below is the the instruction that describes the task:
### Input:
Modify only draft or legacy policies
Published policies cannot be modified
:raises: OperationNotSupportedOnPublishedPolicy
### Response:
def _modify(self, **patch):
'''Modify only draft or legacy policies
Published p... |
def shrink(self, amount):
"""Kill off worker threads (not below self.min)."""
# Grow/shrink the pool if necessary.
# Remove any dead threads from our list
for t in self._threads:
if not t.isAlive():
self._threads.remove(t)
amount -= 1
... | Kill off worker threads (not below self.min). | Below is the the instruction that describes the task:
### Input:
Kill off worker threads (not below self.min).
### Response:
def shrink(self, amount):
"""Kill off worker threads (not below self.min)."""
# Grow/shrink the pool if necessary.
# Remove any dead threads from our list
for... |
def authenticate():
"""
Authenticate the user and store the 'token' for further use
Return the authentication 'token'
"""
print LOGIN_INIT_MESSAGE
username = raw_input('{0}: '.format(LOGIN_USER_MESSAGE))
password = None
while password is None:
password = getpass('Password for ... | Authenticate the user and store the 'token' for further use
Return the authentication 'token' | Below is the the instruction that describes the task:
### Input:
Authenticate the user and store the 'token' for further use
Return the authentication 'token'
### Response:
def authenticate():
"""
Authenticate the user and store the 'token' for further use
Return the authentication 'token'
"""
... |
def extract_table_names(query):
""" Extract table names from an SQL query. """
# a good old fashioned regex. turns out this worked better than actually parsing the code
tables_blocks = re.findall(r'(?:FROM|JOIN)\s+(\w+(?:\s*,\s*\w+)*)', query, re.IGNORECASE)
tables = [tbl
for block in tabl... | Extract table names from an SQL query. | Below is the the instruction that describes the task:
### Input:
Extract table names from an SQL query.
### Response:
def extract_table_names(query):
""" Extract table names from an SQL query. """
# a good old fashioned regex. turns out this worked better than actually parsing the code
tables_blocks = ... |
def _ensure_click(self):
"""Ensures a click gets made, because Selenium can be a bit buggy about clicks
This method gets added to the selenium element returned in '__ensure_element_by_xpath'.
We should probably add it to more selenium methods, such as all the 'find**' methods though.
I wrote this meth... | Ensures a click gets made, because Selenium can be a bit buggy about clicks
This method gets added to the selenium element returned in '__ensure_element_by_xpath'.
We should probably add it to more selenium methods, such as all the 'find**' methods though.
I wrote this method out of frustration with chrom... | Below is the the instruction that describes the task:
### Input:
Ensures a click gets made, because Selenium can be a bit buggy about clicks
This method gets added to the selenium element returned in '__ensure_element_by_xpath'.
We should probably add it to more selenium methods, such as all the 'find**' m... |
def handleRequest(self, obj, socket, multi=False):
'''
Handle one or more requests on a REP socket, with the format
sent by sendRequest()
'''
while 1:
try:
msg = socket.recv_multipart(zmq.NOBLOCK)
method = msg[0].decode()
... | Handle one or more requests on a REP socket, with the format
sent by sendRequest() | Below is the the instruction that describes the task:
### Input:
Handle one or more requests on a REP socket, with the format
sent by sendRequest()
### Response:
def handleRequest(self, obj, socket, multi=False):
'''
Handle one or more requests on a REP socket, with the format
sent ... |
def write_id (self):
"""Write ID for current URL."""
self.writeln(u"<tr>")
self.writeln(u'<td>%s</td>' % self.part("id"))
self.write(u"<td>%d</td></tr>" % self.stats.number) | Write ID for current URL. | Below is the the instruction that describes the task:
### Input:
Write ID for current URL.
### Response:
def write_id (self):
"""Write ID for current URL."""
self.writeln(u"<tr>")
self.writeln(u'<td>%s</td>' % self.part("id"))
self.write(u"<td>%d</td></tr>" % self.stats.number) |
def get_dispatcher(self):
"""
Get Dispatcher instance from environment
:return: :class:`aiogram.Dispatcher`
"""
dp = self.request.app[BOT_DISPATCHER_KEY]
try:
from aiogram import Bot, Dispatcher
Dispatcher.set_current(dp)
Bot.set_curre... | Get Dispatcher instance from environment
:return: :class:`aiogram.Dispatcher` | Below is the the instruction that describes the task:
### Input:
Get Dispatcher instance from environment
:return: :class:`aiogram.Dispatcher`
### Response:
def get_dispatcher(self):
"""
Get Dispatcher instance from environment
:return: :class:`aiogram.Dispatcher`
"""
... |
def revoke(self, revocation_reason, uid=None, revocation_message=None,
compromise_occurrence_date=None):
"""
Revoke a managed object stored by a KMIP appliance.
Args:
revocation_reason (RevocationReasonCode): An enumeration indicating
the revocation re... | Revoke a managed object stored by a KMIP appliance.
Args:
revocation_reason (RevocationReasonCode): An enumeration indicating
the revocation reason.
uid (string): The unique ID of the managed object to revoke.
Optional, defaults to None.
revoc... | Below is the the instruction that describes the task:
### Input:
Revoke a managed object stored by a KMIP appliance.
Args:
revocation_reason (RevocationReasonCode): An enumeration indicating
the revocation reason.
uid (string): The unique ID of the managed object to ... |
def is_excluded_dir(self, path):
"""
Determines whether or not the specified directory is excluded by the
project's configuration.
:param path: the path to check
:type path: pathlib.Path
:rtype: bool
"""
if self.is_excluded(path):
return True... | Determines whether or not the specified directory is excluded by the
project's configuration.
:param path: the path to check
:type path: pathlib.Path
:rtype: bool | Below is the the instruction that describes the task:
### Input:
Determines whether or not the specified directory is excluded by the
project's configuration.
:param path: the path to check
:type path: pathlib.Path
:rtype: bool
### Response:
def is_excluded_dir(self, path):
... |
def filter_attribute_value_assertions(ava, attribute_restrictions=None):
""" Will weed out attribute values and values according to the
rules defined in the attribute restrictions. If filtering results in
an attribute without values, then the attribute is removed from the
assertion.
:param ava: The... | Will weed out attribute values and values according to the
rules defined in the attribute restrictions. If filtering results in
an attribute without values, then the attribute is removed from the
assertion.
:param ava: The incoming attribute value assertion (dictionary)
:param attribute_restriction... | Below is the the instruction that describes the task:
### Input:
Will weed out attribute values and values according to the
rules defined in the attribute restrictions. If filtering results in
an attribute without values, then the attribute is removed from the
assertion.
:param ava: The incoming at... |
def key_to_kind(cls, key):
"""Return the kind specified by a given __property__ key.
Args:
key: key whose kind name is requested.
Returns:
The kind specified by key.
"""
if key.kind() == Kind.KIND_NAME:
return key.id()
else:
return key.parent().id() | Return the kind specified by a given __property__ key.
Args:
key: key whose kind name is requested.
Returns:
The kind specified by key. | Below is the the instruction that describes the task:
### Input:
Return the kind specified by a given __property__ key.
Args:
key: key whose kind name is requested.
Returns:
The kind specified by key.
### Response:
def key_to_kind(cls, key):
"""Return the kind specified by a given __prope... |
def _generate_malformed_query(data):
"""Generates a query on the ``_all`` field with all the query content.
Args:
data (six.text_type or list): The query in the format of ``six.text_type`` (when used from parsing driver)
or ``list`` when used from withing the ES visitor.
... | Generates a query on the ``_all`` field with all the query content.
Args:
data (six.text_type or list): The query in the format of ``six.text_type`` (when used from parsing driver)
or ``list`` when used from withing the ES visitor. | Below is the the instruction that describes the task:
### Input:
Generates a query on the ``_all`` field with all the query content.
Args:
data (six.text_type or list): The query in the format of ``six.text_type`` (when used from parsing driver)
or ``list`` when used from within... |
def arrays_overlap(a1, a2):
"""
Collection function: returns true if the arrays contain any common non-null element; if not,
returns null if both the arrays are non-empty and any of them contains a null element; returns
false otherwise.
>>> df = spark.createDataFrame([(["a", "b"], ["b", "c"]), (["a... | Collection function: returns true if the arrays contain any common non-null element; if not,
returns null if both the arrays are non-empty and any of them contains a null element; returns
false otherwise.
>>> df = spark.createDataFrame([(["a", "b"], ["b", "c"]), (["a"], ["b", "c"])], ['x', 'y'])
>>> df... | Below is the the instruction that describes the task:
### Input:
Collection function: returns true if the arrays contain any common non-null element; if not,
returns null if both the arrays are non-empty and any of them contains a null element; returns
false otherwise.
>>> df = spark.createDataFrame([(... |
def right(self):
'''
Returns the current axis instance on the right side of the
page, where cross-validation information is displayed
'''
res = self.body_right[self.rcount]()
self.rcount += 1
return res | Returns the current axis instance on the right side of the
page, where cross-validation information is displayed | Below is the the instruction that describes the task:
### Input:
Returns the current axis instance on the right side of the
page, where cross-validation information is displayed
### Response:
def right(self):
'''
Returns the current axis instance on the right side of the
page, where... |
def skip():
"""Tell iTunes to skip a song"""
if not settings.platformCompatible():
return False
(output, error) = subprocess.Popen(["osascript", "-e", SKIP], stdout=subprocess.PIPE).communicate() | Tell iTunes to skip a song | Below is the the instruction that describes the task:
### Input:
Tell iTunes to skip a song
### Response:
def skip():
"""Tell iTunes to skip a song"""
if not settings.platformCompatible():
return False
(output, error) = subprocess.Popen(["osascript", "-e", SKIP], stdout=subprocess.PIPE).communicate() |
def accepts(self, package): # type: (poetry.packages.Package) -> bool
"""
Determines if the given package matches this dependency.
"""
return (
self._name == package.name
and self._constraint.allows(package.version)
and (not package.is_prerelease() or... | Determines if the given package matches this dependency. | Below is the the instruction that describes the task:
### Input:
Determines if the given package matches this dependency.
### Response:
def accepts(self, package): # type: (poetry.packages.Package) -> bool
"""
Determines if the given package matches this dependency.
"""
return (
... |
def dumps(self):
'''Create a CBOR byte string from a feature collection.'''
metadata = {'v': 'fc01'}
if self.read_only:
metadata['ro'] = 1
rep = [metadata, self.to_dict()]
return cbor.dumps(rep) | Create a CBOR byte string from a feature collection. | Below is the the instruction that describes the task:
### Input:
Create a CBOR byte string from a feature collection.
### Response:
def dumps(self):
'''Create a CBOR byte string from a feature collection.'''
metadata = {'v': 'fc01'}
if self.read_only:
metadata['ro'] = 1
... |
def js_reverse_inline(context):
"""
Outputs a string of javascript that can generate URLs via the use
of the names given to those URLs.
"""
if 'request' in context:
default_urlresolver = get_resolver(getattr(context['request'], 'urlconf', None))
else:
default_urlresolver = get_re... | Outputs a string of javascript that can generate URLs via the use
of the names given to those URLs. | Below is the the instruction that describes the task:
### Input:
Outputs a string of javascript that can generate URLs via the use
of the names given to those URLs.
### Response:
def js_reverse_inline(context):
"""
Outputs a string of javascript that can generate URLs via the use
of the names given... |
def add_zoom_buttons(viewer, canvas=None, color='black'):
"""Add zoom buttons to a canvas.
Parameters
----------
viewer : an ImageView subclass instance
If True, show the color bar; else remove it if present.
canvas : a DrawingCanvas instance
The canvas to which the buttons should ... | Add zoom buttons to a canvas.
Parameters
----------
viewer : an ImageView subclass instance
If True, show the color bar; else remove it if present.
canvas : a DrawingCanvas instance
The canvas to which the buttons should be added. If not supplied
defaults to the private canvas... | Below is the the instruction that describes the task:
### Input:
Add zoom buttons to a canvas.
Parameters
----------
viewer : an ImageView subclass instance
If True, show the color bar; else remove it if present.
canvas : a DrawingCanvas instance
The canvas to which the buttons sho... |
def happybirthday(person):
"""
Sing Happy Birthday
"""
print('Happy Birthday To You')
time.sleep(2)
print('Happy Birthday To You')
time.sleep(2)
print('Happy Birthday Dear ' + str(person[0].upper()) + str(person[1:]))
time.sleep(2)
print('Happy Birthday To You') | Sing Happy Birthday | Below is the the instruction that describes the task:
### Input:
Sing Happy Birthday
### Response:
def happybirthday(person):
"""
Sing Happy Birthday
"""
print('Happy Birthday To You')
time.sleep(2)
print('Happy Birthday To You')
time.sleep(2)
print('Happy Birthday Dear ' + str(pers... |
def prepare_service(args=None):
"""Configures application and setups logging."""
options.register_opts(cfg.CONF)
services.load_service_opts(cfg.CONF)
_configure(args)
_setup_logging()
cfg.CONF.log_opt_values(logging.getLogger(), logging.DEBUG) | Configures application and setups logging. | Below is the the instruction that describes the task:
### Input:
Configures application and setups logging.
### Response:
def prepare_service(args=None):
"""Configures application and setups logging."""
options.register_opts(cfg.CONF)
services.load_service_opts(cfg.CONF)
_configure(args)
_setup... |
def post(method, hmc, uri, uri_parms, body, logon_required,
wait_for_completion):
"""Operation: Reassign Storage Adapter Port (requires DPM mode)."""
assert wait_for_completion is True # async not supported yet
partition_oid = uri_parms[0]
partition_uri = '/api/partitions/'... | Operation: Reassign Storage Adapter Port (requires DPM mode). | Below is the the instruction that describes the task:
### Input:
Operation: Reassign Storage Adapter Port (requires DPM mode).
### Response:
def post(method, hmc, uri, uri_parms, body, logon_required,
wait_for_completion):
"""Operation: Reassign Storage Adapter Port (requires DPM mode)."""
... |
def modify_qa_v1(self):
"""Add water to or remove water from the calculated lake outflow.
Required control parameter:
|Verzw|
Required derived parameter:
|llake_derived.TOY|
Updated flux sequence:
|llake_fluxes.QA|
Basic Equation:
:math:`QA = QA* - Verzw`
Examples:
... | Add water to or remove water from the calculated lake outflow.
Required control parameter:
|Verzw|
Required derived parameter:
|llake_derived.TOY|
Updated flux sequence:
|llake_fluxes.QA|
Basic Equation:
:math:`QA = QA* - Verzw`
Examples:
In preparation for the f... | Below is the the instruction that describes the task:
### Input:
Add water to or remove water from the calculated lake outflow.
Required control parameter:
|Verzw|
Required derived parameter:
|llake_derived.TOY|
Updated flux sequence:
|llake_fluxes.QA|
Basic Equation:
:ma... |
def eta_mass1_to_mass2(eta, mass1, return_mass_heavier=False, force_real=True):
"""
This function takes values for eta and one component mass and returns the
second component mass. Similar to mchirp_mass1_to_mass2 this requires
finding the roots of a quadratic equation. Basically:
eta m2^2 + (2 eta... | This function takes values for eta and one component mass and returns the
second component mass. Similar to mchirp_mass1_to_mass2 this requires
finding the roots of a quadratic equation. Basically:
eta m2^2 + (2 eta - 1)m1 m2 + \eta m1^2 = 0
This has two solutions which correspond to mass1 being the h... | Below is the the instruction that describes the task:
### Input:
This function takes values for eta and one component mass and returns the
second component mass. Similar to mchirp_mass1_to_mass2 this requires
finding the roots of a quadratic equation. Basically:
eta m2^2 + (2 eta - 1)m1 m2 + \eta m1^2 ... |
def _blkid(fs_type=None):
'''
Return available media devices.
:param fs_type: Filter only devices that are formatted by that file system.
'''
flt = lambda data: [el for el in data if el.strip()]
data = dict()
for dev_meta in flt(os.popen("blkid -o full").read().split(os.linesep)): # No __s... | Return available media devices.
:param fs_type: Filter only devices that are formatted by that file system. | Below is the the instruction that describes the task:
### Input:
Return available media devices.
:param fs_type: Filter only devices that are formatted by that file system.
### Response:
def _blkid(fs_type=None):
'''
Return available media devices.
:param fs_type: Filter only devices that are for... |
def delete(self):
"""
Deletes all layers within this LayeredWidget before deleting itself.
Recommended to call if you are removing the widget, but not yet exiting the interpreter.
"""
for layer,_ in self.layers:
layer.delete()
self.layers = []
... | Deletes all layers within this LayeredWidget before deleting itself.
Recommended to call if you are removing the widget, but not yet exiting the interpreter. | Below is the the instruction that describes the task:
### Input:
Deletes all layers within this LayeredWidget before deleting itself.
Recommended to call if you are removing the widget, but not yet exiting the interpreter.
### Response:
def delete(self):
"""
Deletes all layers with... |
def _write_csv(self, datasets, filename):
"""
Write CSV
:param datasets: Datasets
:param filename: File Name
"""
with open('/'.join([self.output, filename]), mode='w', encoding=self.encoding) as write_file:
writer = csv.writer(write_file, delimiter=',')
... | Write CSV
:param datasets: Datasets
:param filename: File Name | Below is the the instruction that describes the task:
### Input:
Write CSV
:param datasets: Datasets
:param filename: File Name
### Response:
def _write_csv(self, datasets, filename):
"""
Write CSV
:param datasets: Datasets
:param filename: File Name
"""
... |
def build_description(node=None):
"""Return a multi-line string describing a `logging_tree.nodes.Node`.
If no `node` argument is provided, then the entire tree of currently
active `logging` loggers is printed out.
"""
if node is None:
from logging_tree.nodes import tree
node = tree... | Return a multi-line string describing a `logging_tree.nodes.Node`.
If no `node` argument is provided, then the entire tree of currently
active `logging` loggers is printed out. | Below is the the instruction that describes the task:
### Input:
Return a multi-line string describing a `logging_tree.nodes.Node`.
If no `node` argument is provided, then the entire tree of currently
active `logging` loggers is printed out.
### Response:
def build_description(node=None):
"""Return a ... |
def match(self, ra1, dec1, ra2, dec2, radius, maxmatch=1, convertToArray=True):
"""*Crossmatch two lists of ra/dec points*
This is very efficient for large search angles and large lists. Note, if you need to match against the same points many times, you should use a `Matcher` object
**Key Argu... | *Crossmatch two lists of ra/dec points*
This is very efficient for large search angles and large lists. Note, if you need to match against the same points many times, you should use a `Matcher` object
**Key Arguments:**
- ``ra1`` -- list, numpy array or single ra value (first coordinate se... | Below is the the instruction that describes the task:
### Input:
*Crossmatch two lists of ra/dec points*
This is very efficient for large search angles and large lists. Note, if you need to match against the same points many times, you should use a `Matcher` object
**Key Arguments:**
-... |
def print_update(self, stream=sys.stdout, job_stats=None):
"""Print an update about the current number of jobs running """
if job_stats is None:
job_stats = JobStatusVector()
job_det_list = []
job_det_list += self._scatter_link.jobs.values()
for job_dets ... | Print an update about the current number of jobs running | Below is the the instruction that describes the task:
### Input:
Print an update about the current number of jobs running
### Response:
def print_update(self, stream=sys.stdout, job_stats=None):
"""Print an update about the current number of jobs running """
if job_stats is None:
job_st... |
def _search_for_export_symbols(self, matches):
''' Just encapsulating a search that takes place fairly often '''
pattern = '|'.join(re.escape(match) for match in matches)
exp = re.compile(pattern)
symbol_list = []
try:
for symbol in self.pefile_handle.DIRECTORY_ENTRY_... | Just encapsulating a search that takes place fairly often | Below is the the instruction that describes the task:
### Input:
Just encapsulating a search that takes place fairly often
### Response:
def _search_for_export_symbols(self, matches):
''' Just encapsulating a search that takes place fairly often '''
pattern = '|'.join(re.escape(match) for match in ... |
def _packb3(obj, **options):
"""
Serialize a Python object into MessagePack bytes.
Args:
obj: a Python object
Kwargs:
ext_handlers (dict): dictionary of Ext handlers, mapping a custom type
to a callable that packs an instance of the type
... | Serialize a Python object into MessagePack bytes.
Args:
obj: a Python object
Kwargs:
ext_handlers (dict): dictionary of Ext handlers, mapping a custom type
to a callable that packs an instance of the type
into an Ext object
forc... | Below is the the instruction that describes the task:
### Input:
Serialize a Python object into MessagePack bytes.
Args:
obj: a Python object
Kwargs:
ext_handlers (dict): dictionary of Ext handlers, mapping a custom type
to a callable that packs an instance of ... |
def generate_simple_call(opcode: int, index: int):
"""
Generates a simple call, with an index for something.
:param opcode: The opcode to generate.
:param index: The index to use as an argument.
:return:
"""
bs = b""
# add the opcode
bs += opcode.to_bytes(1, byteorder="little")
... | Generates a simple call, with an index for something.
:param opcode: The opcode to generate.
:param index: The index to use as an argument.
:return: | Below is the the instruction that describes the task:
### Input:
Generates a simple call, with an index for something.
:param opcode: The opcode to generate.
:param index: The index to use as an argument.
:return:
### Response:
def generate_simple_call(opcode: int, index: int):
"""
Generates a... |
def _generate_report(self):
""" Generates the visual report """
from niworkflows.viz.utils import plot_registration
NIWORKFLOWS_LOG.info('Generating visual report')
anat = load_img(self._anat_file)
contour_nii = load_img(self._contour) if self._contour is not None else None
... | Generates the visual report | Below is the the instruction that describes the task:
### Input:
Generates the visual report
### Response:
def _generate_report(self):
""" Generates the visual report """
from niworkflows.viz.utils import plot_registration
NIWORKFLOWS_LOG.info('Generating visual report')
anat = loa... |
def getActiveSession(cls):
"""
Returns the active SparkSession for the current thread, returned by the builder.
>>> s = SparkSession.getActiveSession()
>>> l = [('Alice', 1)]
>>> rdd = s.sparkContext.parallelize(l)
>>> df = s.createDataFrame(rdd, ['name', 'age'])
... | Returns the active SparkSession for the current thread, returned by the builder.
>>> s = SparkSession.getActiveSession()
>>> l = [('Alice', 1)]
>>> rdd = s.sparkContext.parallelize(l)
>>> df = s.createDataFrame(rdd, ['name', 'age'])
>>> df.select("age").collect()
[Row(age... | Below is the the instruction that describes the task:
### Input:
Returns the active SparkSession for the current thread, returned by the builder.
>>> s = SparkSession.getActiveSession()
>>> l = [('Alice', 1)]
>>> rdd = s.sparkContext.parallelize(l)
>>> df = s.createDataFrame(rdd, ['n... |
def get(self):
"""
*get the conversions object*
**Return:**
- ``conversions``
.. todo::
- @review: when complete, clean get method
- @review: when complete add logging
"""
self.log.info('starting the ``get`` method')
convers... | *get the conversions object*
**Return:**
- ``conversions``
.. todo::
- @review: when complete, clean get method
- @review: when complete add logging | Below is the the instruction that describes the task:
### Input:
*get the conversions object*
**Return:**
- ``conversions``
.. todo::
- @review: when complete, clean get method
- @review: when complete add logging
### Response:
def get(self):
"""
... |
def change(governor, freq=None):
"""
change function
"""
cpu_number = 0
while True:
try:
subprocess.check_output([
"sudo", "bash", "-c",
"echo {governor} > {CPU_PREFIX}cpu{cpu_number}/cpufreq/scaling_governor"
.format(governor=gove... | change function | Below is the the instruction that describes the task:
### Input:
change function
### Response:
def change(governor, freq=None):
"""
change function
"""
cpu_number = 0
while True:
try:
subprocess.check_output([
"sudo", "bash", "-c",
"echo {gov... |
def import_file(self, ):
"""Import a file
:returns: None
:rtype: None
:raises: NotImplementedError
"""
tfi = self.get_taskfileinfo_selection()
if tfi:
self.reftrack.import_file(tfi) | Import a file
:returns: None
:rtype: None
:raises: NotImplementedError | Below is the the instruction that describes the task:
### Input:
Import a file
:returns: None
:rtype: None
:raises: NotImplementedError
### Response:
def import_file(self, ):
"""Import a file
:returns: None
:rtype: None
:raises: NotImplementedError
... |
def in_ellipsoid(x, A, c):
"""
Determines which of the points ``x`` are in the
closed ellipsoid with shape matrix ``A`` centered at ``c``.
For a single point ``x``, this is computed as
.. math::
(c-x)^T\cdot A^{-1}\cdot (c-x) \leq 1
:param np.ndarray x: Shape ``(n_points, dim)`... | Determines which of the points ``x`` are in the
closed ellipsoid with shape matrix ``A`` centered at ``c``.
For a single point ``x``, this is computed as
.. math::
(c-x)^T\cdot A^{-1}\cdot (c-x) \leq 1
:param np.ndarray x: Shape ``(n_points, dim)`` or ``n_points``.
:param np.ndarra... | Below is the the instruction that describes the task:
### Input:
Determines which of the points ``x`` are in the
closed ellipsoid with shape matrix ``A`` centered at ``c``.
For a single point ``x``, this is computed as
.. math::
(c-x)^T\cdot A^{-1}\cdot (c-x) \leq 1
:param np.ndarr... |
def get_list_objects_arg_dict(self, node_type):
"""Create a dict of arguments that will be passed to listObjects().
If {node_type} is a CN, add filtering to include only objects from this GMN
instance in the ObjectList returned by CNCore.listObjects().
"""
arg_dict = {
... | Create a dict of arguments that will be passed to listObjects().
If {node_type} is a CN, add filtering to include only objects from this GMN
instance in the ObjectList returned by CNCore.listObjects(). | Below is the the instruction that describes the task:
### Input:
Create a dict of arguments that will be passed to listObjects().
If {node_type} is a CN, add filtering to include only objects from this GMN
instance in the ObjectList returned by CNCore.listObjects().
### Response:
def get_list_obje... |
def _filter_extras(dm):
"""
Given a mapping of extras to dependencies, strip off
environment markers and filter out any dependencies
not matching the markers.
"""
for extra in list(filter(None, dm)):
new_extra = extra
reqs = dm.pop(extra)
... | Given a mapping of extras to dependencies, strip off
environment markers and filter out any dependencies
not matching the markers. | Below is the the instruction that describes the task:
### Input:
Given a mapping of extras to dependencies, strip off
environment markers and filter out any dependencies
not matching the markers.
### Response:
def _filter_extras(dm):
"""
Given a mapping of extras to dependencies, st... |
def unicode_compact(func):
"""
Make sure the first parameter of the decorated method to be a unicode
object.
"""
@wraps(func)
def wrapped(self, text, *a, **kw):
if not isinstance(text, six.text_type):
text = text.decode('utf-8')
return func(self, text, *a, **kw)
... | Make sure the first parameter of the decorated method to be a unicode
object. | Below is the the instruction that describes the task:
### Input:
Make sure the first parameter of the decorated method to be a unicode
object.
### Response:
def unicode_compact(func):
"""
Make sure the first parameter of the decorated method to be a unicode
object.
"""
@wraps(func)
def... |
def dict_merged(d, _filter=None, **kw):
"""Update dictionary d with the items passed as kw if the value passes _filter."""
def f(s):
if _filter:
return _filter(s)
return s is not None
d = d or {}
for k, v in iteritems(kw):
if f(v):
d[k] = v
return d | Update dictionary d with the items passed as kw if the value passes _filter. | Below is the the instruction that describes the task:
### Input:
Update dictionary d with the items passed as kw if the value passes _filter.
### Response:
def dict_merged(d, _filter=None, **kw):
"""Update dictionary d with the items passed as kw if the value passes _filter."""
def f(s):
if _filter... |
def plan_branches(self, plan_key, expand=None, favourite=False, clover_enabled=False, max_results=25):
"""api/1.0/plan/{projectKey}-{buildKey}/branch"""
resource = 'plan/{}/branch'.format(plan_key)
return self.base_list_call(resource, expand, favourite, clover_enabled, max_results,
... | api/1.0/plan/{projectKey}-{buildKey}/branch | Below is the the instruction that describes the task:
### Input:
api/1.0/plan/{projectKey}-{buildKey}/branch
### Response:
def plan_branches(self, plan_key, expand=None, favourite=False, clover_enabled=False, max_results=25):
"""api/1.0/plan/{projectKey}-{buildKey}/branch"""
resource = 'plan/{}/bra... |
def create_parameter_group(name, db_parameter_group_family, description,
tags=None, region=None, key=None, keyid=None,
profile=None):
'''
Create an RDS parameter group
CLI example to create an RDS parameter group::
salt myminion boto_rds.create... | Create an RDS parameter group
CLI example to create an RDS parameter group::
salt myminion boto_rds.create_parameter_group my-param-group mysql5.6 \
"group description" | Below is the the instruction that describes the task:
### Input:
Create an RDS parameter group
CLI example to create an RDS parameter group::
salt myminion boto_rds.create_parameter_group my-param-group mysql5.6 \
"group description"
### Response:
def create_parameter_group(name, db_p... |
def read_internal_strain_tensor(self):
"""
Reads the internal strain tensor and populates self.internal_strain_tensor with an array of voigt notation
tensors for each site.
"""
search = []
def internal_strain_start(results, match):
results.internal_strain... | Reads the internal strain tensor and populates self.internal_strain_tensor with an array of voigt notation
tensors for each site. | Below is the the instruction that describes the task:
### Input:
Reads the internal strain tensor and populates self.internal_strain_tensor with an array of voigt notation
tensors for each site.
### Response:
def read_internal_strain_tensor(self):
"""
Reads the internal strain tensor an... |
def check_direct_mode_cluster_definition(cluster, config_path):
'''
Check the cluster definition for direct mode
:param cluster:
:param config_path:
:return:
'''
config_path = config.get_heron_cluster_conf_dir(cluster, config_path)
if not os.path.isdir(config_path):
return False
return True | Check the cluster definition for direct mode
:param cluster:
:param config_path:
:return: | Below is the the instruction that describes the task:
### Input:
Check the cluster definition for direct mode
:param cluster:
:param config_path:
:return:
### Response:
def check_direct_mode_cluster_definition(cluster, config_path):
'''
Check the cluster definition for direct mode
:param cluster:
:pa... |
def earth_rates(ATTITUDE):
'''return angular velocities in earth frame'''
from math import sin, cos, tan, fabs
p = ATTITUDE.rollspeed
q = ATTITUDE.pitchspeed
r = ATTITUDE.yawspeed
phi = ATTITUDE.roll
theta = ATTITUDE.pitch
psi = ATTITUDE.yaw
phiDot = p + tan(theta... | return angular velocities in earth frame | Below is the the instruction that describes the task:
### Input:
return angular velocities in earth frame
### Response:
def earth_rates(ATTITUDE):
'''return angular velocities in earth frame'''
from math import sin, cos, tan, fabs
p = ATTITUDE.rollspeed
q = ATTITUDE.pitchspeed
r = ... |
def do_one_iteration(self):
"""step eventloop just once"""
if self.control_stream:
self.control_stream.flush()
for stream in self.shell_streams:
# handle at most one request per iteration
stream.flush(zmq.POLLIN, 1)
stream.flush(zmq.POLLOUT) | step eventloop just once | Below is the the instruction that describes the task:
### Input:
step eventloop just once
### Response:
def do_one_iteration(self):
"""step eventloop just once"""
if self.control_stream:
self.control_stream.flush()
for stream in self.shell_streams:
# handle at most o... |
def multipoint(self, points):
"""Creates a MULTIPOINT shape.
Points is a list of xy values."""
shapeType = MULTIPOINT
points = [points] # nest the points inside a list to be compatible with the generic shapeparts method
self._shapeparts(parts=points, shapeType=shapeType) | Creates a MULTIPOINT shape.
Points is a list of xy values. | Below is the the instruction that describes the task:
### Input:
Creates a MULTIPOINT shape.
Points is a list of xy values.
### Response:
def multipoint(self, points):
"""Creates a MULTIPOINT shape.
Points is a list of xy values."""
shapeType = MULTIPOINT
points = [poin... |
def get_project_by_name(project_name,**kwargs):
"""
get a project complexmodel
"""
user_id = kwargs.get('user_id')
projects_i = db.DBSession.query(Project).join(ProjectOwner).filter(
Project.name==project_name,
... | get a project complexmodel | Below is the the instruction that describes the task:
### Input:
get a project complexmodel
### Response:
def get_project_by_name(project_name,**kwargs):
"""
get a project complexmodel
"""
user_id = kwargs.get('user_id')
projects_i = db.DBSession.query(Project).join(ProjectOwner).filter(
... |
def run(self, resources):
"""Sets the RTC timestamp to UTC.
Args:
resources (dict): A dictionary containing the required resources that
we needed access to in order to perform this step.
"""
hwman = resources['connection']
con = hwman.hwman.controller... | Sets the RTC timestamp to UTC.
Args:
resources (dict): A dictionary containing the required resources that
we needed access to in order to perform this step. | Below is the the instruction that describes the task:
### Input:
Sets the RTC timestamp to UTC.
Args:
resources (dict): A dictionary containing the required resources that
we needed access to in order to perform this step.
### Response:
def run(self, resources):
"""Sets... |
def sanitize(filename: str, platform: str=None) -> str:
"""
Remove disallowed characters from potential filename. Currently only guaranteed on Linux and
OS X.
"""
win_map = {
# taken from samba Catia module.
# https://www.samba.org/samba/docs/current/man-html/vfs_catia.8.html
... | Remove disallowed characters from potential filename. Currently only guaranteed on Linux and
OS X. | Below is the the instruction that describes the task:
### Input:
Remove disallowed characters from potential filename. Currently only guaranteed on Linux and
OS X.
### Response:
def sanitize(filename: str, platform: str=None) -> str:
"""
Remove disallowed characters from potential filename. Currently o... |
def _get_included_file_path(self, user_specified_path: str, current_processed_file_path: Path) -> Path:
'''Resolve user specified path to the local included file.
:param user_specified_path: User specified string that represents
the path to a local file
:param current_processed_fil... | Resolve user specified path to the local included file.
:param user_specified_path: User specified string that represents
the path to a local file
:param current_processed_file_path: Path to the currently processed Markdown file
that contains include statements
:return... | Below is the the instruction that describes the task:
### Input:
Resolve user specified path to the local included file.
:param user_specified_path: User specified string that represents
the path to a local file
:param current_processed_file_path: Path to the currently processed Markdo... |
def get_center_from_json(cls, data):
"""
Get center information from json data
:param data: json data
:return: tuple with two elements: lat and lon
:rtype: tuple
"""
center_lat = None
center_lon = None
center = data.get("center")
if isinst... | Get center information from json data
:param data: json data
:return: tuple with two elements: lat and lon
:rtype: tuple | Below is the the instruction that describes the task:
### Input:
Get center information from json data
:param data: json data
:return: tuple with two elements: lat and lon
:rtype: tuple
### Response:
def get_center_from_json(cls, data):
"""
Get center information from json ... |
def timezone(self):
"""
timezone of GSSHA model
"""
if self._tz is None:
# GET CENTROID FROM GSSHA GRID
cen_lat, cen_lon = self.centerLatLon()
# update time zone
tf = TimezoneFinder()
tz_name = tf.timezone_at(lng=cen_lon, lat=ce... | timezone of GSSHA model | Below is the the instruction that describes the task:
### Input:
timezone of GSSHA model
### Response:
def timezone(self):
"""
timezone of GSSHA model
"""
if self._tz is None:
# GET CENTROID FROM GSSHA GRID
cen_lat, cen_lon = self.centerLatLon()
#... |
def _is_detach_necessary(cls):
"""Check if detaching the process is even necessary."""
if os.getppid() == 1:
# Process was started by init
return False
if cls._is_socket(sys.stdin):
# If STDIN is a socket, the daemon was started by a super-server
... | Check if detaching the process is even necessary. | Below is the the instruction that describes the task:
### Input:
Check if detaching the process is even necessary.
### Response:
def _is_detach_necessary(cls):
"""Check if detaching the process is even necessary."""
if os.getppid() == 1:
# Process was started by init
return ... |
def referencesGenerator(self, request):
"""
Returns a generator over the (reference, nextPageToken) pairs
defined by the specified request.
"""
referenceSet = self.getDataRepository().getReferenceSet(
request.reference_set_id)
results = []
for obj in r... | Returns a generator over the (reference, nextPageToken) pairs
defined by the specified request. | Below is the the instruction that describes the task:
### Input:
Returns a generator over the (reference, nextPageToken) pairs
defined by the specified request.
### Response:
def referencesGenerator(self, request):
"""
Returns a generator over the (reference, nextPageToken) pairs
de... |
def verify1(self, credentials, session_pub_key, encrypted):
"""First verification step."""
# No additional hashing used
self._shared = self._verify_private.get_shared_key(
curve25519.Public(session_pub_key), hashfunc=lambda x: x)
session_key = hkdf_expand('Pair-Verify-Encryp... | First verification step. | Below is the the instruction that describes the task:
### Input:
First verification step.
### Response:
def verify1(self, credentials, session_pub_key, encrypted):
"""First verification step."""
# No additional hashing used
self._shared = self._verify_private.get_shared_key(
cur... |
def get_session_identifiers(cls, folder=None, inputfile=None):
""" Retrieve the list of session identifiers contained in the
data on the folder.
:kwarg folder: the path to the folder containing the files to
check. This folder may contain sub-folders.
:kwarg inputfile: the pa... | Retrieve the list of session identifiers contained in the
data on the folder.
:kwarg folder: the path to the folder containing the files to
check. This folder may contain sub-folders.
:kwarg inputfile: the path to the input file to use | Below is the the instruction that describes the task:
### Input:
Retrieve the list of session identifiers contained in the
data on the folder.
:kwarg folder: the path to the folder containing the files to
check. This folder may contain sub-folders.
:kwarg inputfile: the path to ... |
def publish_featuretype(self, name, store, native_crs, srs=None, jdbc_virtual_table=None, native_name=None):
'''Publish a featuretype from data in an existing store'''
# @todo native_srs doesn't seem to get detected, even when in the DB
# metadata (at least for postgis in geometry_columns) and t... | Publish a featuretype from data in an existing store | Below is the the instruction that describes the task:
### Input:
Publish a featuretype from data in an existing store
### Response:
def publish_featuretype(self, name, store, native_crs, srs=None, jdbc_virtual_table=None, native_name=None):
'''Publish a featuretype from data in an existing store'''
... |
def check_auth(username, password):
"""Check if a username / password combination is valid."""
legal_hashes = [
"15a7fdade5fa58d38c6d400770e5c0e948fbc03ba365b704a6d205687738ae46",
"057b24043181523e3c3717071953c575bd13862517a8ce228601582a9cbd9dae",
"c8d79ae7d388b6da21cb982a819065b18941925... | Check if a username / password combination is valid. | Below is the the instruction that describes the task:
### Input:
Check if a username / password combination is valid.
### Response:
def check_auth(username, password):
"""Check if a username / password combination is valid."""
legal_hashes = [
"15a7fdade5fa58d38c6d400770e5c0e948fbc03ba365b704a6d205... |
def is_active(self):
"""The audio plugin is active iff any run has at least one relevant tag."""
if not self._multiplexer:
return False
return bool(self._multiplexer.PluginRunToTagToContent(metadata.PLUGIN_NAME)) | The audio plugin is active iff any run has at least one relevant tag. | Below is the the instruction that describes the task:
### Input:
The audio plugin is active iff any run has at least one relevant tag.
### Response:
def is_active(self):
"""The audio plugin is active iff any run has at least one relevant tag."""
if not self._multiplexer:
return False
return bool(... |
def get_all_activities(self, autoscale_group, activity_ids=None,
max_records=None, next_token=None):
"""
Get all activities for the given autoscaling group.
This action supports pagination by returning a token if there are more
pages to retrieve. To get the ne... | Get all activities for the given autoscaling group.
This action supports pagination by returning a token if there are more
pages to retrieve. To get the next page, call this action again with
the returned token as the NextToken parameter
:type autoscale_group: str or
:class... | Below is the the instruction that describes the task:
### Input:
Get all activities for the given autoscaling group.
This action supports pagination by returning a token if there are more
pages to retrieve. To get the next page, call this action again with
the returned token as the NextToke... |
def _complete_string(key, haystack):
""" Returns valid string completions
Takes the string 'key' and compares it to each of the strings in
'haystack'. The ones which beginns with 'key' are returned as result.
"""
if len(key) == 0:
return haystack
match = []
for straw in ha... | Returns valid string completions
Takes the string 'key' and compares it to each of the strings in
'haystack'. The ones which beginns with 'key' are returned as result. | Below is the the instruction that describes the task:
### Input:
Returns valid string completions
Takes the string 'key' and compares it to each of the strings in
'haystack'. The ones which beginns with 'key' are returned as result.
### Response:
def _complete_string(key, haystack):
""" Return... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.