code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def rollforward(self, dt):
"""
Roll provided date forward to next offset only if not on offset.
"""
if not self.onOffset(dt):
if self.n >= 0:
return self._next_opening_time(dt)
else:
return self._prev_opening_time(dt)
return... | Roll provided date forward to next offset only if not on offset. | Below is the the instruction that describes the task:
### Input:
Roll provided date forward to next offset only if not on offset.
### Response:
def rollforward(self, dt):
"""
Roll provided date forward to next offset only if not on offset.
"""
if not self.onOffset(dt):
i... |
def dump(o, f):
"""Writes out dict as toml to a file
Args:
o: Object to dump into toml
f: File descriptor where the toml should be stored
Returns:
String containing the toml corresponding to dictionary
Raises:
TypeError: When anything other than file descriptor is pass... | Writes out dict as toml to a file
Args:
o: Object to dump into toml
f: File descriptor where the toml should be stored
Returns:
String containing the toml corresponding to dictionary
Raises:
TypeError: When anything other than file descriptor is passed | Below is the the instruction that describes the task:
### Input:
Writes out dict as toml to a file
Args:
o: Object to dump into toml
f: File descriptor where the toml should be stored
Returns:
String containing the toml corresponding to dictionary
Raises:
TypeError: Wh... |
def check_file(
state,
fname,
missing_msg="Did you create a file named `{}`?",
is_dir_msg="Want to check a file named `{}`, but found a directory.",
parse=True,
use_fs=True,
use_solution=False,
):
"""Test whether file exists, and make its contents the student code.
Note: this SCT fa... | Test whether file exists, and make its contents the student code.
Note: this SCT fails if the file is a directory. | Below is the the instruction that describes the task:
### Input:
Test whether file exists, and make its contents the student code.
Note: this SCT fails if the file is a directory.
### Response:
def check_file(
state,
fname,
missing_msg="Did you create a file named `{}`?",
is_dir_msg="Want to c... |
def _set_sport(self, v, load=False):
"""
Setter method for sport, mapped from YANG variable /ipv6_acl/ipv6/access_list/extended/seq/sport (enumeration)
If this variable is read-only (config: false) in the
source YANG file, then _set_sport is considered as a private
method. Backends looking to popula... | Setter method for sport, mapped from YANG variable /ipv6_acl/ipv6/access_list/extended/seq/sport (enumeration)
If this variable is read-only (config: false) in the
source YANG file, then _set_sport is considered as a private
method. Backends looking to populate this variable should
do so via calling thi... | Below is the the instruction that describes the task:
### Input:
Setter method for sport, mapped from YANG variable /ipv6_acl/ipv6/access_list/extended/seq/sport (enumeration)
If this variable is read-only (config: false) in the
source YANG file, then _set_sport is considered as a private
method. Backen... |
def get_obsmeta(self, lcid):
"""Get the observation metadata for the given id.
This is table 3 of Sesar 2010
"""
if self._obsdata is None:
self._obsdata = fetch_rrlyrae_fitdata()
i = np.where(self._obsdata['id'] == lcid)[0]
if len(i) == 0:
raise Va... | Get the observation metadata for the given id.
This is table 3 of Sesar 2010 | Below is the the instruction that describes the task:
### Input:
Get the observation metadata for the given id.
This is table 3 of Sesar 2010
### Response:
def get_obsmeta(self, lcid):
"""Get the observation metadata for the given id.
This is table 3 of Sesar 2010
"""
if sel... |
def _growing_step_sequence(interval_growth, max_interval, init_interval, start_level=None):
"""
Returns an iterator that constructs a sequence of trigger levels with growing intervals.
The interval is growing exponentially until it reaches the maximum value. Then the interval
stays the s... | Returns an iterator that constructs a sequence of trigger levels with growing intervals.
The interval is growing exponentially until it reaches the maximum value. Then the interval
stays the same and the sequence becomes linear.
An optional starting level `start_level` defaults to the initial i... | Below is the the instruction that describes the task:
### Input:
Returns an iterator that constructs a sequence of trigger levels with growing intervals.
The interval is growing exponentially until it reaches the maximum value. Then the interval
stays the same and the sequence becomes linear.
... |
def convert(model, input_shape, class_labels=None, mode=None,
preprocessor_args=None, builder=None, verbose=True):
"""Convert an MXNet model to the protobuf spec.
Parameters
----------
model: MXNet model
A trained MXNet neural network model.
input_shape: list of tuples
... | Convert an MXNet model to the protobuf spec.
Parameters
----------
model: MXNet model
A trained MXNet neural network model.
input_shape: list of tuples
A list of (name, shape) tuples, defining the input names and their
shapes. The list also serves to define the desired order of... | Below is the the instruction that describes the task:
### Input:
Convert an MXNet model to the protobuf spec.
Parameters
----------
model: MXNet model
A trained MXNet neural network model.
input_shape: list of tuples
A list of (name, shape) tuples, defining the input names and thei... |
def convert_models_for_lang(language):
"""Convert old SingleByteCharSetModels for the given language"""
# Validate language
language = language.title()
lang_metadata = LANGUAGES.get(language)
if not lang_metadata:
raise ValueError('Unknown language: {}. If you are adding a model for a'
... | Convert old SingleByteCharSetModels for the given language | Below is the the instruction that describes the task:
### Input:
Convert old SingleByteCharSetModels for the given language
### Response:
def convert_models_for_lang(language):
"""Convert old SingleByteCharSetModels for the given language"""
# Validate language
language = language.title()
lang_meta... |
def updateBar(self, bar):
"""更新K线"""
self.count += 1
if not self.inited and self.count >= self.size:
self.inited = True
self.openArray[0:self.size - 1] = self.openArray[1:self.size]
self.highArray[0:self.size - 1] = self.highArray[1:self.size]
self.lowArray[0... | 更新K线 | Below is the the instruction that describes the task:
### Input:
更新K线
### Response:
def updateBar(self, bar):
"""更新K线"""
self.count += 1
if not self.inited and self.count >= self.size:
self.inited = True
self.openArray[0:self.size - 1] = self.openArray[1:self.size]
... |
def update_flowspec_global_table(self, flowspec_family, rules,
actions=None, is_withdraw=False):
"""Update a BGP route in the Global table for Flow Specification.
``flowspec_family`` specifies one of the Flow Specification
family name.
``rules`` sp... | Update a BGP route in the Global table for Flow Specification.
``flowspec_family`` specifies one of the Flow Specification
family name.
``rules`` specifies NLRIs of Flow Specification as
a dictionary type value.
`` actions`` specifies Traffic Filtering Actions of
Flow... | Below is the the instruction that describes the task:
### Input:
Update a BGP route in the Global table for Flow Specification.
``flowspec_family`` specifies one of the Flow Specification
family name.
``rules`` specifies NLRIs of Flow Specification as
a dictionary type value.
... |
def save_metadata(self, data_dir, feature_name=None):
"""See base class for details."""
# Recursively save all child features
for feature_key, feature in six.iteritems(self._feature_dict):
if feature_name:
feature_key = '-'.join((feature_name, feature_key))
feature.save_metadata(data_dir... | See base class for details. | Below is the the instruction that describes the task:
### Input:
See base class for details.
### Response:
def save_metadata(self, data_dir, feature_name=None):
"""See base class for details."""
# Recursively save all child features
for feature_key, feature in six.iteritems(self._feature_dict):
i... |
def rex_assert(self, rex, byte=False):
"""
If `rex` expression is not found then raise `DataNotFound` exception.
"""
self.rex_search(rex, byte=byte) | If `rex` expression is not found then raise `DataNotFound` exception. | Below is the the instruction that describes the task:
### Input:
If `rex` expression is not found then raise `DataNotFound` exception.
### Response:
def rex_assert(self, rex, byte=False):
"""
If `rex` expression is not found then raise `DataNotFound` exception.
"""
self.rex_search(... |
def audits(self, ticket=None, include=None, **kwargs):
"""
Retrieve TicketAudits. If ticket is passed, return the tickets for a specific audit.
If ticket_id is None, a TicketAuditGenerator is returned to handle pagination. The way this generator
works is a different to the other Zenpy g... | Retrieve TicketAudits. If ticket is passed, return the tickets for a specific audit.
If ticket_id is None, a TicketAuditGenerator is returned to handle pagination. The way this generator
works is a different to the other Zenpy generators as it is cursor based, allowing you to change the
directi... | Below is the the instruction that describes the task:
### Input:
Retrieve TicketAudits. If ticket is passed, return the tickets for a specific audit.
If ticket_id is None, a TicketAuditGenerator is returned to handle pagination. The way this generator
works is a different to the other Zenpy generat... |
def whereis(self, channel):
""" get ocurrences of channel name in the file
Parameters
----------
channel : str
channel name string
Returns
-------
ocurrences : tuple
Examples
--------
>>> mdf = MDF(file_name)
>>> mdf... | get ocurrences of channel name in the file
Parameters
----------
channel : str
channel name string
Returns
-------
ocurrences : tuple
Examples
--------
>>> mdf = MDF(file_name)
>>> mdf.whereis('VehicleSpeed') # "VehicleSpeed... | Below is the the instruction that describes the task:
### Input:
get ocurrences of channel name in the file
Parameters
----------
channel : str
channel name string
Returns
-------
ocurrences : tuple
Examples
--------
>>> mdf = M... |
def configure_logging(level):
"""
Configure global log level to given one
:param level: Level (INFO | DEBUG | WARN | ERROR)
:return:
"""
global logging_level
logging_level = logging.ERROR
if "info" == level.lower():
logging_level = logging.INFO
elif "warn" == level.lower():
... | Configure global log level to given one
:param level: Level (INFO | DEBUG | WARN | ERROR)
:return: | Below is the the instruction that describes the task:
### Input:
Configure global log level to given one
:param level: Level (INFO | DEBUG | WARN | ERROR)
:return:
### Response:
def configure_logging(level):
"""
Configure global log level to given one
:param level: Level (INFO | DEBUG | WARN | ... |
def in_memory(self, op_in_mem):
r"""
If set to True, the output will be stored in memory.
"""
old_state = self.in_memory
if not old_state and op_in_mem:
self._map_to_memory()
elif not op_in_mem and old_state:
self._clear_in_memory() | r"""
If set to True, the output will be stored in memory. | Below is the the instruction that describes the task:
### Input:
r"""
If set to True, the output will be stored in memory.
### Response:
def in_memory(self, op_in_mem):
r"""
If set to True, the output will be stored in memory.
"""
old_state = self.in_memory
if not ol... |
def all_subclasses(cls):
"""Recursively returns all the subclasses of the provided class.
"""
subclasses = cls.__subclasses__()
descendants = (descendant for subclass in subclasses
for descendant in all_subclasses(subclass))
return set(subclasses) | set(descendants) | Recursively returns all the subclasses of the provided class. | Below is the the instruction that describes the task:
### Input:
Recursively returns all the subclasses of the provided class.
### Response:
def all_subclasses(cls):
"""Recursively returns all the subclasses of the provided class.
"""
subclasses = cls.__subclasses__()
descendants = (descendant for... |
def connect(url, username, password):
"""
Return a connected Bitbucket session
"""
bb_session = stashy.connect(url, username, password)
logger.info('Connected to: %s as %s', url, username)
return bb_session | Return a connected Bitbucket session | Below is the the instruction that describes the task:
### Input:
Return a connected Bitbucket session
### Response:
def connect(url, username, password):
"""
Return a connected Bitbucket session
"""
bb_session = stashy.connect(url, username, password)
logger.info('Connected to: %s as %s', url... |
def project_with_metadata(self, term_doc_mat, x_dim=0, y_dim=1):
'''
Returns a projection of the
:param term_doc_mat: a TermDocMatrix
:return: CategoryProjection
'''
return self._project_category_corpus(self._get_category_metadata_corpus_and_replace_terms(term_doc_mat),
... | Returns a projection of the
:param term_doc_mat: a TermDocMatrix
:return: CategoryProjection | Below is the the instruction that describes the task:
### Input:
Returns a projection of the
:param term_doc_mat: a TermDocMatrix
:return: CategoryProjection
### Response:
def project_with_metadata(self, term_doc_mat, x_dim=0, y_dim=1):
'''
Returns a projection of the
:par... |
def send_request_email(
authorised_text, authorised_role, authorised_persons, application,
link, is_secret):
"""Sends an email to admin asking to approve user application"""
context = CONTEXT.copy()
context['requester'] = application.applicant
context['link'] = link
context['is_secre... | Sends an email to admin asking to approve user application | Below is the the instruction that describes the task:
### Input:
Sends an email to admin asking to approve user application
### Response:
def send_request_email(
authorised_text, authorised_role, authorised_persons, application,
link, is_secret):
"""Sends an email to admin asking to approve use... |
def gelman_rubin(self, chain=None, threshold=0.05):
r""" Runs the Gelman Rubin diagnostic on the supplied chains.
Parameters
----------
chain : int|str, optional
Which chain to run the diagnostic on. By default, this is `None`,
which will run the diagnostic on al... | r""" Runs the Gelman Rubin diagnostic on the supplied chains.
Parameters
----------
chain : int|str, optional
Which chain to run the diagnostic on. By default, this is `None`,
which will run the diagnostic on all chains. You can also
supply and integer (the c... | Below is the the instruction that describes the task:
### Input:
r""" Runs the Gelman Rubin diagnostic on the supplied chains.
Parameters
----------
chain : int|str, optional
Which chain to run the diagnostic on. By default, this is `None`,
which will run the diagnos... |
def relative_root_dir(self):
"""Build the relative root dir path for the bundle version."""
return Path(self.bundle.name) / str(self.created_at.date()) | Build the relative root dir path for the bundle version. | Below is the the instruction that describes the task:
### Input:
Build the relative root dir path for the bundle version.
### Response:
def relative_root_dir(self):
"""Build the relative root dir path for the bundle version."""
return Path(self.bundle.name) / str(self.created_at.date()) |
def solve_apply(expr, vars):
"""Returns the result of applying function (lhs) to its arguments (rest).
We use IApplicative to apply the function, because that gives the host
application an opportunity to compare the function being called against
a whitelist. EFILTER will never directly call a function ... | Returns the result of applying function (lhs) to its arguments (rest).
We use IApplicative to apply the function, because that gives the host
application an opportunity to compare the function being called against
a whitelist. EFILTER will never directly call a function that wasn't
provided through a p... | Below is the the instruction that describes the task:
### Input:
Returns the result of applying function (lhs) to its arguments (rest).
We use IApplicative to apply the function, because that gives the host
application an opportunity to compare the function being called against
a whitelist. EFILTER wil... |
def __expire_files(self):
"""Because files are always unclean"""
self.__files = OrderedDict(
item for item in self.__files.items() if not item[1].expired
) | Because files are always unclean | Below is the the instruction that describes the task:
### Input:
Because files are always unclean
### Response:
def __expire_files(self):
"""Because files are always unclean"""
self.__files = OrderedDict(
item for item in self.__files.items() if not item[1].expired
) |
def _next_offset(self):
"""Return the offset of the next line to read."""
if self._filestream:
offset = self._filestream.tell()
if offset:
offset -= 1
else:
offset = self._initial_offset
return offset | Return the offset of the next line to read. | Below is the the instruction that describes the task:
### Input:
Return the offset of the next line to read.
### Response:
def _next_offset(self):
"""Return the offset of the next line to read."""
if self._filestream:
offset = self._filestream.tell()
if offset:
offset -= 1
else:
... |
def mem_size(self):
'''used when allocating memory ingame'''
data_len = self._data_mem_size
node_count = len(list(self.xml_doc.iter(tag=etree.Element)))
if self.compressed:
size = 52 * node_count + data_len + 630
else:
tags_len = 0
for e in s... | used when allocating memory ingame | Below is the the instruction that describes the task:
### Input:
used when allocating memory ingame
### Response:
def mem_size(self):
'''used when allocating memory ingame'''
data_len = self._data_mem_size
node_count = len(list(self.xml_doc.iter(tag=etree.Element)))
if self.compre... |
def _history_locked(self):
""" Returns whether history movement is locked.
"""
return (self.history_lock and
(self._get_edited_history(self._history_index) !=
self.input_buffer) and
(self._get_prompt_cursor().blockNumber() !=
self... | Returns whether history movement is locked. | Below is the the instruction that describes the task:
### Input:
Returns whether history movement is locked.
### Response:
def _history_locked(self):
""" Returns whether history movement is locked.
"""
return (self.history_lock and
(self._get_edited_history(self._history_ind... |
def create_volume(kwargs=None, call=None, wait_to_finish=False):
'''
Create a volume.
zone
The availability zone used to create the volume. Required. String.
size
The size of the volume, in GiBs. Defaults to ``10``. Integer.
snapshot
The snapshot-id from which to create th... | Create a volume.
zone
The availability zone used to create the volume. Required. String.
size
The size of the volume, in GiBs. Defaults to ``10``. Integer.
snapshot
The snapshot-id from which to create the volume. Integer.
type
The volume type. This can be gp2 for Gen... | Below is the the instruction that describes the task:
### Input:
Create a volume.
zone
The availability zone used to create the volume. Required. String.
size
The size of the volume, in GiBs. Defaults to ``10``. Integer.
snapshot
The snapshot-id from which to create the volume... |
def _mask_cov_func(self, *args):
"""Masks the covariance function into a form usable by :py:func:`mpmath.diff`.
Parameters
----------
*args : `num_dim` * 2 floats
The individual elements of Xi and Xj to be passed to :py:attr:`cov_func`.
"""
# Have to ... | Masks the covariance function into a form usable by :py:func:`mpmath.diff`.
Parameters
----------
*args : `num_dim` * 2 floats
The individual elements of Xi and Xj to be passed to :py:attr:`cov_func`. | Below is the the instruction that describes the task:
### Input:
Masks the covariance function into a form usable by :py:func:`mpmath.diff`.
Parameters
----------
*args : `num_dim` * 2 floats
The individual elements of Xi and Xj to be passed to :py:attr:`cov_func`.
### R... |
def reserveIdentifierResponse(self, pid, vendorSpecific=None):
"""CNCore.getLogRecords(session[, fromDate][, toDate][, event][, start][,
count]) → Log https://releases.dataone.org/online/api-
documentation-v2.0.1/apis/CN_APIs.html#CNCore.getLogRecords Implemented in
d1_client.baseclient.... | CNCore.getLogRecords(session[, fromDate][, toDate][, event][, start][,
count]) → Log https://releases.dataone.org/online/api-
documentation-v2.0.1/apis/CN_APIs.html#CNCore.getLogRecords Implemented in
d1_client.baseclient.py.
CNCore.reserveIdentifier(session, pid) → Identifier
h... | Below is the the instruction that describes the task:
### Input:
CNCore.getLogRecords(session[, fromDate][, toDate][, event][, start][,
count]) → Log https://releases.dataone.org/online/api-
documentation-v2.0.1/apis/CN_APIs.html#CNCore.getLogRecords Implemented in
d1_client.baseclient.py.
... |
def time(self):
"Return the time part, with tzinfo None."
return time(self.hour, self.minute, self.second, self.microsecond) | Return the time part, with tzinfo None. | Below is the the instruction that describes the task:
### Input:
Return the time part, with tzinfo None.
### Response:
def time(self):
"Return the time part, with tzinfo None."
return time(self.hour, self.minute, self.second, self.microsecond) |
def get_next_instance(self, obj):
"""
Return the next plugin instance for the given object.
This differs from `obj.get_next_sibling()` which returns an unsorted sibling.
"""
ordered_siblings = obj.get_siblings().filter(placeholder=obj.placeholder).order_by('position')
pos... | Return the next plugin instance for the given object.
This differs from `obj.get_next_sibling()` which returns an unsorted sibling. | Below is the the instruction that describes the task:
### Input:
Return the next plugin instance for the given object.
This differs from `obj.get_next_sibling()` which returns an unsorted sibling.
### Response:
def get_next_instance(self, obj):
"""
Return the next plugin instance for the gi... |
def find( cls, name ):
"""
Finds a particular wizard plugin based on its name.
:param name | <str> || None
"""
if ( cls._plugins is None ):
cls._plugins = {}
return cls._plugins.get(nativestring(name)) | Finds a particular wizard plugin based on its name.
:param name | <str> || None | Below is the the instruction that describes the task:
### Input:
Finds a particular wizard plugin based on its name.
:param name | <str> || None
### Response:
def find( cls, name ):
"""
Finds a particular wizard plugin based on its name.
:param name | <st... |
def get_dict_repr(self):
"""
Return a dictionary representation of this phase.
This will be used for checksumming, in order to uniquely compare
instance images against their requirements
"""
return dict(
phase_name = self.phase_name,
phase_type = s... | Return a dictionary representation of this phase.
This will be used for checksumming, in order to uniquely compare
instance images against their requirements | Below is the the instruction that describes the task:
### Input:
Return a dictionary representation of this phase.
This will be used for checksumming, in order to uniquely compare
instance images against their requirements
### Response:
def get_dict_repr(self):
"""
Return a dictiona... |
def from_dict(d):
"""
Re-create the Specs from a dictionary representation.
:param Dict[str, Any] d: The dictionary representation.
:return: The restored Specs.
:rtype: Specs
"""
return Specs(
qubits_specs=sorted([QubitSpecs(id=int(q),
... | Re-create the Specs from a dictionary representation.
:param Dict[str, Any] d: The dictionary representation.
:return: The restored Specs.
:rtype: Specs | Below is the the instruction that describes the task:
### Input:
Re-create the Specs from a dictionary representation.
:param Dict[str, Any] d: The dictionary representation.
:return: The restored Specs.
:rtype: Specs
### Response:
def from_dict(d):
"""
Re-create the Specs ... |
def get_large_image(self, page=1):
"""
Downloads and returns the large sized image of a single page.
The page kwarg specifies which page to return. One is the default.
"""
url = self.get_large_image_url(page=page)
return self._get_url(url) | Downloads and returns the large sized image of a single page.
The page kwarg specifies which page to return. One is the default. | Below is the the instruction that describes the task:
### Input:
Downloads and returns the large sized image of a single page.
The page kwarg specifies which page to return. One is the default.
### Response:
def get_large_image(self, page=1):
"""
Downloads and returns the large sized image... |
def _null_ac_sia(transition, direction, alpha=0.0):
"""Return an |AcSystemIrreducibilityAnalysis| with zero |big_alpha| and
empty accounts.
"""
return AcSystemIrreducibilityAnalysis(
transition=transition,
direction=direction,
alpha=alpha,
account=(),
partitioned_... | Return an |AcSystemIrreducibilityAnalysis| with zero |big_alpha| and
empty accounts. | Below is the the instruction that describes the task:
### Input:
Return an |AcSystemIrreducibilityAnalysis| with zero |big_alpha| and
empty accounts.
### Response:
def _null_ac_sia(transition, direction, alpha=0.0):
"""Return an |AcSystemIrreducibilityAnalysis| with zero |big_alpha| and
empty accounts.... |
def setcontents(source, identifier, pointer):
"""Patch existing bibliographic record."""
record = Record.get_record(identifier)
Document(record, pointer).setcontents(source) | Patch existing bibliographic record. | Below is the the instruction that describes the task:
### Input:
Patch existing bibliographic record.
### Response:
def setcontents(source, identifier, pointer):
"""Patch existing bibliographic record."""
record = Record.get_record(identifier)
Document(record, pointer).setcontents(source) |
def _create_memory_database_interface(self) -> GraphDatabaseInterface:
"""
Creates and returns the in-memory database interface the graph will use.
"""
Base = declarative_base()
engine = sqlalchemy.create_engine("sqlite://", poolclass=StaticPool)
Session = sessionmaker(bi... | Creates and returns the in-memory database interface the graph will use. | Below is the the instruction that describes the task:
### Input:
Creates and returns the in-memory database interface the graph will use.
### Response:
def _create_memory_database_interface(self) -> GraphDatabaseInterface:
"""
Creates and returns the in-memory database interface the graph will use.... |
def createEditor( self, parent, option, index ):
"""
Creates a new editor for the given index parented to the inputed widget.
:param parent | <QWidget>
option | <QStyleOption>
index | <QModelIndex>
:return <QWidg... | Creates a new editor for the given index parented to the inputed widget.
:param parent | <QWidget>
option | <QStyleOption>
index | <QModelIndex>
:return <QWidget> || None | Below is the the instruction that describes the task:
### Input:
Creates a new editor for the given index parented to the inputed widget.
:param parent | <QWidget>
option | <QStyleOption>
index | <QModelIndex>
:return <QWidget... |
def Bernoulli(prob_true: vertex_constructor_param_types, label: Optional[str]=None) -> Vertex:
"""
One to one constructor for mapping some shape of probTrue to
a matching shaped Bernoulli.
:param prob_true: probTrue with same shape as desired Bernoulli tensor or scalar
"""
return Boolean(co... | One to one constructor for mapping some shape of probTrue to
a matching shaped Bernoulli.
:param prob_true: probTrue with same shape as desired Bernoulli tensor or scalar | Below is the the instruction that describes the task:
### Input:
One to one constructor for mapping some shape of probTrue to
a matching shaped Bernoulli.
:param prob_true: probTrue with same shape as desired Bernoulli tensor or scalar
### Response:
def Bernoulli(prob_true: vertex_constructor_param_ty... |
def onPollCreated(
self,
mid=None,
poll=None,
author_id=None,
thread_id=None,
thread_type=None,
ts=None,
metadata=None,
msg=None,
):
"""
Called when the client is listening, and somebody creates a group poll
:param mid:... | Called when the client is listening, and somebody creates a group poll
:param mid: The action ID
:param poll: Created poll
:param author_id: The ID of the person who created the poll
:param thread_id: Thread ID that the action was sent to. See :ref:`intro_threads`
:param thread_... | Below is the the instruction that describes the task:
### Input:
Called when the client is listening, and somebody creates a group poll
:param mid: The action ID
:param poll: Created poll
:param author_id: The ID of the person who created the poll
:param thread_id: Thread ID that th... |
def discover(self, details = False):
'Discover API definitions. Set details=true to show details'
if details and not (isinstance(details, str) and details.lower() == 'false'):
return copy.deepcopy(self.discoverinfo)
else:
return dict((k,v.get('description', '')) for k,v i... | Discover API definitions. Set details=true to show details | Below is the the instruction that describes the task:
### Input:
Discover API definitions. Set details=true to show details
### Response:
def discover(self, details = False):
'Discover API definitions. Set details=true to show details'
if details and not (isinstance(details, str) and details.lower(... |
def getfile(self):
"""Gets the full file path of the entered/selected file
:returns: str -- the name of the data file to open/create
"""
current_file = str(self.selectedFiles()[0])
if os.path.isfile(current_file):
print 'current_file', current_file
if cur... | Gets the full file path of the entered/selected file
:returns: str -- the name of the data file to open/create | Below is the the instruction that describes the task:
### Input:
Gets the full file path of the entered/selected file
:returns: str -- the name of the data file to open/create
### Response:
def getfile(self):
"""Gets the full file path of the entered/selected file
:returns: str -- the nam... |
def _copy(self, axis=True, attr=True, data=False):
"""Create a new instance of Data, but does not copy the data
necessarily.
Parameters
----------
axis : bool, optional
deep copy the axes (default: True)
attr : bool, optional
deep copy the attribu... | Create a new instance of Data, but does not copy the data
necessarily.
Parameters
----------
axis : bool, optional
deep copy the axes (default: True)
attr : bool, optional
deep copy the attributes (default: True)
data : bool, optional
... | Below is the the instruction that describes the task:
### Input:
Create a new instance of Data, but does not copy the data
necessarily.
Parameters
----------
axis : bool, optional
deep copy the axes (default: True)
attr : bool, optional
deep copy the ... |
def factor_mark(field_name, markers, factors, start=0, end=None):
''' Create a ``DataSpec`` dict that applies a client-side
``CategoricalMarkerMapper`` transformation to a ``ColumnDataSource``
column.
.. note::
This transform is primarily only useful with ``scatter``, which
can be param... | Create a ``DataSpec`` dict that applies a client-side
``CategoricalMarkerMapper`` transformation to a ``ColumnDataSource``
column.
.. note::
This transform is primarily only useful with ``scatter``, which
can be parameterized by glyph type.
Args:
field_name (str) : a field name... | Below is the the instruction that describes the task:
### Input:
Create a ``DataSpec`` dict that applies a client-side
``CategoricalMarkerMapper`` transformation to a ``ColumnDataSource``
column.
.. note::
This transform is primarily only useful with ``scatter``, which
can be parameteri... |
def shutdown(self, force=False):
"""
Stop executing any further jobs. If the force argument is True,
the function does not wait until any queued jobs are completed but
stops immediately.
After emptying the queue it is restarted, so you may still call run()
after using th... | Stop executing any further jobs. If the force argument is True,
the function does not wait until any queued jobs are completed but
stops immediately.
After emptying the queue it is restarted, so you may still call run()
after using this method.
:type force: bool
:param... | Below is the the instruction that describes the task:
### Input:
Stop executing any further jobs. If the force argument is True,
the function does not wait until any queued jobs are completed but
stops immediately.
After emptying the queue it is restarted, so you may still call run()
... |
def find_version_by_string_lib(line): # type: (str)->Optional[str]
"""
No regex parsing. Or at least, mostly, not regex.
"""
if not line:
return None
simplified_line = simplify_line(line)
version = None
if simplified_line.startswith("version="):
if '"' not in simplified_line... | No regex parsing. Or at least, mostly, not regex. | Below is the the instruction that describes the task:
### Input:
No regex parsing. Or at least, mostly, not regex.
### Response:
def find_version_by_string_lib(line): # type: (str)->Optional[str]
"""
No regex parsing. Or at least, mostly, not regex.
"""
if not line:
return None
simplif... |
def generateLowerBoundList(confidence, numUniqueFeatures, numLocationsPerObject,
maxNumObjects):
"""
Metric: How unique is each object's most unique feature? Calculate the
probabilistic lower bound for the number of occurrences of an object's most
unique feature. For example, if confi... | Metric: How unique is each object's most unique feature? Calculate the
probabilistic lower bound for the number of occurrences of an object's most
unique feature. For example, if confidence is 0.8, the tick "3" will be placed
at the point where 80% of objects are completely composed of features with 3
or more t... | Below is the the instruction that describes the task:
### Input:
Metric: How unique is each object's most unique feature? Calculate the
probabilistic lower bound for the number of occurrences of an object's most
unique feature. For example, if confidence is 0.8, the tick "3" will be placed
at the point where ... |
def ext_pillar(minion_id, # pylint: disable=W0613
pillar, # pylint: disable=W0613
config_file):
'''
Execute LDAP searches and return the aggregated data
'''
config_template = None
try:
config_template = _render_template(config_file)
except jinja2.exception... | Execute LDAP searches and return the aggregated data | Below is the the instruction that describes the task:
### Input:
Execute LDAP searches and return the aggregated data
### Response:
def ext_pillar(minion_id, # pylint: disable=W0613
pillar, # pylint: disable=W0613
config_file):
'''
Execute LDAP searches and return the aggreg... |
def get_system_uptime_output_show_system_uptime_rbridge_id(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_system_uptime = ET.Element("get_system_uptime")
config = get_system_uptime
output = ET.SubElement(get_system_uptime, "output")
... | Auto Generated Code | Below is the the instruction that describes the task:
### Input:
Auto Generated Code
### Response:
def get_system_uptime_output_show_system_uptime_rbridge_id(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_system_uptime = ET.Element("get_system_uptime")... |
def export_module_spec_with_checkpoint(module_spec,
checkpoint_path,
export_path,
scope_prefix=""):
"""Exports given checkpoint as tfhub module with given spec."""
# The main requirement is that it ... | Exports given checkpoint as tfhub module with given spec. | Below is the the instruction that describes the task:
### Input:
Exports given checkpoint as tfhub module with given spec.
### Response:
def export_module_spec_with_checkpoint(module_spec,
checkpoint_path,
export_path,
... |
def gen_smul(src1, src2, dst):
"""Return a SMUL instruction.
"""
assert src1.size == src2.size
return ReilBuilder.build(ReilMnemonic.SMUL, src1, src2, dst) | Return a SMUL instruction. | Below is the the instruction that describes the task:
### Input:
Return a SMUL instruction.
### Response:
def gen_smul(src1, src2, dst):
"""Return a SMUL instruction.
"""
assert src1.size == src2.size
return ReilBuilder.build(ReilMnemonic.SMUL, src1, src2, dst) |
def update(self, path):
"""
Update the attributes of this CartItem.
"""
self._reset()
self.path = path
self._refresh_synced()
if self.is_synced:
self._refresh_path()
self._refresh_signed()
self._refresh_nvr() | Update the attributes of this CartItem. | Below is the the instruction that describes the task:
### Input:
Update the attributes of this CartItem.
### Response:
def update(self, path):
"""
Update the attributes of this CartItem.
"""
self._reset()
self.path = path
self._refresh_synced()
if self.is_syn... |
def urlencode(txt):
"""Url encode a path."""
if isinstance(txt, unicode):
txt = txt.encode('utf-8')
return urllib.quote_plus(txt) | Url encode a path. | Below is the the instruction that describes the task:
### Input:
Url encode a path.
### Response:
def urlencode(txt):
"""Url encode a path."""
if isinstance(txt, unicode):
txt = txt.encode('utf-8')
return urllib.quote_plus(txt) |
def bulk_insert(self, rows, return_model=False):
"""Creates multiple new records in the database.
This allows specifying custom conflict behavior using .on_conflict().
If no special behavior was specified, this uses the normal Django create(..)
Arguments:
rows:
... | Creates multiple new records in the database.
This allows specifying custom conflict behavior using .on_conflict().
If no special behavior was specified, this uses the normal Django create(..)
Arguments:
rows:
An array of dictionaries, where each dictionary
... | Below is the the instruction that describes the task:
### Input:
Creates multiple new records in the database.
This allows specifying custom conflict behavior using .on_conflict().
If no special behavior was specified, this uses the normal Django create(..)
Arguments:
rows:
... |
def get_all_user(self, **kwargs): # noqa: E501
"""Get all users # noqa: E501
Returns all users # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_all_user(async_req=True)
... | Get all users # noqa: E501
Returns all users # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_all_user(async_req=True)
>>> result = thread.get()
:param async_req... | Below is the the instruction that describes the task:
### Input:
Get all users # noqa: E501
Returns all users # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_all_user(async_... |
def _get_keycachelike(self, keycache, keys, get_adds_dels, parentity, branch, turn, tick, *, forward):
"""Try to retrieve a frozenset representing extant keys.
If I can't, generate one, store it, and return it.
"""
keycache_key = parentity + (branch,)
keycache2 = keycache3 = No... | Try to retrieve a frozenset representing extant keys.
If I can't, generate one, store it, and return it. | Below is the the instruction that describes the task:
### Input:
Try to retrieve a frozenset representing extant keys.
If I can't, generate one, store it, and return it.
### Response:
def _get_keycachelike(self, keycache, keys, get_adds_dels, parentity, branch, turn, tick, *, forward):
"""Try to r... |
def _file_not_empty(tmpfile):
"""
Returns True if file exists and it is not empty
to check if it is time to read container ID from cidfile
:param tmpfile: str, path to file
:return: bool, True if container id is written to the file
"""
if os.path.exists(tmpfile):
... | Returns True if file exists and it is not empty
to check if it is time to read container ID from cidfile
:param tmpfile: str, path to file
:return: bool, True if container id is written to the file | Below is the the instruction that describes the task:
### Input:
Returns True if file exists and it is not empty
to check if it is time to read container ID from cidfile
:param tmpfile: str, path to file
:return: bool, True if container id is written to the file
### Response:
def _file_not_... |
def is_kanji(data):
"""\
Returns if the `data` can be encoded in "kanji" mode.
:param bytes data: The data to check.
:rtype: bool
"""
data_len = len(data)
if not data_len or data_len % 2:
return False
if _PY2:
data = (ord(c) for c in data)
data_iter = iter(data)
... | \
Returns if the `data` can be encoded in "kanji" mode.
:param bytes data: The data to check.
:rtype: bool | Below is the the instruction that describes the task:
### Input:
\
Returns if the `data` can be encoded in "kanji" mode.
:param bytes data: The data to check.
:rtype: bool
### Response:
def is_kanji(data):
"""\
Returns if the `data` can be encoded in "kanji" mode.
:param bytes data: The d... |
def __build_level(self, previous_level_blocks, level):
"""!
@brief Build new level of directory.
@param[in] previous_level_blocks (list): BANG-blocks on the previous level.
@param[in] level (uint): Level number that should be built.
@return (list) New block on the specif... | !
@brief Build new level of directory.
@param[in] previous_level_blocks (list): BANG-blocks on the previous level.
@param[in] level (uint): Level number that should be built.
@return (list) New block on the specified level. | Below is the the instruction that describes the task:
### Input:
!
@brief Build new level of directory.
@param[in] previous_level_blocks (list): BANG-blocks on the previous level.
@param[in] level (uint): Level number that should be built.
@return (list) New block on the spec... |
def quaternion_inverse(quaternion):
"""Return inverse of quaternion.
>>> q0 = random_quaternion()
>>> q1 = quaternion_inverse(q0)
>>> numpy.allclose(quaternion_multiply(q0, q1), [1, 0, 0, 0])
True
"""
q = numpy.array(quaternion, dtype=numpy.float64, copy=True)
numpy.negative(q[1:], q[1... | Return inverse of quaternion.
>>> q0 = random_quaternion()
>>> q1 = quaternion_inverse(q0)
>>> numpy.allclose(quaternion_multiply(q0, q1), [1, 0, 0, 0])
True | Below is the the instruction that describes the task:
### Input:
Return inverse of quaternion.
>>> q0 = random_quaternion()
>>> q1 = quaternion_inverse(q0)
>>> numpy.allclose(quaternion_multiply(q0, q1), [1, 0, 0, 0])
True
### Response:
def quaternion_inverse(quaternion):
"""Return inverse of ... |
def decode(self, longval, nbits):
"""Decode the number to a string using the given statistics.
Parameters
----------
longval : int
The first part of an encoded tuple from encode
nbits : int
The second part of an encoded tuple from encode
Returns
... | Decode the number to a string using the given statistics.
Parameters
----------
longval : int
The first part of an encoded tuple from encode
nbits : int
The second part of an encoded tuple from encode
Returns
-------
str
The a... | Below is the the instruction that describes the task:
### Input:
Decode the number to a string using the given statistics.
Parameters
----------
longval : int
The first part of an encoded tuple from encode
nbits : int
The second part of an encoded tuple from ... |
def _load_converted_gssha_data_from_lsm(self, gssha_var, lsm_var, load_type, time_step=None):
"""
This function loads data from LSM and converts to GSSHA format
"""
if 'radiation' in gssha_var:
conversion_factor = self.netcdf_attributes[gssha_var]['conversion_factor'][load_ty... | This function loads data from LSM and converts to GSSHA format | Below is the the instruction that describes the task:
### Input:
This function loads data from LSM and converts to GSSHA format
### Response:
def _load_converted_gssha_data_from_lsm(self, gssha_var, lsm_var, load_type, time_step=None):
"""
This function loads data from LSM and converts to GSSHA for... |
def _get_parselypage(self, body):
"""extract the parsely-page meta content from a page"""
parser = ParselyPageParser()
ret = None
try:
parser.feed(body)
except HTMLParseError:
pass # ignore and hope we got ppage
if parser.ppage is None:
... | extract the parsely-page meta content from a page | Below is the the instruction that describes the task:
### Input:
extract the parsely-page meta content from a page
### Response:
def _get_parselypage(self, body):
"""extract the parsely-page meta content from a page"""
parser = ParselyPageParser()
ret = None
try:
parser.... |
def message_received(self, message):
"""Message was received from device."""
# If the message identifer is outstanding, then someone is
# waiting for the respone so we save it here
identifier = message.identifier or 'type_' + str(message.type)
if identifier in self._outstanding:
... | Message was received from device. | Below is the the instruction that describes the task:
### Input:
Message was received from device.
### Response:
def message_received(self, message):
"""Message was received from device."""
# If the message identifer is outstanding, then someone is
# waiting for the respone so we save it he... |
def check_roles(self, account, aws_policies, aws_roles):
"""Iterate through the roles of a specific account and create or update the roles if they're missing or
does not match the roles from Git.
Args:
account (:obj:`Account`): The account to check roles on
aws_policies ... | Iterate through the roles of a specific account and create or update the roles if they're missing or
does not match the roles from Git.
Args:
account (:obj:`Account`): The account to check roles on
aws_policies (:obj:`dict` of `str`: `dict`): A dictionary containing all the poli... | Below is the the instruction that describes the task:
### Input:
Iterate through the roles of a specific account and create or update the roles if they're missing or
does not match the roles from Git.
Args:
account (:obj:`Account`): The account to check roles on
aws_policies... |
def process_image(self, image, image_format, save_kwargs={}):
"""Return a BytesIO instance of `image` with inverted colors."""
imagefile = BytesIO()
inv_image = ImageOps.invert(image)
inv_image.save(
imagefile,
**save_kwargs
)
return imagefile | Return a BytesIO instance of `image` with inverted colors. | Below is the the instruction that describes the task:
### Input:
Return a BytesIO instance of `image` with inverted colors.
### Response:
def process_image(self, image, image_format, save_kwargs={}):
"""Return a BytesIO instance of `image` with inverted colors."""
imagefile = BytesIO()
inv_... |
def jd2dt(jd):
"""Convert julian date to datetime
"""
n = int(round(float(jd)))
a = n + 32044
b = (4*a + 3)//146097
c = a - (146097*b)//4
d = (4*c + 3)//1461
e = c - (1461*d)//4
m = (5*e + 2)//153
day = e + 1 - (153*m + 2)//5
month = m + 3 - 12*(m//10)
year = 100*b + d - ... | Convert julian date to datetime | Below is the the instruction that describes the task:
### Input:
Convert julian date to datetime
### Response:
def jd2dt(jd):
"""Convert julian date to datetime
"""
n = int(round(float(jd)))
a = n + 32044
b = (4*a + 3)//146097
c = a - (146097*b)//4
d = (4*c + 3)//1461
e = c - (1461*... |
def register_regex_entity(self, regex_str, domain=0):
"""
A regular expression making use of python named group expressions.
Example: (?P<Artist>.*)
Args:
regex_str(str): a string representing a regular expression as defined above
domain(str): a string represent... | A regular expression making use of python named group expressions.
Example: (?P<Artist>.*)
Args:
regex_str(str): a string representing a regular expression as defined above
domain(str): a string representing the domain you wish to add the entity to | Below is the the instruction that describes the task:
### Input:
A regular expression making use of python named group expressions.
Example: (?P<Artist>.*)
Args:
regex_str(str): a string representing a regular expression as defined above
domain(str): a string representing t... |
def find_DST():
"""Find where this package should be installed to.
"""
if SYS_NAME == "Windows":
return os.path.join(site.getsitepackages()[1], PKG_NAME)
elif SYS_NAME in ["Darwin", "Linux"]:
return os.path.join(site.getsitepackages()[0], PKG_NAME) | Find where this package should be installed to. | Below is the the instruction that describes the task:
### Input:
Find where this package should be installed to.
### Response:
def find_DST():
"""Find where this package should be installed to.
"""
if SYS_NAME == "Windows":
return os.path.join(site.getsitepackages()[1], PKG_NAME)
elif SYS_N... |
def artist_update(self, artist_id, name=None, other_names_comma=None,
group_name=None, url_string=None, body=None):
"""Function to update artists (Requires login) (UNTESTED).
Parameters:
artist_id (str):
name (str): Artist name.
other_names_comm... | Function to update artists (Requires login) (UNTESTED).
Parameters:
artist_id (str):
name (str): Artist name.
other_names_comma (str): List of alternative names for this
artist, comma delimited.
group_name (str): The name of t... | Below is the the instruction that describes the task:
### Input:
Function to update artists (Requires login) (UNTESTED).
Parameters:
artist_id (str):
name (str): Artist name.
other_names_comma (str): List of alternative names for this
... |
def get_attachment(self, ticket_id, attachment_id):
""" Get attachment.
:param ticket_id: ID of ticket
:param attachment_id: ID of attachment for obtain
:returns: Attachment as dictionary with these keys:
* Transaction
* ContentType
... | Get attachment.
:param ticket_id: ID of ticket
:param attachment_id: ID of attachment for obtain
:returns: Attachment as dictionary with these keys:
* Transaction
* ContentType
* Parent
* Creator
... | Below is the the instruction that describes the task:
### Input:
Get attachment.
:param ticket_id: ID of ticket
:param attachment_id: ID of attachment for obtain
:returns: Attachment as dictionary with these keys:
* Transaction
* ContentType
... |
def load():
# type: () -> None
""" Load configuration from file.
This will search the directory structure upwards to find the project root
(directory containing ``pelconf.py`` file). Once found it will import the
config file which should initialize all the configuration (using
`peltak.core.conf... | Load configuration from file.
This will search the directory structure upwards to find the project root
(directory containing ``pelconf.py`` file). Once found it will import the
config file which should initialize all the configuration (using
`peltak.core.conf.init()` function).
You can also have ... | Below is the the instruction that describes the task:
### Input:
Load configuration from file.
This will search the directory structure upwards to find the project root
(directory containing ``pelconf.py`` file). Once found it will import the
config file which should initialize all the configuration (u... |
def photbw(self, floor=0):
"""Calculate :ref:`pysynphot-formula-bandw`.
.. note:: For backward-compatibility with IRAF STSDAS SYNPHOT only.
Parameters
----------
floor : float
Same as :meth:`rmswidth`.
Returns
-------
ans : float
... | Calculate :ref:`pysynphot-formula-bandw`.
.. note:: For backward-compatibility with IRAF STSDAS SYNPHOT only.
Parameters
----------
floor : float
Same as :meth:`rmswidth`.
Returns
-------
ans : float
RMS band width (deprecated). | Below is the the instruction that describes the task:
### Input:
Calculate :ref:`pysynphot-formula-bandw`.
.. note:: For backward-compatibility with IRAF STSDAS SYNPHOT only.
Parameters
----------
floor : float
Same as :meth:`rmswidth`.
Returns
-------
... |
def potential_purviews(self, direction, mechanism, purviews=False):
"""Return all purviews that could belong to the |MIC|/|MIE|.
Filters out trivially-reducible purviews.
Args:
direction (str): Either |CAUSE| or |EFFECT|.
mechanism (tuple[int]): The mechanism of interes... | Return all purviews that could belong to the |MIC|/|MIE|.
Filters out trivially-reducible purviews.
Args:
direction (str): Either |CAUSE| or |EFFECT|.
mechanism (tuple[int]): The mechanism of interest.
Keyword Args:
purviews (tuple[int]): Optional subset of... | Below is the the instruction that describes the task:
### Input:
Return all purviews that could belong to the |MIC|/|MIE|.
Filters out trivially-reducible purviews.
Args:
direction (str): Either |CAUSE| or |EFFECT|.
mechanism (tuple[int]): The mechanism of interest.
... |
def update_cache_settings(self, service_id, version_number, name_key, **kwargs):
"""Update a specific cache settings object."""
body = self._formdata(kwargs, FastlyCacheSettings.FIELDS)
content = self._fetch("/service/%s/version/%d/cache_settings/%s" % (service_id, version_number, name_key), method="PUT", body=bo... | Update a specific cache settings object. | Below is the the instruction that describes the task:
### Input:
Update a specific cache settings object.
### Response:
def update_cache_settings(self, service_id, version_number, name_key, **kwargs):
"""Update a specific cache settings object."""
body = self._formdata(kwargs, FastlyCacheSettings.FIELDS)
con... |
def user_present(name, uid, password, channel=14, callback=False,
link_auth=True, ipmi_msg=True, privilege_level='administrator', **kwargs):
'''
Ensure IPMI user and user privileges.
name
name of user (limit 16 bytes)
uid
user id number (1 to 7)
password
us... | Ensure IPMI user and user privileges.
name
name of user (limit 16 bytes)
uid
user id number (1 to 7)
password
user password (limit 16 bytes)
channel
ipmi channel defaults to 14 for auto
callback
User Restricted to Callback
False = User Privilege ... | Below is the the instruction that describes the task:
### Input:
Ensure IPMI user and user privileges.
name
name of user (limit 16 bytes)
uid
user id number (1 to 7)
password
user password (limit 16 bytes)
channel
ipmi channel defaults to 14 for auto
callback... |
def properties(self): # type: () -> list
"""
Returns:
(list[str]) List of public properties
"""
_type = type(self)
return [_property for _property in dir(_type) if self._is_property(_property)] | Returns:
(list[str]) List of public properties | Below is the the instruction that describes the task:
### Input:
Returns:
(list[str]) List of public properties
### Response:
def properties(self): # type: () -> list
"""
Returns:
(list[str]) List of public properties
"""
_type = type(self)
... |
def qualified_note_rate(pianoroll, threshold=2):
"""Return the ratio of the number of the qualified notes (notes longer than
`threshold` (in time step)) to the total number of notes in a pianoroll."""
_validate_pianoroll(pianoroll)
if np.issubdtype(pianoroll.dtype, np.bool_):
pianoroll = pianoro... | Return the ratio of the number of the qualified notes (notes longer than
`threshold` (in time step)) to the total number of notes in a pianoroll. | Below is the the instruction that describes the task:
### Input:
Return the ratio of the number of the qualified notes (notes longer than
`threshold` (in time step)) to the total number of notes in a pianoroll.
### Response:
def qualified_note_rate(pianoroll, threshold=2):
"""Return the ratio of the number... |
def main (args):
"""Usage: print_sedml input-filename
"""
if len(args) != 2:
print(main.__doc__)
sys.exit(1)
doc = libsedml.readSedML(args[1]);
if ( doc.getErrorLog().getNumFailsWithSeverity(libsedml.LIBSEDML_SEV_ERROR) > 0):
print doc.getErrorLog().toString();
sys.exit(2);
print 'The... | Usage: print_sedml input-filename | Below is the the instruction that describes the task:
### Input:
Usage: print_sedml input-filename
### Response:
def main (args):
"""Usage: print_sedml input-filename
"""
if len(args) != 2:
print(main.__doc__)
sys.exit(1)
doc = libsedml.readSedML(args[1]);
if ( doc.getErrorLog().getNumFailsWithS... |
def convert(self, values, nan_rep, encoding, errors):
""" set the values from this selection: take = take ownership """
# values is a recarray
if values.dtype.fields is not None:
values = values[self.cname]
values = _maybe_convert(values, self.kind, encoding, errors)
... | set the values from this selection: take = take ownership | Below is the the instruction that describes the task:
### Input:
set the values from this selection: take = take ownership
### Response:
def convert(self, values, nan_rep, encoding, errors):
""" set the values from this selection: take = take ownership """
# values is a recarray
if values.... |
def _set_sip_ipv4_address(self, v, load=False):
"""
Setter method for sip_ipv4_address, mapped from YANG variable /rbridge_id/router/router_bgp/router_bgp_attributes/neighbor/neighbor_ips/neighbor_addr/update_source/sip_ipv4_address (sip-ipv4-address)
If this variable is read-only (config: false) in the
... | Setter method for sip_ipv4_address, mapped from YANG variable /rbridge_id/router/router_bgp/router_bgp_attributes/neighbor/neighbor_ips/neighbor_addr/update_source/sip_ipv4_address (sip-ipv4-address)
If this variable is read-only (config: false) in the
source YANG file, then _set_sip_ipv4_address is considered ... | Below is the the instruction that describes the task:
### Input:
Setter method for sip_ipv4_address, mapped from YANG variable /rbridge_id/router/router_bgp/router_bgp_attributes/neighbor/neighbor_ips/neighbor_addr/update_source/sip_ipv4_address (sip-ipv4-address)
If this variable is read-only (config: false) i... |
def fill_translation_cache(instance):
"""
Fill the translation cache using information received in the
instance objects as extra fields.
You can not do this in post_init because the extra fields are
assigned by QuerySet.iterator after model initialization.
"""
if hasattr(instance, '_transl... | Fill the translation cache using information received in the
instance objects as extra fields.
You can not do this in post_init because the extra fields are
assigned by QuerySet.iterator after model initialization. | Below is the the instruction that describes the task:
### Input:
Fill the translation cache using information received in the
instance objects as extra fields.
You can not do this in post_init because the extra fields are
assigned by QuerySet.iterator after model initialization.
### Response:
def fill... |
def lasts(iterable, items=1, default=None):
# type: (Iterable[T], int, T) -> Iterable[T]
""" Lazily return the last x items from this iterable or default. """
last_items = deque(iterable, maxlen=items)
for _ in range(items - len(last_items)):
yield default
for y in last_items:
yie... | Lazily return the last x items from this iterable or default. | Below is the the instruction that describes the task:
### Input:
Lazily return the last x items from this iterable or default.
### Response:
def lasts(iterable, items=1, default=None):
# type: (Iterable[T], int, T) -> Iterable[T]
""" Lazily return the last x items from this iterable or default. """
la... |
def all_subclasses(cls):
"""Generator yielding all subclasses of `cls` recursively"""
for subcls in cls.__subclasses__():
yield subcls
for subsubcls in all_subclasses(subcls):
yield subsubcls | Generator yielding all subclasses of `cls` recursively | Below is the the instruction that describes the task:
### Input:
Generator yielding all subclasses of `cls` recursively
### Response:
def all_subclasses(cls):
"""Generator yielding all subclasses of `cls` recursively"""
for subcls in cls.__subclasses__():
yield subcls
for subsubcls in all_s... |
def login_defs():
"""Discover the minimum and maximum UID number."""
uid_min = None
uid_max = None
login_defs_path = '/etc/login.defs'
if os.path.exists(login_defs_path):
with io.open(text_type(login_defs_path), encoding=text_type('utf-8')) as log_defs_file:
login_data = log_defs... | Discover the minimum and maximum UID number. | Below is the the instruction that describes the task:
### Input:
Discover the minimum and maximum UID number.
### Response:
def login_defs():
"""Discover the minimum and maximum UID number."""
uid_min = None
uid_max = None
login_defs_path = '/etc/login.defs'
if os.path.exists(login_defs_path):
... |
def _dump_to_json(self, with_stats):
"""
Dump the models into a list of strings. Each
string is a text representation of a tree.
Parameters
----------
with_stats : bool
If true, include node statistics in the output.
Returns
-------
o... | Dump the models into a list of strings. Each
string is a text representation of a tree.
Parameters
----------
with_stats : bool
If true, include node statistics in the output.
Returns
-------
out : SFrame
A table with two columns: feature... | Below is the the instruction that describes the task:
### Input:
Dump the models into a list of strings. Each
string is a text representation of a tree.
Parameters
----------
with_stats : bool
If true, include node statistics in the output.
Returns
-----... |
def set_memory_cache(self, results, key=None):
"""Store result in memory cache with key matching model state."""
key = self.model.hash if key is None else key
self.memory_cache[key] = results | Store result in memory cache with key matching model state. | Below is the the instruction that describes the task:
### Input:
Store result in memory cache with key matching model state.
### Response:
def set_memory_cache(self, results, key=None):
"""Store result in memory cache with key matching model state."""
key = self.model.hash if key is None else key
... |
def _update_trial_queue(self, blocking=False, timeout=600):
"""Adds next trials to queue if possible.
Note that the timeout is currently unexposed to the user.
Args:
blocking (bool): Blocks until either a trial is available
or is_finished (timeout or search algorith... | Adds next trials to queue if possible.
Note that the timeout is currently unexposed to the user.
Args:
blocking (bool): Blocks until either a trial is available
or is_finished (timeout or search algorithm finishes).
timeout (int): Seconds before blocking times o... | Below is the the instruction that describes the task:
### Input:
Adds next trials to queue if possible.
Note that the timeout is currently unexposed to the user.
Args:
blocking (bool): Blocks until either a trial is available
or is_finished (timeout or search algorithm ... |
def racks(self):
"""
Gets the Racks API client.
Returns:
Racks:
"""
if not self.__racks:
self.__racks = Racks(self.__connection)
return self.__racks | Gets the Racks API client.
Returns:
Racks: | Below is the the instruction that describes the task:
### Input:
Gets the Racks API client.
Returns:
Racks:
### Response:
def racks(self):
"""
Gets the Racks API client.
Returns:
Racks:
"""
if not self.__racks:
self.__racks = Rac... |
def get_yaml_files_at_env_root(self):
"""Return list of yaml files in env_root."""
yaml_files = glob.glob(
os.path.join(self.env_root, '*.yaml')
)
yml_files = glob.glob(
os.path.join(self.env_root, '*.yml')
)
return yaml_files + yml_files | Return list of yaml files in env_root. | Below is the the instruction that describes the task:
### Input:
Return list of yaml files in env_root.
### Response:
def get_yaml_files_at_env_root(self):
"""Return list of yaml files in env_root."""
yaml_files = glob.glob(
os.path.join(self.env_root, '*.yaml')
)
yml_fi... |
def hide_button_span(self, mode, file=sys.stdout):
"""
:param int mode: 1 or 2
:param io.TextIOBase|io.StringIO file:
"""
file.write("\033[83;%iu" % mode)
yield
file.write("\033[83;0u") | :param int mode: 1 or 2
:param io.TextIOBase|io.StringIO file: | Below is the the instruction that describes the task:
### Input:
:param int mode: 1 or 2
:param io.TextIOBase|io.StringIO file:
### Response:
def hide_button_span(self, mode, file=sys.stdout):
"""
:param int mode: 1 or 2
:param io.TextIOBase|io.StringIO file:
"""
fil... |
def _ns_var(
py_ns_var: str = _NS_VAR, lisp_ns_var: str = LISP_NS_VAR, lisp_ns_ns: str = CORE_NS
) -> ast.Assign:
"""Assign a Python variable named `ns_var` to the value of the current
namespace."""
return ast.Assign(
targets=[ast.Name(id=py_ns_var, ctx=ast.Store())],
value=ast.Call(
... | Assign a Python variable named `ns_var` to the value of the current
namespace. | Below is the the instruction that describes the task:
### Input:
Assign a Python variable named `ns_var` to the value of the current
namespace.
### Response:
def _ns_var(
py_ns_var: str = _NS_VAR, lisp_ns_var: str = LISP_NS_VAR, lisp_ns_ns: str = CORE_NS
) -> ast.Assign:
"""Assign a Python variable nam... |
def reciprocal_rank(
model,
test_interactions,
train_interactions=None,
user_features=None,
item_features=None,
preserve_rows=False,
num_threads=1,
check_intersections=True,
):
"""
Measure the reciprocal rank metric for a model: 1 / the rank of the highest
ranked positive exa... | Measure the reciprocal rank metric for a model: 1 / the rank of the highest
ranked positive example. A perfect score is 1.0.
Parameters
----------
model: LightFM instance
the fitted model to be evaluated
test_interactions: np.float32 csr_matrix of shape [n_users, n_items]
Non-zer... | Below is the the instruction that describes the task:
### Input:
Measure the reciprocal rank metric for a model: 1 / the rank of the highest
ranked positive example. A perfect score is 1.0.
Parameters
----------
model: LightFM instance
the fitted model to be evaluated
test_interaction... |
def sample(self, size=(), rule="R", antithetic=None):
"""
Create pseudo-random generated samples.
By default, the samples are created using standard (pseudo-)random
samples. However, if needed, the samples can also be created by either
low-discrepancy sequences, and/or variance ... | Create pseudo-random generated samples.
By default, the samples are created using standard (pseudo-)random
samples. However, if needed, the samples can also be created by either
low-discrepancy sequences, and/or variance reduction techniques.
Changing the sampling scheme, use the follo... | Below is the the instruction that describes the task:
### Input:
Create pseudo-random generated samples.
By default, the samples are created using standard (pseudo-)random
samples. However, if needed, the samples can also be created by either
low-discrepancy sequences, and/or variance reduc... |
def add_data(self, request, pk=None):
"""Add data to Entity and it's collection."""
# add data to entity
resp = super().add_data(request, pk)
# add data to collections in which entity is
entity = self.get_object()
for collection in entity.collections.all():
c... | Add data to Entity and it's collection. | Below is the the instruction that describes the task:
### Input:
Add data to Entity and it's collection.
### Response:
def add_data(self, request, pk=None):
"""Add data to Entity and it's collection."""
# add data to entity
resp = super().add_data(request, pk)
# add data to collect... |
def all(self, data={}, **kwargs):
""""
Fetch all Subscription entities
Returns:
Dictionary of Subscription data
"""
return super(Subscription, self).all(data, **kwargs) | Fetch all Subscription entities
Returns:
Dictionary of Subscription data | Below is the the instruction that describes the task:
### Input:
Fetch all Subscription entities
Returns:
Dictionary of Subscription data
### Response:
def all(self, data={}, **kwargs):
""""
Fetch all Subscription entities
Returns:
Dictionary of Subscriptio... |
def set_notebook(note_store, my_notebook, notebook_id):
"""
create a notebook
"""
if notebook_id == 0:
new_notebook = Types.Notebook()
new_notebook.name = my_notebook
new_notebook.defaultNotebook = False
notebook_id = note_store.createN... | create a notebook | Below is the the instruction that describes the task:
### Input:
create a notebook
### Response:
def set_notebook(note_store, my_notebook, notebook_id):
"""
create a notebook
"""
if notebook_id == 0:
new_notebook = Types.Notebook()
new_notebook.name = my_... |
def get_assessment_form_for_create(self, assessment_record_types):
"""Gets the assessment form for creating new assessments.
A new form should be requested for each create transaction.
arg: assessment_record_types (osid.type.Type[]): array of
assessment record types to be in... | Gets the assessment form for creating new assessments.
A new form should be requested for each create transaction.
arg: assessment_record_types (osid.type.Type[]): array of
assessment record types to be included in the create
operation or an empty list if none
... | Below is the the instruction that describes the task:
### Input:
Gets the assessment form for creating new assessments.
A new form should be requested for each create transaction.
arg: assessment_record_types (osid.type.Type[]): array of
assessment record types to be included in... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.