code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def save_data(self,session, exp_id, content):
'''save data will obtain the current subid from the session, and save it
depending on the database type. Currently we just support flat files'''
from expfactory.database.models import (
Participant,
Result
)
subid = session.get('subid'... | save data will obtain the current subid from the session, and save it
depending on the database type. Currently we just support flat files | Below is the the instruction that describes the task:
### Input:
save data will obtain the current subid from the session, and save it
depending on the database type. Currently we just support flat files
### Response:
def save_data(self,session, exp_id, content):
'''save data will obtain the current sub... |
def subset_by_supported(input_file, get_coords, calls_by_name, work_dir, data,
headers=("#",)):
"""Limit CNVkit input to calls with support from another caller.
get_coords is a function that return chrom, start, end from a line of the
input_file, allowing handling of multiple input ... | Limit CNVkit input to calls with support from another caller.
get_coords is a function that return chrom, start, end from a line of the
input_file, allowing handling of multiple input file types. | Below is the the instruction that describes the task:
### Input:
Limit CNVkit input to calls with support from another caller.
get_coords is a function that return chrom, start, end from a line of the
input_file, allowing handling of multiple input file types.
### Response:
def subset_by_supported(input_f... |
def add_special(self, name):
"""Register a special name like `loop`."""
self.undeclared.discard(name)
self.declared.add(name) | Register a special name like `loop`. | Below is the the instruction that describes the task:
### Input:
Register a special name like `loop`.
### Response:
def add_special(self, name):
"""Register a special name like `loop`."""
self.undeclared.discard(name)
self.declared.add(name) |
def enable_i2c(self):
"""Set this to `True` to enable the hardware I2C interface. If set to
`False` the hardware interface will be disabled and its pins (SDA and
SCL) can be used as GPIOs.
"""
config = self._interface_configuration(CONFIG_QUERY)
return config == CONFIG_GP... | Set this to `True` to enable the hardware I2C interface. If set to
`False` the hardware interface will be disabled and its pins (SDA and
SCL) can be used as GPIOs. | Below is the the instruction that describes the task:
### Input:
Set this to `True` to enable the hardware I2C interface. If set to
`False` the hardware interface will be disabled and its pins (SDA and
SCL) can be used as GPIOs.
### Response:
def enable_i2c(self):
"""Set this to `True` to e... |
def get_user_data_iobject(user=None,group=None,data_kind=DINGOS_USER_DATA_TYPE_NAME):
"""
Returns either stored settings of a given user or default settings.
This behavior reflects the need for views to have some settings at
hand when running. The settings are returned as dict object.
... | Returns either stored settings of a given user or default settings.
This behavior reflects the need for views to have some settings at
hand when running. The settings are returned as dict object. | Below is the the instruction that describes the task:
### Input:
Returns either stored settings of a given user or default settings.
This behavior reflects the need for views to have some settings at
hand when running. The settings are returned as dict object.
### Response:
def get_user_data_iobjec... |
def cached_idxs(method):
""" this function is used as a decorator for caching """
def method_wrapper(self,*args,**kwargs):
tail = '_'.join(str(idx) for idx in args)
_cache_attr_name = '_cache_'+method.__name__+'_'+tail
_bool_attr_name = '_cached_'+method.__name__+'_'+tail
is_cac... | this function is used as a decorator for caching | Below is the the instruction that describes the task:
### Input:
this function is used as a decorator for caching
### Response:
def cached_idxs(method):
""" this function is used as a decorator for caching """
def method_wrapper(self,*args,**kwargs):
tail = '_'.join(str(idx) for idx in args)
... |
def indent(instr,nspaces=4, ntabs=0, flatten=False):
"""Indent a string a given number of spaces or tabstops.
indent(str,nspaces=4,ntabs=0) -> indent str by ntabs+nspaces.
Parameters
----------
instr : basestring
The string to be indented.
nspaces : int (default: 4)
The number... | Indent a string a given number of spaces or tabstops.
indent(str,nspaces=4,ntabs=0) -> indent str by ntabs+nspaces.
Parameters
----------
instr : basestring
The string to be indented.
nspaces : int (default: 4)
The number of spaces to be indented.
ntabs : int (default: 0)
... | Below is the the instruction that describes the task:
### Input:
Indent a string a given number of spaces or tabstops.
indent(str,nspaces=4,ntabs=0) -> indent str by ntabs+nspaces.
Parameters
----------
instr : basestring
The string to be indented.
nspaces : int (default: 4)
T... |
def to_lonlat(xtile, ytile, zoom):
"""Returns a tuple of (longitude, latitude) from a map tile xyz coordinate.
See http://wiki.openstreetmap.org/wiki/Slippy_map_tilenames#Lon..2Flat._to_tile_numbers_2
Arguments:
xtile - x tile location as int or float
ytile - y tile location as int or float
zo... | Returns a tuple of (longitude, latitude) from a map tile xyz coordinate.
See http://wiki.openstreetmap.org/wiki/Slippy_map_tilenames#Lon..2Flat._to_tile_numbers_2
Arguments:
xtile - x tile location as int or float
ytile - y tile location as int or float
zoom - zoom level as int or float | Below is the the instruction that describes the task:
### Input:
Returns a tuple of (longitude, latitude) from a map tile xyz coordinate.
See http://wiki.openstreetmap.org/wiki/Slippy_map_tilenames#Lon..2Flat._to_tile_numbers_2
Arguments:
xtile - x tile location as int or float
ytile - y tile loca... |
def _connect(self):
"""Connect to PostgreSQL, either by reusing a connection from the pool
if possible, or by creating the new connection.
:rtype: psycopg2.extensions.connection
:raises: pool.NoIdleConnectionsError
"""
# Attempt to get a cached connection from the conne... | Connect to PostgreSQL, either by reusing a connection from the pool
if possible, or by creating the new connection.
:rtype: psycopg2.extensions.connection
:raises: pool.NoIdleConnectionsError | Below is the the instruction that describes the task:
### Input:
Connect to PostgreSQL, either by reusing a connection from the pool
if possible, or by creating the new connection.
:rtype: psycopg2.extensions.connection
:raises: pool.NoIdleConnectionsError
### Response:
def _connect(self):... |
def _factory(slice_, axis, weighted):
"""return subclass for PairwiseSignificance, based on slice dimension types."""
if slice_.dim_types[0] == DT.MR_SUBVAR:
return _MrXCatPairwiseSignificance(slice_, axis, weighted)
return _CatXCatPairwiseSignificance(slice_, axis, weighted) | return subclass for PairwiseSignificance, based on slice dimension types. | Below is the the instruction that describes the task:
### Input:
return subclass for PairwiseSignificance, based on slice dimension types.
### Response:
def _factory(slice_, axis, weighted):
"""return subclass for PairwiseSignificance, based on slice dimension types."""
if slice_.dim_types[0] == DT... |
def write_fits(data, header, file_name):
"""
Combine data and a fits header to write a fits file.
Parameters
----------
data : numpy.ndarray
The data to be written.
header : astropy.io.fits.hduheader
The header for the fits file.
file_name : string
The file to writ... | Combine data and a fits header to write a fits file.
Parameters
----------
data : numpy.ndarray
The data to be written.
header : astropy.io.fits.hduheader
The header for the fits file.
file_name : string
The file to write
Returns
-------
None | Below is the the instruction that describes the task:
### Input:
Combine data and a fits header to write a fits file.
Parameters
----------
data : numpy.ndarray
The data to be written.
header : astropy.io.fits.hduheader
The header for the fits file.
file_name : string
... |
def update_channels(self):
'''update which channels provide input'''
self.interlock_channel = -1
self.override_channel = -1
self.zero_I_channel = -1
self.no_vtol_channel = -1
# output channels
self.rsc_out_channel = 9
self.fwd_thr_channel = 10
fo... | update which channels provide input | Below is the the instruction that describes the task:
### Input:
update which channels provide input
### Response:
def update_channels(self):
'''update which channels provide input'''
self.interlock_channel = -1
self.override_channel = -1
self.zero_I_channel = -1
self.no_vto... |
def declination_spencer71(dayofyear):
"""
Solar declination from Duffie & Beckman [1] and attributed to
Spencer (1971) and Iqbal (1983).
.. warning::
Return units are radians, not degrees.
Parameters
----------
dayofyear : numeric
Returns
-------
declination (radians) ... | Solar declination from Duffie & Beckman [1] and attributed to
Spencer (1971) and Iqbal (1983).
.. warning::
Return units are radians, not degrees.
Parameters
----------
dayofyear : numeric
Returns
-------
declination (radians) : numeric
Angular position of the sun at s... | Below is the the instruction that describes the task:
### Input:
Solar declination from Duffie & Beckman [1] and attributed to
Spencer (1971) and Iqbal (1983).
.. warning::
Return units are radians, not degrees.
Parameters
----------
dayofyear : numeric
Returns
-------
dec... |
def pull_3year(self):
"""Returns a list (in JSON format) containing all the events from the Penn iCal Calendar.
List contains events in chronological order.
Each element of the list is a dictionary, containing:
- Name of the event 'name'
- Start date 'start'
... | Returns a list (in JSON format) containing all the events from the Penn iCal Calendar.
List contains events in chronological order.
Each element of the list is a dictionary, containing:
- Name of the event 'name'
- Start date 'start'
- End date 'end' | Below is the the instruction that describes the task:
### Input:
Returns a list (in JSON format) containing all the events from the Penn iCal Calendar.
List contains events in chronological order.
Each element of the list is a dictionary, containing:
- Name of the event 'name'
... |
def validateOneElement(self, doc, elem):
"""Try to validate a single element and it's attributes,
basically it does the following checks as described by the
XML-1.0 recommendation: - [ VC: Element Valid ] - [ VC:
Required Attribute ] Then call xmlValidateOneAttribute()
fo... | Try to validate a single element and it's attributes,
basically it does the following checks as described by the
XML-1.0 recommendation: - [ VC: Element Valid ] - [ VC:
Required Attribute ] Then call xmlValidateOneAttribute()
for each attribute present. The ID/IDREF checkings ar... | Below is the the instruction that describes the task:
### Input:
Try to validate a single element and it's attributes,
basically it does the following checks as described by the
XML-1.0 recommendation: - [ VC: Element Valid ] - [ VC:
Required Attribute ] Then call xmlValidateOneAttribu... |
def idle_task(self):
'''called in idle time'''
try:
data = self.port.recv(200)
except socket.error as e:
if e.errno in [ errno.EAGAIN, errno.EWOULDBLOCK ]:
return
raise
if len(data) > 110:
print("DGPS data too large: %u byte... | called in idle time | Below is the the instruction that describes the task:
### Input:
called in idle time
### Response:
def idle_task(self):
'''called in idle time'''
try:
data = self.port.recv(200)
except socket.error as e:
if e.errno in [ errno.EAGAIN, errno.EWOULDBLOCK ]:
... |
def validate(self, size):
"""
Ensure that the size of the dimension matches the number of bands in the
scale
Raises:
ValueError: when the dimension size and number of bands don't match
"""
msg = 'scale and array size must match, ' \
'but were s... | Ensure that the size of the dimension matches the number of bands in the
scale
Raises:
ValueError: when the dimension size and number of bands don't match | Below is the the instruction that describes the task:
### Input:
Ensure that the size of the dimension matches the number of bands in the
scale
Raises:
ValueError: when the dimension size and number of bands don't match
### Response:
def validate(self, size):
"""
Ensur... |
def _initiate_starttls(self, **kwargs):
"""Initiate starttls handshake over the socket.
"""
if self._tls_state == "connected":
raise RuntimeError("Already TLS-connected")
kwargs["do_handshake_on_connect"] = False
logger.debug("Wrapping the socket into ssl")
se... | Initiate starttls handshake over the socket. | Below is the the instruction that describes the task:
### Input:
Initiate starttls handshake over the socket.
### Response:
def _initiate_starttls(self, **kwargs):
"""Initiate starttls handshake over the socket.
"""
if self._tls_state == "connected":
raise RuntimeError("Already ... |
def next(self):
"""Move iterator position forward"""
batch = mx.nd.zeros((self.batch_size, self.size[1], self.size[0], 3))
i = self.cur
for i in range(self.cur, min(len(self.list), self.cur+self.batch_size)):
str_img = open(self.root+self.list[i]+'.jpg').read()
im... | Move iterator position forward | Below is the the instruction that describes the task:
### Input:
Move iterator position forward
### Response:
def next(self):
"""Move iterator position forward"""
batch = mx.nd.zeros((self.batch_size, self.size[1], self.size[0], 3))
i = self.cur
for i in range(self.cur, min(len(self... |
def add_key(self):
"Add ssh key to gitlab if necessary"
try:
with open(self.args.ssh_public_key) as f:
public_key = f.read().strip()
except:
log.debug("No key found in {}".format(self.args.ssh_public_key))
return None
g = self.gitlab
... | Add ssh key to gitlab if necessary | Below is the the instruction that describes the task:
### Input:
Add ssh key to gitlab if necessary
### Response:
def add_key(self):
"Add ssh key to gitlab if necessary"
try:
with open(self.args.ssh_public_key) as f:
public_key = f.read().strip()
except:
... |
def _get_perspective_coeffs(startpoints, endpoints):
"""Helper function to get the coefficients (a, b, c, d, e, f, g, h) for the perspective transforms.
In Perspective Transform each pixel (x, y) in the orignal image gets transformed as,
(x, y) -> ( (ax + by + c) / (gx + hy + 1), (dx + ey + f) / (gx + hy ... | Helper function to get the coefficients (a, b, c, d, e, f, g, h) for the perspective transforms.
In Perspective Transform each pixel (x, y) in the orignal image gets transformed as,
(x, y) -> ( (ax + by + c) / (gx + hy + 1), (dx + ey + f) / (gx + hy + 1) )
Args:
List containing [top-left, top-rig... | Below is the the instruction that describes the task:
### Input:
Helper function to get the coefficients (a, b, c, d, e, f, g, h) for the perspective transforms.
In Perspective Transform each pixel (x, y) in the orignal image gets transformed as,
(x, y) -> ( (ax + by + c) / (gx + hy + 1), (dx + ey + f) / ... |
def process_frames_mouth(self, frames):
"""
Preprocess from frames using mouth detector
"""
self.face = np.array(frames)
self.mouth = np.array(frames)
self.set_data(frames) | Preprocess from frames using mouth detector | Below is the the instruction that describes the task:
### Input:
Preprocess from frames using mouth detector
### Response:
def process_frames_mouth(self, frames):
"""
Preprocess from frames using mouth detector
"""
self.face = np.array(frames)
self.mouth = np.array(frames)
... |
def to_api(in_dict, int_keys=None, date_keys=None, bool_keys=None):
"""Extends a given object for API Production."""
# Cast all int_keys to int()
if int_keys:
for in_key in int_keys:
if (in_key in in_dict) and (in_dict.get(in_key, None) is not None):
in_dict[in_key] = in... | Extends a given object for API Production. | Below is the the instruction that describes the task:
### Input:
Extends a given object for API Production.
### Response:
def to_api(in_dict, int_keys=None, date_keys=None, bool_keys=None):
"""Extends a given object for API Production."""
# Cast all int_keys to int()
if int_keys:
for in_key in... |
def load_settings(self, daemon_config, context, origin=None):
"""
The pollers have dependency on the context manager
of the X-Ray recorder. They will respect the customer
specified xray client to poll sampling rules/targets.
Otherwise they falls back to use the same X-Ray daemon
... | The pollers have dependency on the context manager
of the X-Ray recorder. They will respect the customer
specified xray client to poll sampling rules/targets.
Otherwise they falls back to use the same X-Ray daemon
as the emitter. | Below is the the instruction that describes the task:
### Input:
The pollers have dependency on the context manager
of the X-Ray recorder. They will respect the customer
specified xray client to poll sampling rules/targets.
Otherwise they falls back to use the same X-Ray daemon
as th... |
def shepp_logan_ellipsoids(ndim, modified=False):
"""Ellipsoids for the standard Shepp-Logan phantom in 2 or 3 dimensions.
Parameters
----------
ndim : {2, 3}
Dimension of the space the ellipsoids should be in.
modified : bool, optional
True if the modified Shepp-Logan phantom shoul... | Ellipsoids for the standard Shepp-Logan phantom in 2 or 3 dimensions.
Parameters
----------
ndim : {2, 3}
Dimension of the space the ellipsoids should be in.
modified : bool, optional
True if the modified Shepp-Logan phantom should be given.
The modified phantom has greatly ampl... | Below is the the instruction that describes the task:
### Input:
Ellipsoids for the standard Shepp-Logan phantom in 2 or 3 dimensions.
Parameters
----------
ndim : {2, 3}
Dimension of the space the ellipsoids should be in.
modified : bool, optional
True if the modified Shepp-Logan p... |
def GetCalendarFieldValuesTuple(self):
"""Return the tuple of calendar.txt values or None if this ServicePeriod
should not be in calendar.txt ."""
if self.start_date and self.end_date:
return [getattr(self, fn) for fn in self._FIELD_NAMES] | Return the tuple of calendar.txt values or None if this ServicePeriod
should not be in calendar.txt . | Below is the the instruction that describes the task:
### Input:
Return the tuple of calendar.txt values or None if this ServicePeriod
should not be in calendar.txt .
### Response:
def GetCalendarFieldValuesTuple(self):
"""Return the tuple of calendar.txt values or None if this ServicePeriod
should not... |
def get_version(package):
"""
Return package version as listed in `__version__` in `init.py`.
"""
init_py = codecs.open(os.path.join(package, '__init__.py'), encoding='utf-8').read()
return re.search("^__version__ = ['\"]([^'\"]+)['\"]", init_py, re.MULTILINE).group(1) | Return package version as listed in `__version__` in `init.py`. | Below is the the instruction that describes the task:
### Input:
Return package version as listed in `__version__` in `init.py`.
### Response:
def get_version(package):
"""
Return package version as listed in `__version__` in `init.py`.
"""
init_py = codecs.open(os.path.join(package, '__init__.py')... |
def setOverlayTexture(self, ulOverlayHandle):
"""
Texture to draw for the overlay. This function can only be called by the overlay's creator or renderer process (see SetOverlayRenderingPid) .
* OpenGL dirty state:
glBindTexture
"""
fn = self.function_table.setOverlayText... | Texture to draw for the overlay. This function can only be called by the overlay's creator or renderer process (see SetOverlayRenderingPid) .
* OpenGL dirty state:
glBindTexture | Below is the the instruction that describes the task:
### Input:
Texture to draw for the overlay. This function can only be called by the overlay's creator or renderer process (see SetOverlayRenderingPid) .
* OpenGL dirty state:
glBindTexture
### Response:
def setOverlayTexture(self, ulOverlayHandl... |
def status(self):
"""
check the status of the network and the peers
:return: network_height, peer_status
"""
peer = random.choice(self.PEERS)
formatted_peer = 'http://{}:4001'.format(peer)
peerdata = requests.get(url=formatted_peer + '/api/peers/').json()['peers'... | check the status of the network and the peers
:return: network_height, peer_status | Below is the the instruction that describes the task:
### Input:
check the status of the network and the peers
:return: network_height, peer_status
### Response:
def status(self):
"""
check the status of the network and the peers
:return: network_height, peer_status
"""
... |
def event_listeners(self):
"""List of registered event listeners."""
return (self.__command_listeners[:],
self.__server_heartbeat_listeners[:],
self.__server_listeners[:],
self.__topology_listeners[:]) | List of registered event listeners. | Below is the the instruction that describes the task:
### Input:
List of registered event listeners.
### Response:
def event_listeners(self):
"""List of registered event listeners."""
return (self.__command_listeners[:],
self.__server_heartbeat_listeners[:],
self.__s... |
def transpose(self,
name=None,
output_channels=None,
kernel_shapes=None,
strides=None,
paddings=None,
activation=None,
activate_final=None,
normalization_ctor=None,
normalizati... | Returns transposed version of this network.
Args:
name: Optional string specifying the name of the transposed module. The
default name is constructed by appending "_transpose"
to `self.module_name`.
output_channels: Optional iterable of numbers of output channels.
kernel_shapes: O... | Below is the the instruction that describes the task:
### Input:
Returns transposed version of this network.
Args:
name: Optional string specifying the name of the transposed module. The
default name is constructed by appending "_transpose"
to `self.module_name`.
output_channels: Op... |
def generate_ssh_key():
"""
Generates an SSH deploy public and private key.
Returns (private key, public key), a tuple of byte strings.
"""
key = rsa.generate_private_key(
backend=default_backend(),
public_exponent=65537,
key_size=4096
)
private_key = key.privat... | Generates an SSH deploy public and private key.
Returns (private key, public key), a tuple of byte strings. | Below is the the instruction that describes the task:
### Input:
Generates an SSH deploy public and private key.
Returns (private key, public key), a tuple of byte strings.
### Response:
def generate_ssh_key():
"""
Generates an SSH deploy public and private key.
Returns (private key, public key),... |
def create_api_stage(restApiId, stageName, deploymentId, description='',
cacheClusterEnabled=False, cacheClusterSize='0.5', variables=None,
region=None, key=None, keyid=None, profile=None):
'''
Creates a new API stage for a given restApiId and deploymentId.
CLI Exa... | Creates a new API stage for a given restApiId and deploymentId.
CLI Example:
.. code-block:: bash
salt myminion boto_apigateway.create_api_stage restApiId stagename deploymentId \\
description='' cacheClusterEnabled=True|False cacheClusterSize='0.5' variables='{"name": "value"}' | Below is the the instruction that describes the task:
### Input:
Creates a new API stage for a given restApiId and deploymentId.
CLI Example:
.. code-block:: bash
salt myminion boto_apigateway.create_api_stage restApiId stagename deploymentId \\
description='' cacheClusterEnabled=True... |
def transform(self, jam):
'''Apply the sequence of transformations to a single jam object.
Parameters
----------
jam : jams.JAMS
The jam object to transform
Yields
------
jam_out : jams.JAMS
The jam objects produced by the transformation ... | Apply the sequence of transformations to a single jam object.
Parameters
----------
jam : jams.JAMS
The jam object to transform
Yields
------
jam_out : jams.JAMS
The jam objects produced by the transformation sequence | Below is the the instruction that describes the task:
### Input:
Apply the sequence of transformations to a single jam object.
Parameters
----------
jam : jams.JAMS
The jam object to transform
Yields
------
jam_out : jams.JAMS
The jam objects... |
def power_corr(r=None, n=None, power=None, alpha=0.05, tail='two-sided'):
"""
Evaluate power, sample size, correlation coefficient or
significance level of a correlation test.
Parameters
----------
r : float
Correlation coefficient.
n : int
Number of observations (sample siz... | Evaluate power, sample size, correlation coefficient or
significance level of a correlation test.
Parameters
----------
r : float
Correlation coefficient.
n : int
Number of observations (sample size).
power : float
Test power (= 1 - type II error).
alpha : float
... | Below is the the instruction that describes the task:
### Input:
Evaluate power, sample size, correlation coefficient or
significance level of a correlation test.
Parameters
----------
r : float
Correlation coefficient.
n : int
Number of observations (sample size).
power : f... |
def data(self, **query):
"""Query for Data object annotation."""
objects = self.cache['objects']
data = self.api.data.get(**query)['objects']
data_objects = []
for d in data:
_id = d['id']
if _id in objects:
# Update existing object
... | Query for Data object annotation. | Below is the the instruction that describes the task:
### Input:
Query for Data object annotation.
### Response:
def data(self, **query):
"""Query for Data object annotation."""
objects = self.cache['objects']
data = self.api.data.get(**query)['objects']
data_objects = []
f... |
def file_signature(filename):
"""
Return a signature for a file.
"""
if not os.path.isfile(filename):
return None
if not os.path.exists(filename):
return None
# Duplicate auto-generated files can be recognized with the sha1 hash.
sig = hashlib.sha1()
with open(filename... | Return a signature for a file. | Below is the the instruction that describes the task:
### Input:
Return a signature for a file.
### Response:
def file_signature(filename):
"""
Return a signature for a file.
"""
if not os.path.isfile(filename):
return None
if not os.path.exists(filename):
return None
# D... |
def prepare_shell_data(self, shells, key, entry):
"""Prepare one shell or docker task."""
if self.can_process_shell(entry):
if key in ['python']:
entry['type'] = key
if 'with' in entry and isinstance(entry['with'], str):
rendered_with = ast.litera... | Prepare one shell or docker task. | Below is the the instruction that describes the task:
### Input:
Prepare one shell or docker task.
### Response:
def prepare_shell_data(self, shells, key, entry):
"""Prepare one shell or docker task."""
if self.can_process_shell(entry):
if key in ['python']:
entry['type'... |
def ws_connect(message):
"""
Channels connection setup.
Register the current client on the related Group according to the language
"""
prefix, language = message['path'].strip('/').split('/')
gr = Group('knocker-{0}'.format(language))
gr.add(message.reply_channel)
message.channel_session... | Channels connection setup.
Register the current client on the related Group according to the language | Below is the the instruction that describes the task:
### Input:
Channels connection setup.
Register the current client on the related Group according to the language
### Response:
def ws_connect(message):
"""
Channels connection setup.
Register the current client on the related Group according to ... |
def expand_internal(universe: BELGraph, graph: BELGraph, edge_predicates: EdgePredicates = None) -> None:
"""Edges between entities in the sub-graph that pass the given filters.
:param universe: The full graph
:param graph: A sub-graph to find the upstream information
:param edge_predicates: Optional l... | Edges between entities in the sub-graph that pass the given filters.
:param universe: The full graph
:param graph: A sub-graph to find the upstream information
:param edge_predicates: Optional list of edge filter functions (graph, node, node, key, data) -> bool | Below is the the instruction that describes the task:
### Input:
Edges between entities in the sub-graph that pass the given filters.
:param universe: The full graph
:param graph: A sub-graph to find the upstream information
:param edge_predicates: Optional list of edge filter functions (graph, node, n... |
def dump(
state, host,
remote_filename, database=None,
# Details for speaking to MySQL via `mysql` CLI
mysql_user=None, mysql_password=None,
mysql_host=None, mysql_port=None,
):
'''
Dump a MySQL database into a ``.sql`` file. Requires ``mysqldump``.
+ database: name of the database to d... | Dump a MySQL database into a ``.sql`` file. Requires ``mysqldump``.
+ database: name of the database to dump
+ remote_filename: name of the file to dump the SQL to
+ mysql_*: global module arguments, see above | Below is the the instruction that describes the task:
### Input:
Dump a MySQL database into a ``.sql`` file. Requires ``mysqldump``.
+ database: name of the database to dump
+ remote_filename: name of the file to dump the SQL to
+ mysql_*: global module arguments, see above
### Response:
def dump(
... |
def heartbeat(self):
"""
Override the scheduler heartbeat to determine when the test is complete
"""
super(SchedulerMetricsJob, self).heartbeat()
session = settings.Session()
# Get all the relevant task instances
TI = TaskInstance
successful_tis = (
... | Override the scheduler heartbeat to determine when the test is complete | Below is the the instruction that describes the task:
### Input:
Override the scheduler heartbeat to determine when the test is complete
### Response:
def heartbeat(self):
"""
Override the scheduler heartbeat to determine when the test is complete
"""
super(SchedulerMetricsJob, self... |
def create(self, create_missing=None):
"""Manually fetch a complete set of attributes for this entity.
For more information, see `Bugzilla #1216236
<https://bugzilla.redhat.com/show_bug.cgi?id=1216236>`_.
"""
attrs = self.create_json(create_missing)
return Location(self... | Manually fetch a complete set of attributes for this entity.
For more information, see `Bugzilla #1216236
<https://bugzilla.redhat.com/show_bug.cgi?id=1216236>`_. | Below is the the instruction that describes the task:
### Input:
Manually fetch a complete set of attributes for this entity.
For more information, see `Bugzilla #1216236
<https://bugzilla.redhat.com/show_bug.cgi?id=1216236>`_.
### Response:
def create(self, create_missing=None):
"""Manual... |
def search_asn(self, auth, query, search_options=None):
""" Search ASNs for entries matching 'query'
* `auth` [BaseAuth]
AAA options.
* `query` [dict_to_sql]
How the search should be performed.
* `search_options` [options_dict]
... | Search ASNs for entries matching 'query'
* `auth` [BaseAuth]
AAA options.
* `query` [dict_to_sql]
How the search should be performed.
* `search_options` [options_dict]
Search options, see below.
Returns a list of dicts.
... | Below is the the instruction that describes the task:
### Input:
Search ASNs for entries matching 'query'
* `auth` [BaseAuth]
AAA options.
* `query` [dict_to_sql]
How the search should be performed.
* `search_options` [options_dict]
... |
def get_bitcoind_client():
"""
Connect to the bitcoind node
"""
bitcoind_opts = get_bitcoin_opts()
bitcoind_host = bitcoind_opts['bitcoind_server']
bitcoind_port = bitcoind_opts['bitcoind_port']
bitcoind_user = bitcoind_opts['bitcoind_user']
bitcoind_passwd = bitcoind_opts['bitcoind_pass... | Connect to the bitcoind node | Below is the the instruction that describes the task:
### Input:
Connect to the bitcoind node
### Response:
def get_bitcoind_client():
"""
Connect to the bitcoind node
"""
bitcoind_opts = get_bitcoin_opts()
bitcoind_host = bitcoind_opts['bitcoind_server']
bitcoind_port = bitcoind_opts['bitc... |
def sum_distances(self, indices, distance_matrix):
"""Calculate combinatorial distance between a select group of
trajectories, indicated by indices
Arguments
---------
indices : tuple
distance_matrix : numpy.ndarray (M,M)
Returns
-------
numpy.nd... | Calculate combinatorial distance between a select group of
trajectories, indicated by indices
Arguments
---------
indices : tuple
distance_matrix : numpy.ndarray (M,M)
Returns
-------
numpy.ndarray
Notes
-----
This function can p... | Below is the the instruction that describes the task:
### Input:
Calculate combinatorial distance between a select group of
trajectories, indicated by indices
Arguments
---------
indices : tuple
distance_matrix : numpy.ndarray (M,M)
Returns
-------
n... |
def os_path_to_client_path(self, os_path):
"""
Converts an operating system path into a client path by
replacing instances of os.path.sep with '/'.
Note: If the client path contains any instances of '/'
already, they will be replaced with '-'.
"""
if os.path.sep ... | Converts an operating system path into a client path by
replacing instances of os.path.sep with '/'.
Note: If the client path contains any instances of '/'
already, they will be replaced with '-'. | Below is the the instruction that describes the task:
### Input:
Converts an operating system path into a client path by
replacing instances of os.path.sep with '/'.
Note: If the client path contains any instances of '/'
already, they will be replaced with '-'.
### Response:
def os_path_to... |
def yank_last_arg(event):
"""
Like `yank_nth_arg`, but if no argument has been given, yank the last word
of each line.
"""
n = (event.arg if event.arg_present else None)
event.current_buffer.yank_last_arg(n) | Like `yank_nth_arg`, but if no argument has been given, yank the last word
of each line. | Below is the the instruction that describes the task:
### Input:
Like `yank_nth_arg`, but if no argument has been given, yank the last word
of each line.
### Response:
def yank_last_arg(event):
"""
Like `yank_nth_arg`, but if no argument has been given, yank the last word
of each line.
"""
... |
def do_not_track():
"""
Decorator to skip the default metrics collection for the method.
*Note*: explicit metrics decorators will still collect the data
"""
def decorator(f):
@functools.wraps(f)
def func(*args, **kwargs):
request.prom_do_... | Decorator to skip the default metrics collection for the method.
*Note*: explicit metrics decorators will still collect the data | Below is the the instruction that describes the task:
### Input:
Decorator to skip the default metrics collection for the method.
*Note*: explicit metrics decorators will still collect the data
### Response:
def do_not_track():
"""
Decorator to skip the default metrics collection for the m... |
def num_samples(input_filepath):
'''
Show number of samples (0 if unavailable).
Parameters
----------
input_filepath : str
Path to audio file.
Returns
-------
n_samples : int
total number of samples in audio file.
Returns 0 if empty or unavailable
'''
va... | Show number of samples (0 if unavailable).
Parameters
----------
input_filepath : str
Path to audio file.
Returns
-------
n_samples : int
total number of samples in audio file.
Returns 0 if empty or unavailable | Below is the the instruction that describes the task:
### Input:
Show number of samples (0 if unavailable).
Parameters
----------
input_filepath : str
Path to audio file.
Returns
-------
n_samples : int
total number of samples in audio file.
Returns 0 if empty or un... |
def decode_and_resize(image_str_tensor):
"""Decodes jpeg string, resizes it and returns a uint8 tensor."""
# These constants are set by Inception v3's expectations.
height = 299
width = 299
channels = 3
image = tf.image.decode_jpeg(image_str_tensor, channels=channels)
# Note resize expects a batch_size,... | Decodes jpeg string, resizes it and returns a uint8 tensor. | Below is the the instruction that describes the task:
### Input:
Decodes jpeg string, resizes it and returns a uint8 tensor.
### Response:
def decode_and_resize(image_str_tensor):
"""Decodes jpeg string, resizes it and returns a uint8 tensor."""
# These constants are set by Inception v3's expectations.
heig... |
def get_variable_values(
schema, # type: GraphQLSchema
definition_asts, # type: List[VariableDefinition]
inputs, # type: Any
):
# type: (...) -> Dict[str, Any]
"""Prepares an object map of variables of the correct type based on the provided variable definitions and arbitrary input.
If the inp... | Prepares an object map of variables of the correct type based on the provided variable definitions and arbitrary input.
If the input cannot be parsed to match the variable definitions, a GraphQLError will be thrown. | Below is the the instruction that describes the task:
### Input:
Prepares an object map of variables of the correct type based on the provided variable definitions and arbitrary input.
If the input cannot be parsed to match the variable definitions, a GraphQLError will be thrown.
### Response:
def get_variable... |
def array_info(self, dump=None, paths=None, attrs=True,
standardize_dims=True, pwd=None, use_rel_paths=True,
alternative_paths={}, ds_description={'fname', 'store'},
full_ds=True, copy=False, **kwargs):
"""
Get dimension informations on you arrays... | Get dimension informations on you arrays
This method returns a dictionary containing informations on the
array in this instance
Parameters
----------
dump: bool
If True and the dataset has not been dumped so far, it is dumped to
a temporary file or the o... | Below is the the instruction that describes the task:
### Input:
Get dimension informations on you arrays
This method returns a dictionary containing informations on the
array in this instance
Parameters
----------
dump: bool
If True and the dataset has not been... |
def phaseshift_isc(data, pairwise=False, summary_statistic='median',
n_shifts=1000, tolerate_nans=True, random_state=None):
"""Phase randomization for one-sample ISC test
For each voxel or ROI, compute the actual ISC and p-values
from a null distribution of ISCs where response time seri... | Phase randomization for one-sample ISC test
For each voxel or ROI, compute the actual ISC and p-values
from a null distribution of ISCs where response time series
are phase randomized prior to computing ISC. If pairwise,
apply phase randomization to each subject and compute pairwise
ISCs. If leave-... | Below is the the instruction that describes the task:
### Input:
Phase randomization for one-sample ISC test
For each voxel or ROI, compute the actual ISC and p-values
from a null distribution of ISCs where response time series
are phase randomized prior to computing ISC. If pairwise,
apply phase r... |
def get_lightcurve(self, star_id, return_1d=True):
"""Get the light curves for the given ID
Parameters
----------
star_id : int
A valid integer star id representing an object in the dataset
return_1d : boolean (default=True)
Specify whether to return 1D a... | Get the light curves for the given ID
Parameters
----------
star_id : int
A valid integer star id representing an object in the dataset
return_1d : boolean (default=True)
Specify whether to return 1D arrays of (t, y, dy, filts) or
2D arrays of (t, y, ... | Below is the the instruction that describes the task:
### Input:
Get the light curves for the given ID
Parameters
----------
star_id : int
A valid integer star id representing an object in the dataset
return_1d : boolean (default=True)
Specify whether to retu... |
def _pathway_feature_permutation(pathway_feature_tuples,
permutation_max_iters):
"""Permute the pathways across features for one side in the
network. Used in `permute_pathways_across_features`
Parameters
-----------
pathway_feature_tuples : list(tup(str, int))
... | Permute the pathways across features for one side in the
network. Used in `permute_pathways_across_features`
Parameters
-----------
pathway_feature_tuples : list(tup(str, int))
a tuple list [(pathway, feature)] where the pathway, feature pairing
indicates that a pathway was overrepresented ... | Below is the the instruction that describes the task:
### Input:
Permute the pathways across features for one side in the
network. Used in `permute_pathways_across_features`
Parameters
-----------
pathway_feature_tuples : list(tup(str, int))
a tuple list [(pathway, feature)] where the pathway... |
def plot_report_from_path(path, success_name=DEFAULT_SUCCESS_NAME,
fail_names=DEFAULT_FAIL_NAMES, label=None,
is_max_confidence=True,
linewidth=LINEWIDTH,
plot_upper_bound=True):
"""
Plots a success-fail curve fr... | Plots a success-fail curve from a confidence report stored on disk,
:param path: string filepath for the stored report.
(Should be the output of make_confidence_report*.py)
:param success_name: The name (confidence report key) of the data that
should be used to measure success rate
:param fail_names: A li... | Below is the the instruction that describes the task:
### Input:
Plots a success-fail curve from a confidence report stored on disk,
:param path: string filepath for the stored report.
(Should be the output of make_confidence_report*.py)
:param success_name: The name (confidence report key) of the data that... |
def integer_list_file(cls, filename):
"""
Read a list of integers from a file.
The file format is:
- # anywhere in the line begins a comment
- leading and trailing spaces are ignored
- empty lines are ignored
- integers can be specified as:
- dec... | Read a list of integers from a file.
The file format is:
- # anywhere in the line begins a comment
- leading and trailing spaces are ignored
- empty lines are ignored
- integers can be specified as:
- decimal numbers ("100" is 100)
- hexadecimal numb... | Below is the the instruction that describes the task:
### Input:
Read a list of integers from a file.
The file format is:
- # anywhere in the line begins a comment
- leading and trailing spaces are ignored
- empty lines are ignored
- integers can be specified as:
... |
def clear(*signals):
"""
Clears all callbacks for a particular signal or signals
"""
signals = signals if signals else receivers.keys()
for signal in signals:
receivers[signal].clear() | Clears all callbacks for a particular signal or signals | Below is the the instruction that describes the task:
### Input:
Clears all callbacks for a particular signal or signals
### Response:
def clear(*signals):
"""
Clears all callbacks for a particular signal or signals
"""
signals = signals if signals else receivers.keys()
for signal in signals:
... |
def from_str(duration):
"""Parse a duration string to a datetime.timedelta"""
if duration in ("0", "+0", "-0"):
return datetime.timedelta()
pattern = re.compile('([\d\.]+)([a-zµμ]+)')
total = 0
sign = -1 if duration[0] == '-' else 1
matches = pattern.findall(duration)
if not len(m... | Parse a duration string to a datetime.timedelta | Below is the the instruction that describes the task:
### Input:
Parse a duration string to a datetime.timedelta
### Response:
def from_str(duration):
"""Parse a duration string to a datetime.timedelta"""
if duration in ("0", "+0", "-0"):
return datetime.timedelta()
pattern = re.compile('([\d... |
def json(self) -> dict:
"""Returns json compatible state of the ButtonsFrame instance.
Returns json compatible state of the ButtonsFrame instance including
all nested buttons.
Returns:
control_json: Json representation of ButtonsFrame state.
"""
content = {}... | Returns json compatible state of the ButtonsFrame instance.
Returns json compatible state of the ButtonsFrame instance including
all nested buttons.
Returns:
control_json: Json representation of ButtonsFrame state. | Below is the the instruction that describes the task:
### Input:
Returns json compatible state of the ButtonsFrame instance.
Returns json compatible state of the ButtonsFrame instance including
all nested buttons.
Returns:
control_json: Json representation of ButtonsFrame state... |
def serialize_options(opts):
"""
A helper method to serialize and processes the options dictionary.
"""
options = (opts or {}).copy()
for key in opts.keys():
if key not in DEFAULT_OPTIONS:
LOG.warning("Unknown option passed to Flask-CORS: %s", key)
# Ensure origins is a li... | A helper method to serialize and processes the options dictionary. | Below is the the instruction that describes the task:
### Input:
A helper method to serialize and processes the options dictionary.
### Response:
def serialize_options(opts):
"""
A helper method to serialize and processes the options dictionary.
"""
options = (opts or {}).copy()
for key in opt... |
def inq_compound(self, name):
"""
Return the number of fields and size (not yet) of a compound type.
"""
name = create_string_buffer(name)
self.library.inq_compound.argtypes = [c_char_p, POINTER(c_int)]
self.library.inq_compound.restype = None
nfields = c_int()
... | Return the number of fields and size (not yet) of a compound type. | Below is the the instruction that describes the task:
### Input:
Return the number of fields and size (not yet) of a compound type.
### Response:
def inq_compound(self, name):
"""
Return the number of fields and size (not yet) of a compound type.
"""
name = create_string_buffer(name... |
def delete_many(self, mongo_collection, filter_doc, mongo_db=None, **kwargs):
"""
Deletes one or more documents in a mongo collection.
https://api.mongodb.com/python/current/api/pymongo/collection.html#pymongo.collection.Collection.delete_many
:param mongo_collection: The name of the co... | Deletes one or more documents in a mongo collection.
https://api.mongodb.com/python/current/api/pymongo/collection.html#pymongo.collection.Collection.delete_many
:param mongo_collection: The name of the collection to delete from.
:type mongo_collection: str
:param filter_doc: A query th... | Below is the the instruction that describes the task:
### Input:
Deletes one or more documents in a mongo collection.
https://api.mongodb.com/python/current/api/pymongo/collection.html#pymongo.collection.Collection.delete_many
:param mongo_collection: The name of the collection to delete from.
... |
def authenticate_credentials(self, userargs, password, request=None):
"""
Authenticate the userargs and password against Django auth backends.
The "userargs" string may be just the username, or a querystring-encoded set of params.
"""
credentials = {
'password': pass... | Authenticate the userargs and password against Django auth backends.
The "userargs" string may be just the username, or a querystring-encoded set of params. | Below is the the instruction that describes the task:
### Input:
Authenticate the userargs and password against Django auth backends.
The "userargs" string may be just the username, or a querystring-encoded set of params.
### Response:
def authenticate_credentials(self, userargs, password, request=None):
... |
def download_mp4(from_idx, to_idx, _params):
"""
download mp4s
"""
succ = set()
fail = set()
for idx in range(from_idx, to_idx):
name = 's' + str(idx)
save_folder = '{src_path}/{nm}'.format(src_path=_params['src_path'], nm=name)
if idx == 0 or os.path.isdir(save_folder):
... | download mp4s | Below is the the instruction that describes the task:
### Input:
download mp4s
### Response:
def download_mp4(from_idx, to_idx, _params):
"""
download mp4s
"""
succ = set()
fail = set()
for idx in range(from_idx, to_idx):
name = 's' + str(idx)
save_folder = '{src_path}/{nm}'... |
def _parse_prefix_as_idd(idd_pattern, number):
"""Strips the IDD from the start of the number if present.
Helper function used by _maybe_strip_i18n_prefix_and_normalize().
Returns a 2-tuple:
- Boolean indicating if IDD was stripped
- Number with IDD stripped
"""
match = idd_pattern.mat... | Strips the IDD from the start of the number if present.
Helper function used by _maybe_strip_i18n_prefix_and_normalize().
Returns a 2-tuple:
- Boolean indicating if IDD was stripped
- Number with IDD stripped | Below is the the instruction that describes the task:
### Input:
Strips the IDD from the start of the number if present.
Helper function used by _maybe_strip_i18n_prefix_and_normalize().
Returns a 2-tuple:
- Boolean indicating if IDD was stripped
- Number with IDD stripped
### Response:
def _... |
def request_all_data(cls, time, pressure=None, **kwargs):
"""Retrieve upper air observations from Iowa State's archive for all stations.
Parameters
----------
time : datetime
The date and time of the desired observation.
pressure : float, optional
The ma... | Retrieve upper air observations from Iowa State's archive for all stations.
Parameters
----------
time : datetime
The date and time of the desired observation.
pressure : float, optional
The mandatory pressure level at which to request data (in hPa). If none is ... | Below is the the instruction that describes the task:
### Input:
Retrieve upper air observations from Iowa State's archive for all stations.
Parameters
----------
time : datetime
The date and time of the desired observation.
pressure : float, optional
The ma... |
def getTokensForText(self, body, POStags=None):
"""Get tokenized input text
Args:
body, str: The text to be tokenized (required)
POStags, str: Specify desired POS types (optional)
Returns:
list of str
Raises:
CorticalioException: if the req... | Get tokenized input text
Args:
body, str: The text to be tokenized (required)
POStags, str: Specify desired POS types (optional)
Returns:
list of str
Raises:
CorticalioException: if the request was not successful | Below is the the instruction that describes the task:
### Input:
Get tokenized input text
Args:
body, str: The text to be tokenized (required)
POStags, str: Specify desired POS types (optional)
Returns:
list of str
Raises:
CorticalioException: ... |
def pretty (self):
'''This returns a copy of the screen as a unicode string with an ASCII
text box around the screen border. This is similar to
__str__/__unicode__ except that it adds a box.'''
top_bot = u'+' + u'-'*self.cols + u'+\n'
return top_bot + u'\n'.join([u'|'+line+u'|' ... | This returns a copy of the screen as a unicode string with an ASCII
text box around the screen border. This is similar to
__str__/__unicode__ except that it adds a box. | Below is the the instruction that describes the task:
### Input:
This returns a copy of the screen as a unicode string with an ASCII
text box around the screen border. This is similar to
__str__/__unicode__ except that it adds a box.
### Response:
def pretty (self):
'''This returns a copy o... |
def convexHull(actor_or_list, alphaConstant=0):
"""
Create a 3D Delaunay triangulation of input points.
:param actor_or_list: can be either an ``Actor`` or a list of 3D points.
:param float alphaConstant: For a non-zero alpha value, only verts, edges, faces,
or tetra contained within the circum... | Create a 3D Delaunay triangulation of input points.
:param actor_or_list: can be either an ``Actor`` or a list of 3D points.
:param float alphaConstant: For a non-zero alpha value, only verts, edges, faces,
or tetra contained within the circumsphere (of radius alpha) will be output.
Otherwise, ... | Below is the the instruction that describes the task:
### Input:
Create a 3D Delaunay triangulation of input points.
:param actor_or_list: can be either an ``Actor`` or a list of 3D points.
:param float alphaConstant: For a non-zero alpha value, only verts, edges, faces,
or tetra contained within t... |
def select_day(self, day):
"""选取日期(一般用于分钟线)
Arguments:
day {[type]} -- [description]
Raises:
ValueError -- [description]
Returns:
[type] -- [description]
"""
def _select_day(day):
return self.data.loc[day, slice(None)]
... | 选取日期(一般用于分钟线)
Arguments:
day {[type]} -- [description]
Raises:
ValueError -- [description]
Returns:
[type] -- [description] | Below is the the instruction that describes the task:
### Input:
选取日期(一般用于分钟线)
Arguments:
day {[type]} -- [description]
Raises:
ValueError -- [description]
Returns:
[type] -- [description]
### Response:
def select_day(self, day):
"""选取日期(一般用于分钟... |
def mergebydepth(args):
"""
%prog mergebydepth reads.bed genome.fasta
Similar to mergeBed, but only returns regions beyond certain depth.
"""
p = OptionParser(mergebydepth.__doc__)
p.add_option("--mindepth", default=3, type="int",
help="Minimum depth required")
opts, args =... | %prog mergebydepth reads.bed genome.fasta
Similar to mergeBed, but only returns regions beyond certain depth. | Below is the the instruction that describes the task:
### Input:
%prog mergebydepth reads.bed genome.fasta
Similar to mergeBed, but only returns regions beyond certain depth.
### Response:
def mergebydepth(args):
"""
%prog mergebydepth reads.bed genome.fasta
Similar to mergeBed, but only returns ... |
def generate_common(env):
"""Add internal Builders and construction variables for LaTeX to an Environment."""
# Add OSX system paths so TeX tools can be found
# when a list of tools is given the exists() method is not called
generate_darwin(env)
# A generic tex file Action, sufficient for all tex ... | Add internal Builders and construction variables for LaTeX to an Environment. | Below is the the instruction that describes the task:
### Input:
Add internal Builders and construction variables for LaTeX to an Environment.
### Response:
def generate_common(env):
"""Add internal Builders and construction variables for LaTeX to an Environment."""
# Add OSX system paths so TeX tools can... |
def gnom(curve, Rmax, outputfilename=None, Npoints_realspace=None, initial_alpha=None):
"""Run GNOM on the dataset.
Inputs:
curve: an instance of sastool.classes2.Curve or anything which has a
save() method, saving the scattering curve to a given .dat file,
in q=4*pi*sin(theta)/... | Run GNOM on the dataset.
Inputs:
curve: an instance of sastool.classes2.Curve or anything which has a
save() method, saving the scattering curve to a given .dat file,
in q=4*pi*sin(theta)/lambda [1/nm] units
Rmax: the estimated maximum extent of the scattering object, in nm.... | Below is the the instruction that describes the task:
### Input:
Run GNOM on the dataset.
Inputs:
curve: an instance of sastool.classes2.Curve or anything which has a
save() method, saving the scattering curve to a given .dat file,
in q=4*pi*sin(theta)/lambda [1/nm] units
... |
def info(path):
"""info(path)
path is a string
"""
fh = None
try:
fh = open(path,'rb')
return __readHeader(fh)
finally:
if fh:
fh.close()
return None | info(path)
path is a string | Below is the the instruction that describes the task:
### Input:
info(path)
path is a string
### Response:
def info(path):
"""info(path)
path is a string
"""
fh = None
try:
fh = open(path,'rb')
return __readHeader(fh)
finally:
if fh:
fh.close()
return None |
def depth_first_search(root, visit=lambda node: False, traversable=lambda node, edge: True):
""" Simple, multi-purpose depth-first search.
Visits all the nodes connected to the root, depth-first.
The visit function is called on each node.
Recursion will stop if it returns True, and ubsequently dfs... | Simple, multi-purpose depth-first search.
Visits all the nodes connected to the root, depth-first.
The visit function is called on each node.
Recursion will stop if it returns True, and ubsequently dfs() will return True.
The traversable function takes the current node and edge,
and returns Tru... | Below is the the instruction that describes the task:
### Input:
Simple, multi-purpose depth-first search.
Visits all the nodes connected to the root, depth-first.
The visit function is called on each node.
Recursion will stop if it returns True, and ubsequently dfs() will return True.
The trav... |
def corruptVector(v1, noiseLevel, numActiveCols):
"""
Corrupts a copy of a binary vector by inverting noiseLevel percent of its bits.
@param v1 (array) binary vector whose copy will be corrupted
@param noiseLevel (float) amount of noise to be applied on the new vector
@param numActiveCols (int) num... | Corrupts a copy of a binary vector by inverting noiseLevel percent of its bits.
@param v1 (array) binary vector whose copy will be corrupted
@param noiseLevel (float) amount of noise to be applied on the new vector
@param numActiveCols (int) number of sparse columns that represent an input
@return... | Below is the the instruction that describes the task:
### Input:
Corrupts a copy of a binary vector by inverting noiseLevel percent of its bits.
@param v1 (array) binary vector whose copy will be corrupted
@param noiseLevel (float) amount of noise to be applied on the new vector
@param numActiveCols ... |
def value(self):
"""gets the color value"""
return {
"type" : self._type,
"style" : self._style,
"color" : self._color.value,
"width" : self._width
} | gets the color value | Below is the the instruction that describes the task:
### Input:
gets the color value
### Response:
def value(self):
"""gets the color value"""
return {
"type" : self._type,
"style" : self._style,
"color" : self._color.value,
"width" : self._width
... |
def weight(w, sparsity):
"""Weight-level magnitude pruning."""
w_shape = common_layers.shape_list(w)
k = int(np.prod(w_shape[:-1]))
count = tf.to_int32(k * sparsity)
mask = common_layers.weight_targeting(w, count)
return (1 - mask) * w | Weight-level magnitude pruning. | Below is the the instruction that describes the task:
### Input:
Weight-level magnitude pruning.
### Response:
def weight(w, sparsity):
"""Weight-level magnitude pruning."""
w_shape = common_layers.shape_list(w)
k = int(np.prod(w_shape[:-1]))
count = tf.to_int32(k * sparsity)
mask = common_layers.weight_... |
def save(self, model, path=''):
"""Save the file model and return the model with no content."""
if model['type'] != 'notebook':
return super(TextFileContentsManager, self).save(model, path)
nbk = model['content']
try:
metadata = nbk.get('metadata')
re... | Save the file model and return the model with no content. | Below is the the instruction that describes the task:
### Input:
Save the file model and return the model with no content.
### Response:
def save(self, model, path=''):
"""Save the file model and return the model with no content."""
if model['type'] != 'notebook':
return super(TextFileC... |
def send(self, command, _id=None, result={}, frames=[], threads=None,
error_messages=[], warning_messages=[], info_messages=[],
exception=None):
""" Build a message from parameters and send it to debugger.
:param command: The command sent to the debugger client.
... | Build a message from parameters and send it to debugger.
:param command: The command sent to the debugger client.
:type command: str
:param _id: Unique id of the sent message. Right now, it's always `None`
for messages by debugger to client.
:type _i... | Below is the the instruction that describes the task:
### Input:
Build a message from parameters and send it to debugger.
:param command: The command sent to the debugger client.
:type command: str
:param _id: Unique id of the sent message. Right now, it's always `None`
... |
def calculate_one_hot_encoder_output_shapes(operator):
'''
Allowed input/output patterns are
1. [N, 1] ---> [N, C']
C' is the total number of categorical values.
'''
check_input_and_output_numbers(operator, input_count_range=1, output_count_range=1)
if operator.inputs[0].type.shape[1] ... | Allowed input/output patterns are
1. [N, 1] ---> [N, C']
C' is the total number of categorical values. | Below is the the instruction that describes the task:
### Input:
Allowed input/output patterns are
1. [N, 1] ---> [N, C']
C' is the total number of categorical values.
### Response:
def calculate_one_hot_encoder_output_shapes(operator):
'''
Allowed input/output patterns are
1. [N, 1] -... |
def format_lp(nodes, constraints_x, qa, constraints_y, qb):
"""
Maximize
4 x1 + 2 x2 + 3 x3 + x4
Subject To
x1 + x2 <= 1
End
"""
lp_handle = cStringIO.StringIO()
lp_handle.write("Maximize\n ")
records = 0
for i, score in nodes:
lp_handle.write("+ %d x%d " % (score,... | Maximize
4 x1 + 2 x2 + 3 x3 + x4
Subject To
x1 + x2 <= 1
End | Below is the the instruction that describes the task:
### Input:
Maximize
4 x1 + 2 x2 + 3 x3 + x4
Subject To
x1 + x2 <= 1
End
### Response:
def format_lp(nodes, constraints_x, qa, constraints_y, qb):
"""
Maximize
4 x1 + 2 x2 + 3 x3 + x4
Subject To
x1 + x2 <= 1
End
""... |
def load_loops(directory, loops_path=None):
"""
Return a list of tuples indicating the start and end points of the loops
that were sampled in the given directory.
"""
if loops_path is None:
workspace = workspace_from_dir(directory)
loops_path = workspace.loops_path
from klab.ro... | Return a list of tuples indicating the start and end points of the loops
that were sampled in the given directory. | Below is the the instruction that describes the task:
### Input:
Return a list of tuples indicating the start and end points of the loops
that were sampled in the given directory.
### Response:
def load_loops(directory, loops_path=None):
"""
Return a list of tuples indicating the start and end points o... |
def register(key, initializer: callable, param=None):
'''Adds resolver to global container'''
get_current_scope().container.register(key, initializer, param) | Adds resolver to global container | Below is the the instruction that describes the task:
### Input:
Adds resolver to global container
### Response:
def register(key, initializer: callable, param=None):
'''Adds resolver to global container'''
get_current_scope().container.register(key, initializer, param) |
def add_match(self, entity, *traits):
"""
Add a matching entity to the index.
We have to maintain the constraints of the data layout:
- `self.mismatch_unknown` must still contain all matched entities
- each key of the index must mismatch all known matching entities excep... | Add a matching entity to the index.
We have to maintain the constraints of the data layout:
- `self.mismatch_unknown` must still contain all matched entities
- each key of the index must mismatch all known matching entities except those this particular key
explicitly inclu... | Below is the the instruction that describes the task:
### Input:
Add a matching entity to the index.
We have to maintain the constraints of the data layout:
- `self.mismatch_unknown` must still contain all matched entities
- each key of the index must mismatch all known matching ent... |
def _remove_buffers(state):
"""Return (state_without_buffers, buffer_paths, buffers) for binary message parts
A binary message part is a memoryview, bytearray, or python 3 bytes object.
As an example:
>>> state = {'plain': [0, 'text'], 'x': {'ar': memoryview(ar1)}, 'y': {'shape': (10,10), 'data': memo... | Return (state_without_buffers, buffer_paths, buffers) for binary message parts
A binary message part is a memoryview, bytearray, or python 3 bytes object.
As an example:
>>> state = {'plain': [0, 'text'], 'x': {'ar': memoryview(ar1)}, 'y': {'shape': (10,10), 'data': memoryview(ar2)}}
>>> _remove_buffe... | Below is the the instruction that describes the task:
### Input:
Return (state_without_buffers, buffer_paths, buffers) for binary message parts
A binary message part is a memoryview, bytearray, or python 3 bytes object.
As an example:
>>> state = {'plain': [0, 'text'], 'x': {'ar': memoryview(ar1)}, 'y... |
def collect_blame_info(cls, matches):
"""Runs git blame on files, for the specified sets of line ranges.
If no line range tuples are provided, it will do all lines.
"""
old_area = None
for filename, ranges in matches:
area, name = os.path.split(filename)
... | Runs git blame on files, for the specified sets of line ranges.
If no line range tuples are provided, it will do all lines. | Below is the the instruction that describes the task:
### Input:
Runs git blame on files, for the specified sets of line ranges.
If no line range tuples are provided, it will do all lines.
### Response:
def collect_blame_info(cls, matches):
"""Runs git blame on files, for the specified sets of lin... |
def _merge_raw(self, other):
"""For use with binary arithmetic."""
if other is None:
variables = OrderedDict(self.variables)
else:
# don't align because we already called xarray.align
variables = expand_and_merge_variables(
[self.variables, oth... | For use with binary arithmetic. | Below is the the instruction that describes the task:
### Input:
For use with binary arithmetic.
### Response:
def _merge_raw(self, other):
"""For use with binary arithmetic."""
if other is None:
variables = OrderedDict(self.variables)
else:
# don't align because we ... |
def restore(self):
"""
Restore the snapshot
"""
yield from self._project.delete_on_computes()
# We don't send close notif to clients because the close / open dance is purely internal
yield from self._project.close(ignore_notification=True)
self._project.controlle... | Restore the snapshot | Below is the the instruction that describes the task:
### Input:
Restore the snapshot
### Response:
def restore(self):
"""
Restore the snapshot
"""
yield from self._project.delete_on_computes()
# We don't send close notif to clients because the close / open dance is purely ... |
def loaded(self, request, *args, **kwargs):
"""Return a list of loaded Packs.
"""
serializer = self.get_serializer(list(Pack.objects.all()),
many=True)
return Response(serializer.data) | Return a list of loaded Packs. | Below is the the instruction that describes the task:
### Input:
Return a list of loaded Packs.
### Response:
def loaded(self, request, *args, **kwargs):
"""Return a list of loaded Packs.
"""
serializer = self.get_serializer(list(Pack.objects.all()),
... |
def show_fabric_trunk_info_output_show_trunk_list_trunk_list_groups_trunk_list_member_trunk_list_src_port(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
show_fabric_trunk_info = ET.Element("show_fabric_trunk_info")
config = show_fabric_trunk_info
... | Auto Generated Code | Below is the the instruction that describes the task:
### Input:
Auto Generated Code
### Response:
def show_fabric_trunk_info_output_show_trunk_list_trunk_list_groups_trunk_list_member_trunk_list_src_port(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
show... |
def generate_enums_info(enums, msgs):
"""Add camel case swift names for enums an entries, descriptions and sort enums alphabetically"""
for enum in enums:
enum.swift_name = camel_case_from_underscores(enum.name)
enum.raw_value_type = get_enum_raw_type(enum, msgs)
enum.formatted_descrip... | Add camel case swift names for enums an entries, descriptions and sort enums alphabetically | Below is the the instruction that describes the task:
### Input:
Add camel case swift names for enums an entries, descriptions and sort enums alphabetically
### Response:
def generate_enums_info(enums, msgs):
"""Add camel case swift names for enums an entries, descriptions and sort enums alphabetically"""
... |
def _configure_manager(self):
"""
Creates a manager to handle the instances, and another
to handle flavors.
"""
self._manager = CloudDatabaseManager(self,
resource_class=CloudDatabaseInstance, response_key="instance",
uri_base="instances")
... | Creates a manager to handle the instances, and another
to handle flavors. | Below is the the instruction that describes the task:
### Input:
Creates a manager to handle the instances, and another
to handle flavors.
### Response:
def _configure_manager(self):
"""
Creates a manager to handle the instances, and another
to handle flavors.
"""
se... |
def enum_subpattern(p):
subpattern_id, d = p
patterns = list(enum_gen(d))
'''
if subpattern_id:
subpat_iter = EnumSubpatternIterator(subpattern_id, patterns)
SUBPATTERNS[subpattern_id] = subpat_iter
return subpat_iter
else:
return patterns
'''
return patt... | if subpattern_id:
subpat_iter = EnumSubpatternIterator(subpattern_id, patterns)
SUBPATTERNS[subpattern_id] = subpat_iter
return subpat_iter
else:
return patterns | Below is the the instruction that describes the task:
### Input:
if subpattern_id:
subpat_iter = EnumSubpatternIterator(subpattern_id, patterns)
SUBPATTERNS[subpattern_id] = subpat_iter
return subpat_iter
else:
return patterns
### Response:
def enum_subpattern(p):
subpattern... |
def _print_sql_with_error(self, sql, error_line):
"""
Writes a SQL statement with an syntax error to the output. The line where the error occurs is highlighted.
:param str sql: The SQL statement.
:param int error_line: The line where the error occurs.
"""
if os.linesep i... | Writes a SQL statement with an syntax error to the output. The line where the error occurs is highlighted.
:param str sql: The SQL statement.
:param int error_line: The line where the error occurs. | Below is the the instruction that describes the task:
### Input:
Writes a SQL statement with an syntax error to the output. The line where the error occurs is highlighted.
:param str sql: The SQL statement.
:param int error_line: The line where the error occurs.
### Response:
def _print_sql_with_e... |
def ifftn(a, s=None, axes=None, norm=None):
"""
Compute the N-dimensional inverse discrete Fourier Transform.
This function computes the inverse of the N-dimensional discrete
Fourier Transform over any number of axes in an M-dimensional array by
means of the Fast Fourier Transform (FFT). In other ... | Compute the N-dimensional inverse discrete Fourier Transform.
This function computes the inverse of the N-dimensional discrete
Fourier Transform over any number of axes in an M-dimensional array by
means of the Fast Fourier Transform (FFT). In other words,
``ifftn(fftn(a)) == a`` to within numerical a... | Below is the the instruction that describes the task:
### Input:
Compute the N-dimensional inverse discrete Fourier Transform.
This function computes the inverse of the N-dimensional discrete
Fourier Transform over any number of axes in an M-dimensional array by
means of the Fast Fourier Transform (FFT... |
def sql_flush(self, style, tables, sequences, allow_cascade=False):
"""
Truncate all existing tables in current keyspace.
:returns: an empty list
"""
for table in tables:
qs = "TRUNCATE {}".format(table)
self.connection.connection.execute(qs)
re... | Truncate all existing tables in current keyspace.
:returns: an empty list | Below is the the instruction that describes the task:
### Input:
Truncate all existing tables in current keyspace.
:returns: an empty list
### Response:
def sql_flush(self, style, tables, sequences, allow_cascade=False):
"""
Truncate all existing tables in current keyspace.
:retur... |
def update_time_login(u_name):
'''
Update the login time for user.
'''
entry = TabMember.update(
time_login=tools.timestamp()
).where(
TabMember.user_name == u_name
)
entry.execute() | Update the login time for user. | Below is the the instruction that describes the task:
### Input:
Update the login time for user.
### Response:
def update_time_login(u_name):
'''
Update the login time for user.
'''
entry = TabMember.update(
time_login=tools.timestamp()
).where(
TabMe... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.