code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def construct_for(self, service_name):
"""
Builds a new, specialized ``Connection`` subclass for a given service.
This will introspect a service, determine all the API calls it has &
constructs a brand new class with those methods on it.
:param service_name: The name of the ser... | Builds a new, specialized ``Connection`` subclass for a given service.
This will introspect a service, determine all the API calls it has &
constructs a brand new class with those methods on it.
:param service_name: The name of the service to construct a connection
for. Ex. ``sqs``... | Below is the the instruction that describes the task:
### Input:
Builds a new, specialized ``Connection`` subclass for a given service.
This will introspect a service, determine all the API calls it has &
constructs a brand new class with those methods on it.
:param service_name: The name ... |
def walk(fn, obj, *args, **kwargs):
"""Recursively walk an object graph applying `fn`/`args` to objects."""
if type(obj) in [list, tuple]:
return list(walk(fn, o, *args) for o in obj)
if type(obj) is dict:
return dict((walk(fn, k, *args), walk(fn, v, *args)) for k, v in
o... | Recursively walk an object graph applying `fn`/`args` to objects. | Below is the the instruction that describes the task:
### Input:
Recursively walk an object graph applying `fn`/`args` to objects.
### Response:
def walk(fn, obj, *args, **kwargs):
"""Recursively walk an object graph applying `fn`/`args` to objects."""
if type(obj) in [list, tuple]:
return list(wal... |
def cache_file(symbol, func, has_date, root, date_type='date'):
"""
Data file
Args:
symbol: symbol
func: use function to categorize data
has_date: contains date in data file
root: root path
date_type: parameters pass to utils.cur_time, [date, time, time_path, ...]
... | Data file
Args:
symbol: symbol
func: use function to categorize data
has_date: contains date in data file
root: root path
date_type: parameters pass to utils.cur_time, [date, time, time_path, ...]
Returns:
str: date file | Below is the the instruction that describes the task:
### Input:
Data file
Args:
symbol: symbol
func: use function to categorize data
has_date: contains date in data file
root: root path
date_type: parameters pass to utils.cur_time, [date, time, time_path, ...]
Retu... |
def add_members(self, project, params={}, **options):
"""Adds the specified list of users as members of the project. Returns the updated project record.
Parameters
----------
project : {Id} The project to add members to.
[data] : {Object} Data for the request
- member... | Adds the specified list of users as members of the project. Returns the updated project record.
Parameters
----------
project : {Id} The project to add members to.
[data] : {Object} Data for the request
- members : {Array} An array of members to add to the project. | Below is the the instruction that describes the task:
### Input:
Adds the specified list of users as members of the project. Returns the updated project record.
Parameters
----------
project : {Id} The project to add members to.
[data] : {Object} Data for the request
- mem... |
def prt_hier_down(self, goid, prt=sys.stdout):
"""Write hierarchy for all GO IDs below GO ID in arg, goid."""
wrhiercfg = self._get_wrhiercfg()
obj = WrHierPrt(self.gosubdag.go2obj, self.gosubdag.go2nt, wrhiercfg, prt)
obj.prt_hier_rec(goid)
return obj.items_list | Write hierarchy for all GO IDs below GO ID in arg, goid. | Below is the the instruction that describes the task:
### Input:
Write hierarchy for all GO IDs below GO ID in arg, goid.
### Response:
def prt_hier_down(self, goid, prt=sys.stdout):
"""Write hierarchy for all GO IDs below GO ID in arg, goid."""
wrhiercfg = self._get_wrhiercfg()
obj = WrHie... |
def ensure_number(num, *args, **kwargs):
"""
Returns *num* again if it is an instance of :py:class:`Number`, or uses all passed arguments to
create one and returns it.
"""
return num if isinstance(num, Number) else Number(num, *args, **kwargs) | Returns *num* again if it is an instance of :py:class:`Number`, or uses all passed arguments to
create one and returns it. | Below is the the instruction that describes the task:
### Input:
Returns *num* again if it is an instance of :py:class:`Number`, or uses all passed arguments to
create one and returns it.
### Response:
def ensure_number(num, *args, **kwargs):
"""
Returns *num* again if it is an instance of :py:class:`N... |
def sign_cert(self, ca, csr, expires=None, algorithm=None, subject=None, cn_in_san=True,
csr_format=Encoding.PEM, subject_alternative_name=None, key_usage=None,
extended_key_usage=None, tls_feature=None, ocsp_no_check=False, extra_extensions=None,
password=None):
... | Create a signed certificate from a CSR.
**PLEASE NOTE:** This function creates the raw certificate and is usually not invoked directly. It is
called by :py:func:`Certificate.objects.init() <django_ca.managers.CertificateManager.init>`, which
passes along all parameters unchanged and saves the r... | Below is the the instruction that describes the task:
### Input:
Create a signed certificate from a CSR.
**PLEASE NOTE:** This function creates the raw certificate and is usually not invoked directly. It is
called by :py:func:`Certificate.objects.init() <django_ca.managers.CertificateManager.init>`... |
def _interpolate_cube(self, lon, lat, egy=None, interp_log=True):
"""Perform interpolation on a healpix cube. If egy is None
then interpolation will be performed on the existing energy
planes.
"""
shape = np.broadcast(lon, lat, egy).shape
lon = lon * np.ones(shape)
... | Perform interpolation on a healpix cube. If egy is None
then interpolation will be performed on the existing energy
planes. | Below is the the instruction that describes the task:
### Input:
Perform interpolation on a healpix cube. If egy is None
then interpolation will be performed on the existing energy
planes.
### Response:
def _interpolate_cube(self, lon, lat, egy=None, interp_log=True):
"""Perform interpolat... |
def ReadArtifact(self, name, cursor=None):
"""Looks up an artifact with given name from the database."""
cursor.execute("SELECT definition FROM artifacts WHERE name = %s", [name])
row = cursor.fetchone()
if row is None:
raise db.UnknownArtifactError(name)
else:
return _RowToArtifact(row... | Looks up an artifact with given name from the database. | Below is the the instruction that describes the task:
### Input:
Looks up an artifact with given name from the database.
### Response:
def ReadArtifact(self, name, cursor=None):
"""Looks up an artifact with given name from the database."""
cursor.execute("SELECT definition FROM artifacts WHERE name = %s", ... |
def location(self, relative_alt=False):
'''return current location'''
self.wait_gps_fix()
# wait for another VFR_HUD, to ensure we have correct altitude
self.recv_match(type='VFR_HUD', blocking=True)
self.recv_match(type='GLOBAL_POSITION_INT', blocking=True)
if relative_a... | return current location | Below is the the instruction that describes the task:
### Input:
return current location
### Response:
def location(self, relative_alt=False):
'''return current location'''
self.wait_gps_fix()
# wait for another VFR_HUD, to ensure we have correct altitude
self.recv_match(type='VFR_H... |
def get_gcloud_pricelist():
"""Retrieve latest pricelist from Google Cloud, or use
cached copy if not reachable.
"""
try:
r = requests.get('http://cloudpricingcalculator.appspot.com'
'/static/data/pricelist.json')
content = json.loads(r.content)
except Connec... | Retrieve latest pricelist from Google Cloud, or use
cached copy if not reachable. | Below is the the instruction that describes the task:
### Input:
Retrieve latest pricelist from Google Cloud, or use
cached copy if not reachable.
### Response:
def get_gcloud_pricelist():
"""Retrieve latest pricelist from Google Cloud, or use
cached copy if not reachable.
"""
try:
r = ... |
def gencode(data, output=None, tab=" ", indent=0, overwrite=False):
"""Generate code.
:param data: must be list of class data, see a valid data example below
:param output: default None, the python script file name you want to create
:param tab: default " "
:param indent: global indent se... | Generate code.
:param data: must be list of class data, see a valid data example below
:param output: default None, the python script file name you want to create
:param tab: default " "
:param indent: global indent setting
:param overwrite: if True, silently overwrite the output file
... | Below is the the instruction that describes the task:
### Input:
Generate code.
:param data: must be list of class data, see a valid data example below
:param output: default None, the python script file name you want to create
:param tab: default " "
:param indent: global indent setting
... |
def _update_defaults(self, defaults):
"""Updates the given defaults with values from the config files and
the environ. Does a little special handling for certain types of
options (lists)."""
# Accumulate complex default state.
self.values = optparse.Values(self.defaults)
... | Updates the given defaults with values from the config files and
the environ. Does a little special handling for certain types of
options (lists). | Below is the the instruction that describes the task:
### Input:
Updates the given defaults with values from the config files and
the environ. Does a little special handling for certain types of
options (lists).
### Response:
def _update_defaults(self, defaults):
"""Updates the given defaul... |
def ReadFlowObject(self, client_id, flow_id):
"""Reads a flow object from the database."""
try:
return self.flows[(client_id, flow_id)].Copy()
except KeyError:
raise db.UnknownFlowError(client_id, flow_id) | Reads a flow object from the database. | Below is the the instruction that describes the task:
### Input:
Reads a flow object from the database.
### Response:
def ReadFlowObject(self, client_id, flow_id):
"""Reads a flow object from the database."""
try:
return self.flows[(client_id, flow_id)].Copy()
except KeyError:
raise db.Unkn... |
def read(cls, dstore):
"""
:param dstore: a DataStore instance
:returns: a :class:`CompositeRiskModel` instance
"""
oqparam = dstore['oqparam']
tmap = (dstore['taxonomy_mapping'] if 'taxonomy_mapping' in dstore
else {})
crm = dstore.getitem('risk_m... | :param dstore: a DataStore instance
:returns: a :class:`CompositeRiskModel` instance | Below is the the instruction that describes the task:
### Input:
:param dstore: a DataStore instance
:returns: a :class:`CompositeRiskModel` instance
### Response:
def read(cls, dstore):
"""
:param dstore: a DataStore instance
:returns: a :class:`CompositeRiskModel` instance
... |
def use_isolated_vault_view(self):
"""Pass through to provider AuthorizationLookupSession.use_isolated_vault_view"""
self._vault_view = ISOLATED
# self._get_provider_session('authorization_lookup_session') # To make sure the session is tracked
for session in self._get_provider_sessions()... | Pass through to provider AuthorizationLookupSession.use_isolated_vault_view | Below is the the instruction that describes the task:
### Input:
Pass through to provider AuthorizationLookupSession.use_isolated_vault_view
### Response:
def use_isolated_vault_view(self):
"""Pass through to provider AuthorizationLookupSession.use_isolated_vault_view"""
self._vault_view = ISOLATED... |
def upload_ssh_key(host, username, password, ssh_key=None, ssh_key_file=None,
protocol=None, port=None, certificate_verify=False):
'''
Upload an ssh key for root to an ESXi host via http PUT.
This function only works for ESXi, not vCenter.
Only one ssh key can be uploaded for root. U... | Upload an ssh key for root to an ESXi host via http PUT.
This function only works for ESXi, not vCenter.
Only one ssh key can be uploaded for root. Uploading a second key will
replace any existing key.
:param host: The location of the ESXi Host
:param username: Username to connect as
:param pa... | Below is the the instruction that describes the task:
### Input:
Upload an ssh key for root to an ESXi host via http PUT.
This function only works for ESXi, not vCenter.
Only one ssh key can be uploaded for root. Uploading a second key will
replace any existing key.
:param host: The location of th... |
def keltner(self, n, dev, array=False):
"""肯特纳通道"""
mid = self.sma(n, array)
atr = self.atr(n, array)
up = mid + atr * dev
down = mid - atr * dev
return up, down | 肯特纳通道 | Below is the the instruction that describes the task:
### Input:
肯特纳通道
### Response:
def keltner(self, n, dev, array=False):
"""肯特纳通道"""
mid = self.sma(n, array)
atr = self.atr(n, array)
up = mid + atr * dev
down = mid - atr * dev
return up, down |
def remove_links(text):
"""
Helper function to remove the links from the input text
Args:
text (str): A string
Returns:
str: the same text, but with any substring that matches the regex
for a link removed and replaced with a space
Example:
>>> from tweet_parser.get... | Helper function to remove the links from the input text
Args:
text (str): A string
Returns:
str: the same text, but with any substring that matches the regex
for a link removed and replaced with a space
Example:
>>> from tweet_parser.getter_methods.tweet_text import remove... | Below is the the instruction that describes the task:
### Input:
Helper function to remove the links from the input text
Args:
text (str): A string
Returns:
str: the same text, but with any substring that matches the regex
for a link removed and replaced with a space
Example:
... |
def sim(self, key, size=None):
'''
key: memory address(int) or register name(str)
size: size of object in bytes
'''
project = load_project()
if key in project.arch.registers:
if size is None:
size = project.arch.registers[key][1]
si... | key: memory address(int) or register name(str)
size: size of object in bytes | Below is the the instruction that describes the task:
### Input:
key: memory address(int) or register name(str)
size: size of object in bytes
### Response:
def sim(self, key, size=None):
'''
key: memory address(int) or register name(str)
size: size of object in bytes
'''
... |
def is_dataset_on_gcs(dataset_name):
"""If the dataset is available on the GCS bucket gs://tfds-data/datasets."""
dir_name = posixpath.join(GCS_DATASETS_DIR, dataset_name)
return len(gcs_files(prefix_filter=dir_name)) > 2 | If the dataset is available on the GCS bucket gs://tfds-data/datasets. | Below is the the instruction that describes the task:
### Input:
If the dataset is available on the GCS bucket gs://tfds-data/datasets.
### Response:
def is_dataset_on_gcs(dataset_name):
"""If the dataset is available on the GCS bucket gs://tfds-data/datasets."""
dir_name = posixpath.join(GCS_DATASETS_DIR, dat... |
def export(self, top=True):
"""Exports object to its string representation.
Args:
top (bool): if True appends `internal_name` before values.
All non list objects should be exported with value top=True,
all list objects, that are embedded in as fields inlist ... | Exports object to its string representation.
Args:
top (bool): if True appends `internal_name` before values.
All non list objects should be exported with value top=True,
all list objects, that are embedded in as fields inlist objects
should be expor... | Below is the the instruction that describes the task:
### Input:
Exports object to its string representation.
Args:
top (bool): if True appends `internal_name` before values.
All non list objects should be exported with value top=True,
all list objects, that are... |
def atexit_register(func):
"""
Uses either uwsgi's atexit mechanism, or atexit from the stdlib.
When running under uwsgi, using their atexit handler is more reliable,
especially when using gevent
:param func: the function to call at exit
"""
try:
import uwsgi
orig = getattr... | Uses either uwsgi's atexit mechanism, or atexit from the stdlib.
When running under uwsgi, using their atexit handler is more reliable,
especially when using gevent
:param func: the function to call at exit | Below is the the instruction that describes the task:
### Input:
Uses either uwsgi's atexit mechanism, or atexit from the stdlib.
When running under uwsgi, using their atexit handler is more reliable,
especially when using gevent
:param func: the function to call at exit
### Response:
def atexit_regis... |
def save(self, clean=True):
"""Serialize into raw representation. Clears the dirty bit by default.
Args:
clean (bool): Whether to clear the dirty bit.
Returns:
dict: Raw.
"""
ret = {}
if clean:
self._dirty = False
else:
... | Serialize into raw representation. Clears the dirty bit by default.
Args:
clean (bool): Whether to clear the dirty bit.
Returns:
dict: Raw. | Below is the the instruction that describes the task:
### Input:
Serialize into raw representation. Clears the dirty bit by default.
Args:
clean (bool): Whether to clear the dirty bit.
Returns:
dict: Raw.
### Response:
def save(self, clean=True):
"""Serialize into ... |
def _build_query(self, uri, params=None, action_token_type=None):
"""Prepare query string"""
if params is None:
params = QueryParams()
params['response_format'] = 'json'
session_token = None
if action_token_type in self._action_tokens:
# Favor action t... | Prepare query string | Below is the the instruction that describes the task:
### Input:
Prepare query string
### Response:
def _build_query(self, uri, params=None, action_token_type=None):
"""Prepare query string"""
if params is None:
params = QueryParams()
params['response_format'] = 'json'
... |
def device_firmware_str(self, indent):
"""Convenience to string method.
"""
host_build_ns = self.host_firmware_build_timestamp
host_build_s = datetime.datetime.utcfromtimestamp(host_build_ns/1000000000) if host_build_ns != None else None
wifi_build_ns = self.wifi_firmware_build_t... | Convenience to string method. | Below is the the instruction that describes the task:
### Input:
Convenience to string method.
### Response:
def device_firmware_str(self, indent):
"""Convenience to string method.
"""
host_build_ns = self.host_firmware_build_timestamp
host_build_s = datetime.datetime.utcfromtimesta... |
def register(cls, archive_table, engine):
"""
:param archive_table: the model for the users archive table
:param engine: the database engine
:param version_col_names: strings which correspond to columns that versioning will pivot \
around. These columns must have a unique con... | :param archive_table: the model for the users archive table
:param engine: the database engine
:param version_col_names: strings which correspond to columns that versioning will pivot \
around. These columns must have a unique constraint set on them. | Below is the the instruction that describes the task:
### Input:
:param archive_table: the model for the users archive table
:param engine: the database engine
:param version_col_names: strings which correspond to columns that versioning will pivot \
around. These columns must have a uni... |
def DAS(cpu):
"""
Decimal adjusts AL after subtraction.
Adjusts the result of the subtraction of two packed BCD values to create a packed BCD result.
The AL register is the implied source and destination operand. If a decimal borrow is detected,
the CF and AF flags are set accor... | Decimal adjusts AL after subtraction.
Adjusts the result of the subtraction of two packed BCD values to create a packed BCD result.
The AL register is the implied source and destination operand. If a decimal borrow is detected,
the CF and AF flags are set accordingly. This instruction is not va... | Below is the the instruction that describes the task:
### Input:
Decimal adjusts AL after subtraction.
Adjusts the result of the subtraction of two packed BCD values to create a packed BCD result.
The AL register is the implied source and destination operand. If a decimal borrow is detected,
... |
def parse_meta(filename, data):
"""
Parse `data` to EPublication.
Args:
filename (str): Used to choose right parser based at suffix.
data (str): Content of the metadata file.
Returns:
EPublication: object.
"""
if "." not in filename:
raise MetaParsingException(
... | Parse `data` to EPublication.
Args:
filename (str): Used to choose right parser based at suffix.
data (str): Content of the metadata file.
Returns:
EPublication: object. | Below is the the instruction that describes the task:
### Input:
Parse `data` to EPublication.
Args:
filename (str): Used to choose right parser based at suffix.
data (str): Content of the metadata file.
Returns:
EPublication: object.
### Response:
def parse_meta(filename, data):
... |
def convert_yielded(yielded):
"""Convert a yielded object into a `.Future`.
The default implementation accepts lists, dictionaries, and Futures.
If the `~functools.singledispatch` library is available, this function
may be extended to support additional types. For example::
@convert_yielded.r... | Convert a yielded object into a `.Future`.
The default implementation accepts lists, dictionaries, and Futures.
If the `~functools.singledispatch` library is available, this function
may be extended to support additional types. For example::
@convert_yielded.register(asyncio.Future)
def _... | Below is the the instruction that describes the task:
### Input:
Convert a yielded object into a `.Future`.
The default implementation accepts lists, dictionaries, and Futures.
If the `~functools.singledispatch` library is available, this function
may be extended to support additional types. For examp... |
def save(self):
"""Save to database if anything has changed since last load"""
if ( self._new or
(self._validID() and self._changed) or
(self._updated and self._changed > self._updated) ):
# Don't save if we have not loaded existing data!
self._saveDB()
... | Save to database if anything has changed since last load | Below is the the instruction that describes the task:
### Input:
Save to database if anything has changed since last load
### Response:
def save(self):
"""Save to database if anything has changed since last load"""
if ( self._new or
(self._validID() and self._changed) or
(se... |
def mark_flags_as_required(flag_names, flag_values=_flagvalues.FLAGS):
"""Ensures that flags are not None during program execution.
Recommended usage:
if __name__ == '__main__':
flags.mark_flags_as_required(['flag1', 'flag2', 'flag3'])
app.run()
Args:
flag_names: Sequence[str], names of the... | Ensures that flags are not None during program execution.
Recommended usage:
if __name__ == '__main__':
flags.mark_flags_as_required(['flag1', 'flag2', 'flag3'])
app.run()
Args:
flag_names: Sequence[str], names of the flags.
flag_values: flags.FlagValues, optional FlagValues instance wher... | Below is the the instruction that describes the task:
### Input:
Ensures that flags are not None during program execution.
Recommended usage:
if __name__ == '__main__':
flags.mark_flags_as_required(['flag1', 'flag2', 'flag3'])
app.run()
Args:
flag_names: Sequence[str], names of the flags.... |
def make_common_entry(plist, pyver, suffix, req_ver):
"""Generate Python interpreter version entries for 2.x or 3.x series."""
prefix = "Python {pyver}.x{suffix}".format(pyver=pyver, suffix=suffix)
plist.append("{prefix}{ver}".format(prefix=prefix, ver=ops_to_words(req_ver))) | Generate Python interpreter version entries for 2.x or 3.x series. | Below is the the instruction that describes the task:
### Input:
Generate Python interpreter version entries for 2.x or 3.x series.
### Response:
def make_common_entry(plist, pyver, suffix, req_ver):
"""Generate Python interpreter version entries for 2.x or 3.x series."""
prefix = "Python {pyver}.x{suffix}... |
def to_qubo(self):
"""Convert a binary quadratic model to QUBO format.
If the binary quadratic model's vartype is not :class:`.Vartype.BINARY`,
values are converted.
Returns:
tuple: 2-tuple of form (`biases`, `offset`), where `biases` is a dict
in which keys are... | Convert a binary quadratic model to QUBO format.
If the binary quadratic model's vartype is not :class:`.Vartype.BINARY`,
values are converted.
Returns:
tuple: 2-tuple of form (`biases`, `offset`), where `biases` is a dict
in which keys are pairs of variables and values... | Below is the the instruction that describes the task:
### Input:
Convert a binary quadratic model to QUBO format.
If the binary quadratic model's vartype is not :class:`.Vartype.BINARY`,
values are converted.
Returns:
tuple: 2-tuple of form (`biases`, `offset`), where `biases` ... |
def get_option_scope_help_info(self, option_registrations_iter):
"""Returns an OptionScopeHelpInfo for the options registered with the (args, kwargs) pairs."""
basic_options = []
recursive_options = []
advanced_options = []
# Sort the arguments, so we display the help in alphabetical order.
for ... | Returns an OptionScopeHelpInfo for the options registered with the (args, kwargs) pairs. | Below is the the instruction that describes the task:
### Input:
Returns an OptionScopeHelpInfo for the options registered with the (args, kwargs) pairs.
### Response:
def get_option_scope_help_info(self, option_registrations_iter):
"""Returns an OptionScopeHelpInfo for the options registered with the (args, k... |
def versionadded(reason="", version=""):
"""
This decorator can be used to insert a "versionadded" directive
in your function/class docstring in order to documents the
version of the project which adds this new functionality in your library.
:param str reason:
Reason message which documents... | This decorator can be used to insert a "versionadded" directive
in your function/class docstring in order to documents the
version of the project which adds this new functionality in your library.
:param str reason:
Reason message which documents the addition in your library (can be omitted).
... | Below is the the instruction that describes the task:
### Input:
This decorator can be used to insert a "versionadded" directive
in your function/class docstring in order to documents the
version of the project which adds this new functionality in your library.
:param str reason:
Reason message... |
def render_to_response(self, context=False):
"""Send file to client."""
f = self.openfile()
wrapper = FileWrapper(f)
response = HttpResponse(wrapper, content_type=self.content_type())
self.headers(response)
return response | Send file to client. | Below is the the instruction that describes the task:
### Input:
Send file to client.
### Response:
def render_to_response(self, context=False):
"""Send file to client."""
f = self.openfile()
wrapper = FileWrapper(f)
response = HttpResponse(wrapper, content_type=self.content_type())... |
def search_all(self):
'''a "show all" search that doesn't require a query'''
# This should be your apis url for a search
url = '...'
# paginte get is what it sounds like, and what you want for multiple
# pages of results
results = self._paginate_get(url)
if len(results) == 0:
b... | a "show all" search that doesn't require a query | Below is the the instruction that describes the task:
### Input:
a "show all" search that doesn't require a query
### Response:
def search_all(self):
'''a "show all" search that doesn't require a query'''
# This should be your apis url for a search
url = '...'
# paginte get is what it sounds like... |
def get_client_from_cli_profile(client_class, **kwargs):
"""Return a SDK client initialized with current CLI credentials, CLI default subscription and CLI default cloud.
This method will fill automatically the following client parameters:
- credentials
- subscription_id
- base_url
Parameters p... | Return a SDK client initialized with current CLI credentials, CLI default subscription and CLI default cloud.
This method will fill automatically the following client parameters:
- credentials
- subscription_id
- base_url
Parameters provided in kwargs will override CLI parameters and be passed dir... | Below is the the instruction that describes the task:
### Input:
Return a SDK client initialized with current CLI credentials, CLI default subscription and CLI default cloud.
This method will fill automatically the following client parameters:
- credentials
- subscription_id
- base_url
Paramet... |
def initialize_plugin_in_mainwindow_layout(self):
"""
If this is the first time the plugin is shown, perform actions to
initialize plugin position in Spyder's window layout.
Use on_first_registration to define the actions to be run
by your plugin
"""
if self.get_... | If this is the first time the plugin is shown, perform actions to
initialize plugin position in Spyder's window layout.
Use on_first_registration to define the actions to be run
by your plugin | Below is the the instruction that describes the task:
### Input:
If this is the first time the plugin is shown, perform actions to
initialize plugin position in Spyder's window layout.
Use on_first_registration to define the actions to be run
by your plugin
### Response:
def initialize_plu... |
def sanitize_filename(
filename, replacement_text="", platform=None, max_len=_DEFAULT_MAX_FILENAME_LEN
):
"""Make a valid filename from a string.
To make a valid filename the function does:
- Replace invalid characters as file names included in the ``filename``
with the ``replacement_tex... | Make a valid filename from a string.
To make a valid filename the function does:
- Replace invalid characters as file names included in the ``filename``
with the ``replacement_text``. Invalid characters are:
- unprintable characters
- |invalid_filename_chars|
... | Below is the the instruction that describes the task:
### Input:
Make a valid filename from a string.
To make a valid filename the function does:
- Replace invalid characters as file names included in the ``filename``
with the ``replacement_text``. Invalid characters are:
- unpr... |
def select_as_memdb(self, table_name, columns=None, where=None, extra=None):
"""
Get data in the database and return fetched data as a
in-memory |SimpleSQLite| instance.
:param str table_name: |arg_select_table_name|
:param list columns: |arg_select_as_xx_columns|
:param... | Get data in the database and return fetched data as a
in-memory |SimpleSQLite| instance.
:param str table_name: |arg_select_table_name|
:param list columns: |arg_select_as_xx_columns|
:param where: |arg_select_where|
:type where: |arg_where_type|
:param str extra: |arg_s... | Below is the the instruction that describes the task:
### Input:
Get data in the database and return fetched data as a
in-memory |SimpleSQLite| instance.
:param str table_name: |arg_select_table_name|
:param list columns: |arg_select_as_xx_columns|
:param where: |arg_select_where|
... |
def random_walk_graph( self, prev_peer, prev_peer_degree, current_peer, current_peer_neighbors, con=None, path=None, peer_table=None ):
"""
Take one step from current_peer to a neighbor in current_peer_neighbors,
based on Metropolis-Hastings Random Walk with Delayed Acceptance (MHRWDA).
... | Take one step from current_peer to a neighbor in current_peer_neighbors,
based on Metropolis-Hastings Random Walk with Delayed Acceptance (MHRWDA).
The basic idea is to reduce the probability (versus MH alone) that we transition to the previous node.
We do so using the Metropolis-Hastings Rando... | Below is the the instruction that describes the task:
### Input:
Take one step from current_peer to a neighbor in current_peer_neighbors,
based on Metropolis-Hastings Random Walk with Delayed Acceptance (MHRWDA).
The basic idea is to reduce the probability (versus MH alone) that we transition to th... |
def suggestion_delete(self, account_id):
"""
Remove the user with the given `account_id` from the follow suggestions.
"""
account_id = self.__unpack_id(account_id)
url = '/api/v1/suggestions/{0}'.format(str(account_id))
self.__api_request('DELETE', url) | Remove the user with the given `account_id` from the follow suggestions. | Below is the the instruction that describes the task:
### Input:
Remove the user with the given `account_id` from the follow suggestions.
### Response:
def suggestion_delete(self, account_id):
"""
Remove the user with the given `account_id` from the follow suggestions.
"""
account_i... |
def get_audio_metadata(fname):
""" collects basic MP3 metadata
Works, once you use mutagenx (buried deep in issues page)
['Angels']
['Red Back Fever']
['Red Back Fever']
{'album': ['Red Back Fever'], 'title': ['Red Back Fever'], 'artist': ['Angels']}
"""
from mutagenx.easyid3 import ... | collects basic MP3 metadata
Works, once you use mutagenx (buried deep in issues page)
['Angels']
['Red Back Fever']
['Red Back Fever']
{'album': ['Red Back Fever'], 'title': ['Red Back Fever'], 'artist': ['Angels']} | Below is the the instruction that describes the task:
### Input:
collects basic MP3 metadata
Works, once you use mutagenx (buried deep in issues page)
['Angels']
['Red Back Fever']
['Red Back Fever']
{'album': ['Red Back Fever'], 'title': ['Red Back Fever'], 'artist': ['Angels']}
### Response:
... |
def embed(parent_locals=None, parent_globals=None, exec_lines=None,
remove_pyqt_hook=True, N=0):
"""
Starts interactive session. Similar to keyboard command in matlab.
Wrapper around IPython.embed
"""
import utool as ut
from functools import partial
import IPython
if parent_g... | Starts interactive session. Similar to keyboard command in matlab.
Wrapper around IPython.embed | Below is the the instruction that describes the task:
### Input:
Starts interactive session. Similar to keyboard command in matlab.
Wrapper around IPython.embed
### Response:
def embed(parent_locals=None, parent_globals=None, exec_lines=None,
remove_pyqt_hook=True, N=0):
"""
Starts interactiv... |
def list_entity_aliases(self, method='LIST', mount_point=DEFAULT_MOUNT_POINT):
"""List available entity aliases by their identifiers.
:param method: Supported methods:
LIST: /{mount_point}/entity-alias/id. Produces: 200 application/json
GET: /{mount_point}/entity-alias/id?list=t... | List available entity aliases by their identifiers.
:param method: Supported methods:
LIST: /{mount_point}/entity-alias/id. Produces: 200 application/json
GET: /{mount_point}/entity-alias/id?list=true. Produces: 200 application/json
:type method: str | unicode
:param mou... | Below is the the instruction that describes the task:
### Input:
List available entity aliases by their identifiers.
:param method: Supported methods:
LIST: /{mount_point}/entity-alias/id. Produces: 200 application/json
GET: /{mount_point}/entity-alias/id?list=true. Produces: 200 ap... |
def store(self, extractions: List[Extraction], attribute: str, group_by_tags: bool = True) -> None:
"""
Records extractions in the container, and for each individual extraction inserts a
ProvenanceRecord to record where the extraction is stored.
Records the "output_segment" in the proven... | Records extractions in the container, and for each individual extraction inserts a
ProvenanceRecord to record where the extraction is stored.
Records the "output_segment" in the provenance.
Extractions are always recorded in a list.
Errors out if the segment is primitive, such as a str... | Below is the the instruction that describes the task:
### Input:
Records extractions in the container, and for each individual extraction inserts a
ProvenanceRecord to record where the extraction is stored.
Records the "output_segment" in the provenance.
Extractions are always recorded in a... |
def barycentric_to_points(triangles, barycentric):
"""
Convert a list of barycentric coordinates on a list of triangles
to cartesian points.
Parameters
------------
triangles : (n, 3, 3) float
Triangles in space
barycentric : (n, 2) float
Barycentric coordinates
Returns
... | Convert a list of barycentric coordinates on a list of triangles
to cartesian points.
Parameters
------------
triangles : (n, 3, 3) float
Triangles in space
barycentric : (n, 2) float
Barycentric coordinates
Returns
-----------
points : (m, 3) float
Points in space | Below is the the instruction that describes the task:
### Input:
Convert a list of barycentric coordinates on a list of triangles
to cartesian points.
Parameters
------------
triangles : (n, 3, 3) float
Triangles in space
barycentric : (n, 2) float
Barycentric coordinates
Retur... |
def get_eod_frame(self):
"""Return the eod market data frame for pricing"""
close = self.pxs.close
mktval = self.get_mkt_val(close)
dvds = self.pxs.dvds
df = pd.DataFrame({'close': close, 'mkt_val': mktval, 'dvds': dvds})
df.index.name = 'date'
return df | Return the eod market data frame for pricing | Below is the the instruction that describes the task:
### Input:
Return the eod market data frame for pricing
### Response:
def get_eod_frame(self):
"""Return the eod market data frame for pricing"""
close = self.pxs.close
mktval = self.get_mkt_val(close)
dvds = self.pxs.dvds
... |
def load_attachments(self, source, skeleton):
'''Load attachment configuration from the given text source.
The attachment configuration file has a simple format. After discarding
Unix-style comments (any part of a line that starts with the pound (#)
character), each line in the file is ... | Load attachment configuration from the given text source.
The attachment configuration file has a simple format. After discarding
Unix-style comments (any part of a line that starts with the pound (#)
character), each line in the file is then expected to have the following
format::
... | Below is the the instruction that describes the task:
### Input:
Load attachment configuration from the given text source.
The attachment configuration file has a simple format. After discarding
Unix-style comments (any part of a line that starts with the pound (#)
character), each line in ... |
def getTraitCovarStdErrors(self,term_i):
"""
Returns standard errors on trait covariances from term_i (for the covariance estimate \see getTraitCovar)
Args:
term_i: index of the term we are interested in
"""
assert self.init, 'GP not initialised'
a... | Returns standard errors on trait covariances from term_i (for the covariance estimate \see getTraitCovar)
Args:
term_i: index of the term we are interested in | Below is the the instruction that describes the task:
### Input:
Returns standard errors on trait covariances from term_i (for the covariance estimate \see getTraitCovar)
Args:
term_i: index of the term we are interested in
### Response:
def getTraitCovarStdErrors(self,term_i):
"""... |
def format_path(self, repository, namespace=None, rw=False):
'''format the repository's URL
:param repository: name of the repository
:param namespace: namespace of the repository
:param rw: return a git+ssh URL if true, an https URL otherwise
:return: the full URI of the reposi... | format the repository's URL
:param repository: name of the repository
:param namespace: namespace of the repository
:param rw: return a git+ssh URL if true, an https URL otherwise
:return: the full URI of the repository ready to use as remote
if namespace is not given, reposito... | Below is the the instruction that describes the task:
### Input:
format the repository's URL
:param repository: name of the repository
:param namespace: namespace of the repository
:param rw: return a git+ssh URL if true, an https URL otherwise
:return: the full URI of the repositor... |
def ProtoFromDataFrames(self, dataframes):
"""Creates a feature statistics proto from a set of pandas dataframes.
Args:
dataframes: A list of dicts describing tables for each dataset for the
proto. Each entry contains a 'table' field of the dataframe of the
data
and a 'name... | Creates a feature statistics proto from a set of pandas dataframes.
Args:
dataframes: A list of dicts describing tables for each dataset for the
proto. Each entry contains a 'table' field of the dataframe of the
data
and a 'name' field to identify the dataset in the proto.
... | Below is the the instruction that describes the task:
### Input:
Creates a feature statistics proto from a set of pandas dataframes.
Args:
dataframes: A list of dicts describing tables for each dataset for the
proto. Each entry contains a 'table' field of the dataframe of the
data
... |
def count_base_units(units):
"""Returns a dict mapping names of base units to how many times they
appear in the given iterable of units. Effectively this counts how
many length units you have, how many time units, and so forth.
"""
ret = {}
for unit in units:
factor, base_unit = get_con... | Returns a dict mapping names of base units to how many times they
appear in the given iterable of units. Effectively this counts how
many length units you have, how many time units, and so forth. | Below is the the instruction that describes the task:
### Input:
Returns a dict mapping names of base units to how many times they
appear in the given iterable of units. Effectively this counts how
many length units you have, how many time units, and so forth.
### Response:
def count_base_units(units):
... |
def get_power(self):
"""Returns the Power in Watt"""
power_dict = self.get_power_all()
for device in power_dict.keys():
power_dict[device] = float(power_dict[device]) / 1000.0
return power_dict | Returns the Power in Watt | Below is the the instruction that describes the task:
### Input:
Returns the Power in Watt
### Response:
def get_power(self):
"""Returns the Power in Watt"""
power_dict = self.get_power_all()
for device in power_dict.keys():
power_dict[device] = float(power_dict[device]) / 1000.... |
def sell_open(id_or_ins, amount, price=None, style=None):
"""
卖出开仓
:param id_or_ins: 下单标的物
:type id_or_ins: :class:`~Instrument` object | `str` | List[:class:`~Instrument`] | List[`str`]
:param int amount: 下单手数
:param float price: 下单价格,默认为None,表示 :class:`~MarketOrder`, 此参数主要用于简化 `style` 参数。
... | 卖出开仓
:param id_or_ins: 下单标的物
:type id_or_ins: :class:`~Instrument` object | `str` | List[:class:`~Instrument`] | List[`str`]
:param int amount: 下单手数
:param float price: 下单价格,默认为None,表示 :class:`~MarketOrder`, 此参数主要用于简化 `style` 参数。
:param style: 下单类型, 默认是市价单。目前支持的订单类型有 :class:`~LimitOrder` 和 :clas... | Below is the the instruction that describes the task:
### Input:
卖出开仓
:param id_or_ins: 下单标的物
:type id_or_ins: :class:`~Instrument` object | `str` | List[:class:`~Instrument`] | List[`str`]
:param int amount: 下单手数
:param float price: 下单价格,默认为None,表示 :class:`~MarketOrder`, 此参数主要用于简化 `style` 参数。
... |
def solve_semi_dual_entropic(a, b, M, reg, method, numItermax=10000, lr=None,
log=False):
'''
Compute the transportation matrix to solve the regularized discrete
measures optimal transport max problem
The function solves the following optimization problem:
.. ma... | Compute the transportation matrix to solve the regularized discrete
measures optimal transport max problem
The function solves the following optimization problem:
.. math::
\gamma = arg\min_\gamma <\gamma,M>_F + reg\cdot\Omega(\gamma)
s.t. \gamma 1 = a
\gamma^T 1= b
... | Below is the the instruction that describes the task:
### Input:
Compute the transportation matrix to solve the regularized discrete
measures optimal transport max problem
The function solves the following optimization problem:
.. math::
\gamma = arg\min_\gamma <\gamma,M>_F + reg\cdot\Omeg... |
def init_from_wave_file(wavpath):
"""Init a sonic visualiser environment structure based the analysis
of the main audio file. The audio file have to be encoded in wave
Args:
wavpath(str): the full path to the wavfile
"""
try:
samplerate, data = SW.read(... | Init a sonic visualiser environment structure based the analysis
of the main audio file. The audio file have to be encoded in wave
Args:
wavpath(str): the full path to the wavfile | Below is the the instruction that describes the task:
### Input:
Init a sonic visualiser environment structure based the analysis
of the main audio file. The audio file have to be encoded in wave
Args:
wavpath(str): the full path to the wavfile
### Response:
def init_from_wave_file(wavp... |
def optional(name, default) -> 'Wildcard':
"""Create a `Wildcard` that matches a single argument with a default value.
If the wildcard does not match, the substitution will contain the
default value instead.
Args:
name:
The name for the wildcard.
... | Create a `Wildcard` that matches a single argument with a default value.
If the wildcard does not match, the substitution will contain the
default value instead.
Args:
name:
The name for the wildcard.
default:
The default value of the wil... | Below is the the instruction that describes the task:
### Input:
Create a `Wildcard` that matches a single argument with a default value.
If the wildcard does not match, the substitution will contain the
default value instead.
Args:
name:
The name for the wildca... |
def get_interface_detail_output_interface_if_name(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_interface_detail = ET.Element("get_interface_detail")
config = get_interface_detail
output = ET.SubElement(get_interface_detail, "output")
... | Auto Generated Code | Below is the the instruction that describes the task:
### Input:
Auto Generated Code
### Response:
def get_interface_detail_output_interface_if_name(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_interface_detail = ET.Element("get_interface_detail")
... |
def execute_route(self, meta_data, request_pdu):
""" Execute configured route based on requests meta data and request
PDU.
:param meta_data: A dict with meta data. It must at least contain
key 'unit_id'.
:param request_pdu: A bytearray containing request PDU.
:return... | Execute configured route based on requests meta data and request
PDU.
:param meta_data: A dict with meta data. It must at least contain
key 'unit_id'.
:param request_pdu: A bytearray containing request PDU.
:return: A bytearry containing reponse PDU. | Below is the the instruction that describes the task:
### Input:
Execute configured route based on requests meta data and request
PDU.
:param meta_data: A dict with meta data. It must at least contain
key 'unit_id'.
:param request_pdu: A bytearray containing request PDU.
... |
def _to_enos_roles(roles):
"""Transform the roles to use enoslib.host.Host hosts.
Args:
roles (dict): roles returned by
:py:func:`enoslib.infra.provider.Provider.init`
"""
def to_host(h):
extra = {}
# create extra_vars for the nics
# network_role = ethX
... | Transform the roles to use enoslib.host.Host hosts.
Args:
roles (dict): roles returned by
:py:func:`enoslib.infra.provider.Provider.init` | Below is the the instruction that describes the task:
### Input:
Transform the roles to use enoslib.host.Host hosts.
Args:
roles (dict): roles returned by
:py:func:`enoslib.infra.provider.Provider.init`
### Response:
def _to_enos_roles(roles):
"""Transform the roles to use enoslib.host... |
def insert_arguments_into_sql_query(compilation_result, arguments):
"""Insert the arguments into the compiled SQL query to form a complete query.
Args:
compilation_result: CompilationResult, compilation result from the GraphQL compiler.
arguments: Dict[str, Any], parameter name -> value, for ev... | Insert the arguments into the compiled SQL query to form a complete query.
Args:
compilation_result: CompilationResult, compilation result from the GraphQL compiler.
arguments: Dict[str, Any], parameter name -> value, for every parameter the query expects.
Returns:
SQLAlchemy Selectabl... | Below is the the instruction that describes the task:
### Input:
Insert the arguments into the compiled SQL query to form a complete query.
Args:
compilation_result: CompilationResult, compilation result from the GraphQL compiler.
arguments: Dict[str, Any], parameter name -> value, for every pa... |
def create_channel(self,
channel_name,
project_name,
dataset_name,
channel_type,
dtype,
startwindow,
endwindow,
readonly=0,
... | Create a new channel on the Remote, using channel_data.
Arguments:
channel_name (str): Channel name
project_name (str): Project name
dataset_name (str): Dataset name
channel_type (str): Type of the channel (e.g. `neurodata.IMAGE`)
dtype (str): The dat... | Below is the the instruction that describes the task:
### Input:
Create a new channel on the Remote, using channel_data.
Arguments:
channel_name (str): Channel name
project_name (str): Project name
dataset_name (str): Dataset name
channel_type (str): Type of ... |
def get_widget_label_for(self, fieldname, default=None):
"""Lookup the widget of the field and return the label
"""
widget = self.get_widget_for(fieldname)
if widget is None:
return default
return widget.label | Lookup the widget of the field and return the label | Below is the the instruction that describes the task:
### Input:
Lookup the widget of the field and return the label
### Response:
def get_widget_label_for(self, fieldname, default=None):
"""Lookup the widget of the field and return the label
"""
widget = self.get_widget_for(fieldname)
... |
def set_monitoring(module):
""" Defines the monitoring method on the module. """
def monitoring(is_monitoring,
track_data=None,
track_grad=None,
track_update=None,
track_update_ratio=None):
"""
Turn monitoring on or off.... | Defines the monitoring method on the module. | Below is the the instruction that describes the task:
### Input:
Defines the monitoring method on the module.
### Response:
def set_monitoring(module):
""" Defines the monitoring method on the module. """
def monitoring(is_monitoring,
track_data=None,
track_grad=None,
... |
def submit_and_connect(self, spec):
"""Submit a new skein application, and wait to connect to it.
If an error occurs before the application connects, the application is
killed.
Parameters
----------
spec : ApplicationSpec, str, or dict
A description of the a... | Submit a new skein application, and wait to connect to it.
If an error occurs before the application connects, the application is
killed.
Parameters
----------
spec : ApplicationSpec, str, or dict
A description of the application to run. Can be an
``Appl... | Below is the the instruction that describes the task:
### Input:
Submit a new skein application, and wait to connect to it.
If an error occurs before the application connects, the application is
killed.
Parameters
----------
spec : ApplicationSpec, str, or dict
... |
def recover_and_supervise(recovery_file):
""" Retrieve monitor data from recovery_file and resume monitoring """
try:
logging.info("Attempting to recover Supervisor data from " + recovery_file)
with open(recovery_file) as rf:
recovery_data = json.load(rf)
monitor_data = r... | Retrieve monitor data from recovery_file and resume monitoring | Below is the the instruction that describes the task:
### Input:
Retrieve monitor data from recovery_file and resume monitoring
### Response:
def recover_and_supervise(recovery_file):
""" Retrieve monitor data from recovery_file and resume monitoring """
try:
logging.info("Attempting to recover Sup... |
def set_default_value(self, data_id, value=EMPTY, initial_dist=0.0):
"""
Set the default value of a data node in the dispatcher.
:param data_id:
Data node id.
:type data_id: str
:param value:
Data node default value.
.. note:: If `EMPTY` the... | Set the default value of a data node in the dispatcher.
:param data_id:
Data node id.
:type data_id: str
:param value:
Data node default value.
.. note:: If `EMPTY` the previous default value is removed.
:type value: T, optional
:param init... | Below is the the instruction that describes the task:
### Input:
Set the default value of a data node in the dispatcher.
:param data_id:
Data node id.
:type data_id: str
:param value:
Data node default value.
.. note:: If `EMPTY` the previous default va... |
def map_stops(
feed: "Feed", stop_ids: List[str], stop_style: Dict = STOP_STYLE
):
"""
Return a Folium map showing the given stops.
Parameters
----------
feed : Feed
stop_ids : list
IDs of trips in ``feed.stops``
stop_style: dictionary
Folium CircleMarker parameters to u... | Return a Folium map showing the given stops.
Parameters
----------
feed : Feed
stop_ids : list
IDs of trips in ``feed.stops``
stop_style: dictionary
Folium CircleMarker parameters to use for styling stops.
Returns
-------
dictionary
A Folium Map depicting the st... | Below is the the instruction that describes the task:
### Input:
Return a Folium map showing the given stops.
Parameters
----------
feed : Feed
stop_ids : list
IDs of trips in ``feed.stops``
stop_style: dictionary
Folium CircleMarker parameters to use for styling stops.
Ret... |
def _disconnect_temporarily(self, port_v, target=True):
"""Removes a connection between the current connection and the given port
:param rafcon.gui.mygaphas.items.ports.PortView port_v: The port that was connected
:param bool target: Whether the connection origin or target should be disconnecte... | Removes a connection between the current connection and the given port
:param rafcon.gui.mygaphas.items.ports.PortView port_v: The port that was connected
:param bool target: Whether the connection origin or target should be disconnected | Below is the the instruction that describes the task:
### Input:
Removes a connection between the current connection and the given port
:param rafcon.gui.mygaphas.items.ports.PortView port_v: The port that was connected
:param bool target: Whether the connection origin or target should be disconnec... |
def main(args_list=None):
"""
Script which loads variants and annotates them with overlapping genes.
Example usage:
varcode-genes
--vcf mutect.vcf \
--vcf strelka.vcf \
--maf tcga_brca.maf \
--variant chr1 498584 C G \
--json-variants more... | Script which loads variants and annotates them with overlapping genes.
Example usage:
varcode-genes
--vcf mutect.vcf \
--vcf strelka.vcf \
--maf tcga_brca.maf \
--variant chr1 498584 C G \
--json-variants more_variants.json | Below is the the instruction that describes the task:
### Input:
Script which loads variants and annotates them with overlapping genes.
Example usage:
varcode-genes
--vcf mutect.vcf \
--vcf strelka.vcf \
--maf tcga_brca.maf \
--variant chr1 498584 C G \
... |
def create_group_groups(self, description=None, is_public=None, join_level=None, name=None, storage_quota_mb=None):
"""
Create a group.
Creates a new group. Groups created using the "/api/v1/groups/"
endpoint will be community groups.
"""
path = {}
data =... | Create a group.
Creates a new group. Groups created using the "/api/v1/groups/"
endpoint will be community groups. | Below is the the instruction that describes the task:
### Input:
Create a group.
Creates a new group. Groups created using the "/api/v1/groups/"
endpoint will be community groups.
### Response:
def create_group_groups(self, description=None, is_public=None, join_level=None, name=None, storage_q... |
def get_deploy_assets2s3_list(cwd, file="propel.yml"):
"""
Return the list of all the assets2s3 repo to publish when deploying
:param cwd:
:param file:
:return: list
"""
conf = propel_deploy_config(cwd=cwd, file=file)
return conf["assets2s3"] if "assets2s3" in conf else [] | Return the list of all the assets2s3 repo to publish when deploying
:param cwd:
:param file:
:return: list | Below is the the instruction that describes the task:
### Input:
Return the list of all the assets2s3 repo to publish when deploying
:param cwd:
:param file:
:return: list
### Response:
def get_deploy_assets2s3_list(cwd, file="propel.yml"):
"""
Return the list of all the assets2s3 repo to publi... |
async def report(self, msg, timeout=5):
"""Report message to the host manager.
"""
try:
host_manager = await self.env.connect(self.host_manager,
timeout=timeout)
except:
raise ConnectionError("Could not reach host ... | Report message to the host manager. | Below is the the instruction that describes the task:
### Input:
Report message to the host manager.
### Response:
async def report(self, msg, timeout=5):
"""Report message to the host manager.
"""
try:
host_manager = await self.env.connect(self.host_manager,
... |
def rot_state(self, x, y):
"""
Set the rotation state of the camera
:param x: viewport x pos
:param y: viewport y pos
"""
if self.last_x is None:
self.last_x = x
if self.last_y is None:
self.last_y = y
x_offset = self.last_x - x
... | Set the rotation state of the camera
:param x: viewport x pos
:param y: viewport y pos | Below is the the instruction that describes the task:
### Input:
Set the rotation state of the camera
:param x: viewport x pos
:param y: viewport y pos
### Response:
def rot_state(self, x, y):
"""
Set the rotation state of the camera
:param x: viewport x pos
:param... |
def _get(self):
'''
get the value for user in gsettings
'''
user = self.USER
try:
uid = pwd.getpwnam(user).pw_uid
except KeyError:
log.info('User does not exist')
return False
cmd = self.gsetting_command + ['get', str(self.SCH... | get the value for user in gsettings | Below is the the instruction that describes the task:
### Input:
get the value for user in gsettings
### Response:
def _get(self):
'''
get the value for user in gsettings
'''
user = self.USER
try:
uid = pwd.getpwnam(user).pw_uid
except KeyError:
... |
def in_generator(self, generator):
"""Context manager: set the given generator as the current generator."""
previous_generator = self._current_generator
try:
self._current_generator = generator
yield
finally:
self._current_generator = previous_generato... | Context manager: set the given generator as the current generator. | Below is the the instruction that describes the task:
### Input:
Context manager: set the given generator as the current generator.
### Response:
def in_generator(self, generator):
"""Context manager: set the given generator as the current generator."""
previous_generator = self._current_generator
... |
def _replace_event_shape_in_tensorshape(
input_tensorshape, event_shape_in, event_shape_out):
"""Replaces the event shape dims of a `TensorShape`.
Args:
input_tensorshape: a `TensorShape` instance in which to attempt replacing
event shape.
event_shape_in: `Tensor` shape representing the event sha... | Replaces the event shape dims of a `TensorShape`.
Args:
input_tensorshape: a `TensorShape` instance in which to attempt replacing
event shape.
event_shape_in: `Tensor` shape representing the event shape expected to
be present in (rightmost dims of) `tensorshape_in`. Must be compatible
with ... | Below is the the instruction that describes the task:
### Input:
Replaces the event shape dims of a `TensorShape`.
Args:
input_tensorshape: a `TensorShape` instance in which to attempt replacing
event shape.
event_shape_in: `Tensor` shape representing the event shape expected to
be present in... |
def ns(self, prefix, tag):
"""
Given a prefix and an XML tag, output the qualified name
for proper namespace handling on output.
"""
return etree.QName(self.prefixes[prefix], tag) | Given a prefix and an XML tag, output the qualified name
for proper namespace handling on output. | Below is the the instruction that describes the task:
### Input:
Given a prefix and an XML tag, output the qualified name
for proper namespace handling on output.
### Response:
def ns(self, prefix, tag):
"""
Given a prefix and an XML tag, output the qualified name
for proper namespa... |
def GetChildClassId(self, classId):
"""
Method extracts and returns the child object list same as the given classId
"""
childList = []
for ch in self.child:
if ch.classId.lower() == classId.lower():
childList.append(ch)
return childList | Method extracts and returns the child object list same as the given classId | Below is the the instruction that describes the task:
### Input:
Method extracts and returns the child object list same as the given classId
### Response:
def GetChildClassId(self, classId):
"""
Method extracts and returns the child object list same as the given classId
"""
childList = []
for ch in self.... |
def asset_ver_sel_changed(self, index):
"""Callback for when the version selection has changed
Emit asset_taskfile_sel_changed signal.
:param index: the selected index
:type index: QtCore.QModelIndex
:returns: None
:rtype: None
:raises: None
"""
... | Callback for when the version selection has changed
Emit asset_taskfile_sel_changed signal.
:param index: the selected index
:type index: QtCore.QModelIndex
:returns: None
:rtype: None
:raises: None | Below is the the instruction that describes the task:
### Input:
Callback for when the version selection has changed
Emit asset_taskfile_sel_changed signal.
:param index: the selected index
:type index: QtCore.QModelIndex
:returns: None
:rtype: None
:raises: None
##... |
def request(self, uri, method=GET, headers=None, cookies=None, params=None, data=None, post_files=None,**kwargs):
"""Makes a request using requests
@param uri: The uri to send request
@param method: Method to use to send request
@param headers: Any headers to send with request
@... | Makes a request using requests
@param uri: The uri to send request
@param method: Method to use to send request
@param headers: Any headers to send with request
@param cookies: Request cookies (in addition to session cookies)
@param params: Request parameters
@param data... | Below is the the instruction that describes the task:
### Input:
Makes a request using requests
@param uri: The uri to send request
@param method: Method to use to send request
@param headers: Any headers to send with request
@param cookies: Request cookies (in addition to session c... |
def scan_module(egg_dir, base, name, stubs):
"""Check whether module possibly uses unsafe-for-zipfile stuff"""
filename = os.path.join(base,name)
if filename[:-1] in stubs:
return True # Extension module
pkg = base[len(egg_dir)+1:].replace(os.sep,'.')
module = pkg+(pkg and '.' or '')+os... | Check whether module possibly uses unsafe-for-zipfile stuff | Below is the the instruction that describes the task:
### Input:
Check whether module possibly uses unsafe-for-zipfile stuff
### Response:
def scan_module(egg_dir, base, name, stubs):
"""Check whether module possibly uses unsafe-for-zipfile stuff"""
filename = os.path.join(base,name)
if filename[:-1] ... |
def parse_get_tmpl(prs, conn):
"""Retrieve template.
Arguments:
prs: parser object of argparse
conn: dictionary of connection information
"""
prs_tmpl_get = prs.add_parser(
'tmpl_get', help='retrieve templates')
set_option(prs_tmpl_get, 'template')
conn_options(prs_tmp... | Retrieve template.
Arguments:
prs: parser object of argparse
conn: dictionary of connection information | Below is the the instruction that describes the task:
### Input:
Retrieve template.
Arguments:
prs: parser object of argparse
conn: dictionary of connection information
### Response:
def parse_get_tmpl(prs, conn):
"""Retrieve template.
Arguments:
prs: parser object of argp... |
def register_callback(self, fun, npts):
""" Provide a function to be executed periodically on
data collection, every time after the specified number
of points are collected.
:param fun: the function that gets called, it must have a single positional argument that will be the d... | Provide a function to be executed periodically on
data collection, every time after the specified number
of points are collected.
:param fun: the function that gets called, it must have a single positional argument that will be the data buffer read
:type fun: function
... | Below is the the instruction that describes the task:
### Input:
Provide a function to be executed periodically on
data collection, every time after the specified number
of points are collected.
:param fun: the function that gets called, it must have a single positional argument t... |
def tempdir(fun):
'''For use as a decorator of instance methods - creates a temporary dir
named self._tempdir and then deletes it after the method runs.
:param fun: function to decorate
:type fun: instance method
'''
def wrapper(*args, **kwargs):
self = args[0]
if os.path.isdir... | For use as a decorator of instance methods - creates a temporary dir
named self._tempdir and then deletes it after the method runs.
:param fun: function to decorate
:type fun: instance method | Below is the the instruction that describes the task:
### Input:
For use as a decorator of instance methods - creates a temporary dir
named self._tempdir and then deletes it after the method runs.
:param fun: function to decorate
:type fun: instance method
### Response:
def tempdir(fun):
'''For us... |
def _connect_client(self):
"""
Wait for a client to connect to this pipe.
"""
overlapped = OVERLAPPED()
overlapped.hEvent = create_event()
while True:
success = windll.kernel32.ConnectNamedPipe(
self.pipe_handle,
byref(overlapp... | Wait for a client to connect to this pipe. | Below is the the instruction that describes the task:
### Input:
Wait for a client to connect to this pipe.
### Response:
def _connect_client(self):
"""
Wait for a client to connect to this pipe.
"""
overlapped = OVERLAPPED()
overlapped.hEvent = create_event()
while... |
def install(module):
'''
Install a Perl module from CPAN
CLI Example:
.. code-block:: bash
salt '*' cpan.install Template::Alloy
'''
ret = {
'old': None,
'new': None,
}
old_info = show(module)
cmd = 'cpan -i {0}'.format(module)
out = __salt__['cmd.run... | Install a Perl module from CPAN
CLI Example:
.. code-block:: bash
salt '*' cpan.install Template::Alloy | Below is the the instruction that describes the task:
### Input:
Install a Perl module from CPAN
CLI Example:
.. code-block:: bash
salt '*' cpan.install Template::Alloy
### Response:
def install(module):
'''
Install a Perl module from CPAN
CLI Example:
.. code-block:: bash
... |
def rolling_window_sequences(X, index, window_size, target_size, target_column):
"""Create rolling window sequences out of timeseries data."""
out_X = list()
out_y = list()
X_index = list()
y_index = list()
target = X[:, target_column]
for start in range(len(X) - window_size - target_size ... | Create rolling window sequences out of timeseries data. | Below is the the instruction that describes the task:
### Input:
Create rolling window sequences out of timeseries data.
### Response:
def rolling_window_sequences(X, index, window_size, target_size, target_column):
"""Create rolling window sequences out of timeseries data."""
out_X = list()
out_y = li... |
def clear_list_value(self, value):
"""
Clean the argument value to eliminate None or Falsy values if needed.
"""
# Don't go any further: this value is empty.
if not value:
return self.empty_value
# Clean empty items if wanted
if self.clean_empty:
... | Clean the argument value to eliminate None or Falsy values if needed. | Below is the the instruction that describes the task:
### Input:
Clean the argument value to eliminate None or Falsy values if needed.
### Response:
def clear_list_value(self, value):
"""
Clean the argument value to eliminate None or Falsy values if needed.
"""
# Don't go any furthe... |
def module2uri(self, module_name):
"""Convert an encoded module name to an unencoded source uri"""
assert module_name.startswith(self.module_prefix), 'incompatible module name'
path = module_name[len(self.module_prefix):]
path = path.replace('&#DOT', '.')
return path.replace('&#S... | Convert an encoded module name to an unencoded source uri | Below is the the instruction that describes the task:
### Input:
Convert an encoded module name to an unencoded source uri
### Response:
def module2uri(self, module_name):
"""Convert an encoded module name to an unencoded source uri"""
assert module_name.startswith(self.module_prefix), 'incompatibl... |
def extract_all_ss_dssp(in_dssp, path=True):
"""Uses DSSP to extract secondary structure information on every residue.
Parameters
----------
in_dssp : str
Path to DSSP file.
path : bool, optional
Indicates if pdb is a path or a string.
Returns
-------
dssp_residues : [t... | Uses DSSP to extract secondary structure information on every residue.
Parameters
----------
in_dssp : str
Path to DSSP file.
path : bool, optional
Indicates if pdb is a path or a string.
Returns
-------
dssp_residues : [tuple]
Each internal list contains:
... | Below is the the instruction that describes the task:
### Input:
Uses DSSP to extract secondary structure information on every residue.
Parameters
----------
in_dssp : str
Path to DSSP file.
path : bool, optional
Indicates if pdb is a path or a string.
Returns
-------
d... |
def disconnect(self, slot):
"""
Disconnects the slot from the signal
"""
if not callable(slot):
return
if inspect.ismethod(slot):
# If it's a method, then find it by its instance
slotSelf = slot.__self__
for s in self._slots:
... | Disconnects the slot from the signal | Below is the the instruction that describes the task:
### Input:
Disconnects the slot from the signal
### Response:
def disconnect(self, slot):
"""
Disconnects the slot from the signal
"""
if not callable(slot):
return
if inspect.ismethod(slot):
# If... |
def convert(self, path, version, target):
"""Converts the specified source file to a new version number."""
source = self.comparer.get_representation(path)
lines = [ '# <fortpy version="{}"></fortpy>\n'.format(version) ]
for line in self.comparer.template.contents[version].preamble:
... | Converts the specified source file to a new version number. | Below is the the instruction that describes the task:
### Input:
Converts the specified source file to a new version number.
### Response:
def convert(self, path, version, target):
"""Converts the specified source file to a new version number."""
source = self.comparer.get_representation(path)
... |
def parse_remote(cls, filename):
"""Parses a remote filename into bucket and key information.
Handles S3 with optional region name specified in key:
BUCKETNAME@REGIONNAME/KEY
"""
parts = filename.split("//")[-1].split("/", 1)
bucket, key = parts if len(parts) == 2 el... | Parses a remote filename into bucket and key information.
Handles S3 with optional region name specified in key:
BUCKETNAME@REGIONNAME/KEY | Below is the the instruction that describes the task:
### Input:
Parses a remote filename into bucket and key information.
Handles S3 with optional region name specified in key:
BUCKETNAME@REGIONNAME/KEY
### Response:
def parse_remote(cls, filename):
"""Parses a remote filename into bu... |
def synced(func):
'''
Decorator for functions that should be called synchronously from another thread
:param func: function to call
'''
def wrapper(self, *args, **kwargs):
'''
Actual wrapper for the synchronous function
'''
task = DataManagerTask(func, *args, **kwar... | Decorator for functions that should be called synchronously from another thread
:param func: function to call | Below is the the instruction that describes the task:
### Input:
Decorator for functions that should be called synchronously from another thread
:param func: function to call
### Response:
def synced(func):
'''
Decorator for functions that should be called synchronously from another thread
:param... |
def GetAnalysisStatusUpdateCallback(self):
"""Retrieves the analysis status update callback function.
Returns:
function: status update callback function or None if not available.
"""
if self._mode == self.MODE_LINEAR:
return self._PrintAnalysisStatusUpdateLinear
if self._mode == self.M... | Retrieves the analysis status update callback function.
Returns:
function: status update callback function or None if not available. | Below is the the instruction that describes the task:
### Input:
Retrieves the analysis status update callback function.
Returns:
function: status update callback function or None if not available.
### Response:
def GetAnalysisStatusUpdateCallback(self):
"""Retrieves the analysis status update callb... |
def assign_edge_colors_and_widths(self):
"""
Resolve conflict of 'node_color' and 'node_style['fill'] args which are
redundant. Default is node_style.fill unless user entered node_color.
To enter multiple colors user must use node_color not style fill.
Either way, we build a lis... | Resolve conflict of 'node_color' and 'node_style['fill'] args which are
redundant. Default is node_style.fill unless user entered node_color.
To enter multiple colors user must use node_color not style fill.
Either way, we build a list of colors to pass to Drawing.node_colors
which is ... | Below is the the instruction that describes the task:
### Input:
Resolve conflict of 'node_color' and 'node_style['fill'] args which are
redundant. Default is node_style.fill unless user entered node_color.
To enter multiple colors user must use node_color not style fill.
Either way, we bui... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.