code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def consume(self): # pragma: no cover
""" start consuming rabbitmq messages """
print(' [*] Waiting for logs. To exit press CTRL+C')
self.channel.basic_consume(self.queue_name, self.callback)
self.channel.start_consuming() | start consuming rabbitmq messages | Below is the the instruction that describes the task:
### Input:
start consuming rabbitmq messages
### Response:
def consume(self): # pragma: no cover
""" start consuming rabbitmq messages """
print(' [*] Waiting for logs. To exit press CTRL+C')
self.channel.basic_consume(self.queue_name, ... |
def replace_type(items, spec, loader, found, find_embeds=True, deepen=True):
# type: (Any, Dict[Text, Any], Loader, Set[Text], bool, bool) -> Any
""" Go through and replace types in the 'spec' mapping"""
if isinstance(items, MutableMapping):
# recursively check these fields for types to replace
... | Go through and replace types in the 'spec' mapping | Below is the the instruction that describes the task:
### Input:
Go through and replace types in the 'spec' mapping
### Response:
def replace_type(items, spec, loader, found, find_embeds=True, deepen=True):
# type: (Any, Dict[Text, Any], Loader, Set[Text], bool, bool) -> Any
""" Go through and replace type... |
def wallet_balance_total(self, wallet):
"""
Returns the sum of all accounts balances in **wallet**
:param wallet: Wallet to return sum of balances for
:type wallet: str
:raises: :py:exc:`nano.rpc.RPCException`
>>> rpc.wallet_balance_total(
... wallet="000D1... | Returns the sum of all accounts balances in **wallet**
:param wallet: Wallet to return sum of balances for
:type wallet: str
:raises: :py:exc:`nano.rpc.RPCException`
>>> rpc.wallet_balance_total(
... wallet="000D1BAEC8EC208142C99059B393051BAC8380F9B5A2E6B2489A277D81789F3F"... | Below is the the instruction that describes the task:
### Input:
Returns the sum of all accounts balances in **wallet**
:param wallet: Wallet to return sum of balances for
:type wallet: str
:raises: :py:exc:`nano.rpc.RPCException`
>>> rpc.wallet_balance_total(
... wall... |
def _parse_css_color(color):
'''_parse_css_color(css_color) -> gtk.gdk.Color'''
if color.startswith("rgb(") and color.endswith(')'):
r, g, b = [int(c)*257 for c in color[4:-1].split(',')]
return gtk.gdk.Color(r, g, b)
else:
return gtk.gdk.color_parse(color) | _parse_css_color(css_color) -> gtk.gdk.Color | Below is the the instruction that describes the task:
### Input:
_parse_css_color(css_color) -> gtk.gdk.Color
### Response:
def _parse_css_color(color):
'''_parse_css_color(css_color) -> gtk.gdk.Color'''
if color.startswith("rgb(") and color.endswith(')'):
r, g, b = [int(c)*257 for c in color[4:-1]... |
def _dynamic_mul(self, dimensions, other, keys):
"""
Implements dynamic version of overlaying operation overlaying
DynamicMaps and HoloMaps where the key dimensions of one is
a strict superset of the other.
"""
# If either is a HoloMap compute Dimension values
if ... | Implements dynamic version of overlaying operation overlaying
DynamicMaps and HoloMaps where the key dimensions of one is
a strict superset of the other. | Below is the the instruction that describes the task:
### Input:
Implements dynamic version of overlaying operation overlaying
DynamicMaps and HoloMaps where the key dimensions of one is
a strict superset of the other.
### Response:
def _dynamic_mul(self, dimensions, other, keys):
"""
... |
def simOnePrd(self):
'''
Simulate one period of the fashion victom model for this type. Each
agent receives an idiosyncratic preference shock and chooses whether to
change styles (using the optimal decision rule).
Parameters
----------
none
Returns
... | Simulate one period of the fashion victom model for this type. Each
agent receives an idiosyncratic preference shock and chooses whether to
change styles (using the optimal decision rule).
Parameters
----------
none
Returns
-------
none | Below is the the instruction that describes the task:
### Input:
Simulate one period of the fashion victom model for this type. Each
agent receives an idiosyncratic preference shock and chooses whether to
change styles (using the optimal decision rule).
Parameters
----------
... |
def _update_config(self,directory,filename):
"""Manages FB config files"""
basefilename=os.path.splitext(filename)[0]
ext=os.path.splitext(filename)[1].lower()
#if filename==LOCATION_FILE:
#return self._update_config_location(directory)
#FIXME
#elif filename==... | Manages FB config files | Below is the the instruction that describes the task:
### Input:
Manages FB config files
### Response:
def _update_config(self,directory,filename):
"""Manages FB config files"""
basefilename=os.path.splitext(filename)[0]
ext=os.path.splitext(filename)[1].lower()
#if filename==LOCATI... |
def set_default(self):
"""
ensures there's only 1 default group
(logic overridable via custom models)
"""
queryset = self.get_default_queryset()
if queryset.exists():
queryset.update(default=False) | ensures there's only 1 default group
(logic overridable via custom models) | Below is the the instruction that describes the task:
### Input:
ensures there's only 1 default group
(logic overridable via custom models)
### Response:
def set_default(self):
"""
ensures there's only 1 default group
(logic overridable via custom models)
"""
queryse... |
def get_data_en_intervalo(d0=None, df=None, date_fmt=DATE_FMT,
usar_multithread=USAR_MULTITHREAD, max_threads_requests=MAX_THREADS_REQUESTS,
timeout=TIMEOUT, num_retries=NUM_RETRIES,
func_procesa_data_dia=None, func_url_data_dia=None, max_act... | Obtiene los datos en bruto de la red realizando múltiples requests al tiempo
Procesa los datos en bruto obtenidos de la red convirtiendo a Pandas DataFrame | Below is the the instruction that describes the task:
### Input:
Obtiene los datos en bruto de la red realizando múltiples requests al tiempo
Procesa los datos en bruto obtenidos de la red convirtiendo a Pandas DataFrame
### Response:
def get_data_en_intervalo(d0=None, df=None, date_fmt=DATE_FMT,
... |
def outgoing_edges(self, node):
"""
Returns a ``tuple`` of outgoing edges for a **node object**.
Arguments:
- node(``object``) **node object** present in the graph to be queried
for outgoing edges.
"""
#TODO: pls make outgoig_ed... | Returns a ``tuple`` of outgoing edges for a **node object**.
Arguments:
- node(``object``) **node object** present in the graph to be queried
for outgoing edges. | Below is the the instruction that describes the task:
### Input:
Returns a ``tuple`` of outgoing edges for a **node object**.
Arguments:
- node(``object``) **node object** present in the graph to be queried
for outgoing edges.
### Response:
def outgoing_edges(self, ... |
def delete_all_metadata(self):
"""
::
DELETE /:login/machines/:id/metadata
:Returns: current metadata
:rtype: empty :py:class:`dict`
Deletes all the metadata stored for this machine. Also explicitly
requests and returns the machine ... | ::
DELETE /:login/machines/:id/metadata
:Returns: current metadata
:rtype: empty :py:class:`dict`
Deletes all the metadata stored for this machine. Also explicitly
requests and returns the machine metadata so that the local copy stays
sync... | Below is the the instruction that describes the task:
### Input:
::
DELETE /:login/machines/:id/metadata
:Returns: current metadata
:rtype: empty :py:class:`dict`
Deletes all the metadata stored for this machine. Also explicitly
requests and re... |
def _handle_reset(self):
"""Reset this tile.
This process needs to trigger the peripheral tile to reregister itself
with the controller and get new configuration variables. It also
needs to clear app_running.
"""
self._registered.clear()
self._start_received.cl... | Reset this tile.
This process needs to trigger the peripheral tile to reregister itself
with the controller and get new configuration variables. It also
needs to clear app_running. | Below is the the instruction that describes the task:
### Input:
Reset this tile.
This process needs to trigger the peripheral tile to reregister itself
with the controller and get new configuration variables. It also
needs to clear app_running.
### Response:
def _handle_reset(self):
... |
def wheregreater(self, fieldname, value):
"""
Returns a new DataTable with rows only where the value at
`fieldname` > `value`.
"""
return self.mask([elem > value for elem in self[fieldname]]) | Returns a new DataTable with rows only where the value at
`fieldname` > `value`. | Below is the the instruction that describes the task:
### Input:
Returns a new DataTable with rows only where the value at
`fieldname` > `value`.
### Response:
def wheregreater(self, fieldname, value):
"""
Returns a new DataTable with rows only where the value at
`fieldname` > `valu... |
def package_install(name, **kwargs):
'''
Install a "package" on the ssh server
'''
cmd = 'pkg_install ' + name
if kwargs.get('version', False):
cmd += ' ' + kwargs['version']
# Send the command to execute
out, err = DETAILS['server'].sendline(cmd)
# "scrape" the output and retu... | Install a "package" on the ssh server | Below is the the instruction that describes the task:
### Input:
Install a "package" on the ssh server
### Response:
def package_install(name, **kwargs):
'''
Install a "package" on the ssh server
'''
cmd = 'pkg_install ' + name
if kwargs.get('version', False):
cmd += ' ' + kwargs['versi... |
def _sync_notes(self, notes_json):
""""Populate the user's notes from a JSON encoded list."""
for note_json in notes_json:
note_id = note_json['id']
task_id = note_json['item_id']
if task_id not in self.tasks:
# ignore orphan notes
cont... | Populate the user's notes from a JSON encoded list. | Below is the the instruction that describes the task:
### Input:
Populate the user's notes from a JSON encoded list.
### Response:
def _sync_notes(self, notes_json):
""""Populate the user's notes from a JSON encoded list."""
for note_json in notes_json:
note_id = note_json['id']
... |
def create(self, task_name, clone_task=None):
""" Creates a new task directory.
`task_name`
Task name.
`clone_task`
Existing task name to use as a template for new task.
Returns boolean.
* Raises ``Value`` if task name is invalid... | Creates a new task directory.
`task_name`
Task name.
`clone_task`
Existing task name to use as a template for new task.
Returns boolean.
* Raises ``Value`` if task name is invalid, ``TaskExists`` if task
already exists, or ... | Below is the the instruction that describes the task:
### Input:
Creates a new task directory.
`task_name`
Task name.
`clone_task`
Existing task name to use as a template for new task.
Returns boolean.
* Raises ``Value`` if task name... |
def add_styles(self):
"""Add the css to the svg"""
colors = self.graph.style.get_colors(self.id, self.graph._order)
strokes = self.get_strokes()
all_css = []
auto_css = ['file://base.css']
if self.graph.style._google_fonts:
auto_css.append(
'/... | Add the css to the svg | Below is the the instruction that describes the task:
### Input:
Add the css to the svg
### Response:
def add_styles(self):
"""Add the css to the svg"""
colors = self.graph.style.get_colors(self.id, self.graph._order)
strokes = self.get_strokes()
all_css = []
auto_css = ['fi... |
def compute_eigen(self, n_comps=15, sym=None, sort='decrease'):
"""Compute eigen decomposition of transition matrix.
Parameters
----------
n_comps : `int`
Number of eigenvalues/vectors to be computed, set `n_comps = 0` if
you need all eigenvectors.
sym : ... | Compute eigen decomposition of transition matrix.
Parameters
----------
n_comps : `int`
Number of eigenvalues/vectors to be computed, set `n_comps = 0` if
you need all eigenvectors.
sym : `bool`
Instead of computing the eigendecomposition of the assym... | Below is the the instruction that describes the task:
### Input:
Compute eigen decomposition of transition matrix.
Parameters
----------
n_comps : `int`
Number of eigenvalues/vectors to be computed, set `n_comps = 0` if
you need all eigenvectors.
sym : `bool`... |
def addUsage_Label(self,usage_label):
'''Appends one Usage_Label to usage_labels
'''
if isinstance(usage_label, Usage_Label):
self.usage_labels.append(usage_label)
else:
raise (Usage_LabelError,
'usage_label Type should be Usage_Label, not %s' %... | Appends one Usage_Label to usage_labels | Below is the the instruction that describes the task:
### Input:
Appends one Usage_Label to usage_labels
### Response:
def addUsage_Label(self,usage_label):
'''Appends one Usage_Label to usage_labels
'''
if isinstance(usage_label, Usage_Label):
self.usage_labels.append(usage_lab... |
def connect(host='localhost',
port=5672,
username='guest', password='guest',
virtual_host='/',
on_connection_close=None, *,
loop=None, sock=None, **kwargs):
"""
Connect to an AMQP server on the given host and port.
Log in to the given virtual host... | Connect to an AMQP server on the given host and port.
Log in to the given virtual host using the supplied credentials.
This function is a :ref:`coroutine <coroutine>`.
:param str host: the host server to connect to.
:param int port: the port which the AMQP server is listening on.
:param str userna... | Below is the the instruction that describes the task:
### Input:
Connect to an AMQP server on the given host and port.
Log in to the given virtual host using the supplied credentials.
This function is a :ref:`coroutine <coroutine>`.
:param str host: the host server to connect to.
:param int port: ... |
def _create_aural_content_element(self, content, data_property_value):
"""
Create a element to show the content, only to aural displays.
:param content: The text content of element.
:type content: str
:param data_property_value: The value of custom attribute used to
... | Create a element to show the content, only to aural displays.
:param content: The text content of element.
:type content: str
:param data_property_value: The value of custom attribute used to
identify the fix.
:type data_property_value: str
:r... | Below is the the instruction that describes the task:
### Input:
Create a element to show the content, only to aural displays.
:param content: The text content of element.
:type content: str
:param data_property_value: The value of custom attribute used to
... |
def merge_ligolws(elem):
"""
Merge all LIGO_LW elements that are immediate children of elem by
appending their children to the first.
"""
ligolws = [child for child in elem.childNodes if child.tagName == ligolw.LIGO_LW.tagName]
if ligolws:
dest = ligolws.pop(0)
for src in ligolws:
# copy children; LIGO_LW... | Merge all LIGO_LW elements that are immediate children of elem by
appending their children to the first. | Below is the the instruction that describes the task:
### Input:
Merge all LIGO_LW elements that are immediate children of elem by
appending their children to the first.
### Response:
def merge_ligolws(elem):
"""
Merge all LIGO_LW elements that are immediate children of elem by
appending their children to the ... |
def get_diffs(history):
"""
Look at files and compute the diffs intelligently
"""
# First get all possible representations
mgr = plugins_get_mgr()
keys = mgr.search('representation')['representation']
representations = [mgr.get_by_key('representation', k) for k in keys]
for i in range... | Look at files and compute the diffs intelligently | Below is the the instruction that describes the task:
### Input:
Look at files and compute the diffs intelligently
### Response:
def get_diffs(history):
"""
Look at files and compute the diffs intelligently
"""
# First get all possible representations
mgr = plugins_get_mgr()
keys = mgr.se... |
def encode_data(self, data, attributes):
'''(INTERNAL) Encodes a line of data.
Data instances follow the csv format, i.e, attribute values are
delimited by commas. After converted from csv.
:param data: a list of values.
:param attributes: a list of attributes. Used to check if... | (INTERNAL) Encodes a line of data.
Data instances follow the csv format, i.e, attribute values are
delimited by commas. After converted from csv.
:param data: a list of values.
:param attributes: a list of attributes. Used to check if data is valid.
:return: a string with the e... | Below is the the instruction that describes the task:
### Input:
(INTERNAL) Encodes a line of data.
Data instances follow the csv format, i.e, attribute values are
delimited by commas. After converted from csv.
:param data: a list of values.
:param attributes: a list of attributes.... |
def home(request):
"""Renders Datafreezer homepage. Includes recent uploads."""
recent_uploads = Dataset.objects.order_by('-date_uploaded')[:11]
email_list = [upload.uploaded_by.strip() for upload in recent_uploads]
# print all_staff
emails_names = grab_names_from_emails(email_list)
# print em... | Renders Datafreezer homepage. Includes recent uploads. | Below is the the instruction that describes the task:
### Input:
Renders Datafreezer homepage. Includes recent uploads.
### Response:
def home(request):
"""Renders Datafreezer homepage. Includes recent uploads."""
recent_uploads = Dataset.objects.order_by('-date_uploaded')[:11]
email_list = [upload.up... |
def move(self, bearing, distance):
'''move position by bearing and distance'''
lat = self.pkt['I105']['Lat']['val']
lon = self.pkt['I105']['Lon']['val']
(lat, lon) = mp_util.gps_newpos(lat, lon, bearing, distance)
self.setpos(lat, lon) | move position by bearing and distance | Below is the the instruction that describes the task:
### Input:
move position by bearing and distance
### Response:
def move(self, bearing, distance):
'''move position by bearing and distance'''
lat = self.pkt['I105']['Lat']['val']
lon = self.pkt['I105']['Lon']['val']
(lat, lon) = ... |
def func_args(func):
'''Basic function which returns a tuple of arguments of a function or
method.
'''
try:
return tuple(inspect.signature(func).parameters)
except:
return tuple(inspect.getargspec(func).args) | Basic function which returns a tuple of arguments of a function or
method. | Below is the the instruction that describes the task:
### Input:
Basic function which returns a tuple of arguments of a function or
method.
### Response:
def func_args(func):
'''Basic function which returns a tuple of arguments of a function or
method.
'''
try:
return tuple(inspect.sign... |
def altitude(msg):
"""Decode aircraft altitude
Args:
msg (string): 28 bytes hexadecimal message string
Returns:
int: altitude in feet
"""
tc = common.typecode(msg)
if tc<9 or tc==19 or tc>22:
raise RuntimeError("%s: Not a airborn position message" % msg)
mb = com... | Decode aircraft altitude
Args:
msg (string): 28 bytes hexadecimal message string
Returns:
int: altitude in feet | Below is the the instruction that describes the task:
### Input:
Decode aircraft altitude
Args:
msg (string): 28 bytes hexadecimal message string
Returns:
int: altitude in feet
### Response:
def altitude(msg):
"""Decode aircraft altitude
Args:
msg (string): 28 bytes hexad... |
def is_empty(self):
"""
A group of modules is considered empty if it has no children or if
all its children are empty.
>>> from admin_tools.dashboard.modules import DashboardModule, LinkList
>>> mod = Group()
>>> mod.is_empty()
True
>>> mod.children.appen... | A group of modules is considered empty if it has no children or if
all its children are empty.
>>> from admin_tools.dashboard.modules import DashboardModule, LinkList
>>> mod = Group()
>>> mod.is_empty()
True
>>> mod.children.append(DashboardModule())
>>> mod.is_... | Below is the the instruction that describes the task:
### Input:
A group of modules is considered empty if it has no children or if
all its children are empty.
>>> from admin_tools.dashboard.modules import DashboardModule, LinkList
>>> mod = Group()
>>> mod.is_empty()
True
... |
def plot(self, axis, title=None, saved=False):
"""
Plots the planar average electrostatic potential against the Long range and short range models from Freysoldt
"""
x = self.metadata['pot_plot_data'][axis]['x']
v_R = self.metadata['pot_plot_data'][axis]['Vr']
dft_diff =... | Plots the planar average electrostatic potential against the Long range and short range models from Freysoldt | Below is the the instruction that describes the task:
### Input:
Plots the planar average electrostatic potential against the Long range and short range models from Freysoldt
### Response:
def plot(self, axis, title=None, saved=False):
"""
Plots the planar average electrostatic potential against th... |
def groupByWordIndex(self, transaction: 'TransTmpl', offset: int):
"""
Group transaction parts splited on words to words
:param transaction: TransTmpl instance which parts
should be grupped into words
:return: generator of tuples (wordIndex, list of transaction parts
... | Group transaction parts splited on words to words
:param transaction: TransTmpl instance which parts
should be grupped into words
:return: generator of tuples (wordIndex, list of transaction parts
in this word) | Below is the the instruction that describes the task:
### Input:
Group transaction parts splited on words to words
:param transaction: TransTmpl instance which parts
should be grupped into words
:return: generator of tuples (wordIndex, list of transaction parts
in this word)... |
def _parse_api_options(self, options, query_string=False):
"""Select API options out of the provided options object.
Selects API string options out of the provided options object and
formats for either request body (default) or query string.
"""
api_options = self._select_optio... | Select API options out of the provided options object.
Selects API string options out of the provided options object and
formats for either request body (default) or query string. | Below is the the instruction that describes the task:
### Input:
Select API options out of the provided options object.
Selects API string options out of the provided options object and
formats for either request body (default) or query string.
### Response:
def _parse_api_options(self, options, q... |
def pop(self, key, *args):
'Remove *key* from maps[0] and return its value. Raise KeyError if *key* not in maps[0].'
try:
return self.maps[0].pop(key, *args)
except KeyError:
raise KeyError('Key not found in the first mapping: {!r}'.format(key)) | Remove *key* from maps[0] and return its value. Raise KeyError if *key* not in maps[0]. | Below is the the instruction that describes the task:
### Input:
Remove *key* from maps[0] and return its value. Raise KeyError if *key* not in maps[0].
### Response:
def pop(self, key, *args):
'Remove *key* from maps[0] and return its value. Raise KeyError if *key* not in maps[0].'
try:
... |
def run(self):
""" Main entry function. """
args = self._process_flags()
self.todofile = TodoFile.TodoFile(config().todotxt())
self.todolist = TodoList.TodoList(self.todofile.read())
try:
(subcommand, args) = get_subcommand(args)
except ConfigError as ce:
... | Main entry function. | Below is the the instruction that describes the task:
### Input:
Main entry function.
### Response:
def run(self):
""" Main entry function. """
args = self._process_flags()
self.todofile = TodoFile.TodoFile(config().todotxt())
self.todolist = TodoList.TodoList(self.todofile.read())... |
def modify_agent_properties(self, agent_id, key_value_map={}):
'''
modify_agent_properties(self, agent_id, key_value_map={})
Modify properties of an agent. If properties do not exists, they will be created
:Parameters:
* *agent_id* (`string`) -- Identifier of an existing agent
... | modify_agent_properties(self, agent_id, key_value_map={})
Modify properties of an agent. If properties do not exists, they will be created
:Parameters:
* *agent_id* (`string`) -- Identifier of an existing agent
* *key_value_map* (`object`) -- Key value map of properties to change
... | Below is the the instruction that describes the task:
### Input:
modify_agent_properties(self, agent_id, key_value_map={})
Modify properties of an agent. If properties do not exists, they will be created
:Parameters:
* *agent_id* (`string`) -- Identifier of an existing agent
* *key... |
def consolidate(args):
"""
%prog consolidate gffile1 gffile2 ... > consolidated.out
Given 2 or more gff files generated by pasa annotation comparison,
iterate through each locus (shared locus name or overlapping CDS)
and identify same/different isoforms (shared splicing structure)
across the in... | %prog consolidate gffile1 gffile2 ... > consolidated.out
Given 2 or more gff files generated by pasa annotation comparison,
iterate through each locus (shared locus name or overlapping CDS)
and identify same/different isoforms (shared splicing structure)
across the input datasets.
If `slop` is ena... | Below is the the instruction that describes the task:
### Input:
%prog consolidate gffile1 gffile2 ... > consolidated.out
Given 2 or more gff files generated by pasa annotation comparison,
iterate through each locus (shared locus name or overlapping CDS)
and identify same/different isoforms (shared spl... |
def interp1d(x,Z,xout,spline=False,kind='linear',fill_value=np.NaN,**kwargs):
"""
INTERP1D : Interpolate values from a 1D vector at given positions
@param x: 1st dimension vector of size NX
@author: Renaud DUSSURGET, LER/PAC, Ifremer La Seyne
"""
linear = not spline
... | INTERP1D : Interpolate values from a 1D vector at given positions
@param x: 1st dimension vector of size NX
@author: Renaud DUSSURGET, LER/PAC, Ifremer La Seyne | Below is the the instruction that describes the task:
### Input:
INTERP1D : Interpolate values from a 1D vector at given positions
@param x: 1st dimension vector of size NX
@author: Renaud DUSSURGET, LER/PAC, Ifremer La Seyne
### Response:
def interp1d(x,Z,xout,spline=False,kind='linear',fill... |
def explain(self, *args, **kwargs):
'''Return a string that describes how these args are interpreted'''
args = self.get(*args, **kwargs)
results = ['%s = %s' % (name, value) for name, value in args.required]
results.extend(['%s = %s (overridden)' % (
name, value) for name, va... | Return a string that describes how these args are interpreted | Below is the the instruction that describes the task:
### Input:
Return a string that describes how these args are interpreted
### Response:
def explain(self, *args, **kwargs):
'''Return a string that describes how these args are interpreted'''
args = self.get(*args, **kwargs)
results = ['%... |
def pull(directory: str) -> Commit:
"""
Pulls the subrepo that has been cloned into the given directory.
:param directory: the directory containing the subrepo
:return: the commit the subrepo is on
"""
if not os.path.exists(directory):
raise ValueError(f"No subrepo found in \"{directory}... | Pulls the subrepo that has been cloned into the given directory.
:param directory: the directory containing the subrepo
:return: the commit the subrepo is on | Below is the the instruction that describes the task:
### Input:
Pulls the subrepo that has been cloned into the given directory.
:param directory: the directory containing the subrepo
:return: the commit the subrepo is on
### Response:
def pull(directory: str) -> Commit:
"""
Pulls the subrepo that... |
def describe(self, bucket, descriptor=None):
"""https://github.com/frictionlessdata/tableschema-sql-py#storage
"""
# Set descriptor
if descriptor is not None:
self.__descriptors[bucket] = descriptor
# Get descriptor
else:
descriptor = self.__desc... | https://github.com/frictionlessdata/tableschema-sql-py#storage | Below is the the instruction that describes the task:
### Input:
https://github.com/frictionlessdata/tableschema-sql-py#storage
### Response:
def describe(self, bucket, descriptor=None):
"""https://github.com/frictionlessdata/tableschema-sql-py#storage
"""
# Set descriptor
if descr... |
def to_gmfs(shakemap, spatialcorr, crosscorr, site_effects, trunclevel,
num_gmfs, seed, imts=None):
"""
:returns: (IMT-strings, array of GMFs of shape (R, N, E, M)
"""
N = len(shakemap) # number of sites
std = shakemap['std']
if imts is None or len(imts) == 0:
imts = std.dty... | :returns: (IMT-strings, array of GMFs of shape (R, N, E, M) | Below is the the instruction that describes the task:
### Input:
:returns: (IMT-strings, array of GMFs of shape (R, N, E, M)
### Response:
def to_gmfs(shakemap, spatialcorr, crosscorr, site_effects, trunclevel,
num_gmfs, seed, imts=None):
"""
:returns: (IMT-strings, array of GMFs of shape (R, N... |
def status(app_name=None, only_cozy=False, as_boolean=False):
'''Get apps status
:param app_name: If pass app name return this app status
:return: dict with all apps status or str with one app status
'''
apps = {}
# Get all apps status & slip them
apps_status = subprocess.Popen('cozy-monito... | Get apps status
:param app_name: If pass app name return this app status
:return: dict with all apps status or str with one app status | Below is the the instruction that describes the task:
### Input:
Get apps status
:param app_name: If pass app name return this app status
:return: dict with all apps status or str with one app status
### Response:
def status(app_name=None, only_cozy=False, as_boolean=False):
'''Get apps status
:p... |
def _remove_complex_types(dictionary):
'''
Linode-python is now returning some complex types that
are not serializable by msgpack. Kill those.
'''
for k, v in six.iteritems(dictionary):
if isinstance(v, dict):
dictionary[k] = _remove_complex_types(v)
elif hasattr(v, 'to_... | Linode-python is now returning some complex types that
are not serializable by msgpack. Kill those. | Below is the the instruction that describes the task:
### Input:
Linode-python is now returning some complex types that
are not serializable by msgpack. Kill those.
### Response:
def _remove_complex_types(dictionary):
'''
Linode-python is now returning some complex types that
are not serializable ... |
def setKeyColor( self, key, color ):
"""
Sets the color used when rendering pie charts.
:param key | <str>
color | <QColor>
"""
self._keyColors[nativestring(key)] = QColor(color) | Sets the color used when rendering pie charts.
:param key | <str>
color | <QColor> | Below is the the instruction that describes the task:
### Input:
Sets the color used when rendering pie charts.
:param key | <str>
color | <QColor>
### Response:
def setKeyColor( self, key, color ):
"""
Sets the color used when rendering pie charts.
... |
def deleteAllSubscriptions(self):
'''
Delete all subscriptions on the domain (all endpoints, all resources)
:return: successful ``.status_code`` / ``.is_done``. Check the ``.error``
:rtype: asyncResult
'''
result = asyncResult()
data = self._deleteURL("/subscriptions/")
if data.status_code == 204: #i... | Delete all subscriptions on the domain (all endpoints, all resources)
:return: successful ``.status_code`` / ``.is_done``. Check the ``.error``
:rtype: asyncResult | Below is the the instruction that describes the task:
### Input:
Delete all subscriptions on the domain (all endpoints, all resources)
:return: successful ``.status_code`` / ``.is_done``. Check the ``.error``
:rtype: asyncResult
### Response:
def deleteAllSubscriptions(self):
'''
Delete all subscription... |
def string(self, *pattern, **kwargs):
"""
Add string pattern
:param pattern:
:type pattern:
:param kwargs:
:type kwargs:
:return:
:rtype:
"""
set_defaults(self._kwargs, kwargs)
set_defaults(self._functional_defaults, kwargs)
... | Add string pattern
:param pattern:
:type pattern:
:param kwargs:
:type kwargs:
:return:
:rtype: | Below is the the instruction that describes the task:
### Input:
Add string pattern
:param pattern:
:type pattern:
:param kwargs:
:type kwargs:
:return:
:rtype:
### Response:
def string(self, *pattern, **kwargs):
"""
Add string pattern
:para... |
def application(self, func):
"""Parse the function application subgrammar.
Function application can, conceptually, be thought of as a mixfix
operator, similar to the way array subscripting works. However, it is
not clear at this point whether we want to allow it to work as such,
... | Parse the function application subgrammar.
Function application can, conceptually, be thought of as a mixfix
operator, similar to the way array subscripting works. However, it is
not clear at this point whether we want to allow it to work as such,
because doing so would permit queries t... | Below is the the instruction that describes the task:
### Input:
Parse the function application subgrammar.
Function application can, conceptually, be thought of as a mixfix
operator, similar to the way array subscripting works. However, it is
not clear at this point whether we want to allo... |
def rank(matrix, atol=1e-13, rtol=0):
"""
Estimate the rank, i.e., the dimension of the column space, of a matrix.
The algorithm used by this function is based on the singular value
decomposition of `stoichiometry_matrix`.
Parameters
----------
matrix : ndarray
The matrix should be... | Estimate the rank, i.e., the dimension of the column space, of a matrix.
The algorithm used by this function is based on the singular value
decomposition of `stoichiometry_matrix`.
Parameters
----------
matrix : ndarray
The matrix should be at most 2-D. A 1-D array with length k
w... | Below is the the instruction that describes the task:
### Input:
Estimate the rank, i.e., the dimension of the column space, of a matrix.
The algorithm used by this function is based on the singular value
decomposition of `stoichiometry_matrix`.
Parameters
----------
matrix : ndarray
T... |
def unmatched_quotes_in_line(text):
"""Return whether a string has open quotes.
This simply counts whether the number of quote characters of either
type in the string is odd.
Take from the IPython project (in IPython/core/completer.py in v0.13)
Spyder team: Add some changes to deal with escaped qu... | Return whether a string has open quotes.
This simply counts whether the number of quote characters of either
type in the string is odd.
Take from the IPython project (in IPython/core/completer.py in v0.13)
Spyder team: Add some changes to deal with escaped quotes
- Copyright (C) 2008-2011 IPython... | Below is the the instruction that describes the task:
### Input:
Return whether a string has open quotes.
This simply counts whether the number of quote characters of either
type in the string is odd.
Take from the IPython project (in IPython/core/completer.py in v0.13)
Spyder team: Add some chang... |
def sanitize_codon_list(codon_list, forbidden_seqs=()):
"""
Make silent mutations to the given codon lists to remove any undesirable
sequences that are present within it. Undesirable sequences include
restriction sites, which may be optionally specified as a second argument,
and homopolymers abo... | Make silent mutations to the given codon lists to remove any undesirable
sequences that are present within it. Undesirable sequences include
restriction sites, which may be optionally specified as a second argument,
and homopolymers above a pre-defined length. The return value is the
number of cor... | Below is the the instruction that describes the task:
### Input:
Make silent mutations to the given codon lists to remove any undesirable
sequences that are present within it. Undesirable sequences include
restriction sites, which may be optionally specified as a second argument,
and homopolymers ab... |
def _bind_and_call_constructor(self, t: type, *args) -> None:
"""
Accesses the __init__ method of a type directly and calls it with *args
This allows the constructors of both superclasses to be called, as described in get_binding.md
This could be done using two calls to super() with a ... | Accesses the __init__ method of a type directly and calls it with *args
This allows the constructors of both superclasses to be called, as described in get_binding.md
This could be done using two calls to super() with a hack based on how Python searches __mro__:
```
super().__init__(r... | Below is the the instruction that describes the task:
### Input:
Accesses the __init__ method of a type directly and calls it with *args
This allows the constructors of both superclasses to be called, as described in get_binding.md
This could be done using two calls to super() with a hack based on... |
def clear(self):
"""Removes all SSH keys from a user's system."""
r = self._h._http_resource(
method='DELETE',
resource=('user', 'keys'),
)
return r.ok | Removes all SSH keys from a user's system. | Below is the the instruction that describes the task:
### Input:
Removes all SSH keys from a user's system.
### Response:
def clear(self):
"""Removes all SSH keys from a user's system."""
r = self._h._http_resource(
method='DELETE',
resource=('user', 'keys'),
)
... |
def cli(ctx, feature_id, symbol, organism="", sequence=""):
"""Set a feature's description
Output:
A standard apollo feature dictionary ({"features": [{...}]})
"""
return ctx.gi.annotations.set_symbol(feature_id, symbol, organism=organism, sequence=sequence) | Set a feature's description
Output:
A standard apollo feature dictionary ({"features": [{...}]}) | Below is the the instruction that describes the task:
### Input:
Set a feature's description
Output:
A standard apollo feature dictionary ({"features": [{...}]})
### Response:
def cli(ctx, feature_id, symbol, organism="", sequence=""):
"""Set a feature's description
Output:
A standard apollo featur... |
def get_redirect_args(self, request, callback):
"Get request parameters for redirect url."
callback = force_text(request.build_absolute_uri(callback))
raw_token = self.get_request_token(request, callback)
token, secret = self.parse_raw_token(raw_token)
if token is not None and se... | Get request parameters for redirect url. | Below is the the instruction that describes the task:
### Input:
Get request parameters for redirect url.
### Response:
def get_redirect_args(self, request, callback):
"Get request parameters for redirect url."
callback = force_text(request.build_absolute_uri(callback))
raw_token = self.get... |
def add_subject(self, subject_id, attributes, parents=[],
issuer='default'):
"""
Will add the given subject with a given identifier and attribute
dictionary.
example/
add_subject('/user/j12y', {'username': 'j12y'})
"""
# MAINT: consider t... | Will add the given subject with a given identifier and attribute
dictionary.
example/
add_subject('/user/j12y', {'username': 'j12y'}) | Below is the the instruction that describes the task:
### Input:
Will add the given subject with a given identifier and attribute
dictionary.
example/
add_subject('/user/j12y', {'username': 'j12y'})
### Response:
def add_subject(self, subject_id, attributes, parents=[],
... |
def _get_path(path):
"""
Fetch the string value from a path-like object
Returns **None** if there is no string value.
"""
if isinstance(path, (six.string_types, bytes)):
return path
path_type = type(path)
try:
path_repr = path_type.__fspath__(path)
except AttributeError... | Fetch the string value from a path-like object
Returns **None** if there is no string value. | Below is the the instruction that describes the task:
### Input:
Fetch the string value from a path-like object
Returns **None** if there is no string value.
### Response:
def _get_path(path):
"""
Fetch the string value from a path-like object
Returns **None** if there is no string value.
"""... |
def set_available(self, show=None):
"""
Sets the agent availability to True.
Args:
show (aioxmpp.PresenceShow, optional): the show state of the presence (Default value = None)
"""
show = self.state.show if show is None else show
self.set_presence(PresenceState... | Sets the agent availability to True.
Args:
show (aioxmpp.PresenceShow, optional): the show state of the presence (Default value = None) | Below is the the instruction that describes the task:
### Input:
Sets the agent availability to True.
Args:
show (aioxmpp.PresenceShow, optional): the show state of the presence (Default value = None)
### Response:
def set_available(self, show=None):
"""
Sets the agent availabili... |
def get_answers(self):
"""
Returns a {(key,value), ...} dictionary of {(instance_id,Answer),...)}
>>> coarse_wsd = SemEval2007_Coarse_WSD()
>>> inst2ans = coarse_wsd.get_answers()
>>> for inst in inst2ans:
... print inst, inst2ans[inst
... break
"""
... | Returns a {(key,value), ...} dictionary of {(instance_id,Answer),...)}
>>> coarse_wsd = SemEval2007_Coarse_WSD()
>>> inst2ans = coarse_wsd.get_answers()
>>> for inst in inst2ans:
... print inst, inst2ans[inst
... break | Below is the the instruction that describes the task:
### Input:
Returns a {(key,value), ...} dictionary of {(instance_id,Answer),...)}
>>> coarse_wsd = SemEval2007_Coarse_WSD()
>>> inst2ans = coarse_wsd.get_answers()
>>> for inst in inst2ans:
... print inst, inst2ans[inst
... |
def isInfinite(self):
"""Check if rectangle is infinite."""
return self.x0 > self.x1 or self.y0 > self.y1 | Check if rectangle is infinite. | Below is the the instruction that describes the task:
### Input:
Check if rectangle is infinite.
### Response:
def isInfinite(self):
"""Check if rectangle is infinite."""
return self.x0 > self.x1 or self.y0 > self.y1 |
def decrypt_cbc_cts(self, data, init_vector):
"""
Return an iterator that decrypts `data` using the Cipher-Block Chaining
with Ciphertext Stealing (CBC-CTS) mode of operation.
CBC-CTS mode can only operate on `data` that is greater than 8 bytes in
length.
Each iteration, except the las... | Return an iterator that decrypts `data` using the Cipher-Block Chaining
with Ciphertext Stealing (CBC-CTS) mode of operation.
CBC-CTS mode can only operate on `data` that is greater than 8 bytes in
length.
Each iteration, except the last, always returns a block-sized :obj:`bytes`
object (i... | Below is the the instruction that describes the task:
### Input:
Return an iterator that decrypts `data` using the Cipher-Block Chaining
with Ciphertext Stealing (CBC-CTS) mode of operation.
CBC-CTS mode can only operate on `data` that is greater than 8 bytes in
length.
Each iteration, exc... |
def write_pid(self, pid=None):
"""Write the current processes PID to the pidfile location"""
pid = pid or os.getpid()
self.write_metadata_by_name(self._name, 'pid', str(pid)) | Write the current processes PID to the pidfile location | Below is the the instruction that describes the task:
### Input:
Write the current processes PID to the pidfile location
### Response:
def write_pid(self, pid=None):
"""Write the current processes PID to the pidfile location"""
pid = pid or os.getpid()
self.write_metadata_by_name(self._name, 'pid', str... |
def create_figure(*fig_args, **fig_kwargs):
'''Create a single figure.
Args and Kwargs are passed to `matplotlib.figure.Figure`.
This routine is provided in order to avoid usage of pyplot which
is stateful and not thread safe. As drawing routines in tf-matplotlib
are called from py-funcs in th... | Create a single figure.
Args and Kwargs are passed to `matplotlib.figure.Figure`.
This routine is provided in order to avoid usage of pyplot which
is stateful and not thread safe. As drawing routines in tf-matplotlib
are called from py-funcs in their respective thread, avoid usage
of pyplot wh... | Below is the the instruction that describes the task:
### Input:
Create a single figure.
Args and Kwargs are passed to `matplotlib.figure.Figure`.
This routine is provided in order to avoid usage of pyplot which
is stateful and not thread safe. As drawing routines in tf-matplotlib
are called f... |
def get_contradictory_pairs(graph: BELGraph) -> Iterable[Tuple[BaseEntity, BaseEntity]]:
"""Iterates over contradictory node pairs in the graph based on their causal relationships
:return: An iterator over (source, target) node pairs that have contradictory causal edges
"""
for u, v in graph.edges(... | Iterates over contradictory node pairs in the graph based on their causal relationships
:return: An iterator over (source, target) node pairs that have contradictory causal edges | Below is the the instruction that describes the task:
### Input:
Iterates over contradictory node pairs in the graph based on their causal relationships
:return: An iterator over (source, target) node pairs that have contradictory causal edges
### Response:
def get_contradictory_pairs(graph: BELGraph) -> ... |
def online_time_to_string(value, timeFormat, utcOffset=0):
"""Converts AGOL timestamp to formatted string.
Args:
value (float): A UTC timestamp as reported by AGOL (time in ms since Unix epoch * 1000)
timeFormat (str): Date/Time format string as parsed by :py:func:`datetime.strftime`.
u... | Converts AGOL timestamp to formatted string.
Args:
value (float): A UTC timestamp as reported by AGOL (time in ms since Unix epoch * 1000)
timeFormat (str): Date/Time format string as parsed by :py:func:`datetime.strftime`.
utcOffset (int): Hours difference from UTC and desired output. Defa... | Below is the the instruction that describes the task:
### Input:
Converts AGOL timestamp to formatted string.
Args:
value (float): A UTC timestamp as reported by AGOL (time in ms since Unix epoch * 1000)
timeFormat (str): Date/Time format string as parsed by :py:func:`datetime.strftime`.
... |
def get_revision():
"""
:returns: Revision number of this branch/checkout, if available. None if
no revision number can be determined.
"""
package_dir = os.path.dirname(__file__)
checkout_dir = os.path.normpath(os.path.join(package_dir, '..'))
path = os.path.join(checkout_dir, '.git')
... | :returns: Revision number of this branch/checkout, if available. None if
no revision number can be determined. | Below is the the instruction that describes the task:
### Input:
:returns: Revision number of this branch/checkout, if available. None if
no revision number can be determined.
### Response:
def get_revision():
"""
:returns: Revision number of this branch/checkout, if available. None if
no r... |
def set_lowest_numeric_score(self, score):
"""Sets the lowest numeric score.
arg: score (decimal): the lowest numeric score
raise: InvalidArgument - ``score`` is invalid
raise: NoAccess - ``score`` cannot be modified
*compliance: mandatory -- This method must be implemented... | Sets the lowest numeric score.
arg: score (decimal): the lowest numeric score
raise: InvalidArgument - ``score`` is invalid
raise: NoAccess - ``score`` cannot be modified
*compliance: mandatory -- This method must be implemented.* | Below is the the instruction that describes the task:
### Input:
Sets the lowest numeric score.
arg: score (decimal): the lowest numeric score
raise: InvalidArgument - ``score`` is invalid
raise: NoAccess - ``score`` cannot be modified
*compliance: mandatory -- This method must... |
def _enumload(l: Loader, value, type_) -> Enum:
"""
This loads something into an Enum.
It tries with basic types first.
If that fails, it tries to look for type annotations inside the
Enum, and tries to use those to load the value into something
that is compatible with the Enum.
Of course... | This loads something into an Enum.
It tries with basic types first.
If that fails, it tries to look for type annotations inside the
Enum, and tries to use those to load the value into something
that is compatible with the Enum.
Of course if that fails too, a ValueError is raised. | Below is the the instruction that describes the task:
### Input:
This loads something into an Enum.
It tries with basic types first.
If that fails, it tries to look for type annotations inside the
Enum, and tries to use those to load the value into something
that is compatible with the Enum.
... |
def apply_text(incoming, func):
"""Call `func` on text portions of incoming color string.
:param iter incoming: Incoming string/ColorStr/string-like object to iterate.
:param func: Function to call with string portion as first and only parameter.
:return: Modified string, same class type as incoming s... | Call `func` on text portions of incoming color string.
:param iter incoming: Incoming string/ColorStr/string-like object to iterate.
:param func: Function to call with string portion as first and only parameter.
:return: Modified string, same class type as incoming string. | Below is the the instruction that describes the task:
### Input:
Call `func` on text portions of incoming color string.
:param iter incoming: Incoming string/ColorStr/string-like object to iterate.
:param func: Function to call with string portion as first and only parameter.
:return: Modified string,... |
def get_jobs(self, limit=10, skip=0, backend=None, only_completed=False, filter=None, hub=None, group=None, project=None, access_token=None, user_id=None):
"""
Get the information about the user jobs
"""
if access_token:
self.req.credential.set_token(access_token)
if ... | Get the information about the user jobs | Below is the the instruction that describes the task:
### Input:
Get the information about the user jobs
### Response:
def get_jobs(self, limit=10, skip=0, backend=None, only_completed=False, filter=None, hub=None, group=None, project=None, access_token=None, user_id=None):
"""
Get the information ... |
def querying_context(self, packet_type):
""" Context manager for querying.
Sets state to TDS_QUERYING, and reverts it to TDS_IDLE if exception happens inside managed block,
and to TDS_PENDING if managed block succeeds and flushes buffer.
"""
if self.set_state(tds_base.TDS_QUERYI... | Context manager for querying.
Sets state to TDS_QUERYING, and reverts it to TDS_IDLE if exception happens inside managed block,
and to TDS_PENDING if managed block succeeds and flushes buffer. | Below is the the instruction that describes the task:
### Input:
Context manager for querying.
Sets state to TDS_QUERYING, and reverts it to TDS_IDLE if exception happens inside managed block,
and to TDS_PENDING if managed block succeeds and flushes buffer.
### Response:
def querying_context(self,... |
def cmd_gimbal_mode(self, args):
'''control gimbal mode'''
if len(args) != 1:
print("usage: gimbal mode <GPS|MAVLink>")
return
if args[0].upper() == 'GPS':
mode = mavutil.mavlink.MAV_MOUNT_MODE_GPS_POINT
elif args[0].upper() == 'MAVLINK':
m... | control gimbal mode | Below is the the instruction that describes the task:
### Input:
control gimbal mode
### Response:
def cmd_gimbal_mode(self, args):
'''control gimbal mode'''
if len(args) != 1:
print("usage: gimbal mode <GPS|MAVLink>")
return
if args[0].upper() == 'GPS':
... |
def _set_index(self, schema, name, fields, **index_options):
"""
NOTE -- we set the index name using <table_name>_<name> format since indexes have to have
a globally unique name in postgres
http://www.postgresql.org/docs/9.1/static/sql-createindex.html
"""
index_fields =... | NOTE -- we set the index name using <table_name>_<name> format since indexes have to have
a globally unique name in postgres
http://www.postgresql.org/docs/9.1/static/sql-createindex.html | Below is the the instruction that describes the task:
### Input:
NOTE -- we set the index name using <table_name>_<name> format since indexes have to have
a globally unique name in postgres
http://www.postgresql.org/docs/9.1/static/sql-createindex.html
### Response:
def _set_index(self, schema, na... |
def _get_translation(self, field, code):
"""
Gets the translation of a specific field for a specific language code.
This raises ObjectDoesNotExist if the lookup was unsuccesful. As of
today, this stuff is cached. As the cache is rather aggressive it
might cause rather strange ef... | Gets the translation of a specific field for a specific language code.
This raises ObjectDoesNotExist if the lookup was unsuccesful. As of
today, this stuff is cached. As the cache is rather aggressive it
might cause rather strange effects. However, we would see the same
effects when an... | Below is the the instruction that describes the task:
### Input:
Gets the translation of a specific field for a specific language code.
This raises ObjectDoesNotExist if the lookup was unsuccesful. As of
today, this stuff is cached. As the cache is rather aggressive it
might cause rather st... |
def _computeChart(chart, date):
""" Internal function to return a new chart for
a specific date using properties from old chart.
"""
pos = chart.pos
hsys = chart.hsys
IDs = [obj.id for obj in chart.objects]
return Chart(date, pos, IDs=IDs, hsys=hsys) | Internal function to return a new chart for
a specific date using properties from old chart. | Below is the the instruction that describes the task:
### Input:
Internal function to return a new chart for
a specific date using properties from old chart.
### Response:
def _computeChart(chart, date):
""" Internal function to return a new chart for
a specific date using properties from old chart.
... |
def DbGetClassForDevice(self, argin):
""" Get Tango class for the specified device.
:param argin: Device name
:type: tango.DevString
:return: Device Tango class
:rtype: tango.DevString """
self._log.debug("In DbGetClassForDevice()")
return self.db.get_class_for_d... | Get Tango class for the specified device.
:param argin: Device name
:type: tango.DevString
:return: Device Tango class
:rtype: tango.DevString | Below is the the instruction that describes the task:
### Input:
Get Tango class for the specified device.
:param argin: Device name
:type: tango.DevString
:return: Device Tango class
:rtype: tango.DevString
### Response:
def DbGetClassForDevice(self, argin):
""" Get Tango ... |
def inspectSpatialPoolerStats(sp, inputVectors, saveFigPrefix=None):
"""
Inspect the statistics of a spatial pooler given a set of input vectors
@param sp: an spatial pooler instance
@param inputVectors: a set of input vectors
"""
numInputVector, inputSize = inputVectors.shape
numColumns = np.prod(sp.getC... | Inspect the statistics of a spatial pooler given a set of input vectors
@param sp: an spatial pooler instance
@param inputVectors: a set of input vectors | Below is the the instruction that describes the task:
### Input:
Inspect the statistics of a spatial pooler given a set of input vectors
@param sp: an spatial pooler instance
@param inputVectors: a set of input vectors
### Response:
def inspectSpatialPoolerStats(sp, inputVectors, saveFigPrefix=None):
"""
I... |
def update(self, key=values.unset, value=values.unset):
"""
Update the VariableInstance
:param unicode key: The key
:param unicode value: The value
:returns: Updated VariableInstance
:rtype: twilio.rest.serverless.v1.service.environment.variable.VariableInstance
... | Update the VariableInstance
:param unicode key: The key
:param unicode value: The value
:returns: Updated VariableInstance
:rtype: twilio.rest.serverless.v1.service.environment.variable.VariableInstance | Below is the the instruction that describes the task:
### Input:
Update the VariableInstance
:param unicode key: The key
:param unicode value: The value
:returns: Updated VariableInstance
:rtype: twilio.rest.serverless.v1.service.environment.variable.VariableInstance
### Response: ... |
async def freeze(self, *args, **kwargs):
"""
Freeze users balance
Accepts:
- uid [integer] (users id from main server)
- coinid [string] (blockchain type in uppercase)
- amount [integer] (amount for freezing)
Returns:
- uid [integer] (users id from main server)
- coinid [string] (blockchain typ... | Freeze users balance
Accepts:
- uid [integer] (users id from main server)
- coinid [string] (blockchain type in uppercase)
- amount [integer] (amount for freezing)
Returns:
- uid [integer] (users id from main server)
- coinid [string] (blockchain type in uppercase)
- amount_active [integer] (act... | Below is the the instruction that describes the task:
### Input:
Freeze users balance
Accepts:
- uid [integer] (users id from main server)
- coinid [string] (blockchain type in uppercase)
- amount [integer] (amount for freezing)
Returns:
- uid [integer] (users id from main server)
- coinid [str... |
def _check_err(data):
"""
:param data: response json data object (must be not None).
Check possible error code returned in the response body
raise the coresponding exceptions
"""
if data['d'] is None:
raise NoDataReturned()
if data['d']['Messages'] is None:
return
msg = ... | :param data: response json data object (must be not None).
Check possible error code returned in the response body
raise the coresponding exceptions | Below is the the instruction that describes the task:
### Input:
:param data: response json data object (must be not None).
Check possible error code returned in the response body
raise the coresponding exceptions
### Response:
def _check_err(data):
"""
:param data: response json data object (must ... |
def load_json_fixture(fixture_path: str) -> Dict[str, Any]:
"""
Loads a fixture file, caching the most recent files it loaded.
"""
with open(fixture_path) as fixture_file:
file_fixtures = json.load(fixture_file)
return file_fixtures | Loads a fixture file, caching the most recent files it loaded. | Below is the the instruction that describes the task:
### Input:
Loads a fixture file, caching the most recent files it loaded.
### Response:
def load_json_fixture(fixture_path: str) -> Dict[str, Any]:
"""
Loads a fixture file, caching the most recent files it loaded.
"""
with open(fixture_path) as... |
def _logsumexp(ary, *, b=None, b_inv=None, axis=None, keepdims=False, out=None, copy=True):
"""Stable logsumexp when b >= 0 and b is scalar.
b_inv overwrites b unless b_inv is None.
"""
# check dimensions for result arrays
ary = np.asarray(ary)
if ary.dtype.kind == "i":
ary = ary.astype... | Stable logsumexp when b >= 0 and b is scalar.
b_inv overwrites b unless b_inv is None. | Below is the the instruction that describes the task:
### Input:
Stable logsumexp when b >= 0 and b is scalar.
b_inv overwrites b unless b_inv is None.
### Response:
def _logsumexp(ary, *, b=None, b_inv=None, axis=None, keepdims=False, out=None, copy=True):
"""Stable logsumexp when b >= 0 and b is scalar.... |
def sessions(status, access_key, id_only, all):
'''
List and manage compute sessions.
'''
fields = [
('Session ID', 'sess_id'),
]
with Session() as session:
if is_admin(session):
fields.append(('Owner', 'access_key'))
if not id_only:
fields.extend([
... | List and manage compute sessions. | Below is the the instruction that describes the task:
### Input:
List and manage compute sessions.
### Response:
def sessions(status, access_key, id_only, all):
'''
List and manage compute sessions.
'''
fields = [
('Session ID', 'sess_id'),
]
with Session() as session:
if is... |
def register_magics(store_name='_ampl_cells', ampl_object=None):
"""
Register jupyter notebook magics ``%%ampl`` and ``%%ampl_eval``.
Args:
store_name: Name of the store where ``%%ampl cells`` will be stored.
ampl_object: Object used to evaluate ``%%ampl_eval`` cells.
"""
from IPyth... | Register jupyter notebook magics ``%%ampl`` and ``%%ampl_eval``.
Args:
store_name: Name of the store where ``%%ampl cells`` will be stored.
ampl_object: Object used to evaluate ``%%ampl_eval`` cells. | Below is the the instruction that describes the task:
### Input:
Register jupyter notebook magics ``%%ampl`` and ``%%ampl_eval``.
Args:
store_name: Name of the store where ``%%ampl cells`` will be stored.
ampl_object: Object used to evaluate ``%%ampl_eval`` cells.
### Response:
def register_ma... |
def send_text(self, txt, status=200):
"""
Sends plaintext response to client. Automatically sets the content-type
header to text/plain. If txt is not a string, it will be formatted as
one.
Parameters
----------
txt : str
The plaintext string to be sen... | Sends plaintext response to client. Automatically sets the content-type
header to text/plain. If txt is not a string, it will be formatted as
one.
Parameters
----------
txt : str
The plaintext string to be sent back to the client
status : int, optional
... | Below is the the instruction that describes the task:
### Input:
Sends plaintext response to client. Automatically sets the content-type
header to text/plain. If txt is not a string, it will be formatted as
one.
Parameters
----------
txt : str
The plaintext strin... |
def close(self):
"""
Closes the job manager. No more jobs will be assigned, no more job sets
will be added, and any queued or active job sets will be cancelled.
"""
if self._closed:
return
self._closed = True
if self._active_js is not None:
... | Closes the job manager. No more jobs will be assigned, no more job sets
will be added, and any queued or active job sets will be cancelled. | Below is the the instruction that describes the task:
### Input:
Closes the job manager. No more jobs will be assigned, no more job sets
will be added, and any queued or active job sets will be cancelled.
### Response:
def close(self):
"""
Closes the job manager. No more jobs will be assign... |
def add_view(self, *args, **kwargs):
"""
Redirect to the change view if the singleton instance exists.
"""
try:
singleton = self.model.objects.get()
except (self.model.DoesNotExist, self.model.MultipleObjectsReturned):
kwargs.setdefault("extra_context", {}... | Redirect to the change view if the singleton instance exists. | Below is the the instruction that describes the task:
### Input:
Redirect to the change view if the singleton instance exists.
### Response:
def add_view(self, *args, **kwargs):
"""
Redirect to the change view if the singleton instance exists.
"""
try:
singleton = self.m... |
def next_date(self):
"""
Date when this event is next scheduled to occur in the local time zone
(Does not include postponements, but does exclude cancellations)
"""
nextDt = self.__localAfter(timezone.localtime(), dt.time.min)
if nextDt is not None:
return nex... | Date when this event is next scheduled to occur in the local time zone
(Does not include postponements, but does exclude cancellations) | Below is the the instruction that describes the task:
### Input:
Date when this event is next scheduled to occur in the local time zone
(Does not include postponements, but does exclude cancellations)
### Response:
def next_date(self):
"""
Date when this event is next scheduled to occur in ... |
def get_current(self):
"""Get current forecast."""
now = dt.now().timestamp()
url = build_url(self.api_key, self.spot_id, self.fields,
self.unit, now, now)
return get_msw(url) | Get current forecast. | Below is the the instruction that describes the task:
### Input:
Get current forecast.
### Response:
def get_current(self):
"""Get current forecast."""
now = dt.now().timestamp()
url = build_url(self.api_key, self.spot_id, self.fields,
self.unit, now, now)
re... |
def get_template(
self,
url,
dest,
template='jinja',
makedirs=False,
saltenv='base',
cachedir=None,
**kwargs):
'''
Cache a file then process it as a template
'''
if 'env' in kwargs:
... | Cache a file then process it as a template | Below is the the instruction that describes the task:
### Input:
Cache a file then process it as a template
### Response:
def get_template(
self,
url,
dest,
template='jinja',
makedirs=False,
saltenv='base',
cachedir=None,
... |
def mpr(truth, recommend):
"""Mean Percentile Rank (MPR).
Args:
truth (numpy 1d array): Set of truth samples.
recommend (numpy 1d array): Ordered set of recommended samples.
Returns:
float: MPR.
"""
if len(recommend) == 0 and len(truth) == 0:
return 0. # best
... | Mean Percentile Rank (MPR).
Args:
truth (numpy 1d array): Set of truth samples.
recommend (numpy 1d array): Ordered set of recommended samples.
Returns:
float: MPR. | Below is the the instruction that describes the task:
### Input:
Mean Percentile Rank (MPR).
Args:
truth (numpy 1d array): Set of truth samples.
recommend (numpy 1d array): Ordered set of recommended samples.
Returns:
float: MPR.
### Response:
def mpr(truth, recommend):
"""Mea... |
def _prompt_wrapper(message, default=None, validator=None):
""" Handle references piped from file
"""
class MockDocument:
def __init__(self, text):
self.text = text
if HAS_INPUT:
ret = prompt(message, default=default, validator=validator)
else:
ret = sys.stdin.... | Handle references piped from file | Below is the the instruction that describes the task:
### Input:
Handle references piped from file
### Response:
def _prompt_wrapper(message, default=None, validator=None):
""" Handle references piped from file
"""
class MockDocument:
def __init__(self, text):
self.text = text
... |
def get_iterator_from_config(config: dict, data: dict):
"""Create iterator (from config) for specified data."""
iterator_config = config['dataset_iterator']
iterator: Union[DataLearningIterator, DataFittingIterator] = from_params(iterator_config,
... | Create iterator (from config) for specified data. | Below is the the instruction that describes the task:
### Input:
Create iterator (from config) for specified data.
### Response:
def get_iterator_from_config(config: dict, data: dict):
"""Create iterator (from config) for specified data."""
iterator_config = config['dataset_iterator']
iterator: Union[D... |
def _adjust(a, a_offset, b):
"""
a = bytearray
a_offset = int
b = bytearray
"""
x = (b[-1] & 0xFF) + (a[a_offset + len(b) - 1] & 0xFF) + 1
a[a_offset + len(b) - 1] = ctypes.c_ubyte(x).value
x >>= 8
for i in range(len(b)-2, -1, -1):
x += (b[i] & 0xFF) + (a[a_offset + i] & 0xF... | a = bytearray
a_offset = int
b = bytearray | Below is the the instruction that describes the task:
### Input:
a = bytearray
a_offset = int
b = bytearray
### Response:
def _adjust(a, a_offset, b):
"""
a = bytearray
a_offset = int
b = bytearray
"""
x = (b[-1] & 0xFF) + (a[a_offset + len(b) - 1] & 0xFF) + 1
a[a_offset + len(b... |
def cron(name, timespec, user, command, environ=None, disable=False):
"""Create entry in /etc/cron.d"""
path = '/etc/cron.d/{}'.format(name)
if disable:
sudo('rm ' + path)
return
entry = '{}\t{}\t{}\n'.format(timespec, user, command)
if environ:
envstr = '\n'.join('{}={}'.for... | Create entry in /etc/cron.d | Below is the the instruction that describes the task:
### Input:
Create entry in /etc/cron.d
### Response:
def cron(name, timespec, user, command, environ=None, disable=False):
"""Create entry in /etc/cron.d"""
path = '/etc/cron.d/{}'.format(name)
if disable:
sudo('rm ' + path)
return
... |
def delete_publisher_asset(self, publisher_name, asset_type=None):
"""DeletePublisherAsset.
[Preview API] Delete publisher asset like logo
:param str publisher_name: Internal name of the publisher
:param str asset_type: Type of asset. Default value is 'logo'.
"""
route_va... | DeletePublisherAsset.
[Preview API] Delete publisher asset like logo
:param str publisher_name: Internal name of the publisher
:param str asset_type: Type of asset. Default value is 'logo'. | Below is the the instruction that describes the task:
### Input:
DeletePublisherAsset.
[Preview API] Delete publisher asset like logo
:param str publisher_name: Internal name of the publisher
:param str asset_type: Type of asset. Default value is 'logo'.
### Response:
def delete_publisher_a... |
def _archive_single_dir(archive):
"""
Check if all members of the archive are in a single top-level directory
:param archive:
An archive from _open_archive()
:return:
None if not a single top level directory in archive, otherwise a
unicode string of the top level directory name... | Check if all members of the archive are in a single top-level directory
:param archive:
An archive from _open_archive()
:return:
None if not a single top level directory in archive, otherwise a
unicode string of the top level directory name | Below is the the instruction that describes the task:
### Input:
Check if all members of the archive are in a single top-level directory
:param archive:
An archive from _open_archive()
:return:
None if not a single top level directory in archive, otherwise a
unicode string of the t... |
def send_xapi_statements(self, lrs_configuration, days):
"""
Send xAPI analytics data of the enterprise learners to the given LRS.
Arguments:
lrs_configuration (XAPILRSConfiguration): Configuration object containing LRS configurations
of the LRS where to send xAPI l... | Send xAPI analytics data of the enterprise learners to the given LRS.
Arguments:
lrs_configuration (XAPILRSConfiguration): Configuration object containing LRS configurations
of the LRS where to send xAPI learner analytics.
days (int): Include course enrollment of this n... | Below is the the instruction that describes the task:
### Input:
Send xAPI analytics data of the enterprise learners to the given LRS.
Arguments:
lrs_configuration (XAPILRSConfiguration): Configuration object containing LRS configurations
of the LRS where to send xAPI learner a... |
def specimens_results_magic(infile='pmag_specimens.txt', measfile='magic_measurements.txt', sampfile='er_samples.txt', sitefile='er_sites.txt', agefile='er_ages.txt', specout='er_specimens.txt', sampout='pmag_samples.txt', siteout='pmag_sites.txt', resout='pmag_results.txt', critout='pmag_criteria.txt', instout='magic_... | Writes magic_instruments, er_specimens, pmag_samples, pmag_sites, pmag_criteria, and pmag_results. The data used to write this is obtained by reading a pmag_speciemns, a magic_measurements, a er_samples, a er_sites, a er_ages.
@param -> infile: path from the WD to the pmag speciemns table
@param -> measfile: pa... | Below is the the instruction that describes the task:
### Input:
Writes magic_instruments, er_specimens, pmag_samples, pmag_sites, pmag_criteria, and pmag_results. The data used to write this is obtained by reading a pmag_speciemns, a magic_measurements, a er_samples, a er_sites, a er_ages.
@param -> infile: pa... |
def sort_subtrees(self, *subtrees):
"""sort the given subtrees (of type DGParentedTree) based on their
linear position in this RSTTree. If two subtrees have the same
linear position in the RSTTree (i.e. one is a child of the other),
they are sorted by their height in reverse order (i.e. ... | sort the given subtrees (of type DGParentedTree) based on their
linear position in this RSTTree. If two subtrees have the same
linear position in the RSTTree (i.e. one is a child of the other),
they are sorted by their height in reverse order (i.e. the child
appears before its parent). | Below is the the instruction that describes the task:
### Input:
sort the given subtrees (of type DGParentedTree) based on their
linear position in this RSTTree. If two subtrees have the same
linear position in the RSTTree (i.e. one is a child of the other),
they are sorted by their height i... |
def legal_node_coords():
"""
Return all legal node coordinates on the grid
"""
nodes = set()
for tile_id in legal_tile_ids():
for node in nodes_touching_tile(tile_id):
nodes.add(node)
logging.debug('Legal node coords({})={}'.format(len(nodes), nodes))
return nodes | Return all legal node coordinates on the grid | Below is the the instruction that describes the task:
### Input:
Return all legal node coordinates on the grid
### Response:
def legal_node_coords():
"""
Return all legal node coordinates on the grid
"""
nodes = set()
for tile_id in legal_tile_ids():
for node in nodes_touching_tile(tile... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.