code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def _check_realign(data):
"""Check for realignment, which is not supported in GATK4
"""
if "gatk4" not in data["algorithm"].get("tools_off", []) and not "gatk4" == data["algorithm"].get("tools_off"):
if data["algorithm"].get("realign"):
raise ValueError("In sample %s, realign specified b... | Check for realignment, which is not supported in GATK4 | Below is the the instruction that describes the task:
### Input:
Check for realignment, which is not supported in GATK4
### Response:
def _check_realign(data):
"""Check for realignment, which is not supported in GATK4
"""
if "gatk4" not in data["algorithm"].get("tools_off", []) and not "gatk4" == data[... |
def http_method_not_allowed(self, *args, **kwargs):
"""
Returns super after setting the Content-Type header to
``application/json``
"""
resp = super(JsonResponseMixin, self).http_method_not_allowed(*args, **kwargs)
resp['Content-Type'] = 'application/json'
return... | Returns super after setting the Content-Type header to
``application/json`` | Below is the the instruction that describes the task:
### Input:
Returns super after setting the Content-Type header to
``application/json``
### Response:
def http_method_not_allowed(self, *args, **kwargs):
"""
Returns super after setting the Content-Type header to
``application/jso... |
def update_tile_extent_bounds(self):
"""
Updates the :attr:`tile_beg_min` and :attr:`tile_end_max`
data members according to :attr:`tile_bounds_policy`.
"""
if self.tile_bounds_policy == NO_BOUNDS:
self.tile_beg_min = self.array_start - self.halo[:, 0]
se... | Updates the :attr:`tile_beg_min` and :attr:`tile_end_max`
data members according to :attr:`tile_bounds_policy`. | Below is the the instruction that describes the task:
### Input:
Updates the :attr:`tile_beg_min` and :attr:`tile_end_max`
data members according to :attr:`tile_bounds_policy`.
### Response:
def update_tile_extent_bounds(self):
"""
Updates the :attr:`tile_beg_min` and :attr:`tile_end_max`
... |
def _save(self, data):
"""
Take the data from a dict and commit them to appropriate attributes.
"""
self.state = data.get('state')
self.created = dt_time(data.get('created'))
self.updated = dt_time(data.get('updated')) | Take the data from a dict and commit them to appropriate attributes. | Below is the the instruction that describes the task:
### Input:
Take the data from a dict and commit them to appropriate attributes.
### Response:
def _save(self, data):
"""
Take the data from a dict and commit them to appropriate attributes.
"""
self.state = data.get('state')
... |
def _add_state_callback(self, state_id, state):
""" Save summarize(state) on policy shared context before
the state is stored
"""
summary = self.summarize(state)
if summary is None:
return
with self.locked_context('summaries', dict) as ctx:
ctx... | Save summarize(state) on policy shared context before
the state is stored | Below is the the instruction that describes the task:
### Input:
Save summarize(state) on policy shared context before
the state is stored
### Response:
def _add_state_callback(self, state_id, state):
""" Save summarize(state) on policy shared context before
the state is stored
... |
def initialize(state):
"""
Synchronize the stack and register state (manticore->qemu)
"""
logger.debug(f"Copying {stack_top - state.cpu.SP} bytes in the stack..")
stack_bottom = min(state.cpu.SP, gdb.getR('SP'))
for address in range(stack_bottom, stack_top):
b = state.cpu.read_int(addres... | Synchronize the stack and register state (manticore->qemu) | Below is the the instruction that describes the task:
### Input:
Synchronize the stack and register state (manticore->qemu)
### Response:
def initialize(state):
"""
Synchronize the stack and register state (manticore->qemu)
"""
logger.debug(f"Copying {stack_top - state.cpu.SP} bytes in the stack.."... |
def format_sync_stats(self, cnt):
'''
Format stats of the sync output.
:param cnt:
:return:
'''
stats = salt.utils.odict.OrderedDict()
if cnt.get('retcode') == salt.defaults.exitcodes.EX_OK:
for line in cnt.get('stdout', '').split(os.linesep):
... | Format stats of the sync output.
:param cnt:
:return: | Below is the the instruction that describes the task:
### Input:
Format stats of the sync output.
:param cnt:
:return:
### Response:
def format_sync_stats(self, cnt):
'''
Format stats of the sync output.
:param cnt:
:return:
'''
stats = salt.utils.o... |
def delete_user_by_email(self, id, email):
"""Deletes a specified connection user by its email.
Args:
id (str): The id of the connection (must be a database connection).
email (str): The email of the user to delete.
See: https://auth0.com/docs/api/management/v2#!/Connect... | Deletes a specified connection user by its email.
Args:
id (str): The id of the connection (must be a database connection).
email (str): The email of the user to delete.
See: https://auth0.com/docs/api/management/v2#!/Connections/delete_users_by_email
Returns:
... | Below is the the instruction that describes the task:
### Input:
Deletes a specified connection user by its email.
Args:
id (str): The id of the connection (must be a database connection).
email (str): The email of the user to delete.
See: https://auth0.com/docs/api/manageme... |
def get_formset(self, request, obj=None, **kwargs):
"""
Return a form, if the obj has a staffmember object, otherwise
return an empty form
"""
if obj is not None and self.model.objects.filter(user=obj).count():
return super(StaffMemberAdmin, self).get_formset(
... | Return a form, if the obj has a staffmember object, otherwise
return an empty form | Below is the the instruction that describes the task:
### Input:
Return a form, if the obj has a staffmember object, otherwise
return an empty form
### Response:
def get_formset(self, request, obj=None, **kwargs):
"""
Return a form, if the obj has a staffmember object, otherwise
ret... |
def _parse_residue(self, residue):
"""
Extracts Residue Name, Number, Chain, Model, Atoms.
I/O: xml object <response> / dictionary
"""
# Filter Element Nodes
childs = [ child for child in residue.childNodes if child.nodeType == child.ELEMENT_NODE ]
... | Extracts Residue Name, Number, Chain, Model, Atoms.
I/O: xml object <response> / dictionary | Below is the the instruction that describes the task:
### Input:
Extracts Residue Name, Number, Chain, Model, Atoms.
I/O: xml object <response> / dictionary
### Response:
def _parse_residue(self, residue):
"""
Extracts Residue Name, Number, Chain, Model, Atoms.
I/O: xml object <resp... |
def update_client_grants(self, client_id, scope=[], authorities=[],
grant_types=[], redirect_uri=[], replace=False):
"""
Will extend the client with additional scopes or
authorities. Any existing scopes and authorities will be left
as is unless asked to replace entirely.
... | Will extend the client with additional scopes or
authorities. Any existing scopes and authorities will be left
as is unless asked to replace entirely. | Below is the the instruction that describes the task:
### Input:
Will extend the client with additional scopes or
authorities. Any existing scopes and authorities will be left
as is unless asked to replace entirely.
### Response:
def update_client_grants(self, client_id, scope=[], authorities=[],
... |
def _compute_transitions(self, corpus, order=1):
""" Computes the transition probabilities of a corpus
Args:
corpus: the given corpus (a corpus_entry needs to be iterable)
order: the maximal Markov chain order
"""
self.transitions = defaultdict(lambda: defaultdict... | Computes the transition probabilities of a corpus
Args:
corpus: the given corpus (a corpus_entry needs to be iterable)
order: the maximal Markov chain order | Below is the the instruction that describes the task:
### Input:
Computes the transition probabilities of a corpus
Args:
corpus: the given corpus (a corpus_entry needs to be iterable)
order: the maximal Markov chain order
### Response:
def _compute_transitions(self, corpus, order=1)... |
def mutate(self, field):
"""Mutate the given field, modifying it directly. This is not
intended to preserve the value of the field.
:field: The pfp.fields.Field instance that will receive the new value
"""
new_val = self.next_val(field)
field._pfp__set_value(new_val)
... | Mutate the given field, modifying it directly. This is not
intended to preserve the value of the field.
:field: The pfp.fields.Field instance that will receive the new value | Below is the the instruction that describes the task:
### Input:
Mutate the given field, modifying it directly. This is not
intended to preserve the value of the field.
:field: The pfp.fields.Field instance that will receive the new value
### Response:
def mutate(self, field):
"""Mutate th... |
def contour(self, level):
"""Get contour lines at the given level.
Parameters
----------
level : numbers.Number
The data level to calculate the contour lines for.
Returns
-------
:
The result of the :attr:`formatter` called on the contour... | Get contour lines at the given level.
Parameters
----------
level : numbers.Number
The data level to calculate the contour lines for.
Returns
-------
:
The result of the :attr:`formatter` called on the contour at the
given `level`. | Below is the the instruction that describes the task:
### Input:
Get contour lines at the given level.
Parameters
----------
level : numbers.Number
The data level to calculate the contour lines for.
Returns
-------
:
The result of the :attr:`... |
def get_colors(catalog):
"""
Pull colors from catalog
Parameters
----------
catalog: filename
"""
print("Get Colors")
a = pyfits.open(catalog)
data = a[1].data
a.close()
all_ids = data['LAMOST_ID_1']
all_ids = np.array([val.strip() for val in all_ids])
# G magnitude... | Pull colors from catalog
Parameters
----------
catalog: filename | Below is the the instruction that describes the task:
### Input:
Pull colors from catalog
Parameters
----------
catalog: filename
### Response:
def get_colors(catalog):
"""
Pull colors from catalog
Parameters
----------
catalog: filename
"""
print("Get Colors")
a = py... |
def save_json(data, json_file, indent=4, **kwargs):
"""
Takes a dictionary and saves it to a file as JSON
.. code:: python
my_dict = {"key_1": "val_1",
"key_for_dict": {"sub_dict_key": 8}}
reusables.save_json(my_dict,"example.json")
example.json
.. code::
... | Takes a dictionary and saves it to a file as JSON
.. code:: python
my_dict = {"key_1": "val_1",
"key_for_dict": {"sub_dict_key": 8}}
reusables.save_json(my_dict,"example.json")
example.json
.. code::
{
"key_1": "val_1",
"key_for_dict":... | Below is the the instruction that describes the task:
### Input:
Takes a dictionary and saves it to a file as JSON
.. code:: python
my_dict = {"key_1": "val_1",
"key_for_dict": {"sub_dict_key": 8}}
reusables.save_json(my_dict,"example.json")
example.json
.. code::... |
def query(self, action=None):
"""
returns cached query string (without &format=json) for given action,
or list of cached actions
"""
if action in self.cache:
return self.cache[action]['query'].replace('&format=json', '')
return self.cache.keys() or None | returns cached query string (without &format=json) for given action,
or list of cached actions | Below is the the instruction that describes the task:
### Input:
returns cached query string (without &format=json) for given action,
or list of cached actions
### Response:
def query(self, action=None):
"""
returns cached query string (without &format=json) for given action,
or lis... |
def before_request(self, func: Callable, name: AppOrBlueprintKey=None) -> Callable:
"""Add a before request function.
This is designed to be used as a decorator. An example usage,
.. code-block:: python
@app.before_request
def func():
...
Argum... | Add a before request function.
This is designed to be used as a decorator. An example usage,
.. code-block:: python
@app.before_request
def func():
...
Arguments:
func: The before request function itself.
name: Optional blueprin... | Below is the the instruction that describes the task:
### Input:
Add a before request function.
This is designed to be used as a decorator. An example usage,
.. code-block:: python
@app.before_request
def func():
...
Arguments:
func: Th... |
def save_cb(self, mode):
"""Save image, figure, and plot data arrays."""
# This just defines the basename.
# Extension has to be explicitly defined or things can get messy.
w = Widgets.SaveDialog(title='Save {0} data'.format(mode))
filename = w.get_path()
if filename is... | Save image, figure, and plot data arrays. | Below is the the instruction that describes the task:
### Input:
Save image, figure, and plot data arrays.
### Response:
def save_cb(self, mode):
"""Save image, figure, and plot data arrays."""
# This just defines the basename.
# Extension has to be explicitly defined or things can get mes... |
def anonymous_login(self):
"""Login as anonymous user
:return: logon result, see `CMsgClientLogonResponse.eresult <https://github.com/ValvePython/steam/blob/513c68ca081dc9409df932ad86c66100164380a6/protobufs/steammessages_clientserver.proto#L95-L118>`_
:rtype: :class:`.EResult`
"""
... | Login as anonymous user
:return: logon result, see `CMsgClientLogonResponse.eresult <https://github.com/ValvePython/steam/blob/513c68ca081dc9409df932ad86c66100164380a6/protobufs/steammessages_clientserver.proto#L95-L118>`_
:rtype: :class:`.EResult` | Below is the the instruction that describes the task:
### Input:
Login as anonymous user
:return: logon result, see `CMsgClientLogonResponse.eresult <https://github.com/ValvePython/steam/blob/513c68ca081dc9409df932ad86c66100164380a6/protobufs/steammessages_clientserver.proto#L95-L118>`_
:rtype: :cl... |
def colour_for_wp(self, wp_num):
'''return a tuple describing the colour a waypoint should appear on the map'''
wp = self.module('wp').wploader.wp(wp_num)
command = wp.command
return self._colour_for_wp_command.get(command, (0,255,0)) | return a tuple describing the colour a waypoint should appear on the map | Below is the the instruction that describes the task:
### Input:
return a tuple describing the colour a waypoint should appear on the map
### Response:
def colour_for_wp(self, wp_num):
'''return a tuple describing the colour a waypoint should appear on the map'''
wp = self.module('wp').wploader.wp(... |
def createEncoder():
"""
Creates and returns a #MultiEncoder including a ScalarEncoder for
energy consumption and a DateEncoder for the time of the day.
@see nupic/encoders/__init__.py for type to file-name mapping
@see nupic/encoders for encoder source files
"""
encoder = MultiEncoder()
encoder.addMul... | Creates and returns a #MultiEncoder including a ScalarEncoder for
energy consumption and a DateEncoder for the time of the day.
@see nupic/encoders/__init__.py for type to file-name mapping
@see nupic/encoders for encoder source files | Below is the the instruction that describes the task:
### Input:
Creates and returns a #MultiEncoder including a ScalarEncoder for
energy consumption and a DateEncoder for the time of the day.
@see nupic/encoders/__init__.py for type to file-name mapping
@see nupic/encoders for encoder source files
### Respo... |
def unwrap(self, encrypted_data):
"""
Decrypts the data send by the server using the TLS channel negotiated
between the client and the server.
:param encrypted_data: the byte string of the encrypted data
:return: a byte string of the decrypted data
"""
length = s... | Decrypts the data send by the server using the TLS channel negotiated
between the client and the server.
:param encrypted_data: the byte string of the encrypted data
:return: a byte string of the decrypted data | Below is the the instruction that describes the task:
### Input:
Decrypts the data send by the server using the TLS channel negotiated
between the client and the server.
:param encrypted_data: the byte string of the encrypted data
:return: a byte string of the decrypted data
### Response:
... |
def get_vlan_assignment_uuid(self):
"""Returns the UUID for the region's vlan assignment on CVX
:returns: string containing the region's vlan assignment UUID
"""
vlan_uuid_cmd = self.cli_commands['resource-pool']
if vlan_uuid_cmd:
return self._run_eos_cmds(commands=v... | Returns the UUID for the region's vlan assignment on CVX
:returns: string containing the region's vlan assignment UUID | Below is the the instruction that describes the task:
### Input:
Returns the UUID for the region's vlan assignment on CVX
:returns: string containing the region's vlan assignment UUID
### Response:
def get_vlan_assignment_uuid(self):
"""Returns the UUID for the region's vlan assignment on CVX
... |
def get_fault_type_dummy_variables(self, rup):
"""
Fault-type classification dummy variable based on rup.rake.
"``H`` is 1 for a strike-slip mechanism and 0 for a reverse mechanism"
(p. 1201).
Note:
UserWarning is raised if mechanism is determined to be normal
... | Fault-type classification dummy variable based on rup.rake.
"``H`` is 1 for a strike-slip mechanism and 0 for a reverse mechanism"
(p. 1201).
Note:
UserWarning is raised if mechanism is determined to be normal
faulting, since as summarized in Table 2 on p. 1197 the data... | Below is the the instruction that describes the task:
### Input:
Fault-type classification dummy variable based on rup.rake.
"``H`` is 1 for a strike-slip mechanism and 0 for a reverse mechanism"
(p. 1201).
Note:
UserWarning is raised if mechanism is determined to be normal
... |
def error(self, message, payload=None):
"""DEPRECATED"""
self.set_tag('error', True)
if payload:
self.log(event=message, payload=payload)
else:
self.log(event=message)
return self | DEPRECATED | Below is the the instruction that describes the task:
### Input:
DEPRECATED
### Response:
def error(self, message, payload=None):
"""DEPRECATED"""
self.set_tag('error', True)
if payload:
self.log(event=message, payload=payload)
else:
self.log(event=message)
... |
def check_page_for_warnings(html: str) -> None:
"""
Checks if is any warnings on page if so raises an exception
"""
soup = BeautifulSoup(html, 'html.parser')
warnings = soup.find_all('div', {'class': 'service_msg_warning'})
if warnings:
exception_msg = '; '.join((warning.get_text() for w... | Checks if is any warnings on page if so raises an exception | Below is the the instruction that describes the task:
### Input:
Checks if is any warnings on page if so raises an exception
### Response:
def check_page_for_warnings(html: str) -> None:
"""
Checks if is any warnings on page if so raises an exception
"""
soup = BeautifulSoup(html, 'html.parser')
... |
def call_from_thread(self, fn):
"""Allow thread-safe calls to ioloop functions.
Uses add_callback if not in the IOLoop thread, otherwise calls
directly. Returns an already resolved `tornado.concurrent.Future` if in
ioloop, otherwise a `concurrent.Future`. Logs unhandled exceptions.
... | Allow thread-safe calls to ioloop functions.
Uses add_callback if not in the IOLoop thread, otherwise calls
directly. Returns an already resolved `tornado.concurrent.Future` if in
ioloop, otherwise a `concurrent.Future`. Logs unhandled exceptions.
Resolves with an exception if one occur... | Below is the the instruction that describes the task:
### Input:
Allow thread-safe calls to ioloop functions.
Uses add_callback if not in the IOLoop thread, otherwise calls
directly. Returns an already resolved `tornado.concurrent.Future` if in
ioloop, otherwise a `concurrent.Future`. Logs ... |
def crashlog_clean(name, timestamp, size, **kwargs):
"""
For application NAME leave SIZE crashlogs or remove all crashlogs with timestamp > TIMESTAMP.
"""
ctx = Context(**kwargs)
ctx.execute_action('crashlog:clean', **{
'storage': ctx.repo.create_secure_service('storage'),
'name': na... | For application NAME leave SIZE crashlogs or remove all crashlogs with timestamp > TIMESTAMP. | Below is the the instruction that describes the task:
### Input:
For application NAME leave SIZE crashlogs or remove all crashlogs with timestamp > TIMESTAMP.
### Response:
def crashlog_clean(name, timestamp, size, **kwargs):
"""
For application NAME leave SIZE crashlogs or remove all crashlogs with timest... |
def prep_search_string(self, search_string, add_wildcards=False):
"""Prepares search string as a proper whoosh search string.
Args:
search_string (str): it prepares the search string and see if
the lenght is correct.
Optional Args:
add_wildcards (bool): It runs a query for inexact quer... | Prepares search string as a proper whoosh search string.
Args:
search_string (str): it prepares the search string and see if
the lenght is correct.
Optional Args:
add_wildcards (bool): It runs a query for inexact queries.
Raises:
ValueError: When the search string does not have ... | Below is the the instruction that describes the task:
### Input:
Prepares search string as a proper whoosh search string.
Args:
search_string (str): it prepares the search string and see if
the lenght is correct.
Optional Args:
add_wildcards (bool): It runs a query for inexact queries.... |
def _check_feature_dependences(self):
"""Verify feature dependences."""
for mid in self.modules:
for fst in self.modules[mid].statement.find_all("feature"):
fn, fid = self.resolve_pname(fst.argument, mid)
if fn not in self.modules[fid].features:
... | Verify feature dependences. | Below is the the instruction that describes the task:
### Input:
Verify feature dependences.
### Response:
def _check_feature_dependences(self):
"""Verify feature dependences."""
for mid in self.modules:
for fst in self.modules[mid].statement.find_all("feature"):
fn, fid... |
def visit_yield(self, node, parent):
"""visit a Yield node by returning a fresh instance of it"""
newnode = nodes.Yield(node.lineno, node.col_offset, parent)
if node.value is not None:
newnode.postinit(self.visit(node.value, newnode))
return newnode | visit a Yield node by returning a fresh instance of it | Below is the the instruction that describes the task:
### Input:
visit a Yield node by returning a fresh instance of it
### Response:
def visit_yield(self, node, parent):
"""visit a Yield node by returning a fresh instance of it"""
newnode = nodes.Yield(node.lineno, node.col_offset, parent)
... |
def get_stoch(self, symbol, interval='daily', fastkperiod=None,
slowkperiod=None, slowdperiod=None, slowkmatype=None, slowdmatype=None):
""" Return the stochatic oscillator values in two
json objects as data and meta_data. It raises ValueError when problems
arise
Keywo... | Return the stochatic oscillator values in two
json objects as data and meta_data. It raises ValueError when problems
arise
Keyword Arguments:
symbol: the symbol for the equity we want to get its data
interval: time interval between two conscutive values,
... | Below is the the instruction that describes the task:
### Input:
Return the stochatic oscillator values in two
json objects as data and meta_data. It raises ValueError when problems
arise
Keyword Arguments:
symbol: the symbol for the equity we want to get its data
i... |
def load_core_file(core_fp):
"""
For core OTU data file, returns Genus-species identifier for each data
entry.
:type core_fp: str
:param core_fp: A file containing core OTU data.
:rtype: str
:return: Returns genus-species identifier based on identified taxonomical
level.
"""... | For core OTU data file, returns Genus-species identifier for each data
entry.
:type core_fp: str
:param core_fp: A file containing core OTU data.
:rtype: str
:return: Returns genus-species identifier based on identified taxonomical
level. | Below is the the instruction that describes the task:
### Input:
For core OTU data file, returns Genus-species identifier for each data
entry.
:type core_fp: str
:param core_fp: A file containing core OTU data.
:rtype: str
:return: Returns genus-species identifier based on identified taxonomical... |
def fits_recarray_to_dict(table):
"""Convert a FITS recarray to a python dictionary."""
cols = {}
for icol, col in enumerate(table.columns.names):
col_data = table.data[col]
if type(col_data[0]) == np.float32:
cols[col] = np.array(col_data, dtype=float)
elif type(col_da... | Convert a FITS recarray to a python dictionary. | Below is the the instruction that describes the task:
### Input:
Convert a FITS recarray to a python dictionary.
### Response:
def fits_recarray_to_dict(table):
"""Convert a FITS recarray to a python dictionary."""
cols = {}
for icol, col in enumerate(table.columns.names):
col_data = table.da... |
def find_nodes(self, **kwargs):
"""Searches the data nodes that are associated with this graph using
the key word arguments as a filter and returns a
:class:`django.db.models.query.QuerySet`` of the attached
:class:`Node` objects.
:param kwargs:
filter arguments app... | Searches the data nodes that are associated with this graph using
the key word arguments as a filter and returns a
:class:`django.db.models.query.QuerySet`` of the attached
:class:`Node` objects.
:param kwargs:
filter arguments applied to searching the :class:`BaseNodeData`... | Below is the the instruction that describes the task:
### Input:
Searches the data nodes that are associated with this graph using
the key word arguments as a filter and returns a
:class:`django.db.models.query.QuerySet`` of the attached
:class:`Node` objects.
:param kwargs:
... |
def _startStationsNode(self, name, attrs):
"""Process the start of a node under xtvd/stations"""
if name == 'station':
self._stationId = attrs.get('id')
self._callSign = None
self._stationName = None
self._affiliate = None
self._fccChannelNumb... | Process the start of a node under xtvd/stations | Below is the the instruction that describes the task:
### Input:
Process the start of a node under xtvd/stations
### Response:
def _startStationsNode(self, name, attrs):
"""Process the start of a node under xtvd/stations"""
if name == 'station':
self._stationId = attrs.get('id')
... |
def unregister(self, model_or_iterable):
"""
Remove a model or a list of models from the list of models
whose comments will be moderated.
Raise ``NotModerated`` if any of the models are not currently
registered for moderation.
"""
if isinstance(model_or_iterable... | Remove a model or a list of models from the list of models
whose comments will be moderated.
Raise ``NotModerated`` if any of the models are not currently
registered for moderation. | Below is the the instruction that describes the task:
### Input:
Remove a model or a list of models from the list of models
whose comments will be moderated.
Raise ``NotModerated`` if any of the models are not currently
registered for moderation.
### Response:
def unregister(self, model_or... |
def parse_multipart_form_data(boundary, data, arguments, files):
"""Parses a multipart/form-data body.
The boundary and data parameters are both byte strings.
The dictionaries given in the arguments and files parameters
will be updated with the contents of the body.
"""
# The standard allows fo... | Parses a multipart/form-data body.
The boundary and data parameters are both byte strings.
The dictionaries given in the arguments and files parameters
will be updated with the contents of the body. | Below is the the instruction that describes the task:
### Input:
Parses a multipart/form-data body.
The boundary and data parameters are both byte strings.
The dictionaries given in the arguments and files parameters
will be updated with the contents of the body.
### Response:
def parse_multipart_form... |
def tagversion(repo, level='patch', special=''):
"""Increment and return tagged version in git.
Increment levels are patch, minor and major.
Using semver.org versioning: {major}.{minor}.{patch}{special}
Special must start with a-z and consist of _a-zA-Z0-9.
"""
prepend = 'v'
with lcd(repo):... | Increment and return tagged version in git.
Increment levels are patch, minor and major.
Using semver.org versioning: {major}.{minor}.{patch}{special}
Special must start with a-z and consist of _a-zA-Z0-9. | Below is the the instruction that describes the task:
### Input:
Increment and return tagged version in git.
Increment levels are patch, minor and major.
Using semver.org versioning: {major}.{minor}.{patch}{special}
Special must start with a-z and consist of _a-zA-Z0-9.
### Response:
def tagversion(re... |
def join(self, target):
"""join a channel"""
password = self.config.passwords.get(
target.strip(self.server_config['CHANTYPES']))
if password:
target += ' ' + password
self.send_line('JOIN %s' % target) | join a channel | Below is the the instruction that describes the task:
### Input:
join a channel
### Response:
def join(self, target):
"""join a channel"""
password = self.config.passwords.get(
target.strip(self.server_config['CHANTYPES']))
if password:
target += ' ' + password
... |
def patch(
target, new=DEFAULT, spec=None, create=False,
spec_set=None, autospec=None, new_callable=None, **kwargs
):
"""
`patch` acts as a function decorator, class decorator or a context
manager. Inside the body of the function or with statement, the `target`
is patched with a `new... | `patch` acts as a function decorator, class decorator or a context
manager. Inside the body of the function or with statement, the `target`
is patched with a `new` object. When the function/with statement exits
the patch is undone.
If `new` is omitted, then the target is replaced with a
`MagicMock`... | Below is the the instruction that describes the task:
### Input:
`patch` acts as a function decorator, class decorator or a context
manager. Inside the body of the function or with statement, the `target`
is patched with a `new` object. When the function/with statement exits
the patch is undone.
If... |
def on_bind_target(self, target, ctx=None):
"""Fired after target is bound to self.
:param target: newly bound target.
:param ctx: target ctx.
"""
_on_bind_target = getattr(self, Annotation._ON_BIND_TARGET, None)
if _on_bind_target is not None:
_on_bind_tar... | Fired after target is bound to self.
:param target: newly bound target.
:param ctx: target ctx. | Below is the the instruction that describes the task:
### Input:
Fired after target is bound to self.
:param target: newly bound target.
:param ctx: target ctx.
### Response:
def on_bind_target(self, target, ctx=None):
"""Fired after target is bound to self.
:param target: newly b... |
def open_mfbpchdataset(paths, concat_dim='time', compat='no_conflicts',
preprocess=None, lock=None, **kwargs):
""" Open multiple bpch files as a single dataset.
You must have dask installed for this to work, as this greatly
simplifies issues relating to multi-file I/O.
Also, ple... | Open multiple bpch files as a single dataset.
You must have dask installed for this to work, as this greatly
simplifies issues relating to multi-file I/O.
Also, please note that this is not a very performant routine. I/O is still
limited by the fact that we need to manually scan/read through each bpch... | Below is the the instruction that describes the task:
### Input:
Open multiple bpch files as a single dataset.
You must have dask installed for this to work, as this greatly
simplifies issues relating to multi-file I/O.
Also, please note that this is not a very performant routine. I/O is still
lim... |
def patch_sys_version():
""" Remove Continuum copyright statement to avoid parsing errors in IDLE """
if '|' in sys.version:
sys_version = sys.version.split('|')
sys.version = ' '.join([sys_version[0].strip(), sys_version[-1].strip()]) | Remove Continuum copyright statement to avoid parsing errors in IDLE | Below is the the instruction that describes the task:
### Input:
Remove Continuum copyright statement to avoid parsing errors in IDLE
### Response:
def patch_sys_version():
""" Remove Continuum copyright statement to avoid parsing errors in IDLE """
if '|' in sys.version:
sys_version = sys.version.... |
def checkCAS(CASRN):
'''Checks if a CAS number is valid. Returns False if the parser cannot
parse the given string..
Parameters
----------
CASRN : string
A three-piece, dash-separated set of numbers
Returns
-------
result : bool
Boolean value if CASRN was valid. If par... | Checks if a CAS number is valid. Returns False if the parser cannot
parse the given string..
Parameters
----------
CASRN : string
A three-piece, dash-separated set of numbers
Returns
-------
result : bool
Boolean value if CASRN was valid. If parsing fails, return False als... | Below is the the instruction that describes the task:
### Input:
Checks if a CAS number is valid. Returns False if the parser cannot
parse the given string..
Parameters
----------
CASRN : string
A three-piece, dash-separated set of numbers
Returns
-------
result : bool
... |
def CopyToDict(self):
"""Copies the path specification to a dictionary.
Returns:
dict[str, object]: path specification attributes.
"""
path_spec_dict = {}
for attribute_name, attribute_value in iter(self.__dict__.items()):
if attribute_value is None:
continue
if attribute... | Copies the path specification to a dictionary.
Returns:
dict[str, object]: path specification attributes. | Below is the the instruction that describes the task:
### Input:
Copies the path specification to a dictionary.
Returns:
dict[str, object]: path specification attributes.
### Response:
def CopyToDict(self):
"""Copies the path specification to a dictionary.
Returns:
dict[str, object]: path... |
def rewrite_file(self) -> None:
"""
Rewrites the source file.
"""
if not self.needs_rewriting:
return
self._info("Rewriting file")
with open(self.full_path, "w") as outfile:
self._write(outfile) | Rewrites the source file. | Below is the the instruction that describes the task:
### Input:
Rewrites the source file.
### Response:
def rewrite_file(self) -> None:
"""
Rewrites the source file.
"""
if not self.needs_rewriting:
return
self._info("Rewriting file")
with open(self.full... |
def find_element_by_selectors(webdriver, *selectors):
"""
Utility method makes it easier to find an element using multiple selectors. This is
useful for problematic elements what might works with one browser, but fail in another.
(Like different page elements being served up for differe... | Utility method makes it easier to find an element using multiple selectors. This is
useful for problematic elements what might works with one browser, but fail in another.
(Like different page elements being served up for different browsers)
Args:
selectors - var arg if N number of... | Below is the the instruction that describes the task:
### Input:
Utility method makes it easier to find an element using multiple selectors. This is
useful for problematic elements what might works with one browser, but fail in another.
(Like different page elements being served up for different br... |
def login(self, username, password, load=True):
"""
Set the authentication data in the object, and if load is True
(default is True) it also retrieve the ip list and the vm list
in order to build the internal objects list.
@param (str) username: username of the cloud
@par... | Set the authentication data in the object, and if load is True
(default is True) it also retrieve the ip list and the vm list
in order to build the internal objects list.
@param (str) username: username of the cloud
@param (str) password: password of the cloud
@param (bool) load:... | Below is the the instruction that describes the task:
### Input:
Set the authentication data in the object, and if load is True
(default is True) it also retrieve the ip list and the vm list
in order to build the internal objects list.
@param (str) username: username of the cloud
@pa... |
def post_process(self, group, event, is_new, is_sample, **kwargs):
"""
Process error.
"""
if not self.is_configured(group.project):
return
host = self.get_option('server_host', group.project)
port = int(self.get_option('server_port', group.project))
p... | Process error. | Below is the the instruction that describes the task:
### Input:
Process error.
### Response:
def post_process(self, group, event, is_new, is_sample, **kwargs):
"""
Process error.
"""
if not self.is_configured(group.project):
return
host = self.get_option('serve... |
def create_quantiles(items: Sequence, lower_bound, upper_bound):
"""Create quantile start and end boundaries."""
interval = (upper_bound - lower_bound) / len(items)
quantiles = ((g, (x - interval, x)) for g, x in
zip(items, accumulate(repeat(interval, len(items)))))
return quantiles | Create quantile start and end boundaries. | Below is the the instruction that describes the task:
### Input:
Create quantile start and end boundaries.
### Response:
def create_quantiles(items: Sequence, lower_bound, upper_bound):
"""Create quantile start and end boundaries."""
interval = (upper_bound - lower_bound) / len(items)
quantiles = ((g... |
def GameTypeEnum(ctx):
"""Game Type Enumeration."""
return Enum(
ctx,
RM=0,
Regicide=1,
DM=2,
Scenario=3,
Campaign=4,
KingOfTheHill=5,
WonderRace=6,
DefendTheWonder=7,
TurboRandom=8
) | Game Type Enumeration. | Below is the the instruction that describes the task:
### Input:
Game Type Enumeration.
### Response:
def GameTypeEnum(ctx):
"""Game Type Enumeration."""
return Enum(
ctx,
RM=0,
Regicide=1,
DM=2,
Scenario=3,
Campaign=4,
KingOfTheHill=5,
Wonder... |
def get_pending_enrollment_message(cls, pending_users, enrolled_in):
"""
Create message for the users who were enrolled in a course or program.
Args:
users: An iterable of PendingEnterpriseCustomerUsers who were successfully linked with a pending enrollment
enrolled_in (... | Create message for the users who were enrolled in a course or program.
Args:
users: An iterable of PendingEnterpriseCustomerUsers who were successfully linked with a pending enrollment
enrolled_in (str): A string identifier for the course or program the pending users were linked to
... | Below is the the instruction that describes the task:
### Input:
Create message for the users who were enrolled in a course or program.
Args:
users: An iterable of PendingEnterpriseCustomerUsers who were successfully linked with a pending enrollment
enrolled_in (str): A string ident... |
def resolve_path(root, path):
"""Resolve a rfc 6901 path, returning the parent and the last path part."""
path = parse_path(path)
parent = root
for part in path[:-1]:
parent = get_child(parent, rfc_6901_replace(part))
return (parent, rfc_6901_replace(path[-1])) | Resolve a rfc 6901 path, returning the parent and the last path part. | Below is the the instruction that describes the task:
### Input:
Resolve a rfc 6901 path, returning the parent and the last path part.
### Response:
def resolve_path(root, path):
"""Resolve a rfc 6901 path, returning the parent and the last path part."""
path = parse_path(path)
parent = root
for part in ... |
def _Close(self):
"""Closes the file-like object."""
super(VHDIFile, self)._Close()
for vhdi_file in self._parent_vhdi_files:
vhdi_file.close()
for file_object in self._sub_file_objects:
file_object.close()
self._parent_vhdi_files = []
self._sub_file_objects = [] | Closes the file-like object. | Below is the the instruction that describes the task:
### Input:
Closes the file-like object.
### Response:
def _Close(self):
"""Closes the file-like object."""
super(VHDIFile, self)._Close()
for vhdi_file in self._parent_vhdi_files:
vhdi_file.close()
for file_object in self._sub_file_objec... |
def run(self):
"""Fetch remote code."""
link = self.content[0]
try:
r = requests.get(link)
r.raise_for_status()
self.content = [r.text]
return super(RemoteCodeBlock, self).run()
except Exception:
document = self.state.document
... | Fetch remote code. | Below is the the instruction that describes the task:
### Input:
Fetch remote code.
### Response:
def run(self):
"""Fetch remote code."""
link = self.content[0]
try:
r = requests.get(link)
r.raise_for_status()
self.content = [r.text]
return su... |
def run_normalization(self):
"""
Run the normalization procedures
"""
for index, media_file in enumerate(
tqdm(
self.media_files,
desc="File",
disable=not self.progress,
position=0
... | Run the normalization procedures | Below is the the instruction that describes the task:
### Input:
Run the normalization procedures
### Response:
def run_normalization(self):
"""
Run the normalization procedures
"""
for index, media_file in enumerate(
tqdm(
self.media_files,
... |
def step_forward(self):
"""Updates state variables with computed tendencies.
Calls the :func:`compute` method to get current tendencies for all
process states. Multiplied with the timestep and added up to the state
variables is updating all model states.
:Example:
... | Updates state variables with computed tendencies.
Calls the :func:`compute` method to get current tendencies for all
process states. Multiplied with the timestep and added up to the state
variables is updating all model states.
:Example:
::
>>> import clim... | Below is the the instruction that describes the task:
### Input:
Updates state variables with computed tendencies.
Calls the :func:`compute` method to get current tendencies for all
process states. Multiplied with the timestep and added up to the state
variables is updating all model states... |
def on_touch_move(self, touch):
"""Move the scrollbar to the touch, and update my ``scroll``
accordingly.
"""
if not self.scrolling or 'bar' not in self.ids:
touch.ungrab(self)
return
touch.push()
touch.apply_transform_2d(self.parent.to_local)
... | Move the scrollbar to the touch, and update my ``scroll``
accordingly. | Below is the the instruction that describes the task:
### Input:
Move the scrollbar to the touch, and update my ``scroll``
accordingly.
### Response:
def on_touch_move(self, touch):
"""Move the scrollbar to the touch, and update my ``scroll``
accordingly.
"""
if not self.sc... |
def find(names, dirs, file_ext):
"""
Iterating a set of dirs under the static root, this method tries to find
a file named like one of the names and file ext passed, and returns the
storage path to the first file it encounters.
Usage this method makes it possible to over... | Iterating a set of dirs under the static root, this method tries to find
a file named like one of the names and file ext passed, and returns the
storage path to the first file it encounters.
Usage this method makes it possible to override static files (such as
icon sets) in a s... | Below is the the instruction that describes the task:
### Input:
Iterating a set of dirs under the static root, this method tries to find
a file named like one of the names and file ext passed, and returns the
storage path to the first file it encounters.
Usage this method makes it ... |
def qubo_to_ising(Q, offset=0.0):
"""Convert a QUBO problem to an Ising problem.
Map a quadratic unconstrained binary optimization (QUBO) problem :math:`x' Q x`
defined over binary variables (0 or 1 values), where the linear term is contained along
the diagonal of Q, to an Ising model defined on spin... | Convert a QUBO problem to an Ising problem.
Map a quadratic unconstrained binary optimization (QUBO) problem :math:`x' Q x`
defined over binary variables (0 or 1 values), where the linear term is contained along
the diagonal of Q, to an Ising model defined on spins (variables with {-1, +1} values).
R... | Below is the the instruction that describes the task:
### Input:
Convert a QUBO problem to an Ising problem.
Map a quadratic unconstrained binary optimization (QUBO) problem :math:`x' Q x`
defined over binary variables (0 or 1 values), where the linear term is contained along
the diagonal of Q, to an... |
def get_config(self):
"""
Return a formatted text with main configuration parameters.
"""
# Create a dummy report object if necessary
channels = [sect.rsplit('_')[0] for sect in self.config.sections(suffix='_channel')]
channels.sort()
disabled_apps = [app for app ... | Return a formatted text with main configuration parameters. | Below is the the instruction that describes the task:
### Input:
Return a formatted text with main configuration parameters.
### Response:
def get_config(self):
"""
Return a formatted text with main configuration parameters.
"""
# Create a dummy report object if necessary
ch... |
def save_images(images, filenames, output_dir):
"""Saves images to the output directory.
Args:
images: array with minibatch of images
filenames: list of filenames without path
If number of file names in this list less than number of images in
the minibatch then only first len(filenames) images ... | Saves images to the output directory.
Args:
images: array with minibatch of images
filenames: list of filenames without path
If number of file names in this list less than number of images in
the minibatch then only first len(filenames) images will be saved.
output_dir: directory where to sav... | Below is the the instruction that describes the task:
### Input:
Saves images to the output directory.
Args:
images: array with minibatch of images
filenames: list of filenames without path
If number of file names in this list less than number of images in
the minibatch then only first len(fi... |
def fit(self, x, y):
"""Train the model.
Args:
x_tr (pd.DataFrame): CEPC format dataframe containing the pairs
y_tr (pd.DataFrame or np.ndarray): labels associated to the pairs
"""
train = np.vstack((np.array([self.featurize_row(row.iloc[0],
... | Train the model.
Args:
x_tr (pd.DataFrame): CEPC format dataframe containing the pairs
y_tr (pd.DataFrame or np.ndarray): labels associated to the pairs | Below is the the instruction that describes the task:
### Input:
Train the model.
Args:
x_tr (pd.DataFrame): CEPC format dataframe containing the pairs
y_tr (pd.DataFrame or np.ndarray): labels associated to the pairs
### Response:
def fit(self, x, y):
"""Train the model.
... |
def _compute_weight(powers, wg):
"""Return the weight corresponding to given powers."""
# split
pow1 = (powers[0], 0)
pow2 = (0, powers[1])
cal1 = _compute_value(pow1, wg)
cal2 = _compute_value(pow2, wg)
return cal1 * cal2 | Return the weight corresponding to given powers. | Below is the the instruction that describes the task:
### Input:
Return the weight corresponding to given powers.
### Response:
def _compute_weight(powers, wg):
"""Return the weight corresponding to given powers."""
# split
pow1 = (powers[0], 0)
pow2 = (0, powers[1])
cal1 = _compute_value(pow1... |
def flatten(iterable, maps=None, unique=False) -> list:
"""
Flatten any array of items to list
Args:
iterable: any array or value
maps: map items to values
unique: drop duplicates
Returns:
list: flattened list
References:
https://stackoverflow.com/a/4085770... | Flatten any array of items to list
Args:
iterable: any array or value
maps: map items to values
unique: drop duplicates
Returns:
list: flattened list
References:
https://stackoverflow.com/a/40857703/1332656
Examples:
>>> flatten('abc')
['abc']
... | Below is the the instruction that describes the task:
### Input:
Flatten any array of items to list
Args:
iterable: any array or value
maps: map items to values
unique: drop duplicates
Returns:
list: flattened list
References:
https://stackoverflow.com/a/408577... |
def __expand_meta_datas(meta_datas, meta_datas_expanded):
""" expand meta_datas to one level
Args:
meta_datas (dict/list): maybe in nested format
Returns:
list: expanded list in one level
Examples:
>>> meta_datas = [
[
dict1,
... | expand meta_datas to one level
Args:
meta_datas (dict/list): maybe in nested format
Returns:
list: expanded list in one level
Examples:
>>> meta_datas = [
[
dict1,
dict2
],
dict3
]
... | Below is the the instruction that describes the task:
### Input:
expand meta_datas to one level
Args:
meta_datas (dict/list): maybe in nested format
Returns:
list: expanded list in one level
Examples:
>>> meta_datas = [
[
dict1,
... |
def add_tcp_callback(self, port, callback, threaded_callback=False):
"""
Adds a unix socket server callback, which will be invoked when values
arrive from a connected socket client. The callback must accept two
parameters, eg. ``def callback(socket, msg)``.
"""
if not cal... | Adds a unix socket server callback, which will be invoked when values
arrive from a connected socket client. The callback must accept two
parameters, eg. ``def callback(socket, msg)``. | Below is the the instruction that describes the task:
### Input:
Adds a unix socket server callback, which will be invoked when values
arrive from a connected socket client. The callback must accept two
parameters, eg. ``def callback(socket, msg)``.
### Response:
def add_tcp_callback(self, port, ca... |
def _remove_node_or_leaf(self, instance, recursive=False):
"""Removes a single node from the tree.
Only from RAM not from hdf5 file!
:param instance: The node to be deleted
:param recursive: If group nodes with children should be deleted
"""
full_name = instance.v_ful... | Removes a single node from the tree.
Only from RAM not from hdf5 file!
:param instance: The node to be deleted
:param recursive: If group nodes with children should be deleted | Below is the the instruction that describes the task:
### Input:
Removes a single node from the tree.
Only from RAM not from hdf5 file!
:param instance: The node to be deleted
:param recursive: If group nodes with children should be deleted
### Response:
def _remove_node_or_leaf(self, in... |
def compute_von_neumann_entropy(data, t_max=100):
"""
Determines the Von Neumann entropy of data
at varying matrix powers. The user should select a value of t
around the "knee" of the entropy curve.
Parameters
----------
t_max : int, default: 100
Maximum value of t to test
Retu... | Determines the Von Neumann entropy of data
at varying matrix powers. The user should select a value of t
around the "knee" of the entropy curve.
Parameters
----------
t_max : int, default: 100
Maximum value of t to test
Returns
-------
entropy : array, shape=[t_max]
The... | Below is the the instruction that describes the task:
### Input:
Determines the Von Neumann entropy of data
at varying matrix powers. The user should select a value of t
around the "knee" of the entropy curve.
Parameters
----------
t_max : int, default: 100
Maximum value of t to test
... |
def anat_info(suffix, metadata, img, config):
"""
Generate a paragraph describing T1- and T2-weighted structural scans.
Parameters
----------
suffix : :obj:`str`
T1 or T2.
metadata : :obj:`dict`
Data from the json file associated with the scan, in dictionary
form.
im... | Generate a paragraph describing T1- and T2-weighted structural scans.
Parameters
----------
suffix : :obj:`str`
T1 or T2.
metadata : :obj:`dict`
Data from the json file associated with the scan, in dictionary
form.
img : :obj:`nibabel.Nifti1Image`
The nifti image of ... | Below is the the instruction that describes the task:
### Input:
Generate a paragraph describing T1- and T2-weighted structural scans.
Parameters
----------
suffix : :obj:`str`
T1 or T2.
metadata : :obj:`dict`
Data from the json file associated with the scan, in dictionary
f... |
def copy(self):
"""
make an identical copy of the character
"""
return Character(self.name, self.race,self.ch_class, self.stats, self.skills, self.story, self.inventory) | make an identical copy of the character | Below is the the instruction that describes the task:
### Input:
make an identical copy of the character
### Response:
def copy(self):
"""
make an identical copy of the character
"""
return Character(self.name, self.race,self.ch_class, self.stats, self.skills, self.story, self.inve... |
def process_soundcloud(vargs):
"""
Main SoundCloud path.
"""
artist_url = vargs['artist_url']
track_permalink = vargs['track']
keep_previews = vargs['keep']
folders = vargs['folders']
id3_extras = {}
one_track = False
likes = False
client = get_client()
if 'soundcloud' ... | Main SoundCloud path. | Below is the the instruction that describes the task:
### Input:
Main SoundCloud path.
### Response:
def process_soundcloud(vargs):
"""
Main SoundCloud path.
"""
artist_url = vargs['artist_url']
track_permalink = vargs['track']
keep_previews = vargs['keep']
folders = vargs['folders']
... |
def mfccInitFilterBanks(fs, nfft):
"""
Computes the triangular filterbank for MFCC computation
(used in the stFeatureExtraction function before the stMFCC function call)
This function is taken from the scikits.talkbox library (MIT Licence):
https://pypi.python.org/pypi/scikits.talkbox
"""
... | Computes the triangular filterbank for MFCC computation
(used in the stFeatureExtraction function before the stMFCC function call)
This function is taken from the scikits.talkbox library (MIT Licence):
https://pypi.python.org/pypi/scikits.talkbox | Below is the the instruction that describes the task:
### Input:
Computes the triangular filterbank for MFCC computation
(used in the stFeatureExtraction function before the stMFCC function call)
This function is taken from the scikits.talkbox library (MIT Licence):
https://pypi.python.org/pypi/scikits... |
def get_gitignore_template(self, name):
"""
:calls: `GET /gitignore/templates/:name <http://developer.github.com/v3/gitignore>`_
:rtype: :class:`github.GitignoreTemplate.GitignoreTemplate`
"""
assert isinstance(name, (str, unicode)), name
headers, attributes = self.__requ... | :calls: `GET /gitignore/templates/:name <http://developer.github.com/v3/gitignore>`_
:rtype: :class:`github.GitignoreTemplate.GitignoreTemplate` | Below is the the instruction that describes the task:
### Input:
:calls: `GET /gitignore/templates/:name <http://developer.github.com/v3/gitignore>`_
:rtype: :class:`github.GitignoreTemplate.GitignoreTemplate`
### Response:
def get_gitignore_template(self, name):
"""
:calls: `GET /gitignore... |
def set(self, time):
"""Sets time in seconds since Epoch
Args:
time (:obj:`float`): time in seconds since Epoch (see time.time())
Returns:
None
"""
self._time = time
self._pb.sec = int(self._time)
self._pb.nsec = int((self._time - self._p... | Sets time in seconds since Epoch
Args:
time (:obj:`float`): time in seconds since Epoch (see time.time())
Returns:
None | Below is the the instruction that describes the task:
### Input:
Sets time in seconds since Epoch
Args:
time (:obj:`float`): time in seconds since Epoch (see time.time())
Returns:
None
### Response:
def set(self, time):
"""Sets time in seconds since Epoch
... |
def check_dependencies():
"""Check external dependecies
Return a tuple with the available generators.
"""
available = []
try:
shell('ebook-convert')
available.append('calibre')
except OSError:
pass
try:
shell('pandoc --help')
available.append('pandoc')... | Check external dependecies
Return a tuple with the available generators. | Below is the the instruction that describes the task:
### Input:
Check external dependecies
Return a tuple with the available generators.
### Response:
def check_dependencies():
"""Check external dependecies
Return a tuple with the available generators.
"""
available = []
try:
shell... |
def get_subgraph_for_concept_pair(
self, source: str, target: str, cutoff: Optional[int] = None
):
""" Get subgraph comprised of simple paths between the source and the
target.
Args:
source
target
cutoff
"""
paths = nx.all_simple_p... | Get subgraph comprised of simple paths between the source and the
target.
Args:
source
target
cutoff | Below is the the instruction that describes the task:
### Input:
Get subgraph comprised of simple paths between the source and the
target.
Args:
source
target
cutoff
### Response:
def get_subgraph_for_concept_pair(
self, source: str, target: str, cutoff:... |
def best_motif_in_cluster(single_pwm, clus_pwm, clusters, fg_fa, background, stats=None, metrics=("roc_auc", "recall_at_fdr")):
"""Return the best motif per cluster for a clustering results.
The motif can be either the average motif or one of the clustered motifs.
Parameters
----------
single_pwm ... | Return the best motif per cluster for a clustering results.
The motif can be either the average motif or one of the clustered motifs.
Parameters
----------
single_pwm : str
Filename of motifs.
clus_pwm : str
Filename of motifs.
clusters :
Motif clustering result.
... | Below is the the instruction that describes the task:
### Input:
Return the best motif per cluster for a clustering results.
The motif can be either the average motif or one of the clustered motifs.
Parameters
----------
single_pwm : str
Filename of motifs.
clus_pwm : str
File... |
def _tool_from_string(name):
""" Takes a string and returns a corresponding `Tool` instance. """
known_tools = sorted(_known_tools.keys())
if name in known_tools:
tool_fn = _known_tools[name]
if isinstance(tool_fn, string_types):
tool_fn = _known_tools[tool_fn]
return ... | Takes a string and returns a corresponding `Tool` instance. | Below is the the instruction that describes the task:
### Input:
Takes a string and returns a corresponding `Tool` instance.
### Response:
def _tool_from_string(name):
""" Takes a string and returns a corresponding `Tool` instance. """
known_tools = sorted(_known_tools.keys())
if name in known_tools:
... |
def _logout(self):
"""Logout from current session(token)
This functions doesn't return any boolean value, since it can 'fail' for anonymous logins
"""
self.log.debug("Logging out from session ID: %s" % self._token)
try:
info = self._xmlrpc_server.LogOut(self._token)
... | Logout from current session(token)
This functions doesn't return any boolean value, since it can 'fail' for anonymous logins | Below is the the instruction that describes the task:
### Input:
Logout from current session(token)
This functions doesn't return any boolean value, since it can 'fail' for anonymous logins
### Response:
def _logout(self):
"""Logout from current session(token)
This functions doesn't return ... |
def fix_e251(self, result):
"""Remove whitespace around parameter '=' sign."""
line_index = result['line'] - 1
target = self.source[line_index]
# This is necessary since pycodestyle sometimes reports columns that
# goes past the end of the physical line. This happens in cases li... | Remove whitespace around parameter '=' sign. | Below is the the instruction that describes the task:
### Input:
Remove whitespace around parameter '=' sign.
### Response:
def fix_e251(self, result):
"""Remove whitespace around parameter '=' sign."""
line_index = result['line'] - 1
target = self.source[line_index]
# This is nece... |
def calc_distribution_stats(x):
"""Calculate various summary statistics of data.
Parameters
----------
x : numpy.ndarray or pandas.Series
Array to compute summary statistics for.
Returns
-------
pandas.Series
Series containing mean, median, std, as well as 5, 25, 75 and
... | Calculate various summary statistics of data.
Parameters
----------
x : numpy.ndarray or pandas.Series
Array to compute summary statistics for.
Returns
-------
pandas.Series
Series containing mean, median, std, as well as 5, 25, 75 and
95 percentiles of passed in values... | Below is the the instruction that describes the task:
### Input:
Calculate various summary statistics of data.
Parameters
----------
x : numpy.ndarray or pandas.Series
Array to compute summary statistics for.
Returns
-------
pandas.Series
Series containing mean, median, std... |
def show_errors(self):
"""
Loop over configuration warnings and log them as INFO log
Loop over configuration errors and log them as INFO log
Note that the warnings and errors are logged on the fly during the configuration parsing.
It is not necessary to log as WARNING and ERROR ... | Loop over configuration warnings and log them as INFO log
Loop over configuration errors and log them as INFO log
Note that the warnings and errors are logged on the fly during the configuration parsing.
It is not necessary to log as WARNING and ERROR in this function which is used as a sum-up
... | Below is the the instruction that describes the task:
### Input:
Loop over configuration warnings and log them as INFO log
Loop over configuration errors and log them as INFO log
Note that the warnings and errors are logged on the fly during the configuration parsing.
It is not necessary to... |
def packageipa(env, console):
"""
Package the built app as an ipa for distribution in iOS App Store
"""
ipa_path, app_path = _get_ipa(env)
output_dir = path.dirname(ipa_path)
if path.exists(ipa_path):
console.quiet('Removing %s' % ipa_path)
os.remove(ipa_path)
zf = zipfile.... | Package the built app as an ipa for distribution in iOS App Store | Below is the the instruction that describes the task:
### Input:
Package the built app as an ipa for distribution in iOS App Store
### Response:
def packageipa(env, console):
"""
Package the built app as an ipa for distribution in iOS App Store
"""
ipa_path, app_path = _get_ipa(env)
output_dir ... |
def get_gravatar(email, size=80, rating='g', default=None,
protocol=PROTOCOL):
"""
Return url for a Gravatar.
"""
gravatar_protocols = {'http': 'http://www',
'https': 'https://secure'}
url = '%s.gravatar.com/avatar/%s' % (
gravatar_protocols[protoco... | Return url for a Gravatar. | Below is the the instruction that describes the task:
### Input:
Return url for a Gravatar.
### Response:
def get_gravatar(email, size=80, rating='g', default=None,
protocol=PROTOCOL):
"""
Return url for a Gravatar.
"""
gravatar_protocols = {'http': 'http://www',
... |
def export(self, version, export_dir):
"""
Create prov entities and activities.
"""
atts = [
(PROV['type'], self.type),
]
atts += [
(PROV['label'], self.label)
]
if self.extent_rsl is not None:
atts += [
... | Create prov entities and activities. | Below is the the instruction that describes the task:
### Input:
Create prov entities and activities.
### Response:
def export(self, version, export_dir):
"""
Create prov entities and activities.
"""
atts = [
(PROV['type'], self.type),
]
atts += [
... |
def interpolate_motor_positions(self, input_key, nearest_keys):
""" Process linear interpolation to estimate actual speed and position of motors
Method specific to the :meth:~pypot.primitive.move.Move.position() structure
it is a KDTreeDict[timestamp] = {dict[motor]=(position,speed)}
... | Process linear interpolation to estimate actual speed and position of motors
Method specific to the :meth:~pypot.primitive.move.Move.position() structure
it is a KDTreeDict[timestamp] = {dict[motor]=(position,speed)} | Below is the the instruction that describes the task:
### Input:
Process linear interpolation to estimate actual speed and position of motors
Method specific to the :meth:~pypot.primitive.move.Move.position() structure
it is a KDTreeDict[timestamp] = {dict[motor]=(position,speed)}
### Respon... |
def analyse(self, name):
"""
reads the specified file.
:param name: the name.
:return: the analysis as frequency/Pxx.
"""
if name in self._cache:
target = self._cache[name]
if target['type'] == 'wav':
signal = self._uploadController... | reads the specified file.
:param name: the name.
:return: the analysis as frequency/Pxx. | Below is the the instruction that describes the task:
### Input:
reads the specified file.
:param name: the name.
:return: the analysis as frequency/Pxx.
### Response:
def analyse(self, name):
"""
reads the specified file.
:param name: the name.
:return: the analysis... |
def recv_task_request_from_workers(self):
""" Receives 1 task request from MPI comm
Returns:
--------
worker_rank: worker_rank id
"""
info = MPI.Status()
comm.recv(source=MPI.ANY_SOURCE, tag=TASK_REQUEST_TAG, status=info)
worker_rank = info.Get_source... | Receives 1 task request from MPI comm
Returns:
--------
worker_rank: worker_rank id | Below is the the instruction that describes the task:
### Input:
Receives 1 task request from MPI comm
Returns:
--------
worker_rank: worker_rank id
### Response:
def recv_task_request_from_workers(self):
""" Receives 1 task request from MPI comm
Returns:
-----... |
def get_tokens(self, locations=None, extent=None):
"""Obtain tokens in this translation unit.
This is a generator for Token instances. The caller specifies a range
of source code to obtain tokens for. The range can be specified as a
2-tuple of SourceLocation or as a SourceRange. If both... | Obtain tokens in this translation unit.
This is a generator for Token instances. The caller specifies a range
of source code to obtain tokens for. The range can be specified as a
2-tuple of SourceLocation or as a SourceRange. If both are defined,
behavior is undefined. | Below is the the instruction that describes the task:
### Input:
Obtain tokens in this translation unit.
This is a generator for Token instances. The caller specifies a range
of source code to obtain tokens for. The range can be specified as a
2-tuple of SourceLocation or as a SourceRange. ... |
def day_publications_card(date):
"""
Displays Publications that were being read on `date`.
`date` is a date tobject.
"""
d = date.strftime(app_settings.DATE_FORMAT)
card_title = 'Reading on {}'.format(d)
return {
'card_title': card_title,
'publication_list': day_publi... | Displays Publications that were being read on `date`.
`date` is a date tobject. | Below is the the instruction that describes the task:
### Input:
Displays Publications that were being read on `date`.
`date` is a date tobject.
### Response:
def day_publications_card(date):
"""
Displays Publications that were being read on `date`.
`date` is a date tobject.
"""
d = date.st... |
def synchronize(self):
"""Synchronizes Router DB from Neturon DB with EOS.
Walks through the Neturon Db and ensures that all the routers
created in Netuton DB match with EOS. After creating appropriate
routers, it ensures to add interfaces as well.
Uses idempotent properties of ... | Synchronizes Router DB from Neturon DB with EOS.
Walks through the Neturon Db and ensures that all the routers
created in Netuton DB match with EOS. After creating appropriate
routers, it ensures to add interfaces as well.
Uses idempotent properties of EOS configuration, which means
... | Below is the the instruction that describes the task:
### Input:
Synchronizes Router DB from Neturon DB with EOS.
Walks through the Neturon Db and ensures that all the routers
created in Netuton DB match with EOS. After creating appropriate
routers, it ensures to add interfaces as well.
... |
def _initialize_precalculated_series(self,
asset,
trading_calendar,
trading_days,
data_portal):
"""
Internal method that pre-calculates the ... | Internal method that pre-calculates the benchmark return series for
use in the simulation.
Parameters
----------
asset: Asset to use
trading_calendar: TradingCalendar
trading_days: pd.DateTimeIndex
data_portal: DataPortal
Notes
-----
... | Below is the the instruction that describes the task:
### Input:
Internal method that pre-calculates the benchmark return series for
use in the simulation.
Parameters
----------
asset: Asset to use
trading_calendar: TradingCalendar
trading_days: pd.DateTimeIndex
... |
def persistent_attributes(self):
# type: () -> Dict[str, object]
"""Attributes stored at the Persistence level of the skill lifecycle.
:return: persistent_attributes retrieved from persistence adapter
:rtype: Dict[str, object]
:raises: :py:class:`ask_sdk_core.exceptions.Attribut... | Attributes stored at the Persistence level of the skill lifecycle.
:return: persistent_attributes retrieved from persistence adapter
:rtype: Dict[str, object]
:raises: :py:class:`ask_sdk_core.exceptions.AttributesManagerException`
if trying to get persistent attributes without persi... | Below is the the instruction that describes the task:
### Input:
Attributes stored at the Persistence level of the skill lifecycle.
:return: persistent_attributes retrieved from persistence adapter
:rtype: Dict[str, object]
:raises: :py:class:`ask_sdk_core.exceptions.AttributesManagerExcept... |
def singleton(func):
"""
This decorator allows you to make sure that a function is called once and
only once. Note that recursive functions will still work.
WARNING: Not thread-safe!!!
"""
@functools.wraps(func)
def wrapper(*args, **kwargs):
if wrapper.__call_state__ == CALLED:
... | This decorator allows you to make sure that a function is called once and
only once. Note that recursive functions will still work.
WARNING: Not thread-safe!!! | Below is the the instruction that describes the task:
### Input:
This decorator allows you to make sure that a function is called once and
only once. Note that recursive functions will still work.
WARNING: Not thread-safe!!!
### Response:
def singleton(func):
"""
This decorator allows you to make ... |
def find_source_lines(self):
"""Mark all executable source lines in fn as executed 0 times."""
strs = trace.find_strings(self.filename)
lines = trace.find_lines_from_code(self.fn.__code__, strs)
self.firstcodelineno = sys.maxint
for lineno in lines:
self.firstcodeline... | Mark all executable source lines in fn as executed 0 times. | Below is the the instruction that describes the task:
### Input:
Mark all executable source lines in fn as executed 0 times.
### Response:
def find_source_lines(self):
"""Mark all executable source lines in fn as executed 0 times."""
strs = trace.find_strings(self.filename)
lines = trace.fi... |
def distinct_letters(string_matrix: List[List[str]]) -> Set[str]:
"""
Diagnostic function
:param string_matrix: a data matrix: a list wrapping a list of strings, with each sublist being a sentence.
:return:
>>> dl = distinct_letters([['the', 'quick', 'brown'],['how', 'now', 'cow']])
>>> sorted(d... | Diagnostic function
:param string_matrix: a data matrix: a list wrapping a list of strings, with each sublist being a sentence.
:return:
>>> dl = distinct_letters([['the', 'quick', 'brown'],['how', 'now', 'cow']])
>>> sorted(dl)
['b', 'c', 'e', 'h', 'i', 'k', 'n', 'o', 'q', 'r', 't', 'u', 'w'] | Below is the the instruction that describes the task:
### Input:
Diagnostic function
:param string_matrix: a data matrix: a list wrapping a list of strings, with each sublist being a sentence.
:return:
>>> dl = distinct_letters([['the', 'quick', 'brown'],['how', 'now', 'cow']])
>>> sorted(dl)
['... |
def step(self, thumb=False):
"""Executes a single step.
Steps even if there is a breakpoint.
Args:
self (JLink): the ``JLink`` instance
thumb (bool): boolean indicating if to step in thumb mode
Returns:
``None``
Raises:
JLinkException: ... | Executes a single step.
Steps even if there is a breakpoint.
Args:
self (JLink): the ``JLink`` instance
thumb (bool): boolean indicating if to step in thumb mode
Returns:
``None``
Raises:
JLinkException: on error | Below is the the instruction that describes the task:
### Input:
Executes a single step.
Steps even if there is a breakpoint.
Args:
self (JLink): the ``JLink`` instance
thumb (bool): boolean indicating if to step in thumb mode
Returns:
``None``
Raise... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.