code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def get_assessment_taken_ids_by_banks(self, bank_ids):
"""Gets the list of ``AssessmentTaken Ids`` corresponding to a list of ``Banks``.
arg: bank_ids (osid.id.IdList): list of bank ``Ids``
return: (osid.id.IdList) - list of bank ``Ids``
raise: NullArgument - ``bank_ids`` is ``null`... | Gets the list of ``AssessmentTaken Ids`` corresponding to a list of ``Banks``.
arg: bank_ids (osid.id.IdList): list of bank ``Ids``
return: (osid.id.IdList) - list of bank ``Ids``
raise: NullArgument - ``bank_ids`` is ``null``
raise: OperationFailed - unable to complete request
... | Below is the the instruction that describes the task:
### Input:
Gets the list of ``AssessmentTaken Ids`` corresponding to a list of ``Banks``.
arg: bank_ids (osid.id.IdList): list of bank ``Ids``
return: (osid.id.IdList) - list of bank ``Ids``
raise: NullArgument - ``bank_ids`` is ``nu... |
def execute(self):
"""
Execute the actions necessary to perform a `molecule create` and
returns None.
:return: None
"""
self.print_info()
self._config.state.change_state('driver', self._config.driver.name)
if self._config.driver.delegated and not self._c... | Execute the actions necessary to perform a `molecule create` and
returns None.
:return: None | Below is the the instruction that describes the task:
### Input:
Execute the actions necessary to perform a `molecule create` and
returns None.
:return: None
### Response:
def execute(self):
"""
Execute the actions necessary to perform a `molecule create` and
returns None.
... |
def start_all(self):
"""Starts all inactive service instances."""
for alias, service in self._service_objects.items():
if not service.is_alive:
with expects.expect_no_raises(
'Failed to start service "%s".' % alias):
service.start() | Starts all inactive service instances. | Below is the the instruction that describes the task:
### Input:
Starts all inactive service instances.
### Response:
def start_all(self):
"""Starts all inactive service instances."""
for alias, service in self._service_objects.items():
if not service.is_alive:
with expe... |
def init_send(self):
"""
Generates the first (IKE_INIT) packet for Initiator
:return: bytes() containing a valid IKE_INIT packet
"""
packet = Packet()
self.packets.append(packet)
packet.add_payload(payloads.SA())
packet.add_payload(payloads.KE(diffie_hell... | Generates the first (IKE_INIT) packet for Initiator
:return: bytes() containing a valid IKE_INIT packet | Below is the the instruction that describes the task:
### Input:
Generates the first (IKE_INIT) packet for Initiator
:return: bytes() containing a valid IKE_INIT packet
### Response:
def init_send(self):
"""
Generates the first (IKE_INIT) packet for Initiator
:return: bytes() cont... |
def temporary_dir(delete=True, dir=None,
prefix='elasticluster.', suffix='.d'):
"""
Make a temporary directory and make it current for the code in this context.
Delete temporary directory upon exit from the context, unless
``delete=False`` is passed in the arguments.
Arguments *s... | Make a temporary directory and make it current for the code in this context.
Delete temporary directory upon exit from the context, unless
``delete=False`` is passed in the arguments.
Arguments *suffix*, *prefix* and *dir* are exactly as in
:func:`tempfile.mkdtemp()` (but have different defaults). | Below is the the instruction that describes the task:
### Input:
Make a temporary directory and make it current for the code in this context.
Delete temporary directory upon exit from the context, unless
``delete=False`` is passed in the arguments.
Arguments *suffix*, *prefix* and *dir* are exactly as... |
def _generate_read_callable(name, display_name, arguments, regex, doc, supported):
"""
Returns a callable which conjures the URL for the resource and GETs a response
"""
def f(self, *args, **kwargs):
url = self._generate_url(regex, args)
if 'params' in kwargs:
url += "?" + ur... | Returns a callable which conjures the URL for the resource and GETs a response | Below is the the instruction that describes the task:
### Input:
Returns a callable which conjures the URL for the resource and GETs a response
### Response:
def _generate_read_callable(name, display_name, arguments, regex, doc, supported):
"""
Returns a callable which conjures the URL for the resource and... |
def interaction(
self,
frame,
tb=None,
exception='Wdb',
exception_description='Stepping',
init=None,
shell=False,
shell_vars=None,
source=None,
iframe_mode=False,
timeout=None,
... | User interaction handling blocking on socket receive | Below is the the instruction that describes the task:
### Input:
User interaction handling blocking on socket receive
### Response:
def interaction(
self,
frame,
tb=None,
exception='Wdb',
exception_description='Stepping',
init=None,
... |
def import_domaindump():
"""
Parses ldapdomaindump files and stores hosts and users in elasticsearch.
"""
parser = argparse.ArgumentParser(
description="Imports users, groups and computers result files from the ldapdomaindump tool, will resolve the names from domain_computers output for IPs"... | Parses ldapdomaindump files and stores hosts and users in elasticsearch. | Below is the the instruction that describes the task:
### Input:
Parses ldapdomaindump files and stores hosts and users in elasticsearch.
### Response:
def import_domaindump():
"""
Parses ldapdomaindump files and stores hosts and users in elasticsearch.
"""
parser = argparse.ArgumentParser(
... |
def print_spelling_errors(filename, encoding='utf8'):
"""
Print misspelled words returned by sphinxcontrib-spelling
"""
filesize = os.stat(filename).st_size
if filesize:
sys.stdout.write('Misspelled Words:\n')
with io.open(filename, encoding=encoding) as wordlist:
for li... | Print misspelled words returned by sphinxcontrib-spelling | Below is the the instruction that describes the task:
### Input:
Print misspelled words returned by sphinxcontrib-spelling
### Response:
def print_spelling_errors(filename, encoding='utf8'):
"""
Print misspelled words returned by sphinxcontrib-spelling
"""
filesize = os.stat(filename).st_size
... |
def GetID(attrs, tag, val):
"""
handy method which pulls out a nested id: attrs refers to a dictionary holding the id
tag refers to the tag we're looking at (e.g measure, part etc)
val refers to the exact index of the tag we're looking for (e.g number, id etc)
example case: attrs = self.attribs, tag... | handy method which pulls out a nested id: attrs refers to a dictionary holding the id
tag refers to the tag we're looking at (e.g measure, part etc)
val refers to the exact index of the tag we're looking for (e.g number, id etc)
example case: attrs = self.attribs, tag=measure and val=number would
return... | Below is the the instruction that describes the task:
### Input:
handy method which pulls out a nested id: attrs refers to a dictionary holding the id
tag refers to the tag we're looking at (e.g measure, part etc)
val refers to the exact index of the tag we're looking for (e.g number, id etc)
example ca... |
def project(self, q, parent=False):
""" Figure out which attributes should be returned for the current
level of the query. """
if self.parent:
print (self.parent.var, self.predicate, self.var)
q = q.project(self.var, append=True)
if parent and self.parent:
... | Figure out which attributes should be returned for the current
level of the query. | Below is the the instruction that describes the task:
### Input:
Figure out which attributes should be returned for the current
level of the query.
### Response:
def project(self, q, parent=False):
""" Figure out which attributes should be returned for the current
level of the query. """
... |
def digestKey(self, handle):
"""
C_DigestKey
:param handle: key handle
:type handle: CK_OBJECT_HANDLE
"""
rv = self._lib.C_DigestKey(self._session, handle)
if rv != CKR_OK:
raise PyKCS11Error(rv)
return self | C_DigestKey
:param handle: key handle
:type handle: CK_OBJECT_HANDLE | Below is the the instruction that describes the task:
### Input:
C_DigestKey
:param handle: key handle
:type handle: CK_OBJECT_HANDLE
### Response:
def digestKey(self, handle):
"""
C_DigestKey
:param handle: key handle
:type handle: CK_OBJECT_HANDLE
"""
... |
def dump_json(data, indent=None):
"""
:param list | dict data:
:param Optional[int] indent:
:rtype: unicode
"""
return json.dumps(data,
indent=indent,
ensure_ascii=False,
sort_keys=True,
separators=(',', ': '... | :param list | dict data:
:param Optional[int] indent:
:rtype: unicode | Below is the the instruction that describes the task:
### Input:
:param list | dict data:
:param Optional[int] indent:
:rtype: unicode
### Response:
def dump_json(data, indent=None):
"""
:param list | dict data:
:param Optional[int] indent:
:rtype: unicode
"""
return json.dumps(data... |
def _server_extract_frame(self, *, mpfdp, mpkit, mpbuf):
"""Extract frame."""
# check EOF
if self._flag_e:
raise EOFError
# extract frame
try:
frame = Frame(self._ifile, num=self._frnum, proto=self._dlink, layer=self._exlyr,
prot... | Extract frame. | Below is the the instruction that describes the task:
### Input:
Extract frame.
### Response:
def _server_extract_frame(self, *, mpfdp, mpkit, mpbuf):
"""Extract frame."""
# check EOF
if self._flag_e:
raise EOFError
# extract frame
try:
frame = Frame... |
def _population_load_script(work_bams, names, chrom, pairmode, items):
"""Prepare BAMs for assessing CNVs in a population.
"""
bed_file = _get_regional_bed_file(items[0])
if bed_file:
return _population_prep_targeted.format(bam_file_str=",".join(work_bams), names_str=",".join(names),
... | Prepare BAMs for assessing CNVs in a population. | Below is the the instruction that describes the task:
### Input:
Prepare BAMs for assessing CNVs in a population.
### Response:
def _population_load_script(work_bams, names, chrom, pairmode, items):
"""Prepare BAMs for assessing CNVs in a population.
"""
bed_file = _get_regional_bed_file(items[0])
... |
def right(self, num=None):
"""
WITH SLICES BEING FLAT, WE NEED A SIMPLE WAY TO SLICE FROM THE RIGHT [-num:]
"""
if num == None:
return self.last.node
if num <= 0:
return []
if not self.list:
self._build_list()
return self.list[... | WITH SLICES BEING FLAT, WE NEED A SIMPLE WAY TO SLICE FROM THE RIGHT [-num:] | Below is the the instruction that describes the task:
### Input:
WITH SLICES BEING FLAT, WE NEED A SIMPLE WAY TO SLICE FROM THE RIGHT [-num:]
### Response:
def right(self, num=None):
"""
WITH SLICES BEING FLAT, WE NEED A SIMPLE WAY TO SLICE FROM THE RIGHT [-num:]
"""
if num == None:... |
def filters_apply(self, objects, filters, context):
"""
Helper function: Applies a list of filters to a list of either statuses
or notifications and returns only those matched by none. This function will
apply all filters that match the context provided in `context`, i.e.
if you... | Helper function: Applies a list of filters to a list of either statuses
or notifications and returns only those matched by none. This function will
apply all filters that match the context provided in `context`, i.e.
if you want to apply only notification-relevant filters, specify
'noti... | Below is the the instruction that describes the task:
### Input:
Helper function: Applies a list of filters to a list of either statuses
or notifications and returns only those matched by none. This function will
apply all filters that match the context provided in `context`, i.e.
if you wa... |
def eager_partial(self, fn, *a, **kw):
"""Partially apply annotated callable, returning a partial function.
By default, `partial` is lazy so that injections only happen when they
are needed. Use `eager_partial` in place of `partial` when a guarantee
of injection is needed at the time th... | Partially apply annotated callable, returning a partial function.
By default, `partial` is lazy so that injections only happen when they
are needed. Use `eager_partial` in place of `partial` when a guarantee
of injection is needed at the time the partially applied function is
created.
... | Below is the the instruction that describes the task:
### Input:
Partially apply annotated callable, returning a partial function.
By default, `partial` is lazy so that injections only happen when they
are needed. Use `eager_partial` in place of `partial` when a guarantee
of injection is ne... |
def score(self, X, y, **kwargs):
"""
Generates a 2D array where each row is the count of the
predicted classes and each column is the true class
Parameters
----------
X : ndarray or DataFrame of shape n x m
A matrix of n instances with m features
y :... | Generates a 2D array where each row is the count of the
predicted classes and each column is the true class
Parameters
----------
X : ndarray or DataFrame of shape n x m
A matrix of n instances with m features
y : ndarray or Series of length n
An array o... | Below is the the instruction that describes the task:
### Input:
Generates a 2D array where each row is the count of the
predicted classes and each column is the true class
Parameters
----------
X : ndarray or DataFrame of shape n x m
A matrix of n instances with m featu... |
def console_load_xp(con: tcod.console.Console, filename: str) -> bool:
"""Update a console from a REXPaint `.xp` file."""
return bool(
lib.TCOD_console_load_xp(_console(con), filename.encode("utf-8"))
) | Update a console from a REXPaint `.xp` file. | Below is the the instruction that describes the task:
### Input:
Update a console from a REXPaint `.xp` file.
### Response:
def console_load_xp(con: tcod.console.Console, filename: str) -> bool:
"""Update a console from a REXPaint `.xp` file."""
return bool(
lib.TCOD_console_load_xp(_console(con), ... |
def create_mutation_file(self, list_of_tuples):
"""Create the FoldX file 'individual_list.txt' to run BuildModel upon.
Args:
list_of_tuples (list): A list of tuples indicating mutation groups to carry out BuildModel upon. Example::
[
(('N', 'A', 308, 'S'... | Create the FoldX file 'individual_list.txt' to run BuildModel upon.
Args:
list_of_tuples (list): A list of tuples indicating mutation groups to carry out BuildModel upon. Example::
[
(('N', 'A', 308, 'S'), ('S', 'A', 320, 'T'), ('S', 'A', 321, 'H')), # Mutation... | Below is the the instruction that describes the task:
### Input:
Create the FoldX file 'individual_list.txt' to run BuildModel upon.
Args:
list_of_tuples (list): A list of tuples indicating mutation groups to carry out BuildModel upon. Example::
[
(('N', 'A'... |
async def send_voice(self, chat_id: typing.Union[base.Integer, base.String],
voice: typing.Union[base.InputFile, base.String],
caption: typing.Union[base.String, None] = None,
parse_mode: typing.Union[base.String, None] = None,
... | Use this method to send audio files, if you want Telegram clients to display the file
as a playable voice message.
For this to work, your audio must be in an .ogg file encoded with OPUS
(other formats may be sent as Audio or Document).
Source: https://core.telegram.org/bots/api#sendvoi... | Below is the the instruction that describes the task:
### Input:
Use this method to send audio files, if you want Telegram clients to display the file
as a playable voice message.
For this to work, your audio must be in an .ogg file encoded with OPUS
(other formats may be sent as Audio or D... |
def MI_enumInstanceNames(self,
env,
ns,
cimClass):
# pylint: disable=invalid-name
"""Return instance names of a given CIM class
Implements the WBEM operation EnumerateInstanceNames in terms
of the enu... | Return instance names of a given CIM class
Implements the WBEM operation EnumerateInstanceNames in terms
of the enum_instances method. A derived class will not normally
override this method. | Below is the the instruction that describes the task:
### Input:
Return instance names of a given CIM class
Implements the WBEM operation EnumerateInstanceNames in terms
of the enum_instances method. A derived class will not normally
override this method.
### Response:
def MI_enumInstance... |
def get_attribute_proxy(self, attribute):
"""
Returns a traversal proxy (cardinality ONE) or an iterable sequence
data traversal proxy (cardinality MANY) for the specified relation
attribute value of the proxied data.
:raises ValueError: If :param:`attribute` is a terminal attri... | Returns a traversal proxy (cardinality ONE) or an iterable sequence
data traversal proxy (cardinality MANY) for the specified relation
attribute value of the proxied data.
:raises ValueError: If :param:`attribute` is a terminal attribute. | Below is the the instruction that describes the task:
### Input:
Returns a traversal proxy (cardinality ONE) or an iterable sequence
data traversal proxy (cardinality MANY) for the specified relation
attribute value of the proxied data.
:raises ValueError: If :param:`attribute` is a termina... |
def is_pg_at_least_nine_two(self):
"""
Some queries have different syntax depending what version of postgres
we are querying against.
:returns: boolean
"""
if self._is_pg_at_least_nine_two is None:
results = self.version()
regex = re.compile("Pos... | Some queries have different syntax depending what version of postgres
we are querying against.
:returns: boolean | Below is the the instruction that describes the task:
### Input:
Some queries have different syntax depending what version of postgres
we are querying against.
:returns: boolean
### Response:
def is_pg_at_least_nine_two(self):
"""
Some queries have different syntax depending what v... |
def reload_cache_config(self, call_params):
"""REST Reload Plivo Cache Config helper
"""
path = '/' + self.api_version + '/ReloadCacheConfig/'
method = 'POST'
return self.request(path, method, call_params) | REST Reload Plivo Cache Config helper | Below is the the instruction that describes the task:
### Input:
REST Reload Plivo Cache Config helper
### Response:
def reload_cache_config(self, call_params):
"""REST Reload Plivo Cache Config helper
"""
path = '/' + self.api_version + '/ReloadCacheConfig/'
method = 'POST'
... |
def html(header_rows):
"""
Convert a list of tuples describing a table into a HTML string
"""
name = 'table%d' % next(tablecounter)
return HtmlTable([map(str, row) for row in header_rows], name).render() | Convert a list of tuples describing a table into a HTML string | Below is the the instruction that describes the task:
### Input:
Convert a list of tuples describing a table into a HTML string
### Response:
def html(header_rows):
"""
Convert a list of tuples describing a table into a HTML string
"""
name = 'table%d' % next(tablecounter)
return HtmlTable([map... |
def output_raw(self, text):
"""
Output results in raw JSON format
"""
payload = json.loads(text)
out = json.dumps(payload, sort_keys=True, indent=self._indent, separators=(',', ': '))
print(self.colorize_json(out)) | Output results in raw JSON format | Below is the the instruction that describes the task:
### Input:
Output results in raw JSON format
### Response:
def output_raw(self, text):
"""
Output results in raw JSON format
"""
payload = json.loads(text)
out = json.dumps(payload, sort_keys=True, indent=self._indent, se... |
def write(filename, adata, ext=None, compression='gzip', compression_opts=None):
"""Write :class:`~anndata.AnnData` objects to file.
Parameters
----------
filename : `str`
If the filename has no file extension, it is interpreted as a key for
generating a filename via `sc.settings.writed... | Write :class:`~anndata.AnnData` objects to file.
Parameters
----------
filename : `str`
If the filename has no file extension, it is interpreted as a key for
generating a filename via `sc.settings.writedir + filename +
sc.settings.file_format_data`. This is the same behavior as in
... | Below is the the instruction that describes the task:
### Input:
Write :class:`~anndata.AnnData` objects to file.
Parameters
----------
filename : `str`
If the filename has no file extension, it is interpreted as a key for
generating a filename via `sc.settings.writedir + filename +
... |
def execute(self, query, *multiparams, **params):
"""Executes a SQL query with optional parameters.
query - a SQL query string or any sqlalchemy expression.
*multiparams/**params - represent bound parameter values to be
used in the execution. Typically, the format is a dictionary
... | Executes a SQL query with optional parameters.
query - a SQL query string or any sqlalchemy expression.
*multiparams/**params - represent bound parameter values to be
used in the execution. Typically, the format is a dictionary
passed to *multiparams:
await conn.execute(
... | Below is the the instruction that describes the task:
### Input:
Executes a SQL query with optional parameters.
query - a SQL query string or any sqlalchemy expression.
*multiparams/**params - represent bound parameter values to be
used in the execution. Typically, the format is a diction... |
def unless(exception_class_or_tuple, func, *args, **kwargs):
"""
When `exception_class_or_tuple` occurs while executing `func`, it will
be caught and ``None`` will be returned.
>>> f = where(X > 10) | list | unless(IndexError, X[0])
>>> f([5, 8, 12, 4])
12
>>> f([1, 2, 3])
None
"""
... | When `exception_class_or_tuple` occurs while executing `func`, it will
be caught and ``None`` will be returned.
>>> f = where(X > 10) | list | unless(IndexError, X[0])
>>> f([5, 8, 12, 4])
12
>>> f([1, 2, 3])
None | Below is the the instruction that describes the task:
### Input:
When `exception_class_or_tuple` occurs while executing `func`, it will
be caught and ``None`` will be returned.
>>> f = where(X > 10) | list | unless(IndexError, X[0])
>>> f([5, 8, 12, 4])
12
>>> f([1, 2, 3])
None
### Response... |
def set_result (self, msg, valid=True, overwrite=False):
"""
Set result string and validity.
"""
if self.has_result and not overwrite:
log.warn(LOG_CHECK,
"Double result %r (previous %r) for %s", msg, self.result, self)
else:
self.has_result ... | Set result string and validity. | Below is the the instruction that describes the task:
### Input:
Set result string and validity.
### Response:
def set_result (self, msg, valid=True, overwrite=False):
"""
Set result string and validity.
"""
if self.has_result and not overwrite:
log.warn(LOG_CHECK,
... |
def ensure_valid_model_type(specified_type, model_type_list):
"""
Checks to make sure that `specified_type` is in `model_type_list` and
raises a helpful error if this is not the case.
Parameters
----------
specified_type : str.
Denotes the user-specified model type that is to be checked... | Checks to make sure that `specified_type` is in `model_type_list` and
raises a helpful error if this is not the case.
Parameters
----------
specified_type : str.
Denotes the user-specified model type that is to be checked.
model_type_list : list of strings.
Contains all of the model... | Below is the the instruction that describes the task:
### Input:
Checks to make sure that `specified_type` is in `model_type_list` and
raises a helpful error if this is not the case.
Parameters
----------
specified_type : str.
Denotes the user-specified model type that is to be checked.
... |
def delete_csi_node(self, name, **kwargs):
"""
delete a CSINode
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.delete_csi_node(name, async_req=True)
>>> result = thread.get()
... | delete a CSINode
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.delete_csi_node(name, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str name: name of the ... | Below is the the instruction that describes the task:
### Input:
delete a CSINode
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.delete_csi_node(name, async_req=True)
>>> result = thread.get()... |
def pipeline(self, transaction=True, shard_hint=None):
"""
Return a new pipeline object that can queue multiple commands for
later execution. ``transaction`` indicates whether all commands
should be executed atomically. Apart from making a group of operations
atomic, pipelines ar... | Return a new pipeline object that can queue multiple commands for
later execution. ``transaction`` indicates whether all commands
should be executed atomically. Apart from making a group of operations
atomic, pipelines are useful for reducing the back-and-forth overhead
between the clien... | Below is the the instruction that describes the task:
### Input:
Return a new pipeline object that can queue multiple commands for
later execution. ``transaction`` indicates whether all commands
should be executed atomically. Apart from making a group of operations
atomic, pipelines are usef... |
def exptime(self):
''' exptime: 下一個日期時間
:returns: 下一個預設時間
'''
return self.nextday + timedelta(hours=self.__hour - 8,
minutes=self.__minutes) | exptime: 下一個日期時間
:returns: 下一個預設時間 | Below is the the instruction that describes the task:
### Input:
exptime: 下一個日期時間
:returns: 下一個預設時間
### Response:
def exptime(self):
''' exptime: 下一個日期時間
:returns: 下一個預設時間
'''
return self.nextday + timedelta(hours=self.__hour - 8,
... |
def unsubscribe_rpc(self, service, mask, value):
'''Remove a rpc subscription
:param service: the service of the subscription to remove
:type service: anything hash-able
:param mask: the mask of the subscription to remove
:type mask: int
:param value: the value in the su... | Remove a rpc subscription
:param service: the service of the subscription to remove
:type service: anything hash-able
:param mask: the mask of the subscription to remove
:type mask: int
:param value: the value in the subscription to remove
:type value: int
:param... | Below is the the instruction that describes the task:
### Input:
Remove a rpc subscription
:param service: the service of the subscription to remove
:type service: anything hash-able
:param mask: the mask of the subscription to remove
:type mask: int
:param value: the value ... |
def get_multi_generation(self, tables, db='default'):
"""Takes a list of table names and returns an aggregate
value for the generation"""
generations = []
for table in tables:
generations.append(self.get_single_generation(table, db))
key = self.keygen.gen_multi_key(ge... | Takes a list of table names and returns an aggregate
value for the generation | Below is the the instruction that describes the task:
### Input:
Takes a list of table names and returns an aggregate
value for the generation
### Response:
def get_multi_generation(self, tables, db='default'):
"""Takes a list of table names and returns an aggregate
value for the generation... |
def fprob(dfnum, dfden, F):
"""
Returns the (1-tailed) significance level (p-value) of an F
statistic given the degrees of freedom for the numerator (dfR-dfF) and
the degrees of freedom for the denominator (dfF).
Usage: lfprob(dfnum, dfden, F) where usually dfnum=dfbn, dfden=dfwn
"""
p = betai(0.5 * dfden,... | Returns the (1-tailed) significance level (p-value) of an F
statistic given the degrees of freedom for the numerator (dfR-dfF) and
the degrees of freedom for the denominator (dfF).
Usage: lfprob(dfnum, dfden, F) where usually dfnum=dfbn, dfden=dfwn | Below is the the instruction that describes the task:
### Input:
Returns the (1-tailed) significance level (p-value) of an F
statistic given the degrees of freedom for the numerator (dfR-dfF) and
the degrees of freedom for the denominator (dfF).
Usage: lfprob(dfnum, dfden, F) where usually dfnum=dfbn, dfden=df... |
def _get_filters(nodes, context):
"""Get filters to apply to a list of SqlNodes.
Args:
nodes: List[SqlNode], the SqlNodes to get filters for.
context: CompilationContext, global compilation state and metadata.
Returns:
List[Expression], list of SQLAlchemy expressions.
"""
f... | Get filters to apply to a list of SqlNodes.
Args:
nodes: List[SqlNode], the SqlNodes to get filters for.
context: CompilationContext, global compilation state and metadata.
Returns:
List[Expression], list of SQLAlchemy expressions. | Below is the the instruction that describes the task:
### Input:
Get filters to apply to a list of SqlNodes.
Args:
nodes: List[SqlNode], the SqlNodes to get filters for.
context: CompilationContext, global compilation state and metadata.
Returns:
List[Expression], list of SQLAlchem... |
def delete_object(self, container, obj, **kwargs):
"""Delete object in container
:param container: container name (Container is equivalent to
Bucket term in Amazon).
:param obj: object name (Object is equivalent to
Key term in Amazon).
"""
... | Delete object in container
:param container: container name (Container is equivalent to
Bucket term in Amazon).
:param obj: object name (Object is equivalent to
Key term in Amazon). | Below is the the instruction that describes the task:
### Input:
Delete object in container
:param container: container name (Container is equivalent to
Bucket term in Amazon).
:param obj: object name (Object is equivalent to
Key term in Amazon).
### Re... |
def function_dependency_graph(self, func):
"""
Get a dependency graph for the function `func`.
:param func: The Function object in CFG.function_manager.
:returns: A networkx.DiGraph instance.
"""
if self._function_data_dependencies is None:
self._bu... | Get a dependency graph for the function `func`.
:param func: The Function object in CFG.function_manager.
:returns: A networkx.DiGraph instance. | Below is the the instruction that describes the task:
### Input:
Get a dependency graph for the function `func`.
:param func: The Function object in CFG.function_manager.
:returns: A networkx.DiGraph instance.
### Response:
def function_dependency_graph(self, func):
"""
Ge... |
def get_cost_estimates(
self,
start_latitude,
start_longitude,
end_latitude=None,
end_longitude=None,
ride_type=None,
):
"""Get cost estimates (in cents) for rides at a given location.
Parameters
start_latitude (float)
The l... | Get cost estimates (in cents) for rides at a given location.
Parameters
start_latitude (float)
The latitude component of a start location.
start_longitude (float)
The longitude component of a start location.
end_latitude (float)
... | Below is the the instruction that describes the task:
### Input:
Get cost estimates (in cents) for rides at a given location.
Parameters
start_latitude (float)
The latitude component of a start location.
start_longitude (float)
The longitude component ... |
def static(type='artist', artist_pick='song_hotttnesss-desc', variety=.5, artist_id=None, artist=None, song_id=None,
track_id=None, description=None, style=None, mood=None, results=15, max_tempo=None, min_tempo=None,
max_duration=None, min_duration=None, max_loudness=None, min_loudness=None, max_d... | Get a static playlist
Args:
Kwargs:
type (str): a string representing the playlist type ('artist', 'artist-radio', ...)
artist_pick (str): How songs should be chosen for each artist
variety (float): A number between 0 and 1 specifying the variety of the playli... | Below is the the instruction that describes the task:
### Input:
Get a static playlist
Args:
Kwargs:
type (str): a string representing the playlist type ('artist', 'artist-radio', ...)
artist_pick (str): How songs should be chosen for each artist
variety (... |
def generate(self, chars, format='png'):
"""Generate an Image Captcha of the given characters.
:param chars: text to be generated.
:param format: image file format
"""
im = self.generate_image(chars)
out = BytesIO()
im.save(out, format=format)
out.seek(0)... | Generate an Image Captcha of the given characters.
:param chars: text to be generated.
:param format: image file format | Below is the the instruction that describes the task:
### Input:
Generate an Image Captcha of the given characters.
:param chars: text to be generated.
:param format: image file format
### Response:
def generate(self, chars, format='png'):
"""Generate an Image Captcha of the given characte... |
def read(self, size=-1):
"""Read `size` bytes from the reader relative to the parsed output.
This is generally acceptable in practice since VCF lines are
condensed, but if the output line <<< record, this means the actual
memory used will be much greater than `size`.
"""
... | Read `size` bytes from the reader relative to the parsed output.
This is generally acceptable in practice since VCF lines are
condensed, but if the output line <<< record, this means the actual
memory used will be much greater than `size`. | Below is the the instruction that describes the task:
### Input:
Read `size` bytes from the reader relative to the parsed output.
This is generally acceptable in practice since VCF lines are
condensed, but if the output line <<< record, this means the actual
memory used will be much greater ... |
def single_node_env(args):
"""Sets up environment for a single-node TF session.
Args:
:args: command line arguments as either argparse args or argv list
"""
# setup ARGV for the TF process
if isinstance(args, list):
sys.argv = args
elif args.argv:
sys.argv = args.argv
# setup ENV for Had... | Sets up environment for a single-node TF session.
Args:
:args: command line arguments as either argparse args or argv list | Below is the the instruction that describes the task:
### Input:
Sets up environment for a single-node TF session.
Args:
:args: command line arguments as either argparse args or argv list
### Response:
def single_node_env(args):
"""Sets up environment for a single-node TF session.
Args:
:args: comm... |
def asML(self):
"""
Convert this matrix to the new mllib-local representation.
This does NOT copy the data; it copies references.
:return: :py:class:`pyspark.ml.linalg.DenseMatrix`
.. versionadded:: 2.0.0
"""
return newlinalg.DenseMatrix(self.numRows, self.numCo... | Convert this matrix to the new mllib-local representation.
This does NOT copy the data; it copies references.
:return: :py:class:`pyspark.ml.linalg.DenseMatrix`
.. versionadded:: 2.0.0 | Below is the the instruction that describes the task:
### Input:
Convert this matrix to the new mllib-local representation.
This does NOT copy the data; it copies references.
:return: :py:class:`pyspark.ml.linalg.DenseMatrix`
.. versionadded:: 2.0.0
### Response:
def asML(self):
"... |
def process_sub_grow(ref, alt_str):
"""Process substution where the string grows"""
if len(alt_str) == 0:
raise exceptions.InvalidRecordException("Invalid VCF, empty ALT")
elif len(alt_str) == 1:
if ref[0] == alt_str[0]:
return record.Substitution(record.DEL, alt_str)
els... | Process substution where the string grows | Below is the the instruction that describes the task:
### Input:
Process substution where the string grows
### Response:
def process_sub_grow(ref, alt_str):
"""Process substution where the string grows"""
if len(alt_str) == 0:
raise exceptions.InvalidRecordException("Invalid VCF, empty ALT")
el... |
def get_value(value):
""" quoted-string / attribute
"""
v = Value()
if not value:
raise errors.HeaderParseError("Expected value but found end of string")
leader = None
if value[0] in CFWS_LEADER:
leader, value = get_cfws(value)
if not value:
raise errors.HeaderParseE... | quoted-string / attribute | Below is the the instruction that describes the task:
### Input:
quoted-string / attribute
### Response:
def get_value(value):
""" quoted-string / attribute
"""
v = Value()
if not value:
raise errors.HeaderParseError("Expected value but found end of string")
leader = None
if value[... |
def process_config(self, grab):
"""
Setup curl instance with values from ``self.config``.
"""
# Copy some config for future usage
self.config_nobody = grab.config['nobody']
self.config_body_maxsize = grab.config['body_maxsize']
try:
request_url = nor... | Setup curl instance with values from ``self.config``. | Below is the the instruction that describes the task:
### Input:
Setup curl instance with values from ``self.config``.
### Response:
def process_config(self, grab):
"""
Setup curl instance with values from ``self.config``.
"""
# Copy some config for future usage
self.config... |
def generator_telling_position(self) -> Iterator[Tuple[str, int]]:
"""
Create a generate that iterates the whole content of the file or string, and also tells which offset is now.
:return: An iterator iterating tuples, containing lines of the text stream,...
separated by ``'\\n'`` o... | Create a generate that iterates the whole content of the file or string, and also tells which offset is now.
:return: An iterator iterating tuples, containing lines of the text stream,...
separated by ``'\\n'`` or ``'\\r'``; and the offset (in bytes) of current line. | Below is the the instruction that describes the task:
### Input:
Create a generate that iterates the whole content of the file or string, and also tells which offset is now.
:return: An iterator iterating tuples, containing lines of the text stream,...
separated by ``'\\n'`` or ``'\\r'``; and t... |
def get_user(self, id = None):
""" Get user.
Returns:
:class:`User`. User
"""
if not id:
id = self._user.id
if id not in self._users:
self._users[id] = self._user if id == self._user.id else User(self, id)
return self._users[id] | Get user.
Returns:
:class:`User`. User | Below is the the instruction that describes the task:
### Input:
Get user.
Returns:
:class:`User`. User
### Response:
def get_user(self, id = None):
""" Get user.
Returns:
:class:`User`. User
"""
if not id:
id = self._user.id
if... |
def _ConvertValueMessage(value, message):
"""Convert a JSON representation into Value message."""
if isinstance(value, dict):
_ConvertStructMessage(value, message.struct_value)
elif isinstance(value, list):
_ConvertListValueMessage(value, message.list_value)
elif value is None:
message.null_value = ... | Convert a JSON representation into Value message. | Below is the the instruction that describes the task:
### Input:
Convert a JSON representation into Value message.
### Response:
def _ConvertValueMessage(value, message):
"""Convert a JSON representation into Value message."""
if isinstance(value, dict):
_ConvertStructMessage(value, message.struct_value)
... |
def parse_clnsig(acc, sig, revstat, transcripts):
"""Get the clnsig information
Args:
acc(str): The clnsig accession number, raw from vcf
sig(str): The clnsig significance score, raw from vcf
revstat(str): The clnsig revstat, raw from vcf
transcripts(iterable(dict))
Returns... | Get the clnsig information
Args:
acc(str): The clnsig accession number, raw from vcf
sig(str): The clnsig significance score, raw from vcf
revstat(str): The clnsig revstat, raw from vcf
transcripts(iterable(dict))
Returns:
clnsig_accsessions(list): A list with clnsig ac... | Below is the the instruction that describes the task:
### Input:
Get the clnsig information
Args:
acc(str): The clnsig accession number, raw from vcf
sig(str): The clnsig significance score, raw from vcf
revstat(str): The clnsig revstat, raw from vcf
transcripts(iterable(dict))
... |
def _chk_flds_fmt(nt_fields, prtfmt):
"""Check that all fields in the prtfmt have corresponding data in the namedtuple."""
fmtflds = get_fmtflds(prtfmt)
missing_data = set(fmtflds).difference(set(nt_fields))
# All data needed for print is present, return.
if not missing_data:
return
#rai... | Check that all fields in the prtfmt have corresponding data in the namedtuple. | Below is the the instruction that describes the task:
### Input:
Check that all fields in the prtfmt have corresponding data in the namedtuple.
### Response:
def _chk_flds_fmt(nt_fields, prtfmt):
"""Check that all fields in the prtfmt have corresponding data in the namedtuple."""
fmtflds = get_fmtflds(prtf... |
def string_class(cls):
"""Define __unicode__ and __str__ methods on the given class in Python 2.
The given class must define a __str__ method returning a unicode string,
otherwise a TypeError is raised.
Under Python 3, the class is returned as is.
"""
if not PY3:
if '__str__' not in cls... | Define __unicode__ and __str__ methods on the given class in Python 2.
The given class must define a __str__ method returning a unicode string,
otherwise a TypeError is raised.
Under Python 3, the class is returned as is. | Below is the the instruction that describes the task:
### Input:
Define __unicode__ and __str__ methods on the given class in Python 2.
The given class must define a __str__ method returning a unicode string,
otherwise a TypeError is raised.
Under Python 3, the class is returned as is.
### Response:
d... |
def run(self, args):
"""
Main entry point of script
"""
changes_detected = self.detect_changes()
message = self.get_message(changes_detected)
print(message)
return int(changes_detected) | Main entry point of script | Below is the the instruction that describes the task:
### Input:
Main entry point of script
### Response:
def run(self, args):
"""
Main entry point of script
"""
changes_detected = self.detect_changes()
message = self.get_message(changes_detected)
print(message)
... |
def __step3(self):
"""
Cover each column containing a starred zero. If K columns are
covered, the starred zeros describe a complete set of unique
assignments. In this case, Go to DONE, otherwise, Go to Step 4.
"""
n = self.n
count = 0
for i in range(n):
... | Cover each column containing a starred zero. If K columns are
covered, the starred zeros describe a complete set of unique
assignments. In this case, Go to DONE, otherwise, Go to Step 4. | Below is the the instruction that describes the task:
### Input:
Cover each column containing a starred zero. If K columns are
covered, the starred zeros describe a complete set of unique
assignments. In this case, Go to DONE, otherwise, Go to Step 4.
### Response:
def __step3(self):
"""
... |
def pretty_bytes(num):
""" pretty print the given number of bytes """
for unit in ['', 'KB', 'MB', 'GB']:
if num < 1024.0:
if unit == '':
return "%d" % (num)
else:
return "%3.1f%s" % (num, unit)
num /= 1024.0
return "%3.1f%s" % (num, 'T... | pretty print the given number of bytes | Below is the the instruction that describes the task:
### Input:
pretty print the given number of bytes
### Response:
def pretty_bytes(num):
""" pretty print the given number of bytes """
for unit in ['', 'KB', 'MB', 'GB']:
if num < 1024.0:
if unit == '':
return "%d" % (... |
def getWhoisInfo(domain):
"""
Method that trie to recover the whois info from a domain.
Args:
-----
domain: The domain to verify.
Returns:
--------
dict: A dictionary containing the result as an i3visio entity with its
`value`, `type` and `attributes`.
"""
n... | Method that trie to recover the whois info from a domain.
Args:
-----
domain: The domain to verify.
Returns:
--------
dict: A dictionary containing the result as an i3visio entity with its
`value`, `type` and `attributes`. | Below is the the instruction that describes the task:
### Input:
Method that trie to recover the whois info from a domain.
Args:
-----
domain: The domain to verify.
Returns:
--------
dict: A dictionary containing the result as an i3visio entity with its
`value`, `type` ... |
def months_int(self):
"""A sorted list of months of the year in this analysis period as integers."""
if not self._is_reversed:
return list(xrange(self.st_time.month, self.end_time.month + 1))
else:
months_st = list(xrange(self.st_time.month, 13))
months_end = ... | A sorted list of months of the year in this analysis period as integers. | Below is the the instruction that describes the task:
### Input:
A sorted list of months of the year in this analysis period as integers.
### Response:
def months_int(self):
"""A sorted list of months of the year in this analysis period as integers."""
if not self._is_reversed:
return l... |
def validate(self):
""" validate: Makes sure video is valid
Args: None
Returns: boolean indicating if video is valid
"""
from .files import VideoFile, WebVideoFile
try:
assert self.kind == content_kinds.VIDEO, "Assumption Failed: Node should be a video... | validate: Makes sure video is valid
Args: None
Returns: boolean indicating if video is valid | Below is the the instruction that describes the task:
### Input:
validate: Makes sure video is valid
Args: None
Returns: boolean indicating if video is valid
### Response:
def validate(self):
""" validate: Makes sure video is valid
Args: None
Returns: boolean... |
def data(self):
"""Fetch latest data from PyPI, and cache for 30s."""
key = cache_key(self.name)
data = cache.get(key)
if data is None:
logger.debug("Updating package info for %s from PyPI.", self.name)
data = requests.get(self.url).json()
cache.set(ke... | Fetch latest data from PyPI, and cache for 30s. | Below is the the instruction that describes the task:
### Input:
Fetch latest data from PyPI, and cache for 30s.
### Response:
def data(self):
"""Fetch latest data from PyPI, and cache for 30s."""
key = cache_key(self.name)
data = cache.get(key)
if data is None:
logger.d... |
def _get_update_method(self):
"""Return the HTTP method to use.
Returns:
object: http_put (default) or http_post
"""
if getattr(self, '_update_uses_post', False):
http_method = self.gitlab.http_post
else:
http_method = self.gitlab.http_put
... | Return the HTTP method to use.
Returns:
object: http_put (default) or http_post | Below is the the instruction that describes the task:
### Input:
Return the HTTP method to use.
Returns:
object: http_put (default) or http_post
### Response:
def _get_update_method(self):
"""Return the HTTP method to use.
Returns:
object: http_put (default) or htt... |
def get_with_steps(self, name, start, step):
r"""Get a color table from the registry with a corresponding norm.
Builds a `matplotlib.colors.BoundaryNorm` using `start`, `step`, and
the number of colors, based on the color table obtained from `name`.
Parameters
----------
... | r"""Get a color table from the registry with a corresponding norm.
Builds a `matplotlib.colors.BoundaryNorm` using `start`, `step`, and
the number of colors, based on the color table obtained from `name`.
Parameters
----------
name : str
The name under which the col... | Below is the the instruction that describes the task:
### Input:
r"""Get a color table from the registry with a corresponding norm.
Builds a `matplotlib.colors.BoundaryNorm` using `start`, `step`, and
the number of colors, based on the color table obtained from `name`.
Parameters
-... |
def hitail(E: np.ndarray, diffnumflux: np.ndarray, isimE0: np.ndarray, E0: np.ndarray,
Bhf: np.ndarray, bh: float, verbose: int = 0):
"""
strickland 1993 said 0.2, but 0.145 gives better match to peak flux at 2500 = E0
"""
Bh = np.empty_like(E0)
for iE0 in np.arange(E0.size):
Bh[i... | strickland 1993 said 0.2, but 0.145 gives better match to peak flux at 2500 = E0 | Below is the the instruction that describes the task:
### Input:
strickland 1993 said 0.2, but 0.145 gives better match to peak flux at 2500 = E0
### Response:
def hitail(E: np.ndarray, diffnumflux: np.ndarray, isimE0: np.ndarray, E0: np.ndarray,
Bhf: np.ndarray, bh: float, verbose: int = 0):
"""
... |
def pointlist(points, sr):
"""Convert a list of the form [[x, y] ...] to a list of Point instances
with the given x, y coordinates."""
assert all(isinstance(pt, Point) or len(pt) == 2
for pt in points), "Point(s) not in [x, y] form"
return [coord if isinstance(coord, Point)
... | Convert a list of the form [[x, y] ...] to a list of Point instances
with the given x, y coordinates. | Below is the the instruction that describes the task:
### Input:
Convert a list of the form [[x, y] ...] to a list of Point instances
with the given x, y coordinates.
### Response:
def pointlist(points, sr):
"""Convert a list of the form [[x, y] ...] to a list of Point instances
with the given x,... |
def register_to_sys_with_admin_list(class_inst, admin_list=None, is_normal_admin_needed=False):
"""
:param class_inst: model class
:param admin_list: admin class
:param is_normal_admin_needed: is normal admin registration needed
:return:
"""
if admin_list is None:
admin_class = get_v... | :param class_inst: model class
:param admin_list: admin class
:param is_normal_admin_needed: is normal admin registration needed
:return: | Below is the the instruction that describes the task:
### Input:
:param class_inst: model class
:param admin_list: admin class
:param is_normal_admin_needed: is normal admin registration needed
:return:
### Response:
def register_to_sys_with_admin_list(class_inst, admin_list=None, is_normal_admin_neede... |
def parse_string(contents, name='tmp.cpp', **kwargs):
""" Parse a string of C/C++ code
"""
idx = clang.cindex.Index.create()
tu = idx.parse(name, unsaved_files=[(name, contents)], **kwargs)
return _ensure_parse_valid(tu) | Parse a string of C/C++ code | Below is the the instruction that describes the task:
### Input:
Parse a string of C/C++ code
### Response:
def parse_string(contents, name='tmp.cpp', **kwargs):
""" Parse a string of C/C++ code
"""
idx = clang.cindex.Index.create()
tu = idx.parse(name, unsaved_files=[(name, contents)], **kwargs)
... |
def get_as_html(self) -> str:
"""
Returns the table object as an HTML string.
:return: HTML representation of the table.
"""
table_string = self._get_pretty_table().get_html_string()
title = ('{:^' + str(len(table_string.splitlines()[0])) + '}').format(self.title)
... | Returns the table object as an HTML string.
:return: HTML representation of the table. | Below is the the instruction that describes the task:
### Input:
Returns the table object as an HTML string.
:return: HTML representation of the table.
### Response:
def get_as_html(self) -> str:
"""
Returns the table object as an HTML string.
:return: HTML representation of the t... |
def write_script(self, script_name, contents, mode="t", blockers=()):
"""Write an executable file to the scripts directory"""
self.delete_blockers( # clean up old .py/.pyw w/o a script
[os.path.join(self.script_dir, x) for x in blockers]
)
log.info("Installing %s script to %... | Write an executable file to the scripts directory | Below is the the instruction that describes the task:
### Input:
Write an executable file to the scripts directory
### Response:
def write_script(self, script_name, contents, mode="t", blockers=()):
"""Write an executable file to the scripts directory"""
self.delete_blockers( # clean up old .py/.p... |
def func_old_kwargs(a, b=None, **kwargs): # pylint: disable=invalid-name
"""Old function, defined with **kwargs."""
# We extract a specific optional parameter from **kwargs
try:
c = kwargs['c']
except KeyError:
c = None
return a, b, c | Old function, defined with **kwargs. | Below is the the instruction that describes the task:
### Input:
Old function, defined with **kwargs.
### Response:
def func_old_kwargs(a, b=None, **kwargs): # pylint: disable=invalid-name
"""Old function, defined with **kwargs."""
# We extract a specific optional parameter from **kwargs
try:
... |
def enable(self):
"""Return True|False if the AMP is enabled in the configuration file (enable=true|false)."""
ret = self.get('enable')
if ret is None:
return False
else:
return ret.lower().startswith('true') | Return True|False if the AMP is enabled in the configuration file (enable=true|false). | Below is the the instruction that describes the task:
### Input:
Return True|False if the AMP is enabled in the configuration file (enable=true|false).
### Response:
def enable(self):
"""Return True|False if the AMP is enabled in the configuration file (enable=true|false)."""
ret = self.get('enable... |
def common_time_extrator(self, string):
"""一般时间抽取,即年月日分别出现
Keyword arguments:
string -- 含有时间的文本,str类型
"""
try:
if not self.year_check:
str_year = int(re.search('(\d{4})年', string).group(1))
check_year = datetime.datetime.... | 一般时间抽取,即年月日分别出现
Keyword arguments:
string -- 含有时间的文本,str类型 | Below is the the instruction that describes the task:
### Input:
一般时间抽取,即年月日分别出现
Keyword arguments:
string -- 含有时间的文本,str类型
### Response:
def common_time_extrator(self, string):
"""一般时间抽取,即年月日分别出现
Keyword arguments:
string -- 含有时间的文本,str类型
... |
def privatesuffix(self, domain, accept_unknown=None):
""" Return shortest suffix assigned for an individual.
domain: str or unicode to parse. (Required)
accept_unknown: bool, assume unknown TLDs to be public suffix. (Default: object default)
Return None if domain has invalid format.
... | Return shortest suffix assigned for an individual.
domain: str or unicode to parse. (Required)
accept_unknown: bool, assume unknown TLDs to be public suffix. (Default: object default)
Return None if domain has invalid format.
Return None if domain has no private part. | Below is the the instruction that describes the task:
### Input:
Return shortest suffix assigned for an individual.
domain: str or unicode to parse. (Required)
accept_unknown: bool, assume unknown TLDs to be public suffix. (Default: object default)
Return None if domain has invalid format.... |
def set_cookie(self, cookie):
'''
Add a cookie to the remote chromium instance.
Passed value `cookie` must be an instance of `http.cookiejar.Cookie()`.
'''
# Function path: Network.setCookie
# Domain: Network
# Method name: setCookie
# WARNING: This function is marked 'Experimental'!
# Parameters:
... | Add a cookie to the remote chromium instance.
Passed value `cookie` must be an instance of `http.cookiejar.Cookie()`. | Below is the the instruction that describes the task:
### Input:
Add a cookie to the remote chromium instance.
Passed value `cookie` must be an instance of `http.cookiejar.Cookie()`.
### Response:
def set_cookie(self, cookie):
'''
Add a cookie to the remote chromium instance.
Passed value `cookie` must b... |
def league_scores(self, total_data, time, show_upcoming, use_12_hour_format):
"""Store output of fixtures based on league and time to a CSV file"""
headers = ['League', 'Home Team Name', 'Home Team Goals',
'Away Team Goals', 'Away Team Name']
result = [headers]
league ... | Store output of fixtures based on league and time to a CSV file | Below is the the instruction that describes the task:
### Input:
Store output of fixtures based on league and time to a CSV file
### Response:
def league_scores(self, total_data, time, show_upcoming, use_12_hour_format):
"""Store output of fixtures based on league and time to a CSV file"""
headers ... |
def create_keyspace_network_topology(name, dc_replication_map, durable_writes=True, connections=None):
"""
Creates a keyspace with NetworkTopologyStrategy for replica placement
If the keyspace already exists, it will not be modified.
**This function should be used with caution, especially in productio... | Creates a keyspace with NetworkTopologyStrategy for replica placement
If the keyspace already exists, it will not be modified.
**This function should be used with caution, especially in production environments.
Take care to execute schema modifications in a single context (i.e. not concurrently with other... | Below is the the instruction that describes the task:
### Input:
Creates a keyspace with NetworkTopologyStrategy for replica placement
If the keyspace already exists, it will not be modified.
**This function should be used with caution, especially in production environments.
Take care to execute schem... |
def setDateTimeEnd(self, dtime):
"""
Sets the endiing date time for this gantt chart.
:param dtime | <QDateTime>
"""
self._dateEnd = dtime.date()
if self.timescale() in (self.Timescale.Minute, self.Timescale.Hour):
self._timeEnd... | Sets the endiing date time for this gantt chart.
:param dtime | <QDateTime> | Below is the the instruction that describes the task:
### Input:
Sets the endiing date time for this gantt chart.
:param dtime | <QDateTime>
### Response:
def setDateTimeEnd(self, dtime):
"""
Sets the endiing date time for this gantt chart.
:param d... |
def sha1sum_file(filename):
'''
Return the secure hash digest with sha1 algorithm for a given file
>>> from timeside.core.tools.test_samples import samples
>>> wav_file = samples["C4_scale.wav"]
>>> print sha1sum_file(wav_file)
a598e78d0b5c90da54a77e34c083abdcd38d42ba
'''
import hashlib... | Return the secure hash digest with sha1 algorithm for a given file
>>> from timeside.core.tools.test_samples import samples
>>> wav_file = samples["C4_scale.wav"]
>>> print sha1sum_file(wav_file)
a598e78d0b5c90da54a77e34c083abdcd38d42ba | Below is the the instruction that describes the task:
### Input:
Return the secure hash digest with sha1 algorithm for a given file
>>> from timeside.core.tools.test_samples import samples
>>> wav_file = samples["C4_scale.wav"]
>>> print sha1sum_file(wav_file)
a598e78d0b5c90da54a77e34c083abdcd38d42... |
def do_config(self,args):
"""
Deal with configuration. Available subcommands:
* config print - print the current configuration
* config reload - reload the current configuration from disk
* config set - change a setting in the configuration
* config save - save the confi... | Deal with configuration. Available subcommands:
* config print - print the current configuration
* config reload - reload the current configuration from disk
* config set - change a setting in the configuration
* config save - save the configuration to disk
config -h for more d... | Below is the the instruction that describes the task:
### Input:
Deal with configuration. Available subcommands:
* config print - print the current configuration
* config reload - reload the current configuration from disk
* config set - change a setting in the configuration
* confi... |
def assert_penaltymodel_factory_available():
"""For `dwavebinarycsp` to be functional, at least one penalty model factory
has to be installed. See discussion in setup.py for details.
"""
from pkg_resources import iter_entry_points
from penaltymodel.core import FACTORY_ENTRYPOINT
from itertools ... | For `dwavebinarycsp` to be functional, at least one penalty model factory
has to be installed. See discussion in setup.py for details. | Below is the the instruction that describes the task:
### Input:
For `dwavebinarycsp` to be functional, at least one penalty model factory
has to be installed. See discussion in setup.py for details.
### Response:
def assert_penaltymodel_factory_available():
"""For `dwavebinarycsp` to be functional, at lea... |
def write(connection, skip, directory, force):
"""Write a BEL namespace names/identifiers to terminology store."""
os.makedirs(directory, exist_ok=True)
from .manager.namespace_manager import BELNamespaceManagerMixin
for idx, name, manager in _iterate_managers(connection, skip):
if not (isinstan... | Write a BEL namespace names/identifiers to terminology store. | Below is the the instruction that describes the task:
### Input:
Write a BEL namespace names/identifiers to terminology store.
### Response:
def write(connection, skip, directory, force):
"""Write a BEL namespace names/identifiers to terminology store."""
os.makedirs(directory, exist_ok=True)
from .man... |
def reverse_action(self, action):
"""Transform an SC2-style action into an agent-style action.
This should be the inverse of `transform_action`.
Args:
action: a `sc_pb.Action` to be transformed.
Returns:
A corresponding `actions.FunctionCall`.
Raises:
ValueError: if it doesn't ... | Transform an SC2-style action into an agent-style action.
This should be the inverse of `transform_action`.
Args:
action: a `sc_pb.Action` to be transformed.
Returns:
A corresponding `actions.FunctionCall`.
Raises:
ValueError: if it doesn't know how to transform this action. | Below is the the instruction that describes the task:
### Input:
Transform an SC2-style action into an agent-style action.
This should be the inverse of `transform_action`.
Args:
action: a `sc_pb.Action` to be transformed.
Returns:
A corresponding `actions.FunctionCall`.
Raises:
... |
def cmd(command, *args, **kwargs):
'''
run commands from __proxy__
:mod:`salt.proxy.onyx<salt.proxy.onyx>`
command
function from `salt.proxy.onyx` to run
args
positional args to pass to `command` function
kwargs
key word arguments to pass to `command` function
.. ... | run commands from __proxy__
:mod:`salt.proxy.onyx<salt.proxy.onyx>`
command
function from `salt.proxy.onyx` to run
args
positional args to pass to `command` function
kwargs
key word arguments to pass to `command` function
.. code-block:: bash
salt '*' onyx.cmd se... | Below is the the instruction that describes the task:
### Input:
run commands from __proxy__
:mod:`salt.proxy.onyx<salt.proxy.onyx>`
command
function from `salt.proxy.onyx` to run
args
positional args to pass to `command` function
kwargs
key word arguments to pass to `comm... |
def alter_field(self, model, old_field, new_field, strict=False):
"""Ran when the configuration on a field changed."""
is_old_field_hstore = isinstance(old_field, HStoreField)
is_new_field_hstore = isinstance(new_field, HStoreField)
if not is_old_field_hstore and not is_new_field_hstor... | Ran when the configuration on a field changed. | Below is the the instruction that describes the task:
### Input:
Ran when the configuration on a field changed.
### Response:
def alter_field(self, model, old_field, new_field, strict=False):
"""Ran when the configuration on a field changed."""
is_old_field_hstore = isinstance(old_field, HStoreFie... |
def save(self, filename, driver=None, schema=None):
"""Saves collection to file.
"""
if driver is None:
driver = DRIVERS.get(os.path.splitext(filename)[-1])
if schema is None:
schema = self.schema
if driver == "GeoJSON":
# Workaround for htt... | Saves collection to file. | Below is the the instruction that describes the task:
### Input:
Saves collection to file.
### Response:
def save(self, filename, driver=None, schema=None):
"""Saves collection to file.
"""
if driver is None:
driver = DRIVERS.get(os.path.splitext(filename)[-1])
if sche... |
def desc(self):
"""str: The Sonos descriptor to use for this service.
The Sonos descriptor is used as the content of the <desc> tag in
DIDL metadata, to indicate the relevant music service id and username.
"""
desc = "SA_RINCON{}_{}".format(
self.account.service_type... | str: The Sonos descriptor to use for this service.
The Sonos descriptor is used as the content of the <desc> tag in
DIDL metadata, to indicate the relevant music service id and username. | Below is the the instruction that describes the task:
### Input:
str: The Sonos descriptor to use for this service.
The Sonos descriptor is used as the content of the <desc> tag in
DIDL metadata, to indicate the relevant music service id and username.
### Response:
def desc(self):
"""str: ... |
def unfinished_objects(self):
'''
Leaves only versions of those objects that has some version with
`_end == None` or with `_end > right cutoff`.
'''
mask = self._end_isnull
if self._rbound is not None:
mask = mask | (self._end > self._rbound)
oids = se... | Leaves only versions of those objects that has some version with
`_end == None` or with `_end > right cutoff`. | Below is the the instruction that describes the task:
### Input:
Leaves only versions of those objects that has some version with
`_end == None` or with `_end > right cutoff`.
### Response:
def unfinished_objects(self):
'''
Leaves only versions of those objects that has some version with
... |
def gen_WS_DF(df_WS_data):
"""generate DataFrame of weighted sums.
Parameters
----------
df_WS_data : type
Description of parameter `df_WS_data`.
Returns
-------
type
Description of returned object.
"""
df_fs = gen_FS_DF(df_WS_data)
list_index = [('mean', 'T2'... | generate DataFrame of weighted sums.
Parameters
----------
df_WS_data : type
Description of parameter `df_WS_data`.
Returns
-------
type
Description of returned object. | Below is the the instruction that describes the task:
### Input:
generate DataFrame of weighted sums.
Parameters
----------
df_WS_data : type
Description of parameter `df_WS_data`.
Returns
-------
type
Description of returned object.
### Response:
def gen_WS_DF(df_WS_data)... |
def list_all_states(cls, **kwargs):
"""List States
Return a list of States
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.list_all_states(async=True)
>>> result = thread.get()
... | List States
Return a list of States
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.list_all_states(async=True)
>>> result = thread.get()
:param async bool
:param int page: pa... | Below is the the instruction that describes the task:
### Input:
List States
Return a list of States
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.list_all_states(async=True)
>>> result ... |
def using_hg(cwd):
"""Test whether the directory cwd is contained in a mercurial
repository."""
try:
hg_log = shell_out(["hg", "log"], cwd=cwd)
return True
except (CalledProcessError, OSError):
return False | Test whether the directory cwd is contained in a mercurial
repository. | Below is the the instruction that describes the task:
### Input:
Test whether the directory cwd is contained in a mercurial
repository.
### Response:
def using_hg(cwd):
"""Test whether the directory cwd is contained in a mercurial
repository."""
try:
hg_log = shell_out(["hg", "log"], cwd=... |
def handleResponsePart(self, buffer):
"""
Sends the content to the browser and keeps a local copy of it.
buffer is just a str of the content to be shown, father is the intial
request.
"""
self.father.write(buffer)
self.buffer.write(buffer) | Sends the content to the browser and keeps a local copy of it.
buffer is just a str of the content to be shown, father is the intial
request. | Below is the the instruction that describes the task:
### Input:
Sends the content to the browser and keeps a local copy of it.
buffer is just a str of the content to be shown, father is the intial
request.
### Response:
def handleResponsePart(self, buffer):
"""
Sends the content to... |
def __minowski_low_positive_integer_p(h1, h2, p = 2): # 11..43 us for p = 1..24 \w 100 bins
"""
A faster implementation of the Minowski distance for positive integer < 25.
@note do not use this function directly, but the general @link minowski() method.
@note the passed histograms must be scipy arrays.
... | A faster implementation of the Minowski distance for positive integer < 25.
@note do not use this function directly, but the general @link minowski() method.
@note the passed histograms must be scipy arrays. | Below is the the instruction that describes the task:
### Input:
A faster implementation of the Minowski distance for positive integer < 25.
@note do not use this function directly, but the general @link minowski() method.
@note the passed histograms must be scipy arrays.
### Response:
def __minowski_low_p... |
def batch_iterable(iterable, count):
"""
Yield batches of `count` items from the given iterable.
>>> for x in batch([1, 2, 3, 4, 5, 6, 7], 3):
>>> print(x)
[1, 2, 3]
[4, 5, 6]
[7]
:param iterable: An iterable
:type iterable: Iterable
:param count: Number of items per batch. I... | Yield batches of `count` items from the given iterable.
>>> for x in batch([1, 2, 3, 4, 5, 6, 7], 3):
>>> print(x)
[1, 2, 3]
[4, 5, 6]
[7]
:param iterable: An iterable
:type iterable: Iterable
:param count: Number of items per batch. If <= 0, nothing is yielded.
:type count: int
... | Below is the the instruction that describes the task:
### Input:
Yield batches of `count` items from the given iterable.
>>> for x in batch([1, 2, 3, 4, 5, 6, 7], 3):
>>> print(x)
[1, 2, 3]
[4, 5, 6]
[7]
:param iterable: An iterable
:type iterable: Iterable
:param count: Number o... |
def Change(self,cpu=None,memory=None,description=None,group_id=None):
"""Change existing server object.
One more more fields can be set and method will return with a requests
object for all queued activities. This is a convenience function - all
each of these changes requires a seperate API call. Some API ca... | Change existing server object.
One more more fields can be set and method will return with a requests
object for all queued activities. This is a convenience function - all
each of these changes requires a seperate API call. Some API calls are synchronous
(e.g. changing group ID or password) while others are... | Below is the the instruction that describes the task:
### Input:
Change existing server object.
One more more fields can be set and method will return with a requests
object for all queued activities. This is a convenience function - all
each of these changes requires a seperate API call. Some API calls ar... |
def _check_encoding(name, encoding_to_check, alternative_encoding, source=None):
"""
Check that ``encoding`` is a valid Python encoding
:param name: name under which the encoding is known to the user, e.g. 'default encoding'
:param encoding_to_check: name of the encoding to check, e.g. 'utf-8'
:para... | Check that ``encoding`` is a valid Python encoding
:param name: name under which the encoding is known to the user, e.g. 'default encoding'
:param encoding_to_check: name of the encoding to check, e.g. 'utf-8'
:param source: source where the encoding has been set, e.g. option name
:raise pygount.common.... | Below is the the instruction that describes the task:
### Input:
Check that ``encoding`` is a valid Python encoding
:param name: name under which the encoding is known to the user, e.g. 'default encoding'
:param encoding_to_check: name of the encoding to check, e.g. 'utf-8'
:param source: source where t... |
def main(argv=sys.argv[1:], loop=None):
"""Parse argument and setup main program loop."""
args = docopt(__doc__, argv=argv,
version=pkg_resources.require('rflink')[0].version)
level = logging.ERROR
if args['-v']:
level = logging.INFO
if args['-v'] == 2:
level = log... | Parse argument and setup main program loop. | Below is the the instruction that describes the task:
### Input:
Parse argument and setup main program loop.
### Response:
def main(argv=sys.argv[1:], loop=None):
"""Parse argument and setup main program loop."""
args = docopt(__doc__, argv=argv,
version=pkg_resources.require('rflink')[0]... |
def get_agent_cloud_requests(self, agent_cloud_id):
"""GetAgentCloudRequests.
[Preview API]
:param int agent_cloud_id:
:rtype: [TaskAgentCloudRequest]
"""
route_values = {}
if agent_cloud_id is not None:
route_values['agentCloudId'] = self._serialize.u... | GetAgentCloudRequests.
[Preview API]
:param int agent_cloud_id:
:rtype: [TaskAgentCloudRequest] | Below is the the instruction that describes the task:
### Input:
GetAgentCloudRequests.
[Preview API]
:param int agent_cloud_id:
:rtype: [TaskAgentCloudRequest]
### Response:
def get_agent_cloud_requests(self, agent_cloud_id):
"""GetAgentCloudRequests.
[Preview API]
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.