code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def getContext(self, context_name = 'default'):
"""Get a context by name, create the default context if it does not exist
Params:
context_name (string):
Context name
Raises:
KeyError:
If the context name does not exist
Returns:
bubbler.Bubbler:
Named context
"""
if con... | Get a context by name, create the default context if it does not exist
Params:
context_name (string):
Context name
Raises:
KeyError:
If the context name does not exist
Returns:
bubbler.Bubbler:
Named context | Below is the the instruction that describes the task:
### Input:
Get a context by name, create the default context if it does not exist
Params:
context_name (string):
Context name
Raises:
KeyError:
If the context name does not exist
Returns:
bubbler.Bubbler:
Named context
#... |
def resume_service(name):
"""
Resume the service given by name.
@warn: This method requires UAC elevation in Windows Vista and above.
@note: Not all services support this.
@see: L{get_services}, L{get_active_services},
L{start_service}, L{stop_service}, L{pause_ser... | Resume the service given by name.
@warn: This method requires UAC elevation in Windows Vista and above.
@note: Not all services support this.
@see: L{get_services}, L{get_active_services},
L{start_service}, L{stop_service}, L{pause_service} | Below is the the instruction that describes the task:
### Input:
Resume the service given by name.
@warn: This method requires UAC elevation in Windows Vista and above.
@note: Not all services support this.
@see: L{get_services}, L{get_active_services},
L{start_service}, L{sto... |
def add_real_paths(self, path_list, read_only=True, lazy_dir_read=True):
"""This convenience method adds multiple files and/or directories from
the real file system to the fake file system. See `add_real_file()` and
`add_real_directory()`.
Args:
path_list: List of file and d... | This convenience method adds multiple files and/or directories from
the real file system to the fake file system. See `add_real_file()` and
`add_real_directory()`.
Args:
path_list: List of file and directory paths in the real file
system.
read_only: If se... | Below is the the instruction that describes the task:
### Input:
This convenience method adds multiple files and/or directories from
the real file system to the fake file system. See `add_real_file()` and
`add_real_directory()`.
Args:
path_list: List of file and directory paths ... |
def exclusive_ns(guard: StateGuard[A], desc: str, thunk: Callable[..., NS[A, B]], *a: Any) -> Do:
'''this is the central unsafe function, using a lock and updating the state in `guard` in-place.
'''
yield guard.acquire()
log.debug2(lambda: f'exclusive: {desc}')
state, response = yield N.ensure_failu... | this is the central unsafe function, using a lock and updating the state in `guard` in-place. | Below is the the instruction that describes the task:
### Input:
this is the central unsafe function, using a lock and updating the state in `guard` in-place.
### Response:
def exclusive_ns(guard: StateGuard[A], desc: str, thunk: Callable[..., NS[A, B]], *a: Any) -> Do:
'''this is the central unsafe function, ... |
def serialize(self, value, **kwargs):
"""Return a serialized copy of the tuple"""
kwargs.update({'include_class': kwargs.get('include_class', True)})
if self.serializer is not None:
return self.serializer(value, **kwargs)
if value is None:
return None
seri... | Return a serialized copy of the tuple | Below is the the instruction that describes the task:
### Input:
Return a serialized copy of the tuple
### Response:
def serialize(self, value, **kwargs):
"""Return a serialized copy of the tuple"""
kwargs.update({'include_class': kwargs.get('include_class', True)})
if self.serializer is no... |
def getValue(self, prop, default=None):
"""Return the value of feature with that name or ``default``."""
f = self.props.get(prop, None)
if not f:
return default
if isinstance(f, Feature):
return f.getValue()
if isinstance(f, tuple):
# if f[0].... | Return the value of feature with that name or ``default``. | Below is the the instruction that describes the task:
### Input:
Return the value of feature with that name or ``default``.
### Response:
def getValue(self, prop, default=None):
"""Return the value of feature with that name or ``default``."""
f = self.props.get(prop, None)
if not f:
... |
def subset(self, interval: Interval,
flexibility: int = 2) -> "IntervalList":
"""
Returns an IntervalList that's a subset of this one, only containing
intervals that meet the "interval" parameter criterion. What "meet"
means is defined by the ``flexibility`` parameter.
... | Returns an IntervalList that's a subset of this one, only containing
intervals that meet the "interval" parameter criterion. What "meet"
means is defined by the ``flexibility`` parameter.
``flexibility == 0``: permits only wholly contained intervals:
.. code-block:: none
i... | Below is the the instruction that describes the task:
### Input:
Returns an IntervalList that's a subset of this one, only containing
intervals that meet the "interval" parameter criterion. What "meet"
means is defined by the ``flexibility`` parameter.
``flexibility == 0``: permits only who... |
def run(self, manager):
"""Run this query and returns the resulting BEL graph.
:param manager: A cache manager
:rtype: Optional[pybel.BELGraph]
"""
universe = self._get_universe(manager)
graph = self.seeding.run(universe)
return self.pipeline.run(graph, universe=... | Run this query and returns the resulting BEL graph.
:param manager: A cache manager
:rtype: Optional[pybel.BELGraph] | Below is the the instruction that describes the task:
### Input:
Run this query and returns the resulting BEL graph.
:param manager: A cache manager
:rtype: Optional[pybel.BELGraph]
### Response:
def run(self, manager):
"""Run this query and returns the resulting BEL graph.
:param... |
def remove_builtin(self, key, orig):
"""Remove an added builtin and re-set the original."""
if orig is BuiltinUndefined:
del __builtin__.__dict__[key]
else:
__builtin__.__dict__[key] = orig | Remove an added builtin and re-set the original. | Below is the the instruction that describes the task:
### Input:
Remove an added builtin and re-set the original.
### Response:
def remove_builtin(self, key, orig):
"""Remove an added builtin and re-set the original."""
if orig is BuiltinUndefined:
del __builtin__.__dict__[key]
... |
def memoized_property(func=None, key_factory=per_instance, **kwargs):
"""A convenience wrapper for memoizing properties.
Applied like so:
>>> class Foo(object):
... @memoized_property
... def name(self):
... pass
Is equivalent to:
>>> class Foo(object):
... @property
... @memoized_me... | A convenience wrapper for memoizing properties.
Applied like so:
>>> class Foo(object):
... @memoized_property
... def name(self):
... pass
Is equivalent to:
>>> class Foo(object):
... @property
... @memoized_method
... def name(self):
... pass
Which is equivalent to:
>... | Below is the the instruction that describes the task:
### Input:
A convenience wrapper for memoizing properties.
Applied like so:
>>> class Foo(object):
... @memoized_property
... def name(self):
... pass
Is equivalent to:
>>> class Foo(object):
... @property
... @memoized_method
... |
def filter_reports(self, analytes, filt_str='all', nbin=5, samples=None,
outdir=None, subset='All_Samples'):
"""
Plot filter reports for all filters that contain ``filt_str``
in the name.
"""
if outdir is None:
outdir = self.report_dir + '/filte... | Plot filter reports for all filters that contain ``filt_str``
in the name. | Below is the the instruction that describes the task:
### Input:
Plot filter reports for all filters that contain ``filt_str``
in the name.
### Response:
def filter_reports(self, analytes, filt_str='all', nbin=5, samples=None,
outdir=None, subset='All_Samples'):
"""
P... |
def wait_not_displayed(element, timeout=None, fail_on_timeout=None):
"""
Wait until element becomes invisible or time out.
Returns true is element became invisible, otherwise false.
If timeout is not specified or 0, then uses specific element wait timeout.
:param element:
:param timeout:
:pa... | Wait until element becomes invisible or time out.
Returns true is element became invisible, otherwise false.
If timeout is not specified or 0, then uses specific element wait timeout.
:param element:
:param timeout:
:param fail_on_timeout:
:return: | Below is the the instruction that describes the task:
### Input:
Wait until element becomes invisible or time out.
Returns true is element became invisible, otherwise false.
If timeout is not specified or 0, then uses specific element wait timeout.
:param element:
:param timeout:
:param fail_on_... |
def writeToCheckpoint(self, checkpointDir):
"""Serializes model using capnproto and writes data to ``checkpointDir``"""
proto = self.getSchema().new_message()
self.write(proto)
checkpointPath = self._getModelCheckpointFilePath(checkpointDir)
# Clean up old saved state, if any
if os.path.exist... | Serializes model using capnproto and writes data to ``checkpointDir`` | Below is the the instruction that describes the task:
### Input:
Serializes model using capnproto and writes data to ``checkpointDir``
### Response:
def writeToCheckpoint(self, checkpointDir):
"""Serializes model using capnproto and writes data to ``checkpointDir``"""
proto = self.getSchema().new_message()... |
def send(self, stanza):
"""Send a stanza somwhere.
The default implementation sends it via the `uplink` if it is defined
or raises the `NoRouteError`.
:Parameters:
- `stanza`: the stanza to send.
:Types:
- `stanza`: `pyxmpp.stanza.Stanza`"""
if s... | Send a stanza somwhere.
The default implementation sends it via the `uplink` if it is defined
or raises the `NoRouteError`.
:Parameters:
- `stanza`: the stanza to send.
:Types:
- `stanza`: `pyxmpp.stanza.Stanza` | Below is the the instruction that describes the task:
### Input:
Send a stanza somwhere.
The default implementation sends it via the `uplink` if it is defined
or raises the `NoRouteError`.
:Parameters:
- `stanza`: the stanza to send.
:Types:
- `stanza`: `pyx... |
def flat_plane(script, plane=0, aspect_ratio=False):
"""Flat plane parameterization
"""
filter_xml = ''.join([
' <filter name="Parametrization: Flat Plane ">\n',
' <Param name="projectionPlane"',
'value="%d"' % plane,
'description="Projection plane"',
'enum_val0=... | Flat plane parameterization | Below is the the instruction that describes the task:
### Input:
Flat plane parameterization
### Response:
def flat_plane(script, plane=0, aspect_ratio=False):
"""Flat plane parameterization
"""
filter_xml = ''.join([
' <filter name="Parametrization: Flat Plane ">\n',
' <Param name... |
def deploy_stack(awsclient, context, conf, cloudformation, override_stack_policy=False):
"""Deploy the stack to AWS cloud. Does either create or update the stack.
:param conf:
:param override_stack_policy:
:return: exit_code
"""
stack_name = _get_stack_name(conf)
parameters = _generate_para... | Deploy the stack to AWS cloud. Does either create or update the stack.
:param conf:
:param override_stack_policy:
:return: exit_code | Below is the the instruction that describes the task:
### Input:
Deploy the stack to AWS cloud. Does either create or update the stack.
:param conf:
:param override_stack_policy:
:return: exit_code
### Response:
def deploy_stack(awsclient, context, conf, cloudformation, override_stack_policy=False):
... |
def try_to_replace(self, provider, other, problems):
"""
Attempt to replace one provider with another. This is typically used
when resolving dependencies from multiple sources, e.g. A requires
(B >= 1.0) while C requires (B >= 1.1).
For successful replacement, ``provider`` must ... | Attempt to replace one provider with another. This is typically used
when resolving dependencies from multiple sources, e.g. A requires
(B >= 1.0) while C requires (B >= 1.1).
For successful replacement, ``provider`` must meet all the requirements
which ``other`` fulfills.
:par... | Below is the the instruction that describes the task:
### Input:
Attempt to replace one provider with another. This is typically used
when resolving dependencies from multiple sources, e.g. A requires
(B >= 1.0) while C requires (B >= 1.1).
For successful replacement, ``provider`` must meet... |
def iter_genotypes(self):
"""Iterates on available markers.
Returns:
Genotypes instances.
"""
# Parsing each column of the dataframe
for variant in self.df.columns:
genotypes = self.df.loc[:, variant].values
info = self.map_info.loc[variant, ... | Iterates on available markers.
Returns:
Genotypes instances. | Below is the the instruction that describes the task:
### Input:
Iterates on available markers.
Returns:
Genotypes instances.
### Response:
def iter_genotypes(self):
"""Iterates on available markers.
Returns:
Genotypes instances.
"""
# Parsing each... |
def checkedItems( self ):
"""
Returns the checked items for this combobox.
:return [<str>, ..]
"""
if not self.isCheckable():
return []
return [nativestring(self.itemText(i)) for i in self.checkedIndexes()] | Returns the checked items for this combobox.
:return [<str>, ..] | Below is the the instruction that describes the task:
### Input:
Returns the checked items for this combobox.
:return [<str>, ..]
### Response:
def checkedItems( self ):
"""
Returns the checked items for this combobox.
:return [<str>, ..]
"""
... |
def upload_from_shared_memory(self, location, bbox, order='F', cutout_bbox=None):
"""
Upload from a shared memory array.
https://github.com/seung-lab/cloud-volume/wiki/Advanced-Topic:-Shared-Memory
tip: If you want to use slice notation, np.s_[...] will help in a pinch.
MEMORY LIFECYCLE WARNING:... | Upload from a shared memory array.
https://github.com/seung-lab/cloud-volume/wiki/Advanced-Topic:-Shared-Memory
tip: If you want to use slice notation, np.s_[...] will help in a pinch.
MEMORY LIFECYCLE WARNING: You are responsible for managing the lifecycle of the
shared memory. CloudVolume will ... | Below is the the instruction that describes the task:
### Input:
Upload from a shared memory array.
https://github.com/seung-lab/cloud-volume/wiki/Advanced-Topic:-Shared-Memory
tip: If you want to use slice notation, np.s_[...] will help in a pinch.
MEMORY LIFECYCLE WARNING: You are responsible for ... |
def create_queue(self, queue_name, visibility_timeout=None, callback=None):
"""
Create an SQS Queue.
:type queue_name: str or unicode
:param queue_name: The name of the new queue. Names are scoped to
an account and need to be unique within that
... | Create an SQS Queue.
:type queue_name: str or unicode
:param queue_name: The name of the new queue. Names are scoped to
an account and need to be unique within that
account. Calling this method on an existing
queue name ... | Below is the the instruction that describes the task:
### Input:
Create an SQS Queue.
:type queue_name: str or unicode
:param queue_name: The name of the new queue. Names are scoped to
an account and need to be unique within that
account. Call... |
def prt_mrks(self, name_marks_list, prt=sys.stdout):
"""Print summary of all GOEAs.
Example:
Key for GO sections:
A immune
B viral/bacteria
C neuro
D cell death
E lipid
F adhesion
G cell cycle
... | Print summary of all GOEAs.
Example:
Key for GO sections:
A immune
B viral/bacteria
C neuro
D cell death
E lipid
F adhesion
G cell cycle
H chromosome
I development
J ... | Below is the the instruction that describes the task:
### Input:
Print summary of all GOEAs.
Example:
Key for GO sections:
A immune
B viral/bacteria
C neuro
D cell death
E lipid
F adhesion
G cell cycle... |
def _sequence(self, i):
"""Handle character group."""
c = next(i)
if c == '!':
c = next(i)
if c in ('^', '-', '['):
c = next(i)
while c != ']':
if c == '\\':
# Handle escapes
subindex = i.index
... | Handle character group. | Below is the the instruction that describes the task:
### Input:
Handle character group.
### Response:
def _sequence(self, i):
"""Handle character group."""
c = next(i)
if c == '!':
c = next(i)
if c in ('^', '-', '['):
c = next(i)
while c != ']':
... |
def start(self):
'''start sending packets'''
if self.sock is not None:
self.sock.close()
self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self.sock.connect(('', gen_setting... | start sending packets | Below is the the instruction that describes the task:
### Input:
start sending packets
### Response:
def start(self):
'''start sending packets'''
if self.sock is not None:
self.sock.close()
self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
... |
def on_select_mean_type_box(self, event):
"""
set parent Zeq_GUI to reflect change in this box and change the
@param: event -> the wx.ComboBoxEvent that triggered this function
"""
new_mean_type = self.mean_type_box.GetValue()
if new_mean_type == "None":
self.... | set parent Zeq_GUI to reflect change in this box and change the
@param: event -> the wx.ComboBoxEvent that triggered this function | Below is the the instruction that describes the task:
### Input:
set parent Zeq_GUI to reflect change in this box and change the
@param: event -> the wx.ComboBoxEvent that triggered this function
### Response:
def on_select_mean_type_box(self, event):
"""
set parent Zeq_GUI to reflect chang... |
def convert_belscript(ctx, input_fn, output_fn):
"""Convert belscript to nanopubs_bel format
This will convert the OpenBEL BELScript file format to
nanopub_bel-1.0.0 format.
\b
input_fn:
If input fn has *.gz, will read as a gzip file
\b
output_fn:
If output fn has *.gz, wi... | Convert belscript to nanopubs_bel format
This will convert the OpenBEL BELScript file format to
nanopub_bel-1.0.0 format.
\b
input_fn:
If input fn has *.gz, will read as a gzip file
\b
output_fn:
If output fn has *.gz, will written as a gzip file
If output fn has *.jso... | Below is the the instruction that describes the task:
### Input:
Convert belscript to nanopubs_bel format
This will convert the OpenBEL BELScript file format to
nanopub_bel-1.0.0 format.
\b
input_fn:
If input fn has *.gz, will read as a gzip file
\b
output_fn:
If output fn... |
def _paged_api_call(self, func, kwargs, item_type='photo'):
"""
Takes a Flickr API function object and dict of keyword args and calls the
API call repeatedly with an incrementing page value until all contents are exhausted.
Flickr seems to limit to about 500 items.
"""
pa... | Takes a Flickr API function object and dict of keyword args and calls the
API call repeatedly with an incrementing page value until all contents are exhausted.
Flickr seems to limit to about 500 items. | Below is the the instruction that describes the task:
### Input:
Takes a Flickr API function object and dict of keyword args and calls the
API call repeatedly with an incrementing page value until all contents are exhausted.
Flickr seems to limit to about 500 items.
### Response:
def _paged_api_cal... |
def pdna_network_from_bbox(
lat_min=None, lng_min=None, lat_max=None, lng_max=None, bbox=None,
network_type='walk', two_way=True,
timeout=180, memory=None, max_query_area_size=50 * 1000 * 50 * 1000):
"""
Make a Pandana network from a bounding lat/lon box
request to the Overpass API. ... | Make a Pandana network from a bounding lat/lon box
request to the Overpass API. Distance will be in the default units meters.
Parameters
----------
lat_min, lng_min, lat_max, lng_max : float
bbox : tuple
Bounding box formatted as a 4 element tuple:
(lng_max, lat_min, lng_min, lat_ma... | Below is the the instruction that describes the task:
### Input:
Make a Pandana network from a bounding lat/lon box
request to the Overpass API. Distance will be in the default units meters.
Parameters
----------
lat_min, lng_min, lat_max, lng_max : float
bbox : tuple
Bounding box forma... |
def parse(cls, root):
"""
Create a new AMDSec by parsing root.
:param root: Element or ElementTree to be parsed into an object.
"""
if root.tag != utils.lxmlns("mets") + "amdSec":
raise exceptions.ParseError(
"AMDSec can only parse amdSec elements wit... | Create a new AMDSec by parsing root.
:param root: Element or ElementTree to be parsed into an object. | Below is the the instruction that describes the task:
### Input:
Create a new AMDSec by parsing root.
:param root: Element or ElementTree to be parsed into an object.
### Response:
def parse(cls, root):
"""
Create a new AMDSec by parsing root.
:param root: Element or ElementTree t... |
def resample(data, s_freq=None, axis='time', ftype='fir', n=None):
"""Downsample the data after applying a filter.
Parameters
----------
data : instance of Data
data to downsample
s_freq : int or float
desired sampling frequency
axis : str
axis you want to apply downsamp... | Downsample the data after applying a filter.
Parameters
----------
data : instance of Data
data to downsample
s_freq : int or float
desired sampling frequency
axis : str
axis you want to apply downsample on (most likely 'time')
ftype : str
filter type to apply. T... | Below is the the instruction that describes the task:
### Input:
Downsample the data after applying a filter.
Parameters
----------
data : instance of Data
data to downsample
s_freq : int or float
desired sampling frequency
axis : str
axis you want to apply downsample on... |
def next_joystick_device():
"""Finds the next available js device name."""
for i in range(100):
dev = "/dev/input/js{0}".format(i)
if not os.path.exists(dev):
return dev | Finds the next available js device name. | Below is the the instruction that describes the task:
### Input:
Finds the next available js device name.
### Response:
def next_joystick_device():
"""Finds the next available js device name."""
for i in range(100):
dev = "/dev/input/js{0}".format(i)
if not os.path.exists(dev):
... |
def reqHistoricalNews(
self, conId: int, providerCodes: str,
startDateTime: Union[str, datetime.date],
endDateTime: Union[str, datetime.date],
totalResults: int,
historicalNewsOptions: List[TagValue] = None) -> HistoricalNews:
"""
Get historica... | Get historical news headline.
https://interactivebrokers.github.io/tws-api/news.html
This method is blocking.
Args:
conId: Search news articles for contract with this conId.
providerCodes: A '+'-separated list of provider codes, like
'BZ+FLY'.
... | Below is the the instruction that describes the task:
### Input:
Get historical news headline.
https://interactivebrokers.github.io/tws-api/news.html
This method is blocking.
Args:
conId: Search news articles for contract with this conId.
providerCodes: A '+'-separ... |
def get_url_repair_patterns():
"""Initialise and return a list of precompiled regexp patterns that
are used to try to re-assemble URLs that have been broken during
a document's conversion to plain-text.
@return: (list) of compiled re regexp patterns used for finding
various broken URLs.... | Initialise and return a list of precompiled regexp patterns that
are used to try to re-assemble URLs that have been broken during
a document's conversion to plain-text.
@return: (list) of compiled re regexp patterns used for finding
various broken URLs. | Below is the the instruction that describes the task:
### Input:
Initialise and return a list of precompiled regexp patterns that
are used to try to re-assemble URLs that have been broken during
a document's conversion to plain-text.
@return: (list) of compiled re regexp patterns used for findi... |
def load_app(target):
""" Load a bottle application from a module and make sure that the import
does not affect the current default application, but returns a separate
application object. See :func:`load` for the target parameter. """
global NORUN
NORUN, nr_old = True, NORUN
tmp = defaul... | Load a bottle application from a module and make sure that the import
does not affect the current default application, but returns a separate
application object. See :func:`load` for the target parameter. | Below is the the instruction that describes the task:
### Input:
Load a bottle application from a module and make sure that the import
does not affect the current default application, but returns a separate
application object. See :func:`load` for the target parameter.
### Response:
def load_app(ta... |
def get_relationship_admin_session_for_family(self, family_id):
"""Gets the ``OsidSession`` associated with the relationship administration service for the given family.
arg: family_id (osid.id.Id): the ``Id`` of the ``Family``
return: (osid.relationship.RelationshipAdminSession) - a
... | Gets the ``OsidSession`` associated with the relationship administration service for the given family.
arg: family_id (osid.id.Id): the ``Id`` of the ``Family``
return: (osid.relationship.RelationshipAdminSession) - a
``RelationshipAdminSession``
raise: NotFound - no family ... | Below is the the instruction that describes the task:
### Input:
Gets the ``OsidSession`` associated with the relationship administration service for the given family.
arg: family_id (osid.id.Id): the ``Id`` of the ``Family``
return: (osid.relationship.RelationshipAdminSession) - a
... |
def screen(self):
'''
Turn on/off screen.
Usage:
d.screen.on()
d.screen.off()
d.screen == 'on' # Check if the screen is on, same as 'd.screenOn'
d.screen == 'off' # Check if the screen is off, same as 'not d.screenOn'
'''
devive_self = self
... | Turn on/off screen.
Usage:
d.screen.on()
d.screen.off()
d.screen == 'on' # Check if the screen is on, same as 'd.screenOn'
d.screen == 'off' # Check if the screen is off, same as 'not d.screenOn' | Below is the the instruction that describes the task:
### Input:
Turn on/off screen.
Usage:
d.screen.on()
d.screen.off()
d.screen == 'on' # Check if the screen is on, same as 'd.screenOn'
d.screen == 'off' # Check if the screen is off, same as 'not d.screenOn'
### Response... |
def _add_halfwave(data, events, s_freq, opts):
"""Find the next zero crossing and the intervening peak and add
them to events. If no zero found before max_dur, event is discarded. If
peak-to-peak is smaller than min_ptp, the event is discarded.
Parameters
----------
data : ndarray (dtype='float... | Find the next zero crossing and the intervening peak and add
them to events. If no zero found before max_dur, event is discarded. If
peak-to-peak is smaller than min_ptp, the event is discarded.
Parameters
----------
data : ndarray (dtype='float')
vector with the data
events : ndarray (... | Below is the the instruction that describes the task:
### Input:
Find the next zero crossing and the intervening peak and add
them to events. If no zero found before max_dur, event is discarded. If
peak-to-peak is smaller than min_ptp, the event is discarded.
Parameters
----------
data : ndarra... |
def split_string(self, string, splitter='.', allow_empty=True):
"""Split the string with respect of quotes"""
i = 0
rv = []
need_split = False
while i < len(string):
m = re.compile(_KEY_NAME).match(string, i)
if not need_split and m:
i = m.... | Split the string with respect of quotes | Below is the the instruction that describes the task:
### Input:
Split the string with respect of quotes
### Response:
def split_string(self, string, splitter='.', allow_empty=True):
"""Split the string with respect of quotes"""
i = 0
rv = []
need_split = False
while i < len... |
def FindUniqueId(dic):
"""Return a string not used as a key in the dictionary dic"""
name = str(len(dic))
while name in dic:
# Use bigger numbers so it is obvious when an id is picked randomly.
name = str(random.randint(1000000, 999999999))
return name | Return a string not used as a key in the dictionary dic | Below is the the instruction that describes the task:
### Input:
Return a string not used as a key in the dictionary dic
### Response:
def FindUniqueId(dic):
"""Return a string not used as a key in the dictionary dic"""
name = str(len(dic))
while name in dic:
# Use bigger numbers so it is obvious when an... |
def get_cytoband_coord(chrom, pos):
"""Get the cytoband coordinate for a position
Args:
chrom(str): A chromosome
pos(int): The position
Returns:
cytoband
"""
chrom = chrom.strip('chr')
pos = int(pos)
result = None
logger.debug("Finding Cytoba... | Get the cytoband coordinate for a position
Args:
chrom(str): A chromosome
pos(int): The position
Returns:
cytoband | Below is the the instruction that describes the task:
### Input:
Get the cytoband coordinate for a position
Args:
chrom(str): A chromosome
pos(int): The position
Returns:
cytoband
### Response:
def get_cytoband_coord(chrom, pos):
"""Get the cytoband coordin... |
def split_token_in_parts(token):
"""
Take a Token, and turn it in a list of tokens, by splitting
it on ':' (taking that as a separator.)
"""
result = []
current = []
for part in token + (':', ):
if part == ':':
if current:
result.append(tuple(current))
... | Take a Token, and turn it in a list of tokens, by splitting
it on ':' (taking that as a separator.) | Below is the the instruction that describes the task:
### Input:
Take a Token, and turn it in a list of tokens, by splitting
it on ':' (taking that as a separator.)
### Response:
def split_token_in_parts(token):
"""
Take a Token, and turn it in a list of tokens, by splitting
it on ':' (taking that ... |
def _add_formatted_imports(self) -> None:
"""Adds the imports back to the file.
(at the index of the first import) sorted alphabetically and split between groups
"""
sort_ignore_case = self.config['force_alphabetical_sort_within_sections']
sections = itertools.chain(self.sectio... | Adds the imports back to the file.
(at the index of the first import) sorted alphabetically and split between groups | Below is the the instruction that describes the task:
### Input:
Adds the imports back to the file.
(at the index of the first import) sorted alphabetically and split between groups
### Response:
def _add_formatted_imports(self) -> None:
"""Adds the imports back to the file.
(at the index... |
def DictReader(ltsvfile, labels=None, dict_type=dict):
"""Make LTSV Reader for reading selected labels.
:param ltsvfile: iterable of lines.
:param labels: sequence of labels.
:return: generator of record in {label: value, ...} form.
"""
for rec in reader(ltsvfile, labels):
yield dict_... | Make LTSV Reader for reading selected labels.
:param ltsvfile: iterable of lines.
:param labels: sequence of labels.
:return: generator of record in {label: value, ...} form. | Below is the the instruction that describes the task:
### Input:
Make LTSV Reader for reading selected labels.
:param ltsvfile: iterable of lines.
:param labels: sequence of labels.
:return: generator of record in {label: value, ...} form.
### Response:
def DictReader(ltsvfile, labels=None, dict_typ... |
def ppaged(self, msg: str, end: str = '\n', chop: bool = False) -> None:
"""Print output using a pager if it would go off screen and stdout isn't currently being redirected.
Never uses a pager inside of a script (Python or text) or when output is being redirected or piped or when
stdout or stdi... | Print output using a pager if it would go off screen and stdout isn't currently being redirected.
Never uses a pager inside of a script (Python or text) or when output is being redirected or piped or when
stdout or stdin are not a fully functional terminal.
:param msg: message to print to curr... | Below is the the instruction that describes the task:
### Input:
Print output using a pager if it would go off screen and stdout isn't currently being redirected.
Never uses a pager inside of a script (Python or text) or when output is being redirected or piped or when
stdout or stdin are not a ful... |
def parse_header_format(description):
"""Get the format from a vcf header line description
If format begins with white space it will be stripped
Args:
description(str): Description from a vcf header line
Return:
format(str): The format information from description
"""
... | Get the format from a vcf header line description
If format begins with white space it will be stripped
Args:
description(str): Description from a vcf header line
Return:
format(str): The format information from description | Below is the the instruction that describes the task:
### Input:
Get the format from a vcf header line description
If format begins with white space it will be stripped
Args:
description(str): Description from a vcf header line
Return:
format(str): The format information f... |
async def search(self, term: str, limit: int = 3) -> 'List[Word]':
"""Performs a search for a term and returns a list of possible matching :class:`Word`
objects.
Args:
term: The term to be defined.
limit (optional): Max amount of results returned.
... | Performs a search for a term and returns a list of possible matching :class:`Word`
objects.
Args:
term: The term to be defined.
limit (optional): Max amount of results returned.
Defaults to 3.
Note:
The API will relay... | Below is the the instruction that describes the task:
### Input:
Performs a search for a term and returns a list of possible matching :class:`Word`
objects.
Args:
term: The term to be defined.
limit (optional): Max amount of results returned.
... |
def http_query(self, method, path, data=None, dont_connect=False, **kwargs):
"""
:param dont_connect: If true do not reconnect if not connected
"""
if not self._connected and not dont_connect:
if self._id == "vm" and not self._controller.gns3vm.running:
yield... | :param dont_connect: If true do not reconnect if not connected | Below is the the instruction that describes the task:
### Input:
:param dont_connect: If true do not reconnect if not connected
### Response:
def http_query(self, method, path, data=None, dont_connect=False, **kwargs):
"""
:param dont_connect: If true do not reconnect if not connected
"""
... |
def load_json(json_str):
"""Loads symbol from json string.
Parameters
----------
json_str : str
A JSON string.
Returns
-------
sym : Symbol
The loaded symbol.
See Also
--------
Symbol.tojson : Used to save symbol into json string.
"""
if not isinstance(... | Loads symbol from json string.
Parameters
----------
json_str : str
A JSON string.
Returns
-------
sym : Symbol
The loaded symbol.
See Also
--------
Symbol.tojson : Used to save symbol into json string. | Below is the the instruction that describes the task:
### Input:
Loads symbol from json string.
Parameters
----------
json_str : str
A JSON string.
Returns
-------
sym : Symbol
The loaded symbol.
See Also
--------
Symbol.tojson : Used to save symbol into json s... |
def morphAveragePitch(fromDataList, toDataList):
'''
Adjusts the values in fromPitchList to have the same average as toPitchList
Because other manipulations can alter the average pitch, morphing the pitch
is the last pitch manipulation that should be done
After the morphing, the code remov... | Adjusts the values in fromPitchList to have the same average as toPitchList
Because other manipulations can alter the average pitch, morphing the pitch
is the last pitch manipulation that should be done
After the morphing, the code removes any values below zero, thus the
final average might no... | Below is the the instruction that describes the task:
### Input:
Adjusts the values in fromPitchList to have the same average as toPitchList
Because other manipulations can alter the average pitch, morphing the pitch
is the last pitch manipulation that should be done
After the morphing, the co... |
def cee_map_priority_table_map_cos5_pgid(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
cee_map = ET.SubElement(config, "cee-map", xmlns="urn:brocade.com:mgmt:brocade-cee-map")
name_key = ET.SubElement(cee_map, "name")
name_key.text = kwargs.pop... | Auto Generated Code | Below is the the instruction that describes the task:
### Input:
Auto Generated Code
### Response:
def cee_map_priority_table_map_cos5_pgid(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
cee_map = ET.SubElement(config, "cee-map", xmlns="urn:brocade.com:mgm... |
def chrom_sorted(in_chroms):
"""
Sort a list of chromosomes in the order 1..22, X, Y, M, <others in alphabetical order>.
:param list in_chroms: Input chromosomes
:return: Sorted chromosomes
:rtype: list[str]
"""
in_chroms.sort()
canonicals = [str(c) for c in range(1, 23)] + ['X', 'Y', '... | Sort a list of chromosomes in the order 1..22, X, Y, M, <others in alphabetical order>.
:param list in_chroms: Input chromosomes
:return: Sorted chromosomes
:rtype: list[str] | Below is the the instruction that describes the task:
### Input:
Sort a list of chromosomes in the order 1..22, X, Y, M, <others in alphabetical order>.
:param list in_chroms: Input chromosomes
:return: Sorted chromosomes
:rtype: list[str]
### Response:
def chrom_sorted(in_chroms):
"""
Sort a ... |
def compile_column(name: str, data_type: str, nullable: bool) -> str:
"""Create column definition statement."""
null_str = 'NULL' if nullable else 'NOT NULL'
return '{name} {data_type} {null},'.format(name=name,
data_type=data_type,
... | Create column definition statement. | Below is the the instruction that describes the task:
### Input:
Create column definition statement.
### Response:
def compile_column(name: str, data_type: str, nullable: bool) -> str:
"""Create column definition statement."""
null_str = 'NULL' if nullable else 'NOT NULL'
return '{name} {data_type} {... |
def tap_hold(self, x, y, duration=1.0):
"""
Tap and hold for a moment
Args:
- x, y(int): position
- duration(float): seconds of hold time
[[FBRoute POST:@"/wda/touchAndHold"] respondWithTarget:self action:@selector(handleTouchAndHoldCoordinate:)],
"""
... | Tap and hold for a moment
Args:
- x, y(int): position
- duration(float): seconds of hold time
[[FBRoute POST:@"/wda/touchAndHold"] respondWithTarget:self action:@selector(handleTouchAndHoldCoordinate:)], | Below is the the instruction that describes the task:
### Input:
Tap and hold for a moment
Args:
- x, y(int): position
- duration(float): seconds of hold time
[[FBRoute POST:@"/wda/touchAndHold"] respondWithTarget:self action:@selector(handleTouchAndHoldCoordinate:)],
### R... |
def get_as_boolean(self, key):
"""
Converts map element into a boolean or returns false if conversion is not possible.
:param key: an index of element to get.
:return: boolean value ot the element or false if conversion is not supported.
"""
value = self.get(key)
... | Converts map element into a boolean or returns false if conversion is not possible.
:param key: an index of element to get.
:return: boolean value ot the element or false if conversion is not supported. | Below is the the instruction that describes the task:
### Input:
Converts map element into a boolean or returns false if conversion is not possible.
:param key: an index of element to get.
:return: boolean value ot the element or false if conversion is not supported.
### Response:
def get_as_bool... |
def _pickle_batch(self):
"""
Pickle the metrics into a form that can be understood
by the graphite pickle connector.
"""
# Pickle
payload = pickle.dumps(self.batch)
# Pack Message
header = struct.pack("!L", len(payload))
message = header + payload... | Pickle the metrics into a form that can be understood
by the graphite pickle connector. | Below is the the instruction that describes the task:
### Input:
Pickle the metrics into a form that can be understood
by the graphite pickle connector.
### Response:
def _pickle_batch(self):
"""
Pickle the metrics into a form that can be understood
by the graphite pickle connector.... |
def parse(cls, specsFileOrString):
"""Parsers a file or string and returns a list of AudioClipSpec
Arguments:
specsFileOrString (str): specifications' file or string
Examples:
>>> SpecsParser.parse('23.4 34.1\n40.2 79.65 Hello World!')
[<Audi... | Parsers a file or string and returns a list of AudioClipSpec
Arguments:
specsFileOrString (str): specifications' file or string
Examples:
>>> SpecsParser.parse('23.4 34.1\n40.2 79.65 Hello World!')
[<AudioClipSpec start:23.40, end:34.10, text:''>,
... | Below is the the instruction that describes the task:
### Input:
Parsers a file or string and returns a list of AudioClipSpec
Arguments:
specsFileOrString (str): specifications' file or string
Examples:
>>> SpecsParser.parse('23.4 34.1\n40.2 79.65 Hello Worl... |
def calculate_s0_curve(s0, minpval, maxpval, minratio, maxratio, curve_interval=0.1):
"""
Calculate s0 curve for volcano plot.
Taking an min and max p value, and a min and max ratio, calculate an smooth
curve starting from parameter `s0` in each direction.
The `curve_interval` parameter defines th... | Calculate s0 curve for volcano plot.
Taking an min and max p value, and a min and max ratio, calculate an smooth
curve starting from parameter `s0` in each direction.
The `curve_interval` parameter defines the smoothness of the resulting curve.
:param s0: `float` offset of curve from interset
:pa... | Below is the the instruction that describes the task:
### Input:
Calculate s0 curve for volcano plot.
Taking an min and max p value, and a min and max ratio, calculate an smooth
curve starting from parameter `s0` in each direction.
The `curve_interval` parameter defines the smoothness of the resulting... |
def build_tqdm_inner(self, desc, total):
"""
Extension point. Override to provide custom options to inner progress bars (Batch loop)
:param desc: Description
:param total: Number of batches
:return: new progress bar
"""
return self.tqdm(desc=desc, total=total, lea... | Extension point. Override to provide custom options to inner progress bars (Batch loop)
:param desc: Description
:param total: Number of batches
:return: new progress bar | Below is the the instruction that describes the task:
### Input:
Extension point. Override to provide custom options to inner progress bars (Batch loop)
:param desc: Description
:param total: Number of batches
:return: new progress bar
### Response:
def build_tqdm_inner(self, desc, total):
... |
def install_os_updates(distribution, force=False):
""" installs OS updates """
if ('centos' in distribution or
'rhel' in distribution or
'redhat' in distribution):
bookshelf2.logging_helpers.log_green('installing OS updates')
sudo("yum -y --quiet clean all")
sudo(... | installs OS updates | Below is the the instruction that describes the task:
### Input:
installs OS updates
### Response:
def install_os_updates(distribution, force=False):
""" installs OS updates """
if ('centos' in distribution or
'rhel' in distribution or
'redhat' in distribution):
bookshelf2.l... |
def send(socket, data, num_bytes=20):
"""Send data to specified socket.
:param socket: open socket instance
:param data: data to send
:param num_bytes: number of bytes to read
:return: received data
"""
pickled_data = pickle.dumps(data, -1)
length = str(len(pickled_data)).zfill(num_by... | Send data to specified socket.
:param socket: open socket instance
:param data: data to send
:param num_bytes: number of bytes to read
:return: received data | Below is the the instruction that describes the task:
### Input:
Send data to specified socket.
:param socket: open socket instance
:param data: data to send
:param num_bytes: number of bytes to read
:return: received data
### Response:
def send(socket, data, num_bytes=20):
"""Send data to s... |
def _set_show_system_monitor(self, v, load=False):
"""
Setter method for show_system_monitor, mapped from YANG variable /brocade_system_monitor_ext_rpc/show_system_monitor (rpc)
If this variable is read-only (config: false) in the
source YANG file, then _set_show_system_monitor is considered as a privat... | Setter method for show_system_monitor, mapped from YANG variable /brocade_system_monitor_ext_rpc/show_system_monitor (rpc)
If this variable is read-only (config: false) in the
source YANG file, then _set_show_system_monitor is considered as a private
method. Backends looking to populate this variable should... | Below is the the instruction that describes the task:
### Input:
Setter method for show_system_monitor, mapped from YANG variable /brocade_system_monitor_ext_rpc/show_system_monitor (rpc)
If this variable is read-only (config: false) in the
source YANG file, then _set_show_system_monitor is considered as a ... |
def parse_posting_id(text, city):
"""
Parse the posting ID from the Backpage ad.
text -> The ad's HTML (or the a substring containing the "Post ID:" section)
city -> The Backpage city of the ad
"""
parts = text.split('Post ID: ')
if len(parts) == 2:
post_id = parts[1].split(' ')[0]
if p... | Parse the posting ID from the Backpage ad.
text -> The ad's HTML (or the a substring containing the "Post ID:" section)
city -> The Backpage city of the ad | Below is the the instruction that describes the task:
### Input:
Parse the posting ID from the Backpage ad.
text -> The ad's HTML (or the a substring containing the "Post ID:" section)
city -> The Backpage city of the ad
### Response:
def parse_posting_id(text, city):
"""
Parse the posting ID fr... |
def get_text(nodelist):
"""Get the value from a text node."""
value = []
for node in nodelist:
if node.nodeType == node.TEXT_NODE:
value.append(node.data)
return ''.join(value) | Get the value from a text node. | Below is the the instruction that describes the task:
### Input:
Get the value from a text node.
### Response:
def get_text(nodelist):
"""Get the value from a text node."""
value = []
for node in nodelist:
if node.nodeType == node.TEXT_NODE:
value.append(node.data)
return ''.joi... |
def resolve(self, authorization: http.Header):
"""
Determine the user associated with a request, using HTTP Basic Authentication.
"""
if authorization is None:
return None
scheme, token = authorization.split()
if scheme.lower() != 'basic':
return ... | Determine the user associated with a request, using HTTP Basic Authentication. | Below is the the instruction that describes the task:
### Input:
Determine the user associated with a request, using HTTP Basic Authentication.
### Response:
def resolve(self, authorization: http.Header):
"""
Determine the user associated with a request, using HTTP Basic Authentication.
"""... |
def toProtocolElement(self):
"""
Converts this exception into the GA4GH protocol type so that
it can be communicated back to the client.
"""
error = protocol.GAException()
error.error_code = self.getErrorCode()
error.message = self.getMessage()
return erro... | Converts this exception into the GA4GH protocol type so that
it can be communicated back to the client. | Below is the the instruction that describes the task:
### Input:
Converts this exception into the GA4GH protocol type so that
it can be communicated back to the client.
### Response:
def toProtocolElement(self):
"""
Converts this exception into the GA4GH protocol type so that
it can... |
def _set_tunnel(self, v, load=False):
"""
Setter method for tunnel, mapped from YANG variable /interface/tunnel (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_tunnel is considered as a private
method. Backends looking to populate this variable should
do s... | Setter method for tunnel, mapped from YANG variable /interface/tunnel (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_tunnel is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_tunnel() directly. | Below is the the instruction that describes the task:
### Input:
Setter method for tunnel, mapped from YANG variable /interface/tunnel (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_tunnel is considered as a private
method. Backends looking to populate this varia... |
def _insert_base_path(self):
"""If the "base" path is set in the paths section of the config, insert
it into the python path.
"""
if config.BASE in self.paths:
sys.path.insert(0, self.paths[config.BASE]) | If the "base" path is set in the paths section of the config, insert
it into the python path. | Below is the the instruction that describes the task:
### Input:
If the "base" path is set in the paths section of the config, insert
it into the python path.
### Response:
def _insert_base_path(self):
"""If the "base" path is set in the paths section of the config, insert
it into the pytho... |
def matrix_undirected_unweighted(user):
"""
Returns an undirected, unweighted matrix where an edge exists if the
relationship is reciprocated.
"""
matrix = matrix_undirected_weighted(user, interaction=None)
for a, b in combinations(range(len(matrix)), 2):
if matrix[a][b] is None or matri... | Returns an undirected, unweighted matrix where an edge exists if the
relationship is reciprocated. | Below is the the instruction that describes the task:
### Input:
Returns an undirected, unweighted matrix where an edge exists if the
relationship is reciprocated.
### Response:
def matrix_undirected_unweighted(user):
"""
Returns an undirected, unweighted matrix where an edge exists if the
relation... |
def _get_si():
'''
Authenticate with vCenter server and return service instance object.
'''
url = config.get_cloud_config_value(
'url', get_configured_provider(), __opts__, search_global=False
)
username = config.get_cloud_config_value(
'user', get_configured_provider(), __opts_... | Authenticate with vCenter server and return service instance object. | Below is the the instruction that describes the task:
### Input:
Authenticate with vCenter server and return service instance object.
### Response:
def _get_si():
'''
Authenticate with vCenter server and return service instance object.
'''
url = config.get_cloud_config_value(
'url', get_co... |
def acknowledge_message(self, delivery_tag, **kwargs):
"""Acknowledge the message delivery from RabbitMQ by sending a
Basic.Ack RPC method for the delivery tag.
:param int delivery_tag: The delivery tag from the Basic.Deliver frame
"""
logger.info('Acknowledging message', deliv... | Acknowledge the message delivery from RabbitMQ by sending a
Basic.Ack RPC method for the delivery tag.
:param int delivery_tag: The delivery tag from the Basic.Deliver frame | Below is the the instruction that describes the task:
### Input:
Acknowledge the message delivery from RabbitMQ by sending a
Basic.Ack RPC method for the delivery tag.
:param int delivery_tag: The delivery tag from the Basic.Deliver frame
### Response:
def acknowledge_message(self, delivery_tag, *... |
def _get_hostname(self, hostname, metric):
"""
If hostname is None, look at label_to_hostname setting
"""
if hostname is None and self.label_to_hostname is not None:
for label in metric.label:
if label.name == self.label_to_hostname:
return... | If hostname is None, look at label_to_hostname setting | Below is the the instruction that describes the task:
### Input:
If hostname is None, look at label_to_hostname setting
### Response:
def _get_hostname(self, hostname, metric):
"""
If hostname is None, look at label_to_hostname setting
"""
if hostname is None and self.label_to_hostn... |
def ParseVideoRow(self, parser_mediator, query, row, **unused_kwargs):
"""Parses a Video row.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
query (str): query that created the row.
row (sqlite3.Row): ro... | Parses a Video row.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
query (str): query that created the row.
row (sqlite3.Row): row. | Below is the the instruction that describes the task:
### Input:
Parses a Video row.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
query (str): query that created the row.
row (sqlite3.Row): row.
### Re... |
def get_features(self):
"""Get the features contained in `self`.
:return: the list of features.
:returntype: `list` of `unicode`"""
l = self.xpath_ctxt.xpathEval("d:feature")
ret = []
for f in l:
if f.hasProp("var"):
ret.append( f.prop("var").... | Get the features contained in `self`.
:return: the list of features.
:returntype: `list` of `unicode` | Below is the the instruction that describes the task:
### Input:
Get the features contained in `self`.
:return: the list of features.
:returntype: `list` of `unicode`
### Response:
def get_features(self):
"""Get the features contained in `self`.
:return: the list of features.
... |
def start(self):
"""starts behaviour in the event loop"""
self.agent.submit(self._start())
self.is_running = True | starts behaviour in the event loop | Below is the the instruction that describes the task:
### Input:
starts behaviour in the event loop
### Response:
def start(self):
"""starts behaviour in the event loop"""
self.agent.submit(self._start())
self.is_running = True |
def connection_made(self, transport):
"""Called when the connection is made"""
self.logger.info('Connection made at object %s', id(self))
self.transport = transport
self.keepalive = True
if self._timeout:
self.logger.debug('Registering timeout event')
sel... | Called when the connection is made | Below is the the instruction that describes the task:
### Input:
Called when the connection is made
### Response:
def connection_made(self, transport):
"""Called when the connection is made"""
self.logger.info('Connection made at object %s', id(self))
self.transport = transport
self... |
def __should_warn_on_redef(
ctx: GeneratorContext, defsym: sym.Symbol, safe_name: str, def_meta: lmap.Map
) -> bool:
"""Return True if the compiler should emit a warning about this name being redefined."""
no_warn_on_redef = def_meta.entry(SYM_NO_WARN_ON_REDEF_META_KEY, False)
if no_warn_on_redef:
... | Return True if the compiler should emit a warning about this name being redefined. | Below is the the instruction that describes the task:
### Input:
Return True if the compiler should emit a warning about this name being redefined.
### Response:
def __should_warn_on_redef(
ctx: GeneratorContext, defsym: sym.Symbol, safe_name: str, def_meta: lmap.Map
) -> bool:
"""Return True if the compil... |
def find_idx_by_threshold(self, threshold):
"""
Retrieve the index in this metric's threshold list at which the given threshold is located.
:param threshold: Find the index of this input threshold.
:returns: the index
:raises ValueError: if no such index can be found.
""... | Retrieve the index in this metric's threshold list at which the given threshold is located.
:param threshold: Find the index of this input threshold.
:returns: the index
:raises ValueError: if no such index can be found. | Below is the the instruction that describes the task:
### Input:
Retrieve the index in this metric's threshold list at which the given threshold is located.
:param threshold: Find the index of this input threshold.
:returns: the index
:raises ValueError: if no such index can be found.
### R... |
def convert_svhn_format_1(directory, output_directory,
output_filename='svhn_format_1.hdf5'):
"""Converts the SVHN dataset (format 1) to HDF5.
This method assumes the existence of the files
`{train,test,extra}.tar.gz`, which are accessible through the
official website [SVHNSIT... | Converts the SVHN dataset (format 1) to HDF5.
This method assumes the existence of the files
`{train,test,extra}.tar.gz`, which are accessible through the
official website [SVHNSITE].
.. [SVHNSITE] http://ufldl.stanford.edu/housenumbers/
Parameters
----------
directory : str
Direc... | Below is the the instruction that describes the task:
### Input:
Converts the SVHN dataset (format 1) to HDF5.
This method assumes the existence of the files
`{train,test,extra}.tar.gz`, which are accessible through the
official website [SVHNSITE].
.. [SVHNSITE] http://ufldl.stanford.edu/housenumb... |
def merge(args):
"""
%prog merge gffiles
Merge several gff files into one. When only one file is given, it is assumed
to be a file with a list of gff files.
"""
p = OptionParser(merge.__doc__)
p.add_option("--seq", default=False, action="store_true",
help="Print FASTA seque... | %prog merge gffiles
Merge several gff files into one. When only one file is given, it is assumed
to be a file with a list of gff files. | Below is the the instruction that describes the task:
### Input:
%prog merge gffiles
Merge several gff files into one. When only one file is given, it is assumed
to be a file with a list of gff files.
### Response:
def merge(args):
"""
%prog merge gffiles
Merge several gff files into one. Whe... |
def rsync_upload():
"""
Uploads the project with rsync excluding some files and folders.
"""
excludes = ["*.pyc", "*.pyo", "*.db", ".DS_Store", ".coverage",
"local_settings.py", "/static", "/.git", "/.hg"]
local_dir = os.getcwd() + os.sep
return rsync_project(remote_dir=env.proj_... | Uploads the project with rsync excluding some files and folders. | Below is the the instruction that describes the task:
### Input:
Uploads the project with rsync excluding some files and folders.
### Response:
def rsync_upload():
"""
Uploads the project with rsync excluding some files and folders.
"""
excludes = ["*.pyc", "*.pyo", "*.db", ".DS_Store", ".coverage"... |
def calculate_dimensions(image, long_side, short_side):
"""Returns the thumbnail dimensions depending on the images format."""
if image.width >= image.height:
return '{0}x{1}'.format(long_side, short_side)
return '{0}x{1}'.format(short_side, long_side) | Returns the thumbnail dimensions depending on the images format. | Below is the the instruction that describes the task:
### Input:
Returns the thumbnail dimensions depending on the images format.
### Response:
def calculate_dimensions(image, long_side, short_side):
"""Returns the thumbnail dimensions depending on the images format."""
if image.width >= image.height:
... |
def is_storage(self):
"""
Return true if the variable is located in storage
See https://solidity.readthedocs.io/en/v0.4.24/types.html?highlight=storage%20location#data-location
Returns:
(bool)
"""
if self.location == 'memory':
return False
... | Return true if the variable is located in storage
See https://solidity.readthedocs.io/en/v0.4.24/types.html?highlight=storage%20location#data-location
Returns:
(bool) | Below is the the instruction that describes the task:
### Input:
Return true if the variable is located in storage
See https://solidity.readthedocs.io/en/v0.4.24/types.html?highlight=storage%20location#data-location
Returns:
(bool)
### Response:
def is_storage(self):
"""
... |
def fpy_interface_sub(fpy, dtype, kind, suffix=None):
"""Generates the interface for reading/writing values for variables of the specified suffix
for dimensions 0 through 7.
:arg fpy: the generating function that accepts the dimension and type information
and returns the (xnames, subtext).
:arg s... | Generates the interface for reading/writing values for variables of the specified suffix
for dimensions 0 through 7.
:arg fpy: the generating function that accepts the dimension and type information
and returns the (xnames, subtext).
:arg suffix: one of [None, "_f", "_p"] corresponding to "allocatabl... | Below is the the instruction that describes the task:
### Input:
Generates the interface for reading/writing values for variables of the specified suffix
for dimensions 0 through 7.
:arg fpy: the generating function that accepts the dimension and type information
and returns the (xnames, subtext).
... |
def _group_unique(self, clusters, adj_list, counts):
''' return groups for unique method'''
if len(clusters) == 1:
groups = [clusters]
else:
groups = [[x] for x in clusters]
return groups | return groups for unique method | Below is the the instruction that describes the task:
### Input:
return groups for unique method
### Response:
def _group_unique(self, clusters, adj_list, counts):
''' return groups for unique method'''
if len(clusters) == 1:
groups = [clusters]
else:
groups = [[x] f... |
def find_bp(self, filename, lineno, frame):
"""Determine which breakpoint for this file:line is to be acted upon.
Called only if we know there is a bpt at this
location. Returns breakpoint that was triggered and a flag
that indicates if it is ok to delete a temporary breakpoint.
... | Determine which breakpoint for this file:line is to be acted upon.
Called only if we know there is a bpt at this
location. Returns breakpoint that was triggered and a flag
that indicates if it is ok to delete a temporary breakpoint. | Below is the the instruction that describes the task:
### Input:
Determine which breakpoint for this file:line is to be acted upon.
Called only if we know there is a bpt at this
location. Returns breakpoint that was triggered and a flag
that indicates if it is ok to delete a temporary brea... |
def element(self, inp=None):
"""Return a complex number from ``inp`` or from scratch."""
if inp is not None:
# Workaround for missing __complex__ of numpy.ndarray
# for Numpy version < 1.12
# TODO: remove when Numpy >= 1.12 is required
if isinstance(inp, n... | Return a complex number from ``inp`` or from scratch. | Below is the the instruction that describes the task:
### Input:
Return a complex number from ``inp`` or from scratch.
### Response:
def element(self, inp=None):
"""Return a complex number from ``inp`` or from scratch."""
if inp is not None:
# Workaround for missing __complex__ of numpy... |
def _set_original_fields(instance):
"""
Save fields value, only for non-m2m fields.
"""
original_fields = {}
def _set_original_field(instance, field):
if instance.pk is None:
original_fields[field] = None
else:
if isinstance(instance._meta.get_field(field), F... | Save fields value, only for non-m2m fields. | Below is the the instruction that describes the task:
### Input:
Save fields value, only for non-m2m fields.
### Response:
def _set_original_fields(instance):
"""
Save fields value, only for non-m2m fields.
"""
original_fields = {}
def _set_original_field(instance, field):
if instance.... |
def add_or_renew_pool(self, host, is_host_addition):
"""
For internal use only.
"""
distance = self._profile_manager.distance(host)
if distance == HostDistance.IGNORED:
return None
def run_add_or_renew_pool():
try:
if self._protoco... | For internal use only. | Below is the the instruction that describes the task:
### Input:
For internal use only.
### Response:
def add_or_renew_pool(self, host, is_host_addition):
"""
For internal use only.
"""
distance = self._profile_manager.distance(host)
if distance == HostDistance.IGNORED:
... |
def get_emb_szs(self, sz_dict=None):
"Return the default embedding sizes suitable for this data or takes the ones in `sz_dict`."
return [def_emb_sz(self.classes, n, sz_dict) for n in self.cat_names] | Return the default embedding sizes suitable for this data or takes the ones in `sz_dict`. | Below is the the instruction that describes the task:
### Input:
Return the default embedding sizes suitable for this data or takes the ones in `sz_dict`.
### Response:
def get_emb_szs(self, sz_dict=None):
"Return the default embedding sizes suitable for this data or takes the ones in `sz_dict`."
r... |
def mode(self):
"""Get alarm mode."""
mode = self.get_value('mode').get(self.device_id, None)
return mode.lower() | Get alarm mode. | Below is the the instruction that describes the task:
### Input:
Get alarm mode.
### Response:
def mode(self):
"""Get alarm mode."""
mode = self.get_value('mode').get(self.device_id, None)
return mode.lower() |
def from_dict(d: Dict[str, Any]) -> 'CoverageInstructions':
"""
Loads a set of coverage instructions from a given dictionary.
Raises:
BadCoverageInstructions: if the given coverage instructions are
illegal.
"""
name_type = d['type']
cls = _NAM... | Loads a set of coverage instructions from a given dictionary.
Raises:
BadCoverageInstructions: if the given coverage instructions are
illegal. | Below is the the instruction that describes the task:
### Input:
Loads a set of coverage instructions from a given dictionary.
Raises:
BadCoverageInstructions: if the given coverage instructions are
illegal.
### Response:
def from_dict(d: Dict[str, Any]) -> 'CoverageInstruction... |
def get_html_color(self):
"""
get a string representing the color, using HTML notation
"""
color = self.color
return ("#%02x%02x%02x" % (
int(color.red), int(color.green), int(color.blue)
)) | get a string representing the color, using HTML notation | Below is the the instruction that describes the task:
### Input:
get a string representing the color, using HTML notation
### Response:
def get_html_color(self):
"""
get a string representing the color, using HTML notation
"""
color = self.color
return ("#%02x%02x%02x" % (
... |
def exists(self, index):
"""Checks whether :index: exists in the Model.
:index: Index to look for.
:returns: True if :index: exists in the Model, False otherwise.
"""
data = self.data
try:
for c in self._split(index):
i = int(c) - 1
... | Checks whether :index: exists in the Model.
:index: Index to look for.
:returns: True if :index: exists in the Model, False otherwise. | Below is the the instruction that describes the task:
### Input:
Checks whether :index: exists in the Model.
:index: Index to look for.
:returns: True if :index: exists in the Model, False otherwise.
### Response:
def exists(self, index):
"""Checks whether :index: exists in the Model.
... |
def get_gpio_mode(self, gpio_id):
"""
Return the gpio mode for gpio :gpio_id:.
@gpio_id Character A or B.
"""
if not self._connected:
return
return self._protocol.status.get("OTGW_GPIO_{}".format(gpio_id)) | Return the gpio mode for gpio :gpio_id:.
@gpio_id Character A or B. | Below is the the instruction that describes the task:
### Input:
Return the gpio mode for gpio :gpio_id:.
@gpio_id Character A or B.
### Response:
def get_gpio_mode(self, gpio_id):
"""
Return the gpio mode for gpio :gpio_id:.
@gpio_id Character A or B.
"""
if not sel... |
def create_resource(self, resource_type=None, uri=None):
'''
Convenience method for creating a new resource
Note: A Resource is instantiated, but is not yet created. Still requires resource.create().
Args:
uri (rdflib.term.URIRef, str): uri of resource to create
resource_type (NonRDFSource (Binary), B... | Convenience method for creating a new resource
Note: A Resource is instantiated, but is not yet created. Still requires resource.create().
Args:
uri (rdflib.term.URIRef, str): uri of resource to create
resource_type (NonRDFSource (Binary), BasicContainer, DirectContainer, IndirectContainer): resource type... | Below is the the instruction that describes the task:
### Input:
Convenience method for creating a new resource
Note: A Resource is instantiated, but is not yet created. Still requires resource.create().
Args:
uri (rdflib.term.URIRef, str): uri of resource to create
resource_type (NonRDFSource (Binary)... |
def raise_stmt__26(self, raise_loc, type_opt):
"""(2.6, 2.7) raise_stmt: 'raise' [test [',' test [',' test]]]"""
type_ = inst = tback = None
loc = raise_loc
if type_opt:
type_, inst_opt = type_opt
loc = loc.join(type_.loc)
if inst_opt:
... | (2.6, 2.7) raise_stmt: 'raise' [test [',' test [',' test]]] | Below is the the instruction that describes the task:
### Input:
(2.6, 2.7) raise_stmt: 'raise' [test [',' test [',' test]]]
### Response:
def raise_stmt__26(self, raise_loc, type_opt):
"""(2.6, 2.7) raise_stmt: 'raise' [test [',' test [',' test]]]"""
type_ = inst = tback = None
loc = raise... |
def shift_peaks(sig, peak_inds, search_radius, peak_up):
"""
Helper function for correct_peaks. Return the shifted peaks to local
maxima or minima within a radius.
peak_up : bool
Whether the expected peak direction is up
"""
sig_len = sig.shape[0]
n_peaks = len(peak_inds)
# The ... | Helper function for correct_peaks. Return the shifted peaks to local
maxima or minima within a radius.
peak_up : bool
Whether the expected peak direction is up | Below is the the instruction that describes the task:
### Input:
Helper function for correct_peaks. Return the shifted peaks to local
maxima or minima within a radius.
peak_up : bool
Whether the expected peak direction is up
### Response:
def shift_peaks(sig, peak_inds, search_radius, peak_up):
... |
def _unique_name(self, basename, ext, existing, force=False):
"""
Find a unique basename for a new file/key where existing is
either a list of (basename, ext) pairs or an absolute path to
a directory.
By default, uniqueness is enforced depending on the state of
the uniqu... | Find a unique basename for a new file/key where existing is
either a list of (basename, ext) pairs or an absolute path to
a directory.
By default, uniqueness is enforced depending on the state of
the unique_name parameter (for export names). If force is
True, this parameter is i... | Below is the the instruction that describes the task:
### Input:
Find a unique basename for a new file/key where existing is
either a list of (basename, ext) pairs or an absolute path to
a directory.
By default, uniqueness is enforced depending on the state of
the unique_name parame... |
def find(command, on):
"""Find the command usage."""
output_lines = parse_man_page(command, on)
click.echo(''.join(output_lines)) | Find the command usage. | Below is the the instruction that describes the task:
### Input:
Find the command usage.
### Response:
def find(command, on):
"""Find the command usage."""
output_lines = parse_man_page(command, on)
click.echo(''.join(output_lines)) |
def obtain_all_devices(my_devices):
"""Dynamically create 'all' group."""
new_devices = {}
for device_name, device_or_group in my_devices.items():
# Skip any groups
if not isinstance(device_or_group, list):
new_devices[device_name] = device_or_group
return new_devices | Dynamically create 'all' group. | Below is the the instruction that describes the task:
### Input:
Dynamically create 'all' group.
### Response:
def obtain_all_devices(my_devices):
"""Dynamically create 'all' group."""
new_devices = {}
for device_name, device_or_group in my_devices.items():
# Skip any groups
if not isin... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.