code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def exec_command(self, cmd, args='', vdglobals=None, keystrokes=None):
"Execute `cmd` tuple with `vdglobals` as globals and this sheet's attributes as locals. Returns True if user cancelled."
global sheet
sheet = vd.sheets[0]
if not cmd:
debug('no command "%s"' % keystrokes... | Execute `cmd` tuple with `vdglobals` as globals and this sheet's attributes as locals. Returns True if user cancelled. | Below is the the instruction that describes the task:
### Input:
Execute `cmd` tuple with `vdglobals` as globals and this sheet's attributes as locals. Returns True if user cancelled.
### Response:
def exec_command(self, cmd, args='', vdglobals=None, keystrokes=None):
"Execute `cmd` tuple with `vdglobals`... |
def find_systemjs_location():
"""
Figure out where `jspm_packages/system.js` will be put by JSPM.
"""
location = os.path.abspath(os.path.dirname(locate_package_json()))
conf = parse_package_json()
if 'jspm' in conf:
conf = conf['jspm']
try:
conf = conf['directories']
ex... | Figure out where `jspm_packages/system.js` will be put by JSPM. | Below is the the instruction that describes the task:
### Input:
Figure out where `jspm_packages/system.js` will be put by JSPM.
### Response:
def find_systemjs_location():
"""
Figure out where `jspm_packages/system.js` will be put by JSPM.
"""
location = os.path.abspath(os.path.dirname(locate_pack... |
def function(self, func_name):
"""
Returns the Function instance associated with the given func_name, or raises a
RpcException if no function matches.
"""
if self.functions.has_key(func_name):
return self.functions[func_name]
else:
raise RpcExcepti... | Returns the Function instance associated with the given func_name, or raises a
RpcException if no function matches. | Below is the the instruction that describes the task:
### Input:
Returns the Function instance associated with the given func_name, or raises a
RpcException if no function matches.
### Response:
def function(self, func_name):
"""
Returns the Function instance associated with the given func_... |
def schema_remove(dbname, name,
user=None,
db_user=None, db_password=None,
db_host=None, db_port=None):
'''
Removes a schema from the Postgres server.
CLI Example:
.. code-block:: bash
salt '*' postgres.schema_remove dbname schemaname
... | Removes a schema from the Postgres server.
CLI Example:
.. code-block:: bash
salt '*' postgres.schema_remove dbname schemaname
dbname
Database name we work on
schemaname
The schema's name we'll remove
user
System user all operations should be performed on behalf... | Below is the the instruction that describes the task:
### Input:
Removes a schema from the Postgres server.
CLI Example:
.. code-block:: bash
salt '*' postgres.schema_remove dbname schemaname
dbname
Database name we work on
schemaname
The schema's name we'll remove
... |
def get_table_rate_shipping_by_id(cls, table_rate_shipping_id, **kwargs):
"""Find TableRateShipping
Return single instance of TableRateShipping by its ID.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> th... | Find TableRateShipping
Return single instance of TableRateShipping by its ID.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.get_table_rate_shipping_by_id(table_rate_shipping_id, async=True)
... | Below is the the instruction that describes the task:
### Input:
Find TableRateShipping
Return single instance of TableRateShipping by its ID.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.get_t... |
def reconnect(self):
"""
Handle reconnect logic if connection
to crossbar is lost
"""
connect_attempt = 0
max_retries = self.config['max_reconnect_retries']
logging.info('attempting to reconnect to crossbar')
runner = self.setup_runner()
while True... | Handle reconnect logic if connection
to crossbar is lost | Below is the the instruction that describes the task:
### Input:
Handle reconnect logic if connection
to crossbar is lost
### Response:
def reconnect(self):
"""
Handle reconnect logic if connection
to crossbar is lost
"""
connect_attempt = 0
max_retries = sel... |
def create_from_string(self, string, context=EMPTY_CONTEXT, *args, **kwargs):
"""
Deserializes a new instance from a string.
This is a convenience method that creates a StringIO object and calls create_instance_from_stream().
"""
if not PY2 and not isinstance(string, bytes):
... | Deserializes a new instance from a string.
This is a convenience method that creates a StringIO object and calls create_instance_from_stream(). | Below is the the instruction that describes the task:
### Input:
Deserializes a new instance from a string.
This is a convenience method that creates a StringIO object and calls create_instance_from_stream().
### Response:
def create_from_string(self, string, context=EMPTY_CONTEXT, *args, **kwargs):
... |
def disconnect(self):
'''
Disconnect from the serial port
'''
if self._poll_stop_event:
self._poll_stop_event.set()
if self._driver:
if self.status != 'idle':
self.deactivate()
self._driver.disconnect() | Disconnect from the serial port | Below is the the instruction that describes the task:
### Input:
Disconnect from the serial port
### Response:
def disconnect(self):
'''
Disconnect from the serial port
'''
if self._poll_stop_event:
self._poll_stop_event.set()
if self._driver:
if self... |
def move(self, from_path, to_path, **kwargs):
"""移动单个文件或目录.
:param from_path: 源文件/目录在网盘中的路径(包括文件名)。
.. warning::
* 路径长度限制为1000;
* 径中不能包含以下字符:``\\\\ ? | " > < : *``;
* 文件名或路径名开头结尾不能是 ``.`... | 移动单个文件或目录.
:param from_path: 源文件/目录在网盘中的路径(包括文件名)。
.. warning::
* 路径长度限制为1000;
* 径中不能包含以下字符:``\\\\ ? | " > < : *``;
* 文件名或路径名开头结尾不能是 ``.``
或空白字符,空白字符包括:
... | Below is the the instruction that describes the task:
### Input:
移动单个文件或目录.
:param from_path: 源文件/目录在网盘中的路径(包括文件名)。
.. warning::
* 路径长度限制为1000;
* 径中不能包含以下字符:``\\\\ ? | " > < : *``;
* 文件名或路径名... |
def handle_cmd(self, command, application):
"""Handle running a given dot command from a user.
:type command: str
:param command: The full dot command string, e.g. ``.edit``,
of ``.profile prod``.
:type application: AWSShell
:param application: The application objec... | Handle running a given dot command from a user.
:type command: str
:param command: The full dot command string, e.g. ``.edit``,
of ``.profile prod``.
:type application: AWSShell
:param application: The application object. | Below is the the instruction that describes the task:
### Input:
Handle running a given dot command from a user.
:type command: str
:param command: The full dot command string, e.g. ``.edit``,
of ``.profile prod``.
:type application: AWSShell
:param application: The app... |
def put_str(content, path, share='C$', conn=None, host=None, username=None, password=None):
'''
Wrapper around impacket.smbconnection.putFile() that allows a string to be
uploaded, without first writing it as a local file
'''
if HAS_SMBPROTOCOL:
return _put_str_smbprotocol(
conte... | Wrapper around impacket.smbconnection.putFile() that allows a string to be
uploaded, without first writing it as a local file | Below is the the instruction that describes the task:
### Input:
Wrapper around impacket.smbconnection.putFile() that allows a string to be
uploaded, without first writing it as a local file
### Response:
def put_str(content, path, share='C$', conn=None, host=None, username=None, password=None):
'''
Wr... |
def touch(self):
"""
Touch all of the related models for the relationship.
"""
column = self.get_related().get_updated_at_column()
self.raw_update({column: self.get_related().fresh_timestamp()}) | Touch all of the related models for the relationship. | Below is the the instruction that describes the task:
### Input:
Touch all of the related models for the relationship.
### Response:
def touch(self):
"""
Touch all of the related models for the relationship.
"""
column = self.get_related().get_updated_at_column()
self.raw_u... |
def remove_technique(self, tech):
"""
Remove an exploration technique from a list of active techniques.
:param tech: An ExplorationTechnique object.
:type tech: ExplorationTechnique
"""
if not isinstance(tech, ExplorationTechnique):
raise SimulationMan... | Remove an exploration technique from a list of active techniques.
:param tech: An ExplorationTechnique object.
:type tech: ExplorationTechnique | Below is the the instruction that describes the task:
### Input:
Remove an exploration technique from a list of active techniques.
:param tech: An ExplorationTechnique object.
:type tech: ExplorationTechnique
### Response:
def remove_technique(self, tech):
"""
Remove an expl... |
def cmp(cls, v1: 'VersionBase', v2: 'VersionBase') -> int:
""" Compares two instances. """
# TODO types checking
if v1._version > v2._version:
return 1
elif v1._version == v2._version:
return 0
else:
return -1 | Compares two instances. | Below is the the instruction that describes the task:
### Input:
Compares two instances.
### Response:
def cmp(cls, v1: 'VersionBase', v2: 'VersionBase') -> int:
""" Compares two instances. """
# TODO types checking
if v1._version > v2._version:
return 1
elif v1._version... |
def _is_file(filename):
"""Check that the size of the thing which is supposed to be a filename has
size greater than zero, without following symbolic links or using
:func:os.path.isfile.
:param filename: An object to check.
:rtype: bool
:returns: True if **filename** is file-like, False otherwi... | Check that the size of the thing which is supposed to be a filename has
size greater than zero, without following symbolic links or using
:func:os.path.isfile.
:param filename: An object to check.
:rtype: bool
:returns: True if **filename** is file-like, False otherwise. | Below is the the instruction that describes the task:
### Input:
Check that the size of the thing which is supposed to be a filename has
size greater than zero, without following symbolic links or using
:func:os.path.isfile.
:param filename: An object to check.
:rtype: bool
:returns: True if **... |
def _parse_uptime_string(self, uptime):
""" Parse u' 16:53:48 up 1 day, 21:34, 3 users, load average: 0.04, 0.14, 0.19\n' """
uptime = uptime.strip()
load_averages = uptime[uptime.find('load average:') :].split(':')[1].strip().split(',')
load_averages = [float(load_avg) for load_avg in... | Parse u' 16:53:48 up 1 day, 21:34, 3 users, load average: 0.04, 0.14, 0.19\n' | Below is the the instruction that describes the task:
### Input:
Parse u' 16:53:48 up 1 day, 21:34, 3 users, load average: 0.04, 0.14, 0.19\n'
### Response:
def _parse_uptime_string(self, uptime):
""" Parse u' 16:53:48 up 1 day, 21:34, 3 users, load average: 0.04, 0.14, 0.19\n' """
uptime = upt... |
def find_near_matches_substitutions(subsequence, sequence, max_substitutions):
"""Find near-matches of the subsequence in the sequence.
This chooses a suitable fuzzy search implementation according to the given
parameters.
Returns a list of fuzzysearch.Match objects describing the matching parts
o... | Find near-matches of the subsequence in the sequence.
This chooses a suitable fuzzy search implementation according to the given
parameters.
Returns a list of fuzzysearch.Match objects describing the matching parts
of the sequence. | Below is the the instruction that describes the task:
### Input:
Find near-matches of the subsequence in the sequence.
This chooses a suitable fuzzy search implementation according to the given
parameters.
Returns a list of fuzzysearch.Match objects describing the matching parts
of the sequence.
#... |
def split_dae_alg(eqs: SYM, dx: SYM) -> Dict[str, SYM]:
"""Split equations into differential algebraic and algebraic only"""
dae = []
alg = []
for eq in ca.vertsplit(eqs):
if ca.depends_on(eq, dx):
dae.append(eq)
else:
alg.append(eq)
return {
'dae': ca... | Split equations into differential algebraic and algebraic only | Below is the the instruction that describes the task:
### Input:
Split equations into differential algebraic and algebraic only
### Response:
def split_dae_alg(eqs: SYM, dx: SYM) -> Dict[str, SYM]:
"""Split equations into differential algebraic and algebraic only"""
dae = []
alg = []
for eq in ca.v... |
def get_view_names(engine: Engine) -> List[str]:
"""
Returns a list of database view names from the :class:`Engine`.
"""
insp = Inspector.from_engine(engine)
return insp.get_view_names() | Returns a list of database view names from the :class:`Engine`. | Below is the the instruction that describes the task:
### Input:
Returns a list of database view names from the :class:`Engine`.
### Response:
def get_view_names(engine: Engine) -> List[str]:
"""
Returns a list of database view names from the :class:`Engine`.
"""
insp = Inspector.from_engine(engine... |
def reverse(self):
'S.reverse() -- reverse *IN PLACE*'
n = len(self)
for i in range(n//2):
self[i], self[n-i-1] = self[n-i-1], self[i] | S.reverse() -- reverse *IN PLACE* | Below is the the instruction that describes the task:
### Input:
S.reverse() -- reverse *IN PLACE*
### Response:
def reverse(self):
'S.reverse() -- reverse *IN PLACE*'
n = len(self)
for i in range(n//2):
self[i], self[n-i-1] = self[n-i-1], self[i] |
def _send_to_timeseries(self, message):
"""
Establish or reuse socket connection and send
the given message to the timeseries service.
"""
logging.debug("MESSAGE=" + str(message))
result = None
try:
ws = self._get_websocket()
ws.send(json.... | Establish or reuse socket connection and send
the given message to the timeseries service. | Below is the the instruction that describes the task:
### Input:
Establish or reuse socket connection and send
the given message to the timeseries service.
### Response:
def _send_to_timeseries(self, message):
"""
Establish or reuse socket connection and send
the given message to th... |
def exists(cls, query=None, path=None, **kwargs):
"""
Like __init__ but simply returns a boolean as to whether or not the
object exists, rather than returning the whole object.
NOTE: if you pass in a single argument to exists, this will
match against ID_KEY.
... | Like __init__ but simply returns a boolean as to whether or not the
object exists, rather than returning the whole object.
NOTE: if you pass in a single argument to exists, this will
match against ID_KEY.
@param query: a dictionary specifying key-value pairs that the re... | Below is the the instruction that describes the task:
### Input:
Like __init__ but simply returns a boolean as to whether or not the
object exists, rather than returning the whole object.
NOTE: if you pass in a single argument to exists, this will
match against ID_KEY.
... |
def random_date_between(start_date, end_date):
"""Return random date between start/end"""
assert isinstance(start_date, datetime.date)
delta_secs = int((end_date - start_date).total_seconds())
delta = datetime.timedelta(seconds=random.randint(0, delta_secs))
return (start_date + delta) | Return random date between start/end | Below is the the instruction that describes the task:
### Input:
Return random date between start/end
### Response:
def random_date_between(start_date, end_date):
"""Return random date between start/end"""
assert isinstance(start_date, datetime.date)
delta_secs = int((end_date - start_date).total_secon... |
def snmp_server_user_ipv6_acl(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
snmp_server = ET.SubElement(config, "snmp-server", xmlns="urn:brocade.com:mgmt:brocade-snmp")
user = ET.SubElement(snmp_server, "user")
username_key = ET.SubElement(use... | Auto Generated Code | Below is the the instruction that describes the task:
### Input:
Auto Generated Code
### Response:
def snmp_server_user_ipv6_acl(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
snmp_server = ET.SubElement(config, "snmp-server", xmlns="urn:brocade.com:mgmt:b... |
def add_data(self, path, time_info, data, exprs):
"""
Stores data before it can be put into a time series
"""
# Dont add if empty
if not nonempty(data):
for d in self.data[path]:
if nonempty(d['values']):
return
# Add data ... | Stores data before it can be put into a time series | Below is the the instruction that describes the task:
### Input:
Stores data before it can be put into a time series
### Response:
def add_data(self, path, time_info, data, exprs):
"""
Stores data before it can be put into a time series
"""
# Dont add if empty
if not nonempt... |
def list_nodes_full(call=None, for_output=True):
'''
Return a list of the VMs that are on the provider
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_full function must be called with -f or --function.'
)
return _list_nodes(full=True, for_output=for_o... | Return a list of the VMs that are on the provider | Below is the the instruction that describes the task:
### Input:
Return a list of the VMs that are on the provider
### Response:
def list_nodes_full(call=None, for_output=True):
'''
Return a list of the VMs that are on the provider
'''
if call == 'action':
raise SaltCloudSystemExit(
... |
def create(client, _type, **kwargs):
"""Create a suds object of the requested _type."""
obj = client.factory.create("ns0:%s" % _type)
for key, value in kwargs.items():
setattr(obj, key, value)
return obj | Create a suds object of the requested _type. | Below is the the instruction that describes the task:
### Input:
Create a suds object of the requested _type.
### Response:
def create(client, _type, **kwargs):
"""Create a suds object of the requested _type."""
obj = client.factory.create("ns0:%s" % _type)
for key, value in kwargs.items():
set... |
def get_current_time(self):
"""
returns current time of simulation
"""
current_time = c_double()
self.library.get_current_time.argtypes = [POINTER(c_double)]
self.library.get_current_time.restype = None
self.library.get_current_time(byref(current_time))
re... | returns current time of simulation | Below is the the instruction that describes the task:
### Input:
returns current time of simulation
### Response:
def get_current_time(self):
"""
returns current time of simulation
"""
current_time = c_double()
self.library.get_current_time.argtypes = [POINTER(c_double)]
... |
def _build(self, inputs, prev_state, is_training=None, test_local_stats=True):
"""Connects the LSTM module into the graph.
If this is not the first time the module has been connected to the graph,
the Tensors provided as inputs and state must have the same final
dimension, in order for the existing var... | Connects the LSTM module into the graph.
If this is not the first time the module has been connected to the graph,
the Tensors provided as inputs and state must have the same final
dimension, in order for the existing variables to be the correct size for
their corresponding multiplications. The batch s... | Below is the the instruction that describes the task:
### Input:
Connects the LSTM module into the graph.
If this is not the first time the module has been connected to the graph,
the Tensors provided as inputs and state must have the same final
dimension, in order for the existing variables to be the ... |
def add_action(self, dash, dashdash, action_code):
"""Add a specialized option that is the action to execute."""
option = self.add_option(dash, dashdash, action='callback',
callback=self._append_action
)
option.action_code = action_code | Add a specialized option that is the action to execute. | Below is the the instruction that describes the task:
### Input:
Add a specialized option that is the action to execute.
### Response:
def add_action(self, dash, dashdash, action_code):
"""Add a specialized option that is the action to execute."""
option = self.add_option(dash, dashdash, action='ca... |
async def get_search_page(self, term: str):
"""Get search page.
This function will get the first link from the search term we do on term and then
it will return the link we want to parse from.
:param term: Light Novel to Search For
"""
# Uses the BASEURL and also builds... | Get search page.
This function will get the first link from the search term we do on term and then
it will return the link we want to parse from.
:param term: Light Novel to Search For | Below is the the instruction that describes the task:
### Input:
Get search page.
This function will get the first link from the search term we do on term and then
it will return the link we want to parse from.
:param term: Light Novel to Search For
### Response:
async def get_search_page... |
def get_detail_intro(self, content_id):
"""
Inquire detail introduction
:param content_id: Content ID to inquire
:type content_id: str
:rtype: dict
"""
content_type_id = self.get_detail_common(content_id)['content_type_id']
# Get content type id
... | Inquire detail introduction
:param content_id: Content ID to inquire
:type content_id: str
:rtype: dict | Below is the the instruction that describes the task:
### Input:
Inquire detail introduction
:param content_id: Content ID to inquire
:type content_id: str
:rtype: dict
### Response:
def get_detail_intro(self, content_id):
"""
Inquire detail introduction
:param co... |
def copy_on_s3(self, src_file_name, dst_file_name, bucket_name):
"""
Copies src file to destination within a bucket.
"""
try:
self.s3_client.head_bucket(Bucket=bucket_name)
except botocore.exceptions.ClientError as e: # pragma: no cover
# If a client erro... | Copies src file to destination within a bucket. | Below is the the instruction that describes the task:
### Input:
Copies src file to destination within a bucket.
### Response:
def copy_on_s3(self, src_file_name, dst_file_name, bucket_name):
"""
Copies src file to destination within a bucket.
"""
try:
self.s3_client.hea... |
def get_share_uk_and_shareid(cookie, url):
'''从共享链接中提示uk和shareid.
如果共享文件需要输入密码, 就会将need_pwd设为True
如果成功, 返回(need_pwd, uk, shareid)
如果失败, 就返回None
目前支持的链接格式有:
* http://pan.baidu.com/wap/link?uk=202032639&shareid=420754&third=0
* http://pan.baidu.com/share/link?uk=202032639&shareid=420754
... | 从共享链接中提示uk和shareid.
如果共享文件需要输入密码, 就会将need_pwd设为True
如果成功, 返回(need_pwd, uk, shareid)
如果失败, 就返回None
目前支持的链接格式有:
* http://pan.baidu.com/wap/link?uk=202032639&shareid=420754&third=0
* http://pan.baidu.com/share/link?uk=202032639&shareid=420754
* http://pan.baidu.com/s/1i3iQY48 | Below is the the instruction that describes the task:
### Input:
从共享链接中提示uk和shareid.
如果共享文件需要输入密码, 就会将need_pwd设为True
如果成功, 返回(need_pwd, uk, shareid)
如果失败, 就返回None
目前支持的链接格式有:
* http://pan.baidu.com/wap/link?uk=202032639&shareid=420754&third=0
* http://pan.baidu.com/share/link?uk=202032... |
def send_theme_file(self, filename):
"""
Function used to send static theme files from the theme folder to the browser.
"""
cache_timeout = self.get_send_file_max_age(filename)
return send_from_directory(self.config['THEME_STATIC_FOLDER'], filename,
... | Function used to send static theme files from the theme folder to the browser. | Below is the the instruction that describes the task:
### Input:
Function used to send static theme files from the theme folder to the browser.
### Response:
def send_theme_file(self, filename):
"""
Function used to send static theme files from the theme folder to the browser.
"""
c... |
def load_fasta_file_as_dict_of_seqs(filename):
"""Load a FASTA file and return the sequences as a dict of {ID: sequence string}
Args:
filename (str): Path to the FASTA file to load
Returns:
dict: Dictionary of IDs to their sequence strings
"""
results = {}
records = load_fast... | Load a FASTA file and return the sequences as a dict of {ID: sequence string}
Args:
filename (str): Path to the FASTA file to load
Returns:
dict: Dictionary of IDs to their sequence strings | Below is the the instruction that describes the task:
### Input:
Load a FASTA file and return the sequences as a dict of {ID: sequence string}
Args:
filename (str): Path to the FASTA file to load
Returns:
dict: Dictionary of IDs to their sequence strings
### Response:
def load_fasta_file_... |
def pelican_init(pelicanobj):
global global_siteurl
global_siteurl = pelicanobj.settings['SITEURL']
""" Prepare configurations for the MD plugin """
try:
import markdown
from .plantuml_md import PlantUMLMarkdownExtension
except:
# Markdown not available
logger.debug... | Prepare configurations for the MD plugin | Below is the the instruction that describes the task:
### Input:
Prepare configurations for the MD plugin
### Response:
def pelican_init(pelicanobj):
global global_siteurl
global_siteurl = pelicanobj.settings['SITEURL']
""" Prepare configurations for the MD plugin """
try:
import markdown... |
def create_for_data(cls, data, format, width, height, stride=None):
"""Same as ``ImageSurface(format, width, height, data, stride)``.
Exists for compatibility with pycairo.
"""
return cls(format, width, height, data, stride) | Same as ``ImageSurface(format, width, height, data, stride)``.
Exists for compatibility with pycairo. | Below is the the instruction that describes the task:
### Input:
Same as ``ImageSurface(format, width, height, data, stride)``.
Exists for compatibility with pycairo.
### Response:
def create_for_data(cls, data, format, width, height, stride=None):
"""Same as ``ImageSurface(format, width, height, d... |
def usage(self, auth, resource, metric, starttime, endtime, defer=False):
""" Returns metric usage for client and its subhierarchy.
Args:
auth: <cik> for authentication
resource: ResourceID
metrics: Metric to measure (as string), it may be an entity or consumable.
... | Returns metric usage for client and its subhierarchy.
Args:
auth: <cik> for authentication
resource: ResourceID
metrics: Metric to measure (as string), it may be an entity or consumable.
starttime: Start time of window to measure useage (format is ___).
... | Below is the the instruction that describes the task:
### Input:
Returns metric usage for client and its subhierarchy.
Args:
auth: <cik> for authentication
resource: ResourceID
metrics: Metric to measure (as string), it may be an entity or consumable.
startti... |
def to_dict(ramons, flatten=False):
"""
Converts a RAMON object list to a JSON-style dictionary. Useful for going
from an array of RAMONs to a dictionary, indexed by ID.
Arguments:
ramons (RAMON[]): A list of RAMON objects
flatten (boolean: False): Not implemented
Returns:
... | Converts a RAMON object list to a JSON-style dictionary. Useful for going
from an array of RAMONs to a dictionary, indexed by ID.
Arguments:
ramons (RAMON[]): A list of RAMON objects
flatten (boolean: False): Not implemented
Returns:
dict: A python dictionary of RAMON objects. | Below is the the instruction that describes the task:
### Input:
Converts a RAMON object list to a JSON-style dictionary. Useful for going
from an array of RAMONs to a dictionary, indexed by ID.
Arguments:
ramons (RAMON[]): A list of RAMON objects
flatten (boolean: False): Not implemented
... |
def alter(self, id_option_vip, tipo_opcao, nome_opcao_txt):
"""Change Option VIP from by the identifier.
:param id_option_vip: Identifier of the Option VIP. Integer value and greater than zero.
:param tipo_opcao: Type. String with a maximum of 50 characters and respect [a-zA-Z\_-]
:para... | Change Option VIP from by the identifier.
:param id_option_vip: Identifier of the Option VIP. Integer value and greater than zero.
:param tipo_opcao: Type. String with a maximum of 50 characters and respect [a-zA-Z\_-]
:param nome_opcao_txt: Name Option. String with a maximum of 50 characters a... | Below is the the instruction that describes the task:
### Input:
Change Option VIP from by the identifier.
:param id_option_vip: Identifier of the Option VIP. Integer value and greater than zero.
:param tipo_opcao: Type. String with a maximum of 50 characters and respect [a-zA-Z\_-]
:param ... |
def add(self, name, description):
"""Inserts a new Filter and returns its identifier.
:param name: Name. String with a maximum of 100 characters and respect [a-zA-Z\_-]
:param description: Description. String with a maximum of 200 characters and respect [a-zA-Z\_-]
:return: Following d... | Inserts a new Filter and returns its identifier.
:param name: Name. String with a maximum of 100 characters and respect [a-zA-Z\_-]
:param description: Description. String with a maximum of 200 characters and respect [a-zA-Z\_-]
:return: Following dictionary:
::
{'filter'... | Below is the the instruction that describes the task:
### Input:
Inserts a new Filter and returns its identifier.
:param name: Name. String with a maximum of 100 characters and respect [a-zA-Z\_-]
:param description: Description. String with a maximum of 200 characters and respect [a-zA-Z\_-]
... |
def save(self, annot=None, output_path=None):
"""Saves the collage to disk as an image.
Parameters
-----------
annot : str
text to annotate the figure with a super title
output_path : str
path to save the figure to.
Note: any spaces in the f... | Saves the collage to disk as an image.
Parameters
-----------
annot : str
text to annotate the figure with a super title
output_path : str
path to save the figure to.
Note: any spaces in the filename will be replace with ``_`` | Below is the the instruction that describes the task:
### Input:
Saves the collage to disk as an image.
Parameters
-----------
annot : str
text to annotate the figure with a super title
output_path : str
path to save the figure to.
Note: any spa... |
def _term(self, term):
"""Add a term to the query.
Arguments:
term (str): The term to add.
Returns:
SearchHelper: Self
"""
# All terms must be strings for Elasticsearch
term = str(term)
if term:
self.__query["q"] += term
... | Add a term to the query.
Arguments:
term (str): The term to add.
Returns:
SearchHelper: Self | Below is the the instruction that describes the task:
### Input:
Add a term to the query.
Arguments:
term (str): The term to add.
Returns:
SearchHelper: Self
### Response:
def _term(self, term):
"""Add a term to the query.
Arguments:
term (str)... |
def search_simple_form(context, **kwargs):
"""
Форма поиска
Пример использования::
{% search_simple_form %}
:param context: контекст
:param kwargs: html атрибуты формы
:return:
"""
data = kwargs
if 'action' in data:
del data['action']
if 'method' in data:
... | Форма поиска
Пример использования::
{% search_simple_form %}
:param context: контекст
:param kwargs: html атрибуты формы
:return: | Below is the the instruction that describes the task:
### Input:
Форма поиска
Пример использования::
{% search_simple_form %}
:param context: контекст
:param kwargs: html атрибуты формы
:return:
### Response:
def search_simple_form(context, **kwargs):
"""
Форма поиска
Пример... |
def check_can_migrate(cls, resource):
"""Check if virtual machine can be migrated to another datacenter."""
vm_id = cls.usable_id(resource)
result = cls.call('hosting.vm.can_migrate', vm_id)
if not result['can_migrate']:
if result['matched']:
matched = result... | Check if virtual machine can be migrated to another datacenter. | Below is the the instruction that describes the task:
### Input:
Check if virtual machine can be migrated to another datacenter.
### Response:
def check_can_migrate(cls, resource):
"""Check if virtual machine can be migrated to another datacenter."""
vm_id = cls.usable_id(resource)
result =... |
def create(self, path, value=b"", acl=None, ephemeral=False,
sequence=False):
""" wrapper that handles encoding (yay Py3k) """
super(XTransactionRequest, self).create(path, to_bytes(value), acl, ephemeral, sequence) | wrapper that handles encoding (yay Py3k) | Below is the the instruction that describes the task:
### Input:
wrapper that handles encoding (yay Py3k)
### Response:
def create(self, path, value=b"", acl=None, ephemeral=False,
sequence=False):
""" wrapper that handles encoding (yay Py3k) """
super(XTransactionRequest, self).crea... |
def _update_internal_column_state(self, column_names):
""" Update the internal state with some (possibly) new columns
:param column_names: an iterable which contains new column names
"""
for k in column_names:
if k not in self._column_name_idx:
self._column_n... | Update the internal state with some (possibly) new columns
:param column_names: an iterable which contains new column names | Below is the the instruction that describes the task:
### Input:
Update the internal state with some (possibly) new columns
:param column_names: an iterable which contains new column names
### Response:
def _update_internal_column_state(self, column_names):
""" Update the internal state with some ... |
def request(cls, name, *args, **kwargs):
"""Helper method for creating request messages.
Parameters
----------
name : str
The name of the message.
args : list of strings
The message arguments.
Keyword arguments
-----------------
m... | Helper method for creating request messages.
Parameters
----------
name : str
The name of the message.
args : list of strings
The message arguments.
Keyword arguments
-----------------
mid : str or None
Message ID to use or No... | Below is the the instruction that describes the task:
### Input:
Helper method for creating request messages.
Parameters
----------
name : str
The name of the message.
args : list of strings
The message arguments.
Keyword arguments
----------... |
def samples(self, nsamples, rstate=None):
"""
Draw `nsamples` samples randomly distributed within the unit cube.
Returns
-------
x : `~numpy.ndarray` with shape (nsamples, ndim)
A collection of coordinates within the unit cube.
"""
if rstate is None... | Draw `nsamples` samples randomly distributed within the unit cube.
Returns
-------
x : `~numpy.ndarray` with shape (nsamples, ndim)
A collection of coordinates within the unit cube. | Below is the the instruction that describes the task:
### Input:
Draw `nsamples` samples randomly distributed within the unit cube.
Returns
-------
x : `~numpy.ndarray` with shape (nsamples, ndim)
A collection of coordinates within the unit cube.
### Response:
def samples(self,... |
def psetex(self, key, milliseconds, value):
"""Set the value and expiration in milliseconds of a key.
:raises TypeError: if milliseconds is not int
"""
if not isinstance(milliseconds, int):
raise TypeError("milliseconds argument must be int")
fut = self.execute(b'PSE... | Set the value and expiration in milliseconds of a key.
:raises TypeError: if milliseconds is not int | Below is the the instruction that describes the task:
### Input:
Set the value and expiration in milliseconds of a key.
:raises TypeError: if milliseconds is not int
### Response:
def psetex(self, key, milliseconds, value):
"""Set the value and expiration in milliseconds of a key.
:raises... |
def position_and_velocity(self, name, tdb, tdb2=0.0):
"""[DEPRECATED] Compute the position and velocity of `name` at ``tdb [+ tdb2]``.
The position and velocity are returned in a 2-tuple::
([x y z], [xdot ydot zdot])
The barycentric dynamical time `tdb` argument should be a float.... | [DEPRECATED] Compute the position and velocity of `name` at ``tdb [+ tdb2]``.
The position and velocity are returned in a 2-tuple::
([x y z], [xdot ydot zdot])
The barycentric dynamical time `tdb` argument should be a float.
If there are many dates you want computed, then make `td... | Below is the the instruction that describes the task:
### Input:
[DEPRECATED] Compute the position and velocity of `name` at ``tdb [+ tdb2]``.
The position and velocity are returned in a 2-tuple::
([x y z], [xdot ydot zdot])
The barycentric dynamical time `tdb` argument should be a fl... |
def _longest_contig(self, contig_set, contig_lengths):
'''Returns the name of the longest contig, from the set of names contig_set. contig_lengths
is expected to be a dictionary of contig name => length.'''
longest_name = None
max_length = -1
for name in contig_set:
... | Returns the name of the longest contig, from the set of names contig_set. contig_lengths
is expected to be a dictionary of contig name => length. | Below is the the instruction that describes the task:
### Input:
Returns the name of the longest contig, from the set of names contig_set. contig_lengths
is expected to be a dictionary of contig name => length.
### Response:
def _longest_contig(self, contig_set, contig_lengths):
'''Returns the n... |
def split_predicate(ex: Extraction) -> Extraction:
"""
Ensure single word predicate
by adding "before-predicate" and "after-predicate"
arguments.
"""
rel_toks = ex.toks[char_to_word_index(ex.rel.span[0], ex.sent) \
: char_to_word_index(ex.rel.span[1], ex.sent) + 1]
if ... | Ensure single word predicate
by adding "before-predicate" and "after-predicate"
arguments. | Below is the the instruction that describes the task:
### Input:
Ensure single word predicate
by adding "before-predicate" and "after-predicate"
arguments.
### Response:
def split_predicate(ex: Extraction) -> Extraction:
"""
Ensure single word predicate
by adding "before-predicate" and "after-p... |
def get_invocation_command_nodefault(
toolset, tool, user_provided_command=[], additional_paths=[], path_last=False):
"""
A helper rule to get the command to invoke some tool. If
'user-provided-command' is not given, tries to find binary named 'tool' in
PATH and in the passed 'additional... | A helper rule to get the command to invoke some tool. If
'user-provided-command' is not given, tries to find binary named 'tool' in
PATH and in the passed 'additional-path'. Otherwise, verifies that the first
element of 'user-provided-command' is an existing program.
This rule returns t... | Below is the the instruction that describes the task:
### Input:
A helper rule to get the command to invoke some tool. If
'user-provided-command' is not given, tries to find binary named 'tool' in
PATH and in the passed 'additional-path'. Otherwise, verifies that the first
element of 'user-p... |
def _write(self, data):
"""
Note: print()-statements cause to multiple write calls.
(write('line') and write('\n')). Of course we don't want to call
`run_in_terminal` for every individual call, because that's too
expensive, and as long as the newline hasn't been... | Note: print()-statements cause to multiple write calls.
(write('line') and write('\n')). Of course we don't want to call
`run_in_terminal` for every individual call, because that's too
expensive, and as long as the newline hasn't been written, the
text itself is a... | Below is the the instruction that describes the task:
### Input:
Note: print()-statements cause to multiple write calls.
(write('line') and write('\n')). Of course we don't want to call
`run_in_terminal` for every individual call, because that's too
expensive, and as long a... |
def focus_next(self):
"""move focus to next position (DFO)"""
w, focuspos = self.get_focus()
next = self._tree.next_position(focuspos)
if next is not None:
self.set_focus(next) | move focus to next position (DFO) | Below is the the instruction that describes the task:
### Input:
move focus to next position (DFO)
### Response:
def focus_next(self):
"""move focus to next position (DFO)"""
w, focuspos = self.get_focus()
next = self._tree.next_position(focuspos)
if next is not None:
se... |
def _dist_to_trans(self, dist):
"""Convert mouse x, y movement into x, y, z translations"""
rae = np.array([self.roll, self.azimuth, self.elevation]) * np.pi / 180
sro, saz, sel = np.sin(rae)
cro, caz, cel = np.cos(rae)
dx = (+ dist[0] * (cro * caz + sro * sel * saz)
... | Convert mouse x, y movement into x, y, z translations | Below is the the instruction that describes the task:
### Input:
Convert mouse x, y movement into x, y, z translations
### Response:
def _dist_to_trans(self, dist):
"""Convert mouse x, y movement into x, y, z translations"""
rae = np.array([self.roll, self.azimuth, self.elevation]) * np.pi / 180
... |
def get_queryset(self):
"""
Return queryset limited to not removed entries.
"""
kwargs = {'model': self.model, 'using': self._db}
if hasattr(self, '_hints'):
kwargs['hints'] = self._hints
return self._queryset_class(**kwargs).filter(is_removed=False) | Return queryset limited to not removed entries. | Below is the the instruction that describes the task:
### Input:
Return queryset limited to not removed entries.
### Response:
def get_queryset(self):
"""
Return queryset limited to not removed entries.
"""
kwargs = {'model': self.model, 'using': self._db}
if hasattr(self, '... |
def _diff(state_data, resource_object):
'''helper method to compare salt state info with the PagerDuty API json structure,
and determine if we need to update.
returns the dict to pass to the PD API to perform the update, or empty dict if no update.
'''
objects_differ = None
for k, v in state_d... | helper method to compare salt state info with the PagerDuty API json structure,
and determine if we need to update.
returns the dict to pass to the PD API to perform the update, or empty dict if no update. | Below is the the instruction that describes the task:
### Input:
helper method to compare salt state info with the PagerDuty API json structure,
and determine if we need to update.
returns the dict to pass to the PD API to perform the update, or empty dict if no update.
### Response:
def _diff(state_data,... |
def load_colormap(self, name=None):
"""
Loads a colormap of the supplied name. None means used the internal
name. (See self.get_name())
"""
if name == None: name = self.get_name()
if name == "" or not type(name)==str: return "Error: Bad name."
# assemble the pat... | Loads a colormap of the supplied name. None means used the internal
name. (See self.get_name()) | Below is the the instruction that describes the task:
### Input:
Loads a colormap of the supplied name. None means used the internal
name. (See self.get_name())
### Response:
def load_colormap(self, name=None):
"""
Loads a colormap of the supplied name. None means used the internal
... |
def get_id(self):
"""Returns unique id of an alignment. """
return hash(str(self.title) + str(self.best_score()) + str(self.hit_def)) | Returns unique id of an alignment. | Below is the the instruction that describes the task:
### Input:
Returns unique id of an alignment.
### Response:
def get_id(self):
"""Returns unique id of an alignment. """
return hash(str(self.title) + str(self.best_score()) + str(self.hit_def)) |
def _interpolate_with_fill(self, method='pad', axis=0, inplace=False,
limit=None, fill_value=None, coerce=False,
downcast=None):
""" fillna but using the interpolate machinery """
inplace = validate_bool_kwarg(inplace, 'inplace')
# ... | fillna but using the interpolate machinery | Below is the the instruction that describes the task:
### Input:
fillna but using the interpolate machinery
### Response:
def _interpolate_with_fill(self, method='pad', axis=0, inplace=False,
limit=None, fill_value=None, coerce=False,
downcast=None):
... |
def AppMoVCopeland(profile, alpha=0.5):
"""
Returns an integer that is equal to the margin of victory of the election profile, that is,
the smallest number k such that changing k votes can change the winners.
:ivar Profile profile: A Profile object that represents an election profile.
"""
# Cu... | Returns an integer that is equal to the margin of victory of the election profile, that is,
the smallest number k such that changing k votes can change the winners.
:ivar Profile profile: A Profile object that represents an election profile. | Below is the the instruction that describes the task:
### Input:
Returns an integer that is equal to the margin of victory of the election profile, that is,
the smallest number k such that changing k votes can change the winners.
:ivar Profile profile: A Profile object that represents an election profile.
... |
def _init_unique_sets(self):
"""Initialise sets used for uniqueness checking."""
ks = dict()
for t in self._unique_checks:
key = t[0]
ks[key] = set() # empty set
return ks | Initialise sets used for uniqueness checking. | Below is the the instruction that describes the task:
### Input:
Initialise sets used for uniqueness checking.
### Response:
def _init_unique_sets(self):
"""Initialise sets used for uniqueness checking."""
ks = dict()
for t in self._unique_checks:
key = t[0]
ks[key]... |
def match_alphabet(self, pattern):
"""Initialise the alphabet for the Bitap algorithm.
Args:
pattern: The text to encode.
Returns:
Hash of character locations.
"""
s = {}
for char in pattern:
s[char] = 0
for i in xrange(len(pattern)):
s[pattern[i]] |= 1 << (len(patt... | Initialise the alphabet for the Bitap algorithm.
Args:
pattern: The text to encode.
Returns:
Hash of character locations. | Below is the the instruction that describes the task:
### Input:
Initialise the alphabet for the Bitap algorithm.
Args:
pattern: The text to encode.
Returns:
Hash of character locations.
### Response:
def match_alphabet(self, pattern):
"""Initialise the alphabet for the Bitap algorithm.
... |
def is_dec(ip):
"""Return true if the IP address is in decimal notation."""
try:
dec = int(str(ip))
except ValueError:
return False
if dec > 4294967295 or dec < 0:
return False
return True | Return true if the IP address is in decimal notation. | Below is the the instruction that describes the task:
### Input:
Return true if the IP address is in decimal notation.
### Response:
def is_dec(ip):
"""Return true if the IP address is in decimal notation."""
try:
dec = int(str(ip))
except ValueError:
return False
if dec > 429496729... |
def _generate_queues(queues, exchange, platform_queue):
""" Queues known by this worker """
return set([
Queue('celery', exchange, routing_key='celery'),
Queue(platform_queue, exchange, routing_key='#'),
] + [
Queue(q_name, exchange, routing_key=q_name)
... | Queues known by this worker | Below is the the instruction that describes the task:
### Input:
Queues known by this worker
### Response:
def _generate_queues(queues, exchange, platform_queue):
""" Queues known by this worker """
return set([
Queue('celery', exchange, routing_key='celery'),
Queue(platform... |
def readFILTERLIST(self):
""" Read a length-prefixed list of FILTERs """
number = self.readUI8()
return [self.readFILTER() for _ in range(number)] | Read a length-prefixed list of FILTERs | Below is the the instruction that describes the task:
### Input:
Read a length-prefixed list of FILTERs
### Response:
def readFILTERLIST(self):
""" Read a length-prefixed list of FILTERs """
number = self.readUI8()
return [self.readFILTER() for _ in range(number)] |
def get_permission_checks(self, request, view):
"""
Get permission checks that will be executed for current action.
"""
if view.action is None:
return []
# if permissions are defined for view directly - use them.
if hasattr(view, view.action + '_permissions'):... | Get permission checks that will be executed for current action. | Below is the the instruction that describes the task:
### Input:
Get permission checks that will be executed for current action.
### Response:
def get_permission_checks(self, request, view):
"""
Get permission checks that will be executed for current action.
"""
if view.action is No... |
def analyze_entities(self, document, encoding_type=None, retry=None, timeout=None, metadata=None):
"""
Finds named entities in the text along with entity types,
salience, mentions for each entity, and other properties.
:param document: Input document.
If a dict is provided, ... | Finds named entities in the text along with entity types,
salience, mentions for each entity, and other properties.
:param document: Input document.
If a dict is provided, it must be of the same form as the protobuf message Document
:type document: dict or class google.cloud.languag... | Below is the the instruction that describes the task:
### Input:
Finds named entities in the text along with entity types,
salience, mentions for each entity, and other properties.
:param document: Input document.
If a dict is provided, it must be of the same form as the protobuf messag... |
def _get_statevector(self):
"""Return the current statevector in JSON Result spec format"""
vec = np.reshape(self._statevector, 2 ** self._number_of_qubits)
# Expand complex numbers
vec = np.stack([vec.real, vec.imag], axis=1)
# Truncate small values
vec[abs(vec) < self._... | Return the current statevector in JSON Result spec format | Below is the the instruction that describes the task:
### Input:
Return the current statevector in JSON Result spec format
### Response:
def _get_statevector(self):
"""Return the current statevector in JSON Result spec format"""
vec = np.reshape(self._statevector, 2 ** self._number_of_qubits)
... |
def get_chat_administrators(self, chat_id):
"""
Use this method to get a list of administrators in a chat. On success, returns an Array of ChatMember objects that contains information about all chat administrators except other bots. If the chat is a group or a supergroup and no administrators were appoi... | Use this method to get a list of administrators in a chat. On success, returns an Array of ChatMember objects that contains information about all chat administrators except other bots. If the chat is a group or a supergroup and no administrators were appointed, only the creator will be returned.
https://core.t... | Below is the the instruction that describes the task:
### Input:
Use this method to get a list of administrators in a chat. On success, returns an Array of ChatMember objects that contains information about all chat administrators except other bots. If the chat is a group or a supergroup and no administrators were ... |
def delete_image_tar(file_obj, tar):
'''delete image tar will close a file object (if extracted into
memory) or delete from the file system (if saved to disk)'''
try:
file_obj.close()
except:
tar.close()
if os.path.exists(file_obj):
os.remove(file_obj)
deleted = True
... | delete image tar will close a file object (if extracted into
memory) or delete from the file system (if saved to disk) | Below is the the instruction that describes the task:
### Input:
delete image tar will close a file object (if extracted into
memory) or delete from the file system (if saved to disk)
### Response:
def delete_image_tar(file_obj, tar):
'''delete image tar will close a file object (if extracted into
memo... |
def enable_job(name, **kwargs):
'''
Enable a job in the minion's schedule
CLI Example:
.. code-block:: bash
salt '*' schedule.enable_job job1
'''
ret = {'comment': [],
'result': True}
if not name:
ret['comment'] = 'Job name is required.'
ret['result'] ... | Enable a job in the minion's schedule
CLI Example:
.. code-block:: bash
salt '*' schedule.enable_job job1 | Below is the the instruction that describes the task:
### Input:
Enable a job in the minion's schedule
CLI Example:
.. code-block:: bash
salt '*' schedule.enable_job job1
### Response:
def enable_job(name, **kwargs):
'''
Enable a job in the minion's schedule
CLI Example:
.. cod... |
def get_base_url(html: str) -> str:
"""
Search for login url from VK login page
"""
forms = BeautifulSoup(html, 'html.parser').find_all('form')
if not forms:
raise VVKBaseUrlException('Form for login not found')
elif len(forms) > 1:
raise VVKBaseUrlException('More than one login ... | Search for login url from VK login page | Below is the the instruction that describes the task:
### Input:
Search for login url from VK login page
### Response:
def get_base_url(html: str) -> str:
"""
Search for login url from VK login page
"""
forms = BeautifulSoup(html, 'html.parser').find_all('form')
if not forms:
raise VVKB... |
def retain_error(self, error, frame=None):
"""
Adds details of an error to the report.
:param error: The error exception to add to the report.
"""
if frame is None:
stack = traceback.format_exc()
self.labels.add("@iopipe/error")
else:
... | Adds details of an error to the report.
:param error: The error exception to add to the report. | Below is the the instruction that describes the task:
### Input:
Adds details of an error to the report.
:param error: The error exception to add to the report.
### Response:
def retain_error(self, error, frame=None):
"""
Adds details of an error to the report.
:param error: The e... |
def find_shows_by_ids(self, show_ids):
"""doc: http://open.youku.com/docs/doc?id=60
"""
url = 'https://openapi.youku.com/v2/shows/show_batch.json'
params = {
'client_id': self.client_id,
'show_ids': show_ids
}
r = requests.get(url, params=params)
... | doc: http://open.youku.com/docs/doc?id=60 | Below is the the instruction that describes the task:
### Input:
doc: http://open.youku.com/docs/doc?id=60
### Response:
def find_shows_by_ids(self, show_ids):
"""doc: http://open.youku.com/docs/doc?id=60
"""
url = 'https://openapi.youku.com/v2/shows/show_batch.json'
params = {
... |
def make_utool_json_encoder(allow_pickle=False):
"""
References:
http://stackoverflow.com/questions/8230315/python-sets-are
http://stackoverflow.com/questions/11561932/why-does-json
https://github.com/jsonpickle/jsonpickle
http://stackoverflow.com/questions/24369666/typeerror-b1
... | References:
http://stackoverflow.com/questions/8230315/python-sets-are
http://stackoverflow.com/questions/11561932/why-does-json
https://github.com/jsonpickle/jsonpickle
http://stackoverflow.com/questions/24369666/typeerror-b1
http://stackoverflow.com/questions/30469575/how-to-pi... | Below is the the instruction that describes the task:
### Input:
References:
http://stackoverflow.com/questions/8230315/python-sets-are
http://stackoverflow.com/questions/11561932/why-does-json
https://github.com/jsonpickle/jsonpickle
http://stackoverflow.com/questions/24369666/typee... |
def delete_dcnm_in_nwk(self, tenant_id, fw_dict, is_fw_virt=False):
"""Delete the DCNM In Network and store the result in DB. """
tenant_name = fw_dict.get('tenant_name')
ret = self._delete_service_nwk(tenant_id, tenant_name, 'in')
if ret:
res = fw_const.DCNM_IN_NETWORK_DEL_S... | Delete the DCNM In Network and store the result in DB. | Below is the the instruction that describes the task:
### Input:
Delete the DCNM In Network and store the result in DB.
### Response:
def delete_dcnm_in_nwk(self, tenant_id, fw_dict, is_fw_virt=False):
"""Delete the DCNM In Network and store the result in DB. """
tenant_name = fw_dict.get('tenant_n... |
def _compute_follow(self):
"""Computes the FOLLOW set for every non-terminal in the grammar.
Tenatively based on _compute_follow in PLY.
"""
self._follow[self.start_symbol].add(END_OF_INPUT)
while True:
changed = False
for nonterminal, productions in se... | Computes the FOLLOW set for every non-terminal in the grammar.
Tenatively based on _compute_follow in PLY. | Below is the the instruction that describes the task:
### Input:
Computes the FOLLOW set for every non-terminal in the grammar.
Tenatively based on _compute_follow in PLY.
### Response:
def _compute_follow(self):
"""Computes the FOLLOW set for every non-terminal in the grammar.
Tenatively... |
def exception_occurred(self, text, is_traceback):
"""
Exception ocurred in the internal console.
Show a QDialog or the internal console to warn the user.
"""
# Skip errors without traceback or dismiss
if (not is_traceback and self.error_dlg is None) or self.dismis... | Exception ocurred in the internal console.
Show a QDialog or the internal console to warn the user. | Below is the the instruction that describes the task:
### Input:
Exception ocurred in the internal console.
Show a QDialog or the internal console to warn the user.
### Response:
def exception_occurred(self, text, is_traceback):
"""
Exception ocurred in the internal console.
... |
def _find_usage_network_interfaces(self):
"""find usage of network interfaces"""
enis = paginate_dict(
self.conn.describe_network_interfaces,
alc_marker_path=['NextToken'],
alc_data_path=['NetworkInterfaces'],
alc_marker_param='NextToken'
)
... | find usage of network interfaces | Below is the the instruction that describes the task:
### Input:
find usage of network interfaces
### Response:
def _find_usage_network_interfaces(self):
"""find usage of network interfaces"""
enis = paginate_dict(
self.conn.describe_network_interfaces,
alc_marker_path=['Nex... |
def async_session_handler(self, signal: str) -> None:
"""Signalling from websocket.
data - new data available for processing.
state - network state has changed.
"""
if signal == 'data':
self.async_event_handler(self.websocket.data)
elif signal == 'state... | Signalling from websocket.
data - new data available for processing.
state - network state has changed. | Below is the the instruction that describes the task:
### Input:
Signalling from websocket.
data - new data available for processing.
state - network state has changed.
### Response:
def async_session_handler(self, signal: str) -> None:
"""Signalling from websocket.
data ... |
def copy(string):
"""Copy given string into system clipboard.
"""
win32clipboard.OpenClipboard()
win32clipboard.EmptyClipboard()
win32clipboard.SetClipboardText(string)
win32clipboard.CloseClipboard() | Copy given string into system clipboard. | Below is the the instruction that describes the task:
### Input:
Copy given string into system clipboard.
### Response:
def copy(string):
"""Copy given string into system clipboard.
"""
win32clipboard.OpenClipboard()
win32clipboard.EmptyClipboard()
win32clipboard.SetClipboardText(string)
wi... |
def is_all_field_none(self):
"""
:rtype: bool
"""
if self._id_ is not None:
return False
if self._created is not None:
return False
if self._updated is not None:
return False
if self._action is not None:
return F... | :rtype: bool | Below is the the instruction that describes the task:
### Input:
:rtype: bool
### Response:
def is_all_field_none(self):
"""
:rtype: bool
"""
if self._id_ is not None:
return False
if self._created is not None:
return False
if self._updated... |
def name_of_the_nearest_place(feature, parent):
"""If the impact layer has a distance field, it will return the name
of the nearest place.
e.g. name_of_the_nearest_place() -> Tokyo
"""
_ = feature, parent # NOQA
layer = exposure_summary_layer()
if not layer:
return None
index... | If the impact layer has a distance field, it will return the name
of the nearest place.
e.g. name_of_the_nearest_place() -> Tokyo | Below is the the instruction that describes the task:
### Input:
If the impact layer has a distance field, it will return the name
of the nearest place.
e.g. name_of_the_nearest_place() -> Tokyo
### Response:
def name_of_the_nearest_place(feature, parent):
"""If the impact layer has a distance field, ... |
async def dispatch_request(
self, request_context: Optional[RequestContext]=None,
) -> ResponseReturnValue:
"""Dispatch the request to the view function.
Arguments:
request_context: The request context, optional as Flask
omits this argument.
"""
r... | Dispatch the request to the view function.
Arguments:
request_context: The request context, optional as Flask
omits this argument. | Below is the the instruction that describes the task:
### Input:
Dispatch the request to the view function.
Arguments:
request_context: The request context, optional as Flask
omits this argument.
### Response:
async def dispatch_request(
self, request_context: Optional[... |
def phenSpecificEffects(snps,pheno1,pheno2,K=None,covs=None,test='lrt'):
"""
Univariate fixed effects interaction test for phenotype specific SNP effects
Args:
snps: [N x S] SP.array of S SNPs for N individuals (test SNPs)
pheno1: [N x 1] SP.array of 1 phenotype for N individuals
... | Univariate fixed effects interaction test for phenotype specific SNP effects
Args:
snps: [N x S] SP.array of S SNPs for N individuals (test SNPs)
pheno1: [N x 1] SP.array of 1 phenotype for N individuals
pheno2: [N x 1] SP.array of 1 phenotype for N individuals
K: [N x N] SP.... | Below is the the instruction that describes the task:
### Input:
Univariate fixed effects interaction test for phenotype specific SNP effects
Args:
snps: [N x S] SP.array of S SNPs for N individuals (test SNPs)
pheno1: [N x 1] SP.array of 1 phenotype for N individuals
pheno2: [N x 1] ... |
def __find_prime_in_row(self, row):
"""
Find the first prime element in the specified row. Returns
the column index, or -1 if no starred element was found.
"""
col = -1
for j in range(self.n):
if self.marked[row][j] == 2:
col = j
... | Find the first prime element in the specified row. Returns
the column index, or -1 if no starred element was found. | Below is the the instruction that describes the task:
### Input:
Find the first prime element in the specified row. Returns
the column index, or -1 if no starred element was found.
### Response:
def __find_prime_in_row(self, row):
"""
Find the first prime element in the specified row. Retur... |
def isolate_region(sequences, start, end, gap_char='-'):
"""
Replace regions before and after start:end with gap chars
"""
# Check arguments
if end <= start:
raise ValueError("start of slice must precede end ({0} !> {1})".format(
end, start))
for sequence in sequences:
... | Replace regions before and after start:end with gap chars | Below is the the instruction that describes the task:
### Input:
Replace regions before and after start:end with gap chars
### Response:
def isolate_region(sequences, start, end, gap_char='-'):
"""
Replace regions before and after start:end with gap chars
"""
# Check arguments
if end <= start:
... |
def replace_pod_security_policy(self, name, body, **kwargs): # noqa: E501
"""replace_pod_security_policy # noqa: E501
replace the specified PodSecurityPolicy # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_... | replace_pod_security_policy # noqa: E501
replace the specified PodSecurityPolicy # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.replace_pod_security_policy(name, body, async_req=Tr... | Below is the the instruction that describes the task:
### Input:
replace_pod_security_policy # noqa: E501
replace the specified PodSecurityPolicy # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
... |
def get_version(version=None):
"""
Return full version nr, inc. rc, beta etc tags.
For example: `2.0.0a1`
:rtype: str
"""
v = version or __version__
if len(v) == 4:
return '{0}{1}'.format(short_version(v), v[3])
return short_version(v) | Return full version nr, inc. rc, beta etc tags.
For example: `2.0.0a1`
:rtype: str | Below is the the instruction that describes the task:
### Input:
Return full version nr, inc. rc, beta etc tags.
For example: `2.0.0a1`
:rtype: str
### Response:
def get_version(version=None):
"""
Return full version nr, inc. rc, beta etc tags.
For example: `2.0.0a1`
:rtype: str
"""
... |
def convert_images(image_list, image_format="png", timeout=20):
"""Convert images from list of images to given format, if needed.
Figure out the types of the images that were extracted from
the tarball and determine how to convert them into PNG.
:param: image_list ([string, string, ...]): the list of ... | Convert images from list of images to given format, if needed.
Figure out the types of the images that were extracted from
the tarball and determine how to convert them into PNG.
:param: image_list ([string, string, ...]): the list of image files
extracted from the tarball in step 1
:param: im... | Below is the the instruction that describes the task:
### Input:
Convert images from list of images to given format, if needed.
Figure out the types of the images that were extracted from
the tarball and determine how to convert them into PNG.
:param: image_list ([string, string, ...]): the list of im... |
def collapse_all(self):
"""
Collapse all positions; works only if the underlying tree allows it.
"""
if implementsCollapseAPI(self._tree):
self._tree.collapse_all()
self.set_focus(self._tree.root)
self._walker.clear_cache()
self.refresh() | Collapse all positions; works only if the underlying tree allows it. | Below is the the instruction that describes the task:
### Input:
Collapse all positions; works only if the underlying tree allows it.
### Response:
def collapse_all(self):
"""
Collapse all positions; works only if the underlying tree allows it.
"""
if implementsCollapseAPI(self._tre... |
def content_type(self):
"""Return the value of Content-Type header field.
The value for the Content-Type header field is determined from
the :attr:`media_type` and :attr:`charset` data attributes.
Returns:
str: Value of Content-Type header field
"""
if (self.m... | Return the value of Content-Type header field.
The value for the Content-Type header field is determined from
the :attr:`media_type` and :attr:`charset` data attributes.
Returns:
str: Value of Content-Type header field | Below is the the instruction that describes the task:
### Input:
Return the value of Content-Type header field.
The value for the Content-Type header field is determined from
the :attr:`media_type` and :attr:`charset` data attributes.
Returns:
str: Value of Content-Type header fi... |
def new_log_filepath(self):
'''returns a filepath to a log which does not currently exist and is suitable for DF logging'''
lastlog_filename = os.path.join(self.dataflash_dir,'LASTLOG.TXT')
if os.path.exists(lastlog_filename) and os.stat(lastlog_filename).st_size != 0:
fh = open(last... | returns a filepath to a log which does not currently exist and is suitable for DF logging | Below is the the instruction that describes the task:
### Input:
returns a filepath to a log which does not currently exist and is suitable for DF logging
### Response:
def new_log_filepath(self):
'''returns a filepath to a log which does not currently exist and is suitable for DF logging'''
lastlo... |
def get_remote_client(self, target_name, user=None, password=None):
"""
Returns a new client for the remote target. This is a lightweight
client that only uses different credentials and shares the transport
with the underlying client
"""
if user:
base = self.g... | Returns a new client for the remote target. This is a lightweight
client that only uses different credentials and shares the transport
with the underlying client | Below is the the instruction that describes the task:
### Input:
Returns a new client for the remote target. This is a lightweight
client that only uses different credentials and shares the transport
with the underlying client
### Response:
def get_remote_client(self, target_name, user=None, passwo... |
def load(hdfs_path, **kwargs):
"""\
Read the content of ``hdfs_path`` and return it.
Keyword arguments are passed to :func:`open`. The `"mode"` kwarg
must be readonly.
"""
m, _ = common.parse_mode(kwargs.get("mode", "r"))
if m != "r":
raise ValueError("opening mode must be readonly"... | \
Read the content of ``hdfs_path`` and return it.
Keyword arguments are passed to :func:`open`. The `"mode"` kwarg
must be readonly. | Below is the the instruction that describes the task:
### Input:
\
Read the content of ``hdfs_path`` and return it.
Keyword arguments are passed to :func:`open`. The `"mode"` kwarg
must be readonly.
### Response:
def load(hdfs_path, **kwargs):
"""\
Read the content of ``hdfs_path`` and return ... |
def _add_data(self, plotter_cls, *args, **kwargs):
"""
Add new plots to the project
Parameters
----------
%(ProjectPlotter._add_data.parameters.no_filename_or_obj)s
Other Parameters
----------------
%(ProjectPlotter._add_data.other_parameters)s
... | Add new plots to the project
Parameters
----------
%(ProjectPlotter._add_data.parameters.no_filename_or_obj)s
Other Parameters
----------------
%(ProjectPlotter._add_data.other_parameters)s
Returns
-------
%(ProjectPlotter._add_data.returns)s | Below is the the instruction that describes the task:
### Input:
Add new plots to the project
Parameters
----------
%(ProjectPlotter._add_data.parameters.no_filename_or_obj)s
Other Parameters
----------------
%(ProjectPlotter._add_data.other_parameters)s
Re... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.