code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def parseProfileLine(fp):
'''
Helper function for profile parsing
@param fp - the file pointer to get the next line from
@return - (kmer, kmerCount) as (string, int)
'''
nextLine = fp.readline()
if nextLine == None or nextLine == '':
return (None, None)
else:
pieces = nex... | Helper function for profile parsing
@param fp - the file pointer to get the next line from
@return - (kmer, kmerCount) as (string, int) | Below is the the instruction that describes the task:
### Input:
Helper function for profile parsing
@param fp - the file pointer to get the next line from
@return - (kmer, kmerCount) as (string, int)
### Response:
def parseProfileLine(fp):
'''
Helper function for profile parsing
@param fp - th... |
def lev_bounds(self):
"""Pressure levels at grid interfaces (hPa or mb)
:getter: Returns the bounds of axis ``'lev'`` if availible in the
process's domains.
:type: array
:raises: :exc:`ValueError`
if no ``'lev'`` axis can be found.
... | Pressure levels at grid interfaces (hPa or mb)
:getter: Returns the bounds of axis ``'lev'`` if availible in the
process's domains.
:type: array
:raises: :exc:`ValueError`
if no ``'lev'`` axis can be found. | Below is the the instruction that describes the task:
### Input:
Pressure levels at grid interfaces (hPa or mb)
:getter: Returns the bounds of axis ``'lev'`` if availible in the
process's domains.
:type: array
:raises: :exc:`ValueError`
if no ... |
def covars_(self):
"""Return covars as a full matrix."""
return fill_covars(self._covars_, self.covariance_type,
self.n_components, self.n_features) | Return covars as a full matrix. | Below is the the instruction that describes the task:
### Input:
Return covars as a full matrix.
### Response:
def covars_(self):
"""Return covars as a full matrix."""
return fill_covars(self._covars_, self.covariance_type,
self.n_components, self.n_features) |
def create(self, recording_status_callback_event=values.unset,
recording_status_callback=values.unset,
recording_status_callback_method=values.unset, trim=values.unset,
recording_channels=values.unset):
"""
Create a new RecordingInstance
:param unico... | Create a new RecordingInstance
:param unicode recording_status_callback_event: The recording status changes that should generate a callback
:param unicode recording_status_callback: The callback URL on each selected recording event
:param unicode recording_status_callback_method: The HTTP metho... | Below is the the instruction that describes the task:
### Input:
Create a new RecordingInstance
:param unicode recording_status_callback_event: The recording status changes that should generate a callback
:param unicode recording_status_callback: The callback URL on each selected recording event
... |
def readDoc(cur, URL, encoding, options):
"""parse an XML in-memory document and build a tree. """
ret = libxml2mod.xmlReadDoc(cur, URL, encoding, options)
if ret is None:raise treeError('xmlReadDoc() failed')
return xmlDoc(_obj=ret) | parse an XML in-memory document and build a tree. | Below is the the instruction that describes the task:
### Input:
parse an XML in-memory document and build a tree.
### Response:
def readDoc(cur, URL, encoding, options):
"""parse an XML in-memory document and build a tree. """
ret = libxml2mod.xmlReadDoc(cur, URL, encoding, options)
if ret is None:rai... |
def get_trace_id_from_flask():
"""Get trace_id from flask request headers.
:rtype: str
:returns: TraceID in HTTP request headers.
"""
if flask is None or not flask.request:
return None
header = flask.request.headers.get(_FLASK_TRACE_HEADER)
if header is None:
return None
... | Get trace_id from flask request headers.
:rtype: str
:returns: TraceID in HTTP request headers. | Below is the the instruction that describes the task:
### Input:
Get trace_id from flask request headers.
:rtype: str
:returns: TraceID in HTTP request headers.
### Response:
def get_trace_id_from_flask():
"""Get trace_id from flask request headers.
:rtype: str
:returns: TraceID in HTTP reque... |
def MouseOver(cls):
''' 鼠标悬浮 '''
element = cls._element()
action = ActionChains(Web.driver)
action.move_to_element(element)
action.perform()
time.sleep(1) | 鼠标悬浮 | Below is the the instruction that describes the task:
### Input:
鼠标悬浮
### Response:
def MouseOver(cls):
''' 鼠标悬浮 '''
element = cls._element()
action = ActionChains(Web.driver)
action.move_to_element(element)
action.perform()
time.sleep(1) |
def _byte_buffer_md5(buffer_):
"""
Computes the md5 digest of a byte buffer in base64 encoding.
"""
md5 = hashlib.md5(buffer_)
byte_digest = md5.digest()
return base64.b64encode(byte_digest).decode() | Computes the md5 digest of a byte buffer in base64 encoding. | Below is the the instruction that describes the task:
### Input:
Computes the md5 digest of a byte buffer in base64 encoding.
### Response:
def _byte_buffer_md5(buffer_):
"""
Computes the md5 digest of a byte buffer in base64 encoding.
"""
md5 = hashlib.md5(buffer_)
byte_digest = md5.digest()
... |
def parse_dependencies(dependencies: List[List[str]],
patton_config: PattonRunningConfig) -> Dict:
"""This function try to find the better function to parser input banners
and parse it"""
result = {}
for source_type, source_content in dependencies:
# Select parser
... | This function try to find the better function to parser input banners
and parse it | Below is the the instruction that describes the task:
### Input:
This function try to find the better function to parser input banners
and parse it
### Response:
def parse_dependencies(dependencies: List[List[str]],
patton_config: PattonRunningConfig) -> Dict:
"""This function try to... |
def index_by_id(cls, target_id, resources):
"""Helper method to fetch the index of a resource by its id or address
Args:
resources (list of objects): The resources to be paginated
target_id (string): The address or header_signature of the resource
Returns:
i... | Helper method to fetch the index of a resource by its id or address
Args:
resources (list of objects): The resources to be paginated
target_id (string): The address or header_signature of the resource
Returns:
integer: The index of the target resource
Raise... | Below is the the instruction that describes the task:
### Input:
Helper method to fetch the index of a resource by its id or address
Args:
resources (list of objects): The resources to be paginated
target_id (string): The address or header_signature of the resource
Returns:... |
def polypeptide_vector(p, start_index=0, end_index=-1, unit=True):
"""Vector along the Chain primitive (default is from N-terminus to C-terminus).
Notes
-----
`start_index` and `end_index` can be changed to examine smaller
sections of the Chain, or reversed to change the direction of
the vector... | Vector along the Chain primitive (default is from N-terminus to C-terminus).
Notes
-----
`start_index` and `end_index` can be changed to examine smaller
sections of the Chain, or reversed to change the direction of
the vector.
Parameters
----------
p : ampal.Polymer
Reference `... | Below is the the instruction that describes the task:
### Input:
Vector along the Chain primitive (default is from N-terminus to C-terminus).
Notes
-----
`start_index` and `end_index` can be changed to examine smaller
sections of the Chain, or reversed to change the direction of
the vector.
... |
def _sigma_pi_hiE(self, Tp, a):
"""
General expression for Tp > 5 GeV (Eq 7)
"""
m_p = self._m_p
csip = (Tp - 3.0) / m_p
m1 = a[0] * csip ** a[3] * (1 + np.exp(-a[1] * csip ** a[4]))
m2 = 1 - np.exp(-a[2] * csip ** 0.25)
multip = m1 * m2
return sel... | General expression for Tp > 5 GeV (Eq 7) | Below is the the instruction that describes the task:
### Input:
General expression for Tp > 5 GeV (Eq 7)
### Response:
def _sigma_pi_hiE(self, Tp, a):
"""
General expression for Tp > 5 GeV (Eq 7)
"""
m_p = self._m_p
csip = (Tp - 3.0) / m_p
m1 = a[0] * csip ** a[3] *... |
def __add_symbols(self, cmd):
"""
Add all additional defined and undefined symbols.
"""
if self.__config.define_symbols:
symbols = self.__config.define_symbols
cmd.append(''.join(
[' -D"%s"' % def_symbol for def_symbol in symbols]))
if s... | Add all additional defined and undefined symbols. | Below is the the instruction that describes the task:
### Input:
Add all additional defined and undefined symbols.
### Response:
def __add_symbols(self, cmd):
"""
Add all additional defined and undefined symbols.
"""
if self.__config.define_symbols:
symbols = self.__co... |
def gc(self):
""" Garbage collect overflow and/or aged entries. """
manifest = []
overlimit = len(self.data) - self.maxsize \
if self.maxsize is not None else 0
now = self.ttl is not None and self.timer()
for key, entry in self.data.items():
if overlimit >... | Garbage collect overflow and/or aged entries. | Below is the the instruction that describes the task:
### Input:
Garbage collect overflow and/or aged entries.
### Response:
def gc(self):
""" Garbage collect overflow and/or aged entries. """
manifest = []
overlimit = len(self.data) - self.maxsize \
if self.maxsize is not None ... |
def p_boolean_expr(self, p):
'''boolean_expr : expr AND expr
| expr AMPERSAND expr
| expr OR expr
| expr IMPLY expr
| expr EQUIV expr
| NOT expr %prec UMINUS
| bool_typ... | boolean_expr : expr AND expr
| expr AMPERSAND expr
| expr OR expr
| expr IMPLY expr
| expr EQUIV expr
| NOT expr %prec UMINUS
| bool_type | Below is the the instruction that describes the task:
### Input:
boolean_expr : expr AND expr
| expr AMPERSAND expr
| expr OR expr
| expr IMPLY expr
| expr EQUIV expr
| NOT expr %prec UMINUS
... |
def discovery(self, logfile=None, tracefile=None):
"""Discover the device details.
This method discover several device attributes.
Args:
logfile (file): Optional file descriptor for session logging. The file must be open for write.
The session is logged only if ``lo... | Discover the device details.
This method discover several device attributes.
Args:
logfile (file): Optional file descriptor for session logging. The file must be open for write.
The session is logged only if ``log_session=True`` was passed to the constructor.
... | Below is the the instruction that describes the task:
### Input:
Discover the device details.
This method discover several device attributes.
Args:
logfile (file): Optional file descriptor for session logging. The file must be open for write.
The session is logged only ... |
def _prepare_filtering_params(domain=None, category=None,
sponsored_source=None, has_field=None,
has_fields=None, query_params_match=None,
query_person_match=None, **kwargs):
"""Transform the params to th... | Transform the params to the API format, return a list of params. | Below is the the instruction that describes the task:
### Input:
Transform the params to the API format, return a list of params.
### Response:
def _prepare_filtering_params(domain=None, category=None,
sponsored_source=None, has_field=None,
has... |
def from_url(url):
"""Creates an Eddystone_Frame with a Eddystone_URL for a given URL."""
url = url.encode('ascii')
scheme = None
for k, v in EDDYSTONE_URL_SCHEMES.items():
if url.startswith(v):
scheme = k
url = url[len(v):]
bre... | Creates an Eddystone_Frame with a Eddystone_URL for a given URL. | Below is the the instruction that describes the task:
### Input:
Creates an Eddystone_Frame with a Eddystone_URL for a given URL.
### Response:
def from_url(url):
"""Creates an Eddystone_Frame with a Eddystone_URL for a given URL."""
url = url.encode('ascii')
scheme = None
for k, v ... |
def _start(self):
"""Start the server."""
assert self._tempdir is not None
assert self._process is None
self._process = subprocess.Popen(
[
self.paths.slapd,
'-f', self._slapd_conf,
'-h', self.uri,
'-d', str(self... | Start the server. | Below is the the instruction that describes the task:
### Input:
Start the server.
### Response:
def _start(self):
"""Start the server."""
assert self._tempdir is not None
assert self._process is None
self._process = subprocess.Popen(
[
self.paths.slapd,
... |
def main() -> None:
"""Command-line wrapper to re-run a script whenever its source changes.
Scripts may be specified by filename or module name::
python -m tornado.autoreload -m tornado.test.runtests
python -m tornado.autoreload tornado/test/runtests.py
Running a script with this wrapper ... | Command-line wrapper to re-run a script whenever its source changes.
Scripts may be specified by filename or module name::
python -m tornado.autoreload -m tornado.test.runtests
python -m tornado.autoreload tornado/test/runtests.py
Running a script with this wrapper is similar to calling
`... | Below is the the instruction that describes the task:
### Input:
Command-line wrapper to re-run a script whenever its source changes.
Scripts may be specified by filename or module name::
python -m tornado.autoreload -m tornado.test.runtests
python -m tornado.autoreload tornado/test/runtests.p... |
def _parse(self, string):
"""Parse a string and return its features.
:param string: A one-symbol string in NFD
Notes
-----
Strategy is rather simple: we determine the base part of a string and
then search left and right of this part for the additional features as
... | Parse a string and return its features.
:param string: A one-symbol string in NFD
Notes
-----
Strategy is rather simple: we determine the base part of a string and
then search left and right of this part for the additional features as
expressed by the diacritics. Fails ... | Below is the the instruction that describes the task:
### Input:
Parse a string and return its features.
:param string: A one-symbol string in NFD
Notes
-----
Strategy is rather simple: we determine the base part of a string and
then search left and right of this part for t... |
def path_yield(path):
"""Yield on all path parts."""
for part in (x for x in path.strip(SEP).split(SEP) if x not in (None, '')):
yield part | Yield on all path parts. | Below is the the instruction that describes the task:
### Input:
Yield on all path parts.
### Response:
def path_yield(path):
"""Yield on all path parts."""
for part in (x for x in path.strip(SEP).split(SEP) if x not in (None, '')):
yield part |
def _check_for_pending(self, *args, **kwargs):
"""
Checks if a notification is pending.
"""
if self._notification_pending and not self._processing:
self._processing = True
args, kwargs = self._data
self._notify(*args, **kwargs)
self._notifi... | Checks if a notification is pending. | Below is the the instruction that describes the task:
### Input:
Checks if a notification is pending.
### Response:
def _check_for_pending(self, *args, **kwargs):
"""
Checks if a notification is pending.
"""
if self._notification_pending and not self._processing:
self._p... |
def seq_match(seq0, seq1):
"""True if seq0 is a subset of seq1 and their elements are in same order.
>>> seq_match([], [])
True
>>> seq_match([1], [1])
True
>>> seq_match([1, 1], [1])
False
>>> seq_match([1], [1, 2])
True
>>> seq_match([1, 1], [1, 1])
True
>>> seq_match(... | True if seq0 is a subset of seq1 and their elements are in same order.
>>> seq_match([], [])
True
>>> seq_match([1], [1])
True
>>> seq_match([1, 1], [1])
False
>>> seq_match([1], [1, 2])
True
>>> seq_match([1, 1], [1, 1])
True
>>> seq_match([3], [1, 2, 3])
True
>>> s... | Below is the the instruction that describes the task:
### Input:
True if seq0 is a subset of seq1 and their elements are in same order.
>>> seq_match([], [])
True
>>> seq_match([1], [1])
True
>>> seq_match([1, 1], [1])
False
>>> seq_match([1], [1, 2])
True
>>> seq_match([1, 1], ... |
def _get_key_info(self):
"""Get key info appropriate for signing."""
if self._key_info_cache is None:
self._key_info_cache = agent_key_info_from_key_id(self.key_id)
return self._key_info_cache | Get key info appropriate for signing. | Below is the the instruction that describes the task:
### Input:
Get key info appropriate for signing.
### Response:
def _get_key_info(self):
"""Get key info appropriate for signing."""
if self._key_info_cache is None:
self._key_info_cache = agent_key_info_from_key_id(self.key_id)
... |
def _visit_for(self, cls, node, parent):
"""visit a For node by returning a fresh instance of it"""
newnode = cls(node.lineno, node.col_offset, parent)
type_annotation = self.check_type_comment(node)
newnode.postinit(
target=self.visit(node.target, newnode),
iter=... | visit a For node by returning a fresh instance of it | Below is the the instruction that describes the task:
### Input:
visit a For node by returning a fresh instance of it
### Response:
def _visit_for(self, cls, node, parent):
"""visit a For node by returning a fresh instance of it"""
newnode = cls(node.lineno, node.col_offset, parent)
type_an... |
def fire_event(key, msg, tag, sock_dir, args=None, transport='zeromq'):
'''
Fire deploy action
'''
event = salt.utils.event.get_event(
'master',
sock_dir,
transport,
listen=False)
try:
event.fire_event(msg, tag)
except ValueError:
# We're using at... | Fire deploy action | Below is the the instruction that describes the task:
### Input:
Fire deploy action
### Response:
def fire_event(key, msg, tag, sock_dir, args=None, transport='zeromq'):
'''
Fire deploy action
'''
event = salt.utils.event.get_event(
'master',
sock_dir,
transport,
lis... |
def read_code(self, name):
"""Reads code from a python file called 'name'"""
file_path = self.gen_file_path(name)
with open(file_path) as f:
code = f.read()
return code | Reads code from a python file called 'name | Below is the the instruction that describes the task:
### Input:
Reads code from a python file called 'name
### Response:
def read_code(self, name):
"""Reads code from a python file called 'name'"""
file_path = self.gen_file_path(name)
with open(file_path) as f:
code = f.read()... |
def go_to_line(self, line):
"""
Moves the text cursor to given line.
:param line: Line to go to.
:type line: int
:return: Method success.
:rtype: bool
"""
cursor = self.textCursor()
cursor.setPosition(self.document().findBlockByNumber(line - 1).p... | Moves the text cursor to given line.
:param line: Line to go to.
:type line: int
:return: Method success.
:rtype: bool | Below is the the instruction that describes the task:
### Input:
Moves the text cursor to given line.
:param line: Line to go to.
:type line: int
:return: Method success.
:rtype: bool
### Response:
def go_to_line(self, line):
"""
Moves the text cursor to given line.... |
def _get_pipe_name(self):
"""
Returns the pipe name to create a serial connection.
:returns: pipe path (string)
"""
if sys.platform.startswith("win"):
pipe_name = r"\\.\pipe\gns3_vmware\{}".format(self.id)
else:
pipe_name = os.path.join(tempfile.... | Returns the pipe name to create a serial connection.
:returns: pipe path (string) | Below is the the instruction that describes the task:
### Input:
Returns the pipe name to create a serial connection.
:returns: pipe path (string)
### Response:
def _get_pipe_name(self):
"""
Returns the pipe name to create a serial connection.
:returns: pipe path (string)
... |
def check_function(
state,
name,
index=0,
missing_msg=None,
params_not_matched_msg=None,
expand_msg=None,
signature=True,
):
"""Check whether a particular function is called.
``check_function()`` is typically followed by:
- ``check_args()`` to check whether the arguments we... | Check whether a particular function is called.
``check_function()`` is typically followed by:
- ``check_args()`` to check whether the arguments were specified.
In turn, ``check_args()`` can be followed by ``has_equal_value()`` or ``has_equal_ast()``
to assert that the arguments were correctly ... | Below is the the instruction that describes the task:
### Input:
Check whether a particular function is called.
``check_function()`` is typically followed by:
- ``check_args()`` to check whether the arguments were specified.
In turn, ``check_args()`` can be followed by ``has_equal_value()`` or `... |
def rpc_get_name_history_page(self, name, page, **con_info):
"""
Get the list of history entries for a name or subdomain's history, paginated.
Small pages correspond to later history (page = 0 is the page of last updates)
Page size is 20 rows.
Return {'status': True, 'history': [... | Get the list of history entries for a name or subdomain's history, paginated.
Small pages correspond to later history (page = 0 is the page of last updates)
Page size is 20 rows.
Return {'status': True, 'history': [...]} on success
Return {'error': ...} on error | Below is the the instruction that describes the task:
### Input:
Get the list of history entries for a name or subdomain's history, paginated.
Small pages correspond to later history (page = 0 is the page of last updates)
Page size is 20 rows.
Return {'status': True, 'history': [...]} on suc... |
def unwrap_or(self, default: U) -> Union[T, U]:
"""
Returns the contained value or ``default``.
Args:
default: The default value.
Returns:
The contained value if the :py:class:`Option` is ``Some``,
otherwise ``default``.
Notes:
I... | Returns the contained value or ``default``.
Args:
default: The default value.
Returns:
The contained value if the :py:class:`Option` is ``Some``,
otherwise ``default``.
Notes:
If you wish to use a result of a function call as the default,
... | Below is the the instruction that describes the task:
### Input:
Returns the contained value or ``default``.
Args:
default: The default value.
Returns:
The contained value if the :py:class:`Option` is ``Some``,
otherwise ``default``.
Notes:
... |
def adopt(self, grab):
"""
Copy the state of another `Grab` instance.
Use case: create backup of current state to the cloned instance and
then restore the state from it.
"""
self.load_config(grab.config)
self.doc = grab.doc.copy(new_grab=self)
for key ... | Copy the state of another `Grab` instance.
Use case: create backup of current state to the cloned instance and
then restore the state from it. | Below is the the instruction that describes the task:
### Input:
Copy the state of another `Grab` instance.
Use case: create backup of current state to the cloned instance and
then restore the state from it.
### Response:
def adopt(self, grab):
"""
Copy the state of another `Grab` ... |
def exec_path(self, baseVersion=None):
"""Get the exec_path for this platform. Possibly find the latest build."""
if not os.path.isdir(self.data_dir):
raise sc_process.SC2LaunchError("Install Starcraft II at %s or set the SC2PATH environment variable"%(self.data_dir))
if baseVersion==None: # then se... | Get the exec_path for this platform. Possibly find the latest build. | Below is the the instruction that describes the task:
### Input:
Get the exec_path for this platform. Possibly find the latest build.
### Response:
def exec_path(self, baseVersion=None):
"""Get the exec_path for this platform. Possibly find the latest build."""
if not os.path.isdir(self.data_dir):
... |
def get_services(cls, request=None):
""" Get a list of services endpoints.
{
"Oracle": "/api/oracle/",
"OpenStack": "/api/openstack/",
"GitLab": "/api/gitlab/",
"DigitalOcean": "/api/digitalocean/"
}
"""
retu... | Get a list of services endpoints.
{
"Oracle": "/api/oracle/",
"OpenStack": "/api/openstack/",
"GitLab": "/api/gitlab/",
"DigitalOcean": "/api/digitalocean/"
} | Below is the the instruction that describes the task:
### Input:
Get a list of services endpoints.
{
"Oracle": "/api/oracle/",
"OpenStack": "/api/openstack/",
"GitLab": "/api/gitlab/",
"DigitalOcean": "/api/digitalocean/"
}
### ... |
def make_fout(fout='./tmp', fmt='pcap'):
"""Make root path for output.
Positional arguments:
* fout -- str, root path for output
* fmt -- str, output format
Returns:
* output -- dumper of specified format
"""
if fmt == 'pcap': # output... | Make root path for output.
Positional arguments:
* fout -- str, root path for output
* fmt -- str, output format
Returns:
* output -- dumper of specified format | Below is the the instruction that describes the task:
### Input:
Make root path for output.
Positional arguments:
* fout -- str, root path for output
* fmt -- str, output format
Returns:
* output -- dumper of specified format
### Response:
def make_fout(fout='.... |
def parse_connection_string(value):
"""Original Governor stores connection strings for each cluster members if a following format:
postgres://{username}:{password}@{connect_address}/postgres
Since each of our patroni instances provides own REST API endpoint it's good to store this information
in DCS... | Original Governor stores connection strings for each cluster members if a following format:
postgres://{username}:{password}@{connect_address}/postgres
Since each of our patroni instances provides own REST API endpoint it's good to store this information
in DCS among with postgresql connection string. I... | Below is the the instruction that describes the task:
### Input:
Original Governor stores connection strings for each cluster members if a following format:
postgres://{username}:{password}@{connect_address}/postgres
Since each of our patroni instances provides own REST API endpoint it's good to store t... |
def get_notifications(self, **params):
"""https://developers.coinbase.com/api/v2#list-notifications"""
response = self._get('v2', 'notifications', params=params)
return self._make_api_object(response, Notification) | https://developers.coinbase.com/api/v2#list-notifications | Below is the the instruction that describes the task:
### Input:
https://developers.coinbase.com/api/v2#list-notifications
### Response:
def get_notifications(self, **params):
"""https://developers.coinbase.com/api/v2#list-notifications"""
response = self._get('v2', 'notifications', params=params)
... |
def apply(request, task_name):
"""View applying a task.
**Note:** Please use this with caution. Preferably you shouldn't make this
publicly accessible without ensuring your code is safe!
"""
try:
task = tasks[task_name]
except KeyError:
raise Http404('apply: no such task')
... | View applying a task.
**Note:** Please use this with caution. Preferably you shouldn't make this
publicly accessible without ensuring your code is safe! | Below is the the instruction that describes the task:
### Input:
View applying a task.
**Note:** Please use this with caution. Preferably you shouldn't make this
publicly accessible without ensuring your code is safe!
### Response:
def apply(request, task_name):
"""View applying a task.
**Not... |
def QA_indicator_OSC(DataFrame, N=20, M=6):
"""变动速率线
震荡量指标OSC,也叫变动速率线。属于超买超卖类指标,是从移动平均线原理派生出来的一种分析指标。
它反应当日收盘价与一段时间内平均收盘价的差离值,从而测出股价的震荡幅度。
按照移动平均线原理,根据OSC的值可推断价格的趋势,如果远离平均线,就很可能向平均线回归。
"""
C = DataFrame['close']
OS = (C - MA(C, N)) * 100
MAOSC = EMA(OS, M)
DICT = {'OSC': OS, 'MAOS... | 变动速率线
震荡量指标OSC,也叫变动速率线。属于超买超卖类指标,是从移动平均线原理派生出来的一种分析指标。
它反应当日收盘价与一段时间内平均收盘价的差离值,从而测出股价的震荡幅度。
按照移动平均线原理,根据OSC的值可推断价格的趋势,如果远离平均线,就很可能向平均线回归。 | Below is the the instruction that describes the task:
### Input:
变动速率线
震荡量指标OSC,也叫变动速率线。属于超买超卖类指标,是从移动平均线原理派生出来的一种分析指标。
它反应当日收盘价与一段时间内平均收盘价的差离值,从而测出股价的震荡幅度。
按照移动平均线原理,根据OSC的值可推断价格的趋势,如果远离平均线,就很可能向平均线回归。
### Response:
def QA_indicator_OSC(DataFrame, N=20, M=6):
"""变动速率线
震荡量指标OSC,也叫变动速率线。属于超买... |
def alias_grade_system(self, grade_system_id, alias_id):
"""Adds an ``Id`` to a ``GradeSystem`` for the purpose of creating compatibility.
The primary ``Id`` of the ``GradeSystem`` is determined by the
provider. The new ``Id`` performs as an alias to the primary
``Id``. If the alias is ... | Adds an ``Id`` to a ``GradeSystem`` for the purpose of creating compatibility.
The primary ``Id`` of the ``GradeSystem`` is determined by the
provider. The new ``Id`` performs as an alias to the primary
``Id``. If the alias is a pointer to another grade system, it is
reassigned to the g... | Below is the the instruction that describes the task:
### Input:
Adds an ``Id`` to a ``GradeSystem`` for the purpose of creating compatibility.
The primary ``Id`` of the ``GradeSystem`` is determined by the
provider. The new ``Id`` performs as an alias to the primary
``Id``. If the alias is... |
def get_domain_and_port(self):
"""
Django's request.get_host() returns the requested host and possibly the
port number. Return a tuple of domain, port number.
Domain will be lowercased
"""
host = self.request.get_host()
if ':' in host:
domain, port = ... | Django's request.get_host() returns the requested host and possibly the
port number. Return a tuple of domain, port number.
Domain will be lowercased | Below is the the instruction that describes the task:
### Input:
Django's request.get_host() returns the requested host and possibly the
port number. Return a tuple of domain, port number.
Domain will be lowercased
### Response:
def get_domain_and_port(self):
"""
Django's request.g... |
def train_rdp_classifier(
training_seqs_file, taxonomy_file, model_output_dir, max_memory=None,
tmp_dir=tempfile.gettempdir()):
""" Train RDP Classifier, saving to model_output_dir
training_seqs_file, taxonomy_file: file-like objects used to
train the RDP Classifier (see RdpTrai... | Train RDP Classifier, saving to model_output_dir
training_seqs_file, taxonomy_file: file-like objects used to
train the RDP Classifier (see RdpTrainer documentation for
format of training data)
model_output_dir: directory in which to save the files
necessary to clas... | Below is the the instruction that describes the task:
### Input:
Train RDP Classifier, saving to model_output_dir
training_seqs_file, taxonomy_file: file-like objects used to
train the RDP Classifier (see RdpTrainer documentation for
format of training data)
model_output_di... |
def _to_dict(self):
"""Return a json dictionary representing this model."""
_dict = {}
if hasattr(self, 'document_id') and self.document_id is not None:
_dict['document_id'] = self.document_id
if hasattr(self, 'status') and self.status is not None:
_dict['status']... | Return a json dictionary representing this model. | Below is the the instruction that describes the task:
### Input:
Return a json dictionary representing this model.
### Response:
def _to_dict(self):
"""Return a json dictionary representing this model."""
_dict = {}
if hasattr(self, 'document_id') and self.document_id is not None:
... |
def filter(self, func):
"""Returns a SndRcv list filtered by a truth function"""
return self.__class__( [ i for i in self.res if func(*i) ], name='filtered %s'%self.listname) | Returns a SndRcv list filtered by a truth function | Below is the the instruction that describes the task:
### Input:
Returns a SndRcv list filtered by a truth function
### Response:
def filter(self, func):
"""Returns a SndRcv list filtered by a truth function"""
return self.__class__( [ i for i in self.res if func(*i) ], name='filtered %s'%self.list... |
def create_peptidequant_lookup(fns, pqdb, poolnames, pepseq_colnr,
ms1_qcolpattern=None, isobqcolpattern=None,
psmnrpattern=None, fdrcolpattern=None,
pepcolpattern=None):
"""Calls lower level function to create a peptide qu... | Calls lower level function to create a peptide quant lookup | Below is the the instruction that describes the task:
### Input:
Calls lower level function to create a peptide quant lookup
### Response:
def create_peptidequant_lookup(fns, pqdb, poolnames, pepseq_colnr,
ms1_qcolpattern=None, isobqcolpattern=None,
psm... |
def activate(self, engine):
"""
Activates the Component.
:param engine: Engine to attach the Component to.
:type engine: QObject
:return: Method success.
:rtype: bool
"""
LOGGER.debug("> Activating '{0}' Component.".format(self.__class__.__name__))
... | Activates the Component.
:param engine: Engine to attach the Component to.
:type engine: QObject
:return: Method success.
:rtype: bool | Below is the the instruction that describes the task:
### Input:
Activates the Component.
:param engine: Engine to attach the Component to.
:type engine: QObject
:return: Method success.
:rtype: bool
### Response:
def activate(self, engine):
"""
Activates the Compon... |
def fft_transpose_fftw(vec):
"""
Perform an FFT transpose from vec into outvec.
(Alex to provide more details in a write-up.)
Parameters
-----------
vec : array
Input array.
Returns
--------
outvec : array
Transposed output array.
"""
global _thetransposepla... | Perform an FFT transpose from vec into outvec.
(Alex to provide more details in a write-up.)
Parameters
-----------
vec : array
Input array.
Returns
--------
outvec : array
Transposed output array. | Below is the the instruction that describes the task:
### Input:
Perform an FFT transpose from vec into outvec.
(Alex to provide more details in a write-up.)
Parameters
-----------
vec : array
Input array.
Returns
--------
outvec : array
Transposed output array.
### Res... |
def pack(self):
"""
Encode a BFD Control packet without authentication section.
"""
diag = (self.ver << 5) + self.diag
flags = (self.state << 6) + self.flags
length = len(self)
return struct.pack(self._PACK_STR, diag, flags, self.detect_mult,
... | Encode a BFD Control packet without authentication section. | Below is the the instruction that describes the task:
### Input:
Encode a BFD Control packet without authentication section.
### Response:
def pack(self):
"""
Encode a BFD Control packet without authentication section.
"""
diag = (self.ver << 5) + self.diag
flags = (self.sta... |
def pre_connect(self, peer):
"""
Ensures that we have an open connection to the given peer.
Returns the peer id. This should be equal to the given one, but
it might not if the given peer was, say, the IP and the peer
actually identifies itself with a host name. The retur... | Ensures that we have an open connection to the given peer.
Returns the peer id. This should be equal to the given one, but
it might not if the given peer was, say, the IP and the peer
actually identifies itself with a host name. The returned peer
is the real one that should be u... | Below is the the instruction that describes the task:
### Input:
Ensures that we have an open connection to the given peer.
Returns the peer id. This should be equal to the given one, but
it might not if the given peer was, say, the IP and the peer
actually identifies itself with a ... |
def qt_at_least(needed_version, test_version=None):
"""Check if the installed Qt version is greater than the requested
:param needed_version: minimally needed Qt version in format like 4.8.4
:type needed_version: str
:param test_version: Qt version as returned from Qt.QT_VERSION. As in
0x040100 T... | Check if the installed Qt version is greater than the requested
:param needed_version: minimally needed Qt version in format like 4.8.4
:type needed_version: str
:param test_version: Qt version as returned from Qt.QT_VERSION. As in
0x040100 This is used only for tests
:type test_version: int
... | Below is the the instruction that describes the task:
### Input:
Check if the installed Qt version is greater than the requested
:param needed_version: minimally needed Qt version in format like 4.8.4
:type needed_version: str
:param test_version: Qt version as returned from Qt.QT_VERSION. As in
... |
def AddArguments(cls, argument_group):
"""Adds command line arguments the helper supports to an argument group.
This function takes an argument parser or an argument group object and adds
to it all the command line arguments this helper supports.
Args:
argument_group (argparse._ArgumentGroup|arg... | Adds command line arguments the helper supports to an argument group.
This function takes an argument parser or an argument group object and adds
to it all the command line arguments this helper supports.
Args:
argument_group (argparse._ArgumentGroup|argparse.ArgumentParser):
argparse grou... | Below is the the instruction that describes the task:
### Input:
Adds command line arguments the helper supports to an argument group.
This function takes an argument parser or an argument group object and adds
to it all the command line arguments this helper supports.
Args:
argument_group (argp... |
def _silent_exec_callback(self, expr, callback):
"""Silently execute `expr` in the kernel and call `callback` with reply
the `expr` is evaluated silently in the kernel (without) output in
the frontend. Call `callback` with the
`repr <http://docs.python.org/library/functions.html#repr> `... | Silently execute `expr` in the kernel and call `callback` with reply
the `expr` is evaluated silently in the kernel (without) output in
the frontend. Call `callback` with the
`repr <http://docs.python.org/library/functions.html#repr> `_ as first argument
Parameters
----------
... | Below is the the instruction that describes the task:
### Input:
Silently execute `expr` in the kernel and call `callback` with reply
the `expr` is evaluated silently in the kernel (without) output in
the frontend. Call `callback` with the
`repr <http://docs.python.org/library/functions.htm... |
def exp4(x, c, a, b, alpha):
"""exp4
Parameters
----------
x: int
c: float
a: float
b: float
alpha: float
Returns
-------
float
c - np.exp(-a*(x**alpha)+b)
"""
return c - np.exp(-a*(x**alpha)+b) | exp4
Parameters
----------
x: int
c: float
a: float
b: float
alpha: float
Returns
-------
float
c - np.exp(-a*(x**alpha)+b) | Below is the the instruction that describes the task:
### Input:
exp4
Parameters
----------
x: int
c: float
a: float
b: float
alpha: float
Returns
-------
float
c - np.exp(-a*(x**alpha)+b)
### Response:
def exp4(x, c, a, b, alpha):
"""exp4
Parameters
-... |
def sequence_to_alignment_coords(self, seq_name, start, end, trim=False):
"""
convert an interval in one of the sequences into an interval in the
alignment. Alignment intervals are inclusive of start, but not end. They
are one-based. Hence the full alignment has coords [1, N+1), where N is the
lengt... | convert an interval in one of the sequences into an interval in the
alignment. Alignment intervals are inclusive of start, but not end. They
are one-based. Hence the full alignment has coords [1, N+1), where N is the
length of the alignment (number of columns). Sequence coords follow the
same convention... | Below is the the instruction that describes the task:
### Input:
convert an interval in one of the sequences into an interval in the
alignment. Alignment intervals are inclusive of start, but not end. They
are one-based. Hence the full alignment has coords [1, N+1), where N is the
length of the alignmen... |
def exec_task(task_path, data):
"""Execute task.
:param task_path: task path
:type task_path: str|Callable
:param data: task's data
:type data: Any
:return:
"""
if not data:
data = {'data': None, 'path': task_path}
elif not isinstance(data, (str, bytes)):
data = {'d... | Execute task.
:param task_path: task path
:type task_path: str|Callable
:param data: task's data
:type data: Any
:return: | Below is the the instruction that describes the task:
### Input:
Execute task.
:param task_path: task path
:type task_path: str|Callable
:param data: task's data
:type data: Any
:return:
### Response:
def exec_task(task_path, data):
"""Execute task.
:param task_path: task path
:ty... |
def _query_by_installer(self, table_name):
"""
Query for download data broken down by installer, for one day.
:param table_name: table name to query against
:type table_name: str
:return: dict of download information by installer; keys are project
name, values are a di... | Query for download data broken down by installer, for one day.
:param table_name: table name to query against
:type table_name: str
:return: dict of download information by installer; keys are project
name, values are a dict of installer names to dicts of installer
version t... | Below is the the instruction that describes the task:
### Input:
Query for download data broken down by installer, for one day.
:param table_name: table name to query against
:type table_name: str
:return: dict of download information by installer; keys are project
name, values ar... |
def delete_ldap_group_link(self, cn, provider=None, **kwargs):
"""Delete an LDAP group link.
Args:
cn (str): CN of the LDAP group
provider (str): LDAP provider for the LDAP group
**kwargs: Extra options to send to the server (e.g. sudo)
Raises:
G... | Delete an LDAP group link.
Args:
cn (str): CN of the LDAP group
provider (str): LDAP provider for the LDAP group
**kwargs: Extra options to send to the server (e.g. sudo)
Raises:
GitlabAuthenticationError: If authentication is not correct
Git... | Below is the the instruction that describes the task:
### Input:
Delete an LDAP group link.
Args:
cn (str): CN of the LDAP group
provider (str): LDAP provider for the LDAP group
**kwargs: Extra options to send to the server (e.g. sudo)
Raises:
Gitlab... |
def get(self):
"""
Constructs a WorkflowStatisticsContext
:returns: twilio.rest.taskrouter.v1.workspace.workflow.workflow_statistics.WorkflowStatisticsContext
:rtype: twilio.rest.taskrouter.v1.workspace.workflow.workflow_statistics.WorkflowStatisticsContext
"""
return Wo... | Constructs a WorkflowStatisticsContext
:returns: twilio.rest.taskrouter.v1.workspace.workflow.workflow_statistics.WorkflowStatisticsContext
:rtype: twilio.rest.taskrouter.v1.workspace.workflow.workflow_statistics.WorkflowStatisticsContext | Below is the the instruction that describes the task:
### Input:
Constructs a WorkflowStatisticsContext
:returns: twilio.rest.taskrouter.v1.workspace.workflow.workflow_statistics.WorkflowStatisticsContext
:rtype: twilio.rest.taskrouter.v1.workspace.workflow.workflow_statistics.WorkflowStatisticsCon... |
def nested_to_record(ds, prefix="", sep=".", level=0):
"""a simplified json_normalize
converts a nested dict into a flat dict ("record"), unlike json_normalize,
it does not attempt to extract a subset of the data.
Parameters
----------
ds : dict or list of dicts
prefix: the prefix, optiona... | a simplified json_normalize
converts a nested dict into a flat dict ("record"), unlike json_normalize,
it does not attempt to extract a subset of the data.
Parameters
----------
ds : dict or list of dicts
prefix: the prefix, optional, default: ""
sep : string, default '.'
Nested re... | Below is the the instruction that describes the task:
### Input:
a simplified json_normalize
converts a nested dict into a flat dict ("record"), unlike json_normalize,
it does not attempt to extract a subset of the data.
Parameters
----------
ds : dict or list of dicts
prefix: the prefix, ... |
def UpdateAcqEraEndDate(self, acquisition_era_name ="", end_date=0):
"""
Input dictionary has to have the following keys:
acquisition_era_name, end_date.
"""
if acquisition_era_name =="" or end_date==0:
dbsExceptionHandler('dbsException-invalid-input', "acquisition_er... | Input dictionary has to have the following keys:
acquisition_era_name, end_date. | Below is the the instruction that describes the task:
### Input:
Input dictionary has to have the following keys:
acquisition_era_name, end_date.
### Response:
def UpdateAcqEraEndDate(self, acquisition_era_name ="", end_date=0):
"""
Input dictionary has to have the following keys:
a... |
def lha2matrix(values, shape):
"""Return a matrix given a list of values of the form
[[1, 1, float], [1, 2, float], ...]
referring to the (1,1)-element etc.
`shape` is the shape of the final matrix. All elements not provided
will be assumed to be zero. Also works for higher-rank tensors."""
M = ... | Return a matrix given a list of values of the form
[[1, 1, float], [1, 2, float], ...]
referring to the (1,1)-element etc.
`shape` is the shape of the final matrix. All elements not provided
will be assumed to be zero. Also works for higher-rank tensors. | Below is the the instruction that describes the task:
### Input:
Return a matrix given a list of values of the form
[[1, 1, float], [1, 2, float], ...]
referring to the (1,1)-element etc.
`shape` is the shape of the final matrix. All elements not provided
will be assumed to be zero. Also works for h... |
def get_admin_ids(self):
"""Method to get the administrator id list."""
admins = self.json_response.get("admin_list", None)
admin_ids = [admin_id for admin_id in admins["userid"]]
return admin_ids | Method to get the administrator id list. | Below is the the instruction that describes the task:
### Input:
Method to get the administrator id list.
### Response:
def get_admin_ids(self):
"""Method to get the administrator id list."""
admins = self.json_response.get("admin_list", None)
admin_ids = [admin_id for admin_id in admins... |
def get(self, username=None, password=None, headers={}):
"""Factory method to get the correct AuthInfo object.
The returned value depends on the arguments given. In case the
username and password don't have a value (ie evaluate to False),
return an object for anonymous access. Else, ret... | Factory method to get the correct AuthInfo object.
The returned value depends on the arguments given. In case the
username and password don't have a value (ie evaluate to False),
return an object for anonymous access. Else, return an auth
object that supports basic authentication.
... | Below is the the instruction that describes the task:
### Input:
Factory method to get the correct AuthInfo object.
The returned value depends on the arguments given. In case the
username and password don't have a value (ie evaluate to False),
return an object for anonymous access. Else, re... |
def drop_udf(
self,
name,
input_types=None,
database=None,
force=False,
aggregate=False,
):
"""
Drops a UDF
If only name is given, this will search
for the relevant UDF and drop it.
To delete an overloaded UDF, give only a name ... | Drops a UDF
If only name is given, this will search
for the relevant UDF and drop it.
To delete an overloaded UDF, give only a name and force=True
Parameters
----------
name : string
input_types : list of strings (optional)
force : boolean, default False ... | Below is the the instruction that describes the task:
### Input:
Drops a UDF
If only name is given, this will search
for the relevant UDF and drop it.
To delete an overloaded UDF, give only a name and force=True
Parameters
----------
name : string
input_types... |
def get_error_message(exception, context=None, suggestion=None):
"""Convert exception into an ErrorMessage containing a stack trace.
:param exception: Exception object.
:type exception: Exception
:param context: Optional context message.
:type context: str
:param suggestion: Optional suggesti... | Convert exception into an ErrorMessage containing a stack trace.
:param exception: Exception object.
:type exception: Exception
:param context: Optional context message.
:type context: str
:param suggestion: Optional suggestion.
:type suggestion: str
.. see also:: https://github.com/inas... | Below is the the instruction that describes the task:
### Input:
Convert exception into an ErrorMessage containing a stack trace.
:param exception: Exception object.
:type exception: Exception
:param context: Optional context message.
:type context: str
:param suggestion: Optional suggestion.... |
def reset_parameters(self):
"""Reinitiate the weight parameters.
"""
stdv = 1.0 / math.sqrt(self.num_features)
self.weight.weight.data.uniform_(-stdv, stdv)
if self.bias is not None:
self.bias.data.uniform_(-stdv, stdv)
if self.padding_idx is not None:
... | Reinitiate the weight parameters. | Below is the the instruction that describes the task:
### Input:
Reinitiate the weight parameters.
### Response:
def reset_parameters(self):
"""Reinitiate the weight parameters.
"""
stdv = 1.0 / math.sqrt(self.num_features)
self.weight.weight.data.uniform_(-stdv, stdv)
if s... |
def create(dataset, target,
features=None,
validation_set='auto',
max_depth=6,
min_loss_reduction=0.0, min_child_weight=0.1,
verbose=True,
random_seed = None,
metric = 'auto',
**kwargs):
"""
Create a :class:`~turicreate.deci... | Create a :class:`~turicreate.decision_tree_regression.DecisionTreeRegression` to predict
a scalar target variable using one or more features. In addition to standard
numeric and categorical types, features can also be extracted automatically
from list- or dictionary-type SFrame columns.
Parameters
... | Below is the the instruction that describes the task:
### Input:
Create a :class:`~turicreate.decision_tree_regression.DecisionTreeRegression` to predict
a scalar target variable using one or more features. In addition to standard
numeric and categorical types, features can also be extracted automatically
... |
def as_sparse_array(self, kind=None, fill_value=None, copy=False):
""" return my self as a sparse array, do not copy by default """
if fill_value is None:
fill_value = self.fill_value
if kind is None:
kind = self.kind
return SparseArray(self.values, sparse_index=... | return my self as a sparse array, do not copy by default | Below is the the instruction that describes the task:
### Input:
return my self as a sparse array, do not copy by default
### Response:
def as_sparse_array(self, kind=None, fill_value=None, copy=False):
""" return my self as a sparse array, do not copy by default """
if fill_value is None:
... |
def get_type(t):
"""
Convert a type to a str
If the instance is a Contract, return 'address' instead
"""
if isinstance(t, UserDefinedType):
if isinstance(t.type, Contract):
return 'address'
return str(t) | Convert a type to a str
If the instance is a Contract, return 'address' instead | Below is the the instruction that describes the task:
### Input:
Convert a type to a str
If the instance is a Contract, return 'address' instead
### Response:
def get_type(t):
"""
Convert a type to a str
If the instance is a Contract, return 'address' instead
"""
if isinstance(t... |
def DynamicCmd(name, plugins):
"""
Returns a cmd with the added plugins,
:param name: TODO:
:param plugins: list of plugins
"""
exec('class %s(cmd.Cmd):\n prompt="cm> "' % name)
plugin_objects = []
for plugin in plugins:
classprefix = plugin['class']
plugin_list =... | Returns a cmd with the added plugins,
:param name: TODO:
:param plugins: list of plugins | Below is the the instruction that describes the task:
### Input:
Returns a cmd with the added plugins,
:param name: TODO:
:param plugins: list of plugins
### Response:
def DynamicCmd(name, plugins):
"""
Returns a cmd with the added plugins,
:param name: TODO:
:param plugins: list ... |
def generate_uncertainties(N, dist='Gamma', rseed=None):
"""
This function generates a uncertainties for the white noise component
in the synthetic light curve.
Parameters
---------
N: positive integer
Lenght of the returned uncertainty vector
dist: {'EMG', 'Gamma'}
Pro... | This function generates a uncertainties for the white noise component
in the synthetic light curve.
Parameters
---------
N: positive integer
Lenght of the returned uncertainty vector
dist: {'EMG', 'Gamma'}
Probability density function (PDF) used to generate the
uncerta... | Below is the the instruction that describes the task:
### Input:
This function generates a uncertainties for the white noise component
in the synthetic light curve.
Parameters
---------
N: positive integer
Lenght of the returned uncertainty vector
dist: {'EMG', 'Gamma'}
Pro... |
def sparse_dot_product_attention_truncated(
q,
k,
v,
bi, # Unused
experts_params,
use_map_fn=False, # Unused
mask_right=False,
): # pylint: disable=unused-argument
"""Sparse multihead self attention.
Perform an approximation of the full multihead attention by dispatching
the tokens... | Sparse multihead self attention.
Perform an approximation of the full multihead attention by dispatching
the tokens using their keys/values. Thus the attention matrix are only
computed each times on a subset of the tokens.
Notes:
* The function don't perform scaling here (multihead_attention does
the /sq... | Below is the the instruction that describes the task:
### Input:
Sparse multihead self attention.
Perform an approximation of the full multihead attention by dispatching
the tokens using their keys/values. Thus the attention matrix are only
computed each times on a subset of the tokens.
Notes:
* The fu... |
def Chat(self, Name=''):
"""Queries a chat object.
:Parameters:
Name : str
Chat name.
:return: A chat object.
:rtype: `chat.Chat`
"""
o = Chat(self, Name)
o.Status # Tests if such a chat really exists.
return o | Queries a chat object.
:Parameters:
Name : str
Chat name.
:return: A chat object.
:rtype: `chat.Chat` | Below is the the instruction that describes the task:
### Input:
Queries a chat object.
:Parameters:
Name : str
Chat name.
:return: A chat object.
:rtype: `chat.Chat`
### Response:
def Chat(self, Name=''):
"""Queries a chat object.
:Parameters:
... |
def random_insertion(self,fastq,rate,max_inserts=1):
"""Perform the permutation on the sequence. If authorized to do multiple bases they are done at hte rate defined here.
:param fastq: FASTQ sequence to permute
:type fastq: format.fastq.FASTQ
:param rate: how frequently to permute
:type rate: floa... | Perform the permutation on the sequence. If authorized to do multiple bases they are done at hte rate defined here.
:param fastq: FASTQ sequence to permute
:type fastq: format.fastq.FASTQ
:param rate: how frequently to permute
:type rate: float
:param max_inserts: the maximum number of bases to ins... | Below is the the instruction that describes the task:
### Input:
Perform the permutation on the sequence. If authorized to do multiple bases they are done at hte rate defined here.
:param fastq: FASTQ sequence to permute
:type fastq: format.fastq.FASTQ
:param rate: how frequently to permute
:type r... |
def construct_mail(recipients=None, context=None, template_base='emailit/email', subject=None, message=None, site=None,
subject_templates=None, body_templates=None, html_templates=None, from_email=None, language=None,
**kwargs):
"""
usage:
construct_mail(['my@email.com'... | usage:
construct_mail(['my@email.com'], {'my_obj': obj}, template_base='myapp/emails/my_obj_notification').send()
:param recipients: recipient or list of recipients
:param context: context for template rendering
:param template_base: the base template. '.subject.txt', '.body.txt' and '.body.html' will b... | Below is the the instruction that describes the task:
### Input:
usage:
construct_mail(['my@email.com'], {'my_obj': obj}, template_base='myapp/emails/my_obj_notification').send()
:param recipients: recipient or list of recipients
:param context: context for template rendering
:param template_base: t... |
def update(self,
message=None,
subject=None,
days=None,
downloads=None,
notify=None):
"""Update properties for a transfer.
:param message: updated message to recipient(s)
:param subject: updated subject for trasfer
... | Update properties for a transfer.
:param message: updated message to recipient(s)
:param subject: updated subject for trasfer
:param days: updated amount of days transfer is available
:param downloads: update amount of downloads allowed for transfer
:param notify: update whether... | Below is the the instruction that describes the task:
### Input:
Update properties for a transfer.
:param message: updated message to recipient(s)
:param subject: updated subject for trasfer
:param days: updated amount of days transfer is available
:param downloads: update amount of... |
def p_state_invariant_list(self, p):
'''state_invariant_list : state_invariant_list state_invariant_def
| state_invariant_def'''
if len(p) == 3:
p[1].append(p[2])
p[0] = p[1]
elif len(p) == 2:
p[0] = [p[1]] | state_invariant_list : state_invariant_list state_invariant_def
| state_invariant_def | Below is the the instruction that describes the task:
### Input:
state_invariant_list : state_invariant_list state_invariant_def
| state_invariant_def
### Response:
def p_state_invariant_list(self, p):
'''state_invariant_list : state_invariant_list state_invariant_def
... |
def is_valid(self) -> bool:
"""
Return True if CRC is valid
:return:
"""
return CRCPubkey.from_pubkey(self.pubkey).crc == self.crc | Return True if CRC is valid
:return: | Below is the the instruction that describes the task:
### Input:
Return True if CRC is valid
:return:
### Response:
def is_valid(self) -> bool:
"""
Return True if CRC is valid
:return:
"""
return CRCPubkey.from_pubkey(self.pubkey).crc == self.crc |
def write_real (self, url_data):
"""Write url_data.url."""
self.write(self.part("realurl") + self.spaces("realurl"))
self.writeln(unicode(url_data.url), color=self.colorreal) | Write url_data.url. | Below is the the instruction that describes the task:
### Input:
Write url_data.url.
### Response:
def write_real (self, url_data):
"""Write url_data.url."""
self.write(self.part("realurl") + self.spaces("realurl"))
self.writeln(unicode(url_data.url), color=self.colorreal) |
def run(dataset):
"""Run brain locally"""
config = _get_config()
if dataset:
_print("getting dataset from brains...")
cprint("done", 'green')
# check dataset cache for dataset
# if not exists
# r = requests.get('https://api.github.com/events', stream=True)
#... | Run brain locally | Below is the the instruction that describes the task:
### Input:
Run brain locally
### Response:
def run(dataset):
"""Run brain locally"""
config = _get_config()
if dataset:
_print("getting dataset from brains...")
cprint("done", 'green')
# check dataset cache for dataset
... |
def _parse_fmdump(output):
'''
Parses fmdump output
'''
result = []
output = output.split("\n")
# extract header
header = [field for field in output[0].lower().split(" ") if field]
del output[0]
# parse entries
for entry in output:
entry = [item for item in entry.split(... | Parses fmdump output | Below is the the instruction that describes the task:
### Input:
Parses fmdump output
### Response:
def _parse_fmdump(output):
'''
Parses fmdump output
'''
result = []
output = output.split("\n")
# extract header
header = [field for field in output[0].lower().split(" ") if field]
d... |
def handle(self, event):
"""
Entry point to handle user events.
:param event: Received event. See a full list `here <https://dev.twitter.com/streaming/overview/messages-types#Events_event>`_.
"""
callback = getattr(self, 'on_{event}'.format(event=event.event), None)
call... | Entry point to handle user events.
:param event: Received event. See a full list `here <https://dev.twitter.com/streaming/overview/messages-types#Events_event>`_. | Below is the the instruction that describes the task:
### Input:
Entry point to handle user events.
:param event: Received event. See a full list `here <https://dev.twitter.com/streaming/overview/messages-types#Events_event>`_.
### Response:
def handle(self, event):
"""
Entry point to hand... |
def resource_url(path):
"""Get the a local filesystem url to a given resource.
.. versionadded:: 3.0
Note that in version 3.0 we removed the use of Qt Resource files in
favour of directly accessing on-disk resources.
:param path: Path to resource e.g. /home/timlinux/foo/bar.png
:type path: st... | Get the a local filesystem url to a given resource.
.. versionadded:: 3.0
Note that in version 3.0 we removed the use of Qt Resource files in
favour of directly accessing on-disk resources.
:param path: Path to resource e.g. /home/timlinux/foo/bar.png
:type path: str
:return: A valid file ur... | Below is the the instruction that describes the task:
### Input:
Get the a local filesystem url to a given resource.
.. versionadded:: 3.0
Note that in version 3.0 we removed the use of Qt Resource files in
favour of directly accessing on-disk resources.
:param path: Path to resource e.g. /home/t... |
def purge_old_request_logs(delete_before_days=7):
"""
Purges old request logs from the database table
"""
delete_before_date = timezone.now() - timedelta(days=delete_before_days)
logs_deleted = RequestLog.objects.filter(
created_on__lte=delete_before_date).delete()
return logs_deleted | Purges old request logs from the database table | Below is the the instruction that describes the task:
### Input:
Purges old request logs from the database table
### Response:
def purge_old_request_logs(delete_before_days=7):
"""
Purges old request logs from the database table
"""
delete_before_date = timezone.now() - timedelta(days=delete_before... |
def resolve_outputs(self):
'''Resolve the names of outputs for this layer into shape tuples.'''
input_shape = None
for i, shape in enumerate(self._input_shapes.values()):
if i == 0:
input_shape = shape
if len(input_shape) != len(shape) or any(
... | Resolve the names of outputs for this layer into shape tuples. | Below is the the instruction that describes the task:
### Input:
Resolve the names of outputs for this layer into shape tuples.
### Response:
def resolve_outputs(self):
'''Resolve the names of outputs for this layer into shape tuples.'''
input_shape = None
for i, shape in enumerate(self._in... |
def login(remote_app):
"""Send user to remote application for authentication."""
oauth = current_app.extensions['oauthlib.client']
if remote_app not in oauth.remote_apps:
return abort(404)
# Get redirect target in safe manner.
next_param = get_safe_redirect_target(arg='next')
# Redire... | Send user to remote application for authentication. | Below is the the instruction that describes the task:
### Input:
Send user to remote application for authentication.
### Response:
def login(remote_app):
"""Send user to remote application for authentication."""
oauth = current_app.extensions['oauthlib.client']
if remote_app not in oauth.remote_apps:
... |
def team_ids(year):
"""Returns a mapping from team name to team ID for a given season. Inverse
mapping of team_names. Example of a full team name: "New England Patriots"
:year: The year of the season in question (as an int).
:returns: A dictionary with full team name keys and teamID values.
"""
... | Returns a mapping from team name to team ID for a given season. Inverse
mapping of team_names. Example of a full team name: "New England Patriots"
:year: The year of the season in question (as an int).
:returns: A dictionary with full team name keys and teamID values. | Below is the the instruction that describes the task:
### Input:
Returns a mapping from team name to team ID for a given season. Inverse
mapping of team_names. Example of a full team name: "New England Patriots"
:year: The year of the season in question (as an int).
:returns: A dictionary with full tea... |
def get_usrgos_g_section(self, section=None):
"""Get usrgos in a requested section."""
if section is None:
section = self.hdrobj.secdflt
if section is True:
return self.usrgos
# Get dict of sections and hdrgos actually used in grouping
section2hdrgos = cx.... | Get usrgos in a requested section. | Below is the the instruction that describes the task:
### Input:
Get usrgos in a requested section.
### Response:
def get_usrgos_g_section(self, section=None):
"""Get usrgos in a requested section."""
if section is None:
section = self.hdrobj.secdflt
if section is True:
... |
def load_code(name, base_path=None, recurse=False):
"""Load executable code from a URL or a path"""
if '/' in name:
return load_location(name, base_path, module=False)
return importer.import_code(name, base_path, recurse=recurse) | Load executable code from a URL or a path | Below is the the instruction that describes the task:
### Input:
Load executable code from a URL or a path
### Response:
def load_code(name, base_path=None, recurse=False):
"""Load executable code from a URL or a path"""
if '/' in name:
return load_location(name, base_path, module=False)
retur... |
def canOrder(self, commit: Commit) -> Tuple[bool, Optional[str]]:
"""
Return whether the specified commitRequest can be returned to the node.
Decision criteria:
- If have got just n-f Commit requests then return request to node
- If less than n-f of commit requests then probabl... | Return whether the specified commitRequest can be returned to the node.
Decision criteria:
- If have got just n-f Commit requests then return request to node
- If less than n-f of commit requests then probably don't have
consensus on the request; don't return request to node
... | Below is the the instruction that describes the task:
### Input:
Return whether the specified commitRequest can be returned to the node.
Decision criteria:
- If have got just n-f Commit requests then return request to node
- If less than n-f of commit requests then probably don't have
... |
def get_load(jid):
'''
Return the load data that marks a specified jid
'''
with _get_serv(ret=None, commit=True) as cur:
sql = '''SELECT load FROM jids WHERE jid = %s;'''
cur.execute(sql, (jid,))
data = cur.fetchone()
if data:
return data[0]
return {} | Return the load data that marks a specified jid | Below is the the instruction that describes the task:
### Input:
Return the load data that marks a specified jid
### Response:
def get_load(jid):
'''
Return the load data that marks a specified jid
'''
with _get_serv(ret=None, commit=True) as cur:
sql = '''SELECT load FROM jids WHERE jid =... |
def save_assessment_taken(self, assessment_taken_form, *args, **kwargs):
"""Pass through to provider AssessmentTakenAdminSession.update_assessment_taken"""
# Implemented from kitosid template for -
# osid.resource.ResourceAdminSession.update_resource
if assessment_taken_form.is_for_updat... | Pass through to provider AssessmentTakenAdminSession.update_assessment_taken | Below is the the instruction that describes the task:
### Input:
Pass through to provider AssessmentTakenAdminSession.update_assessment_taken
### Response:
def save_assessment_taken(self, assessment_taken_form, *args, **kwargs):
"""Pass through to provider AssessmentTakenAdminSession.update_assessment_take... |
def varinq(self, variable):
"""
Returns a dictionary that shows the basic variable information.
This information includes
+-----------------+--------------------------------------------------------------------------------+
| ['Variable'] | the name of the vari... | Returns a dictionary that shows the basic variable information.
This information includes
+-----------------+--------------------------------------------------------------------------------+
| ['Variable'] | the name of the variable ... | Below is the the instruction that describes the task:
### Input:
Returns a dictionary that shows the basic variable information.
This information includes
+-----------------+--------------------------------------------------------------------------------+
| ['Variable'] |... |
def move_wheel_files(
name, # type: str
req, # type: Requirement
wheeldir, # type: str
user=False, # type: bool
home=None, # type: Optional[str]
root=None, # type: Optional[str]
pycompile=True, # type: bool
scheme=None, # type: Optional[Mapping[str, str]]
isolated=False, # t... | Install a wheel | Below is the the instruction that describes the task:
### Input:
Install a wheel
### Response:
def move_wheel_files(
name, # type: str
req, # type: Requirement
wheeldir, # type: str
user=False, # type: bool
home=None, # type: Optional[str]
root=None, # type: Optional[str]
pycompil... |
def from_json(self, value):
"""
Parse the date from an ISO-formatted date string, or None.
"""
if value is None:
return None
if isinstance(value, six.binary_type):
value = value.decode('utf-8')
if isinstance(value, six.text_type):
# P... | Parse the date from an ISO-formatted date string, or None. | Below is the the instruction that describes the task:
### Input:
Parse the date from an ISO-formatted date string, or None.
### Response:
def from_json(self, value):
"""
Parse the date from an ISO-formatted date string, or None.
"""
if value is None:
return None
... |
def preferred_height(self, cli, width, max_available_height, wrap_lines):
"""
Preferred height: as much as needed in order to display all the completions.
"""
complete_state = cli.current_buffer.complete_state
column_width = self._get_column_width(complete_state)
column_c... | Preferred height: as much as needed in order to display all the completions. | Below is the the instruction that describes the task:
### Input:
Preferred height: as much as needed in order to display all the completions.
### Response:
def preferred_height(self, cli, width, max_available_height, wrap_lines):
"""
Preferred height: as much as needed in order to display all the c... |
def get_storage(self, id_or_uri):
"""
Get storage details of an OS Volume.
Args:
id_or_uri: ID or URI of the OS Volume.
Returns:
dict: Storage details
"""
uri = self.URI + "/{}/storage".format(extract_id_from_uri(id_or_uri))
return self._... | Get storage details of an OS Volume.
Args:
id_or_uri: ID or URI of the OS Volume.
Returns:
dict: Storage details | Below is the the instruction that describes the task:
### Input:
Get storage details of an OS Volume.
Args:
id_or_uri: ID or URI of the OS Volume.
Returns:
dict: Storage details
### Response:
def get_storage(self, id_or_uri):
"""
Get storage details of an O... |
def get_kb_mapping(kb_name="", key="", value="", match_type="e", default="",
limit=None):
"""Get one unique mapping. If not found, return default.
:param kb_name: the name of the kb
:param key: include only lines matching this on left side in the results
:param value: include only li... | Get one unique mapping. If not found, return default.
:param kb_name: the name of the kb
:param key: include only lines matching this on left side in the results
:param value: include only lines matching this on right side in the results
:param match_type: s = substring match, e = exact match
:para... | Below is the the instruction that describes the task:
### Input:
Get one unique mapping. If not found, return default.
:param kb_name: the name of the kb
:param key: include only lines matching this on left side in the results
:param value: include only lines matching this on right side in the results
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.