code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def count(self, object_class=None, params=None, **kwargs): # pragma: no cover
"""Retrieve the attribute configuration object.
Retrieve a count of all directory entries that belong to the
identified objectClass. The count is limited to a single domain.
Args:
params (dict): ... | Retrieve the attribute configuration object.
Retrieve a count of all directory entries that belong to the
identified objectClass. The count is limited to a single domain.
Args:
params (dict): Payload/request dictionary.
object_class (str): Directory object class.
... | Below is the the instruction that describes the task:
### Input:
Retrieve the attribute configuration object.
Retrieve a count of all directory entries that belong to the
identified objectClass. The count is limited to a single domain.
Args:
params (dict): Payload/request dicti... |
def add_fields(self, field_dict):
"""Add a mapping of field names to PayloadField instances.
:API: public
"""
for key, field in field_dict.items():
self.add_field(key, field) | Add a mapping of field names to PayloadField instances.
:API: public | Below is the the instruction that describes the task:
### Input:
Add a mapping of field names to PayloadField instances.
:API: public
### Response:
def add_fields(self, field_dict):
"""Add a mapping of field names to PayloadField instances.
:API: public
"""
for key, field in field_dict.items(... |
def get_info(handle):
"""Get information about this current console window (for Microsoft Windows only).
Raises IOError if attempt to get information fails (if there is no console window).
Don't forget to call _WindowsCSBI.initialize() once in your application before calling this method.
... | Get information about this current console window (for Microsoft Windows only).
Raises IOError if attempt to get information fails (if there is no console window).
Don't forget to call _WindowsCSBI.initialize() once in your application before calling this method.
Positional arguments:
... | Below is the the instruction that describes the task:
### Input:
Get information about this current console window (for Microsoft Windows only).
Raises IOError if attempt to get information fails (if there is no console window).
Don't forget to call _WindowsCSBI.initialize() once in your applicati... |
def usernames(urls):
'''Take an iterable of `urls` of normalized URL or file paths and
attempt to extract usernames. Returns a list.
'''
usernames = StringCounter()
for url, count in urls.items():
uparse = urlparse(url)
path = uparse.path
hostname = uparse.hostname
... | Take an iterable of `urls` of normalized URL or file paths and
attempt to extract usernames. Returns a list. | Below is the the instruction that describes the task:
### Input:
Take an iterable of `urls` of normalized URL or file paths and
attempt to extract usernames. Returns a list.
### Response:
def usernames(urls):
'''Take an iterable of `urls` of normalized URL or file paths and
attempt to extract username... |
def _load_properties(self):
"""Load User properties from Flickr."""
method = 'flickr.people.getInfo'
data = _doget(method, user_id=self.__id)
self.__loaded = True
person = data.rsp.person
self.__isadmin = person.isadmin
self.__ispro = person.ispro
... | Load User properties from Flickr. | Below is the the instruction that describes the task:
### Input:
Load User properties from Flickr.
### Response:
def _load_properties(self):
"""Load User properties from Flickr."""
method = 'flickr.people.getInfo'
data = _doget(method, user_id=self.__id)
self.__loaded = True
... |
def build(self, words):
"""Construct dictionary DAWG from tokenized words."""
words = [self._normalize(tokens) for tokens in words]
self._dawg = dawg.CompletionDAWG(words)
self._loaded_model = True | Construct dictionary DAWG from tokenized words. | Below is the the instruction that describes the task:
### Input:
Construct dictionary DAWG from tokenized words.
### Response:
def build(self, words):
"""Construct dictionary DAWG from tokenized words."""
words = [self._normalize(tokens) for tokens in words]
self._dawg = dawg.CompletionDAWG... |
def make_processor(func, arg=None):
"""
A pre-called processor that wraps the execution of the target callable ``func``.
This is useful for when ``func`` is a third party mapping function that can take your column's
value and return an expected result, but doesn't understand all of the extra kwargs tha... | A pre-called processor that wraps the execution of the target callable ``func``.
This is useful for when ``func`` is a third party mapping function that can take your column's
value and return an expected result, but doesn't understand all of the extra kwargs that get
sent to processor callbacks. Because ... | Below is the the instruction that describes the task:
### Input:
A pre-called processor that wraps the execution of the target callable ``func``.
This is useful for when ``func`` is a third party mapping function that can take your column's
value and return an expected result, but doesn't understand all of... |
def get_api(
profile=None,
config_file=None,
requirements=None):
'''
Generate a datafs.DataAPI object from a config profile
``get_api`` generates a DataAPI object based on a
pre-configured datafs profile specified in your datafs
config file.
To create a datafs config fi... | Generate a datafs.DataAPI object from a config profile
``get_api`` generates a DataAPI object based on a
pre-configured datafs profile specified in your datafs
config file.
To create a datafs config file, use the command line
tool ``datafs configure --helper`` or export an existing
DataAPI obj... | Below is the the instruction that describes the task:
### Input:
Generate a datafs.DataAPI object from a config profile
``get_api`` generates a DataAPI object based on a
pre-configured datafs profile specified in your datafs
config file.
To create a datafs config file, use the command line
too... |
def scale_and_crop(im, crop_spec):
"""
Scale and Crop.
"""
im = im.crop((crop_spec.x, crop_spec.y, crop_spec.x2, crop_spec.y2))
if crop_spec.width and crop_spec.height:
im = im.resize((crop_spec.width, crop_spec.height),
resample=Image.ANTIALIAS)
return im | Scale and Crop. | Below is the the instruction that describes the task:
### Input:
Scale and Crop.
### Response:
def scale_and_crop(im, crop_spec):
"""
Scale and Crop.
"""
im = im.crop((crop_spec.x, crop_spec.y, crop_spec.x2, crop_spec.y2))
if crop_spec.width and crop_spec.height:
im = im.resize((crop_s... |
def listFigures(self,walkTrace=tuple(),case=None,element=None):
"""List section figures.
"""
if case == 'sectionmain': print(walkTrace,self.title)
if case == 'figure':
caption,fig = element
try:
print(walkTrace,fig._leopardref,caption)
... | List section figures. | Below is the the instruction that describes the task:
### Input:
List section figures.
### Response:
def listFigures(self,walkTrace=tuple(),case=None,element=None):
"""List section figures.
"""
if case == 'sectionmain': print(walkTrace,self.title)
if case == 'figure':
ca... |
def pformat(self):
""" Pretty string format """
lines = []
lines.append(("%s (%s)" % (self.name, self.status)).center(50, "-"))
lines.append("items: {0:,} ({1:,} bytes)".format(self.item_count, self.size))
cap = self.consumed_capacity.get("__table__", {})
read = "Read: " ... | Pretty string format | Below is the the instruction that describes the task:
### Input:
Pretty string format
### Response:
def pformat(self):
""" Pretty string format """
lines = []
lines.append(("%s (%s)" % (self.name, self.status)).center(50, "-"))
lines.append("items: {0:,} ({1:,} bytes)".format(self.i... |
def validate_scopes(self, request):
"""
:param request: OAuthlib request.
:type request: oauthlib.common.Request
"""
if not request.scopes:
request.scopes = utils.scope_to_list(request.scope) or utils.scope_to_list(
self.request_validator.get_default_s... | :param request: OAuthlib request.
:type request: oauthlib.common.Request | Below is the the instruction that describes the task:
### Input:
:param request: OAuthlib request.
:type request: oauthlib.common.Request
### Response:
def validate_scopes(self, request):
"""
:param request: OAuthlib request.
:type request: oauthlib.common.Request
"""
... |
def transform(self, X, **kwargs):
"""
The transform method is the primary drawing hook for ranking classes.
Parameters
----------
X : ndarray or DataFrame of shape n x m
A matrix of n instances with m features
kwargs : dict
Pass generic arguments... | The transform method is the primary drawing hook for ranking classes.
Parameters
----------
X : ndarray or DataFrame of shape n x m
A matrix of n instances with m features
kwargs : dict
Pass generic arguments to the drawing method
Returns
------... | Below is the the instruction that describes the task:
### Input:
The transform method is the primary drawing hook for ranking classes.
Parameters
----------
X : ndarray or DataFrame of shape n x m
A matrix of n instances with m features
kwargs : dict
Pass ge... |
def spell_checker(
self, text, accept_language=None, pragma=None, user_agent=None, client_id=None, client_ip=None, location=None, action_type=None, app_name=None, country_code=None, client_machine_name=None, doc_id=None, market=None, session_id=None, set_lang=None, user_id=None, mode=None, pre_context_text=... | The Bing Spell Check API lets you perform contextual grammar and spell
checking. Bing has developed a web-based spell-checker that leverages
machine learning and statistical machine translation to dynamically
train a constantly evolving and highly contextual algorithm. The
spell-checker ... | Below is the the instruction that describes the task:
### Input:
The Bing Spell Check API lets you perform contextual grammar and spell
checking. Bing has developed a web-based spell-checker that leverages
machine learning and statistical machine translation to dynamically
train a constantly... |
def _sign_payload(self, payload):
"""使用 appkey 对 payload 进行签名,返回新的请求参数
"""
app_key = self._app_key
t = int(time.time() * 1000)
requestStr = {
'header': self._req_header,
'model': payload
}
data = json.dumps({'requestStr': json.dumps(request... | 使用 appkey 对 payload 进行签名,返回新的请求参数 | Below is the the instruction that describes the task:
### Input:
使用 appkey 对 payload 进行签名,返回新的请求参数
### Response:
def _sign_payload(self, payload):
"""使用 appkey 对 payload 进行签名,返回新的请求参数
"""
app_key = self._app_key
t = int(time.time() * 1000)
requestStr = {
'header'... |
def from_pycbc(cls, fs, copy=True):
"""Convert a `pycbc.types.frequencyseries.FrequencySeries` into
a `FrequencySeries`
Parameters
----------
fs : `pycbc.types.frequencyseries.FrequencySeries`
the input PyCBC `~pycbc.types.frequencyseries.FrequencySeries`
... | Convert a `pycbc.types.frequencyseries.FrequencySeries` into
a `FrequencySeries`
Parameters
----------
fs : `pycbc.types.frequencyseries.FrequencySeries`
the input PyCBC `~pycbc.types.frequencyseries.FrequencySeries`
array
copy : `bool`, optional, defaul... | Below is the the instruction that describes the task:
### Input:
Convert a `pycbc.types.frequencyseries.FrequencySeries` into
a `FrequencySeries`
Parameters
----------
fs : `pycbc.types.frequencyseries.FrequencySeries`
the input PyCBC `~pycbc.types.frequencyseries.Freque... |
def attachviewers(self, profiles):
"""Attach viewers *and converters* to file, automatically scan all profiles for outputtemplate or inputtemplate"""
if self.metadata:
template = None
for profile in profiles:
if isinstance(self, CLAMInputFile):
... | Attach viewers *and converters* to file, automatically scan all profiles for outputtemplate or inputtemplate | Below is the the instruction that describes the task:
### Input:
Attach viewers *and converters* to file, automatically scan all profiles for outputtemplate or inputtemplate
### Response:
def attachviewers(self, profiles):
"""Attach viewers *and converters* to file, automatically scan all profiles for outp... |
def mono_FM(x,fs=2.4e6,file_name='test.wav'):
"""
Decimate complex baseband input by 10
Design 1st decimation lowpass filter (f_c = 200 KHz)
"""
b = signal.firwin(64,2*200e3/float(fs))
# Filter and decimate (should be polyphase)
y = signal.lfilter(b,1,x)
z = ss.downsample(y,10)
... | Decimate complex baseband input by 10
Design 1st decimation lowpass filter (f_c = 200 KHz) | Below is the the instruction that describes the task:
### Input:
Decimate complex baseband input by 10
Design 1st decimation lowpass filter (f_c = 200 KHz)
### Response:
def mono_FM(x,fs=2.4e6,file_name='test.wav'):
"""
Decimate complex baseband input by 10
Design 1st decimation lowpass filter ... |
def _get_deps(self, tree, include_punct, representation, universal):
"""Get a list of dependencies from a Stanford Tree for a specific
Stanford Dependencies representation."""
if universal:
converter = self.universal_converter
if self.universal_converter == self.converte... | Get a list of dependencies from a Stanford Tree for a specific
Stanford Dependencies representation. | Below is the the instruction that describes the task:
### Input:
Get a list of dependencies from a Stanford Tree for a specific
Stanford Dependencies representation.
### Response:
def _get_deps(self, tree, include_punct, representation, universal):
"""Get a list of dependencies from a Stanford Tree... |
def get_core(self):
"""
Get an unsatisfiable core if the formula was previously
unsatisfied.
"""
if self.minicard and self.status == False:
return pysolvers.minicard_core(self.minicard) | Get an unsatisfiable core if the formula was previously
unsatisfied. | Below is the the instruction that describes the task:
### Input:
Get an unsatisfiable core if the formula was previously
unsatisfied.
### Response:
def get_core(self):
"""
Get an unsatisfiable core if the formula was previously
unsatisfied.
"""
if self.m... |
def wrap_iterable(obj):
"""
Returns:
wrapped_obj, was_scalar
"""
was_scalar = not isiterable(obj)
wrapped_obj = [obj] if was_scalar else obj
return wrapped_obj, was_scalar | Returns:
wrapped_obj, was_scalar | Below is the the instruction that describes the task:
### Input:
Returns:
wrapped_obj, was_scalar
### Response:
def wrap_iterable(obj):
"""
Returns:
wrapped_obj, was_scalar
"""
was_scalar = not isiterable(obj)
wrapped_obj = [obj] if was_scalar else obj
return wrapped_obj, wa... |
def send_text(self, sender, receiver_type, receiver_id, content):
"""
发送文本消息
详情请参考
https://qydev.weixin.qq.com/wiki/index.php?title=企业会话接口说明
:param sender: 发送人
:param receiver_type: 接收人类型:single|group,分别表示:单聊|群聊
:param receiver_id: 接收人的值,为userid|chatid,分别表示:成员id... | 发送文本消息
详情请参考
https://qydev.weixin.qq.com/wiki/index.php?title=企业会话接口说明
:param sender: 发送人
:param receiver_type: 接收人类型:single|group,分别表示:单聊|群聊
:param receiver_id: 接收人的值,为userid|chatid,分别表示:成员id|会话id
:param content: 消息内容
:return: 返回的 JSON 数据包 | Below is the the instruction that describes the task:
### Input:
发送文本消息
详情请参考
https://qydev.weixin.qq.com/wiki/index.php?title=企业会话接口说明
:param sender: 发送人
:param receiver_type: 接收人类型:single|group,分别表示:单聊|群聊
:param receiver_id: 接收人的值,为userid|chatid,分别表示:成员id|会话id
:pa... |
def user_token(scopes, client_id=None, client_secret=None, redirect_uri=None):
"""
Generate a user access token
:param List[str] scopes: Scopes to get
:param str client_id: Spotify Client ID
:param str client_secret: Spotify Client secret
:param str redirect_uri: Spotify redirect URI
:retur... | Generate a user access token
:param List[str] scopes: Scopes to get
:param str client_id: Spotify Client ID
:param str client_secret: Spotify Client secret
:param str redirect_uri: Spotify redirect URI
:return: Generated access token
:rtype: User | Below is the the instruction that describes the task:
### Input:
Generate a user access token
:param List[str] scopes: Scopes to get
:param str client_id: Spotify Client ID
:param str client_secret: Spotify Client secret
:param str redirect_uri: Spotify redirect URI
:return: Generated access to... |
def probably_wkt(text):
'''Quick check to determine if the provided text looks like WKT'''
valid = False
valid_types = set([
'POINT', 'LINESTRING', 'POLYGON', 'MULTIPOINT',
'MULTILINESTRING', 'MULTIPOLYGON', 'GEOMETRYCOLLECTION',
])
matched = re.match(r'(\w+)\s*\([^)]+\)', text.strip... | Quick check to determine if the provided text looks like WKT | Below is the the instruction that describes the task:
### Input:
Quick check to determine if the provided text looks like WKT
### Response:
def probably_wkt(text):
'''Quick check to determine if the provided text looks like WKT'''
valid = False
valid_types = set([
'POINT', 'LINESTRING', 'POLYGO... |
def mask_catalog(regionfile, infile, outfile, negate=False, racol='ra', deccol='dec'):
"""
Apply a region file as a mask to a catalog, removing all the rows with ra/dec inside the region
If negate=False then remove the rows with ra/dec outside the region.
Parameters
----------
regionfile : str... | Apply a region file as a mask to a catalog, removing all the rows with ra/dec inside the region
If negate=False then remove the rows with ra/dec outside the region.
Parameters
----------
regionfile : str
A file which can be loaded as a :class:`AegeanTools.regions.Region`.
The catalogue... | Below is the the instruction that describes the task:
### Input:
Apply a region file as a mask to a catalog, removing all the rows with ra/dec inside the region
If negate=False then remove the rows with ra/dec outside the region.
Parameters
----------
regionfile : str
A file which can be l... |
def forward(self, x: torch.Tensor, mask: torch.Tensor) -> torch.Tensor:
"""Follow Figure 1 (left) for connections."""
x = self.sublayer[0](x, lambda x: self.self_attn(x, x, x, mask))
return self.sublayer[1](x, self.feed_forward) | Follow Figure 1 (left) for connections. | Below is the the instruction that describes the task:
### Input:
Follow Figure 1 (left) for connections.
### Response:
def forward(self, x: torch.Tensor, mask: torch.Tensor) -> torch.Tensor:
"""Follow Figure 1 (left) for connections."""
x = self.sublayer[0](x, lambda x: self.self_attn(x, x, x, mask... |
def admin_startWS(self, host='localhost', port=8546, cors=None, apis=None):
"""https://github.com/ethereum/go-ethereum/wiki/Management-APIs#admin_startws
:param host: Network interface to open the listener socket (optional)
:type host: str
:param port: Network port to open the listener... | https://github.com/ethereum/go-ethereum/wiki/Management-APIs#admin_startws
:param host: Network interface to open the listener socket (optional)
:type host: str
:param port: Network port to open the listener socket (optional)
:type port: int
:param cors: Cross-origin resource ... | Below is the the instruction that describes the task:
### Input:
https://github.com/ethereum/go-ethereum/wiki/Management-APIs#admin_startws
:param host: Network interface to open the listener socket (optional)
:type host: str
:param port: Network port to open the listener socket (optional)... |
def compute_ratio(x):
"""
计算每一类数据的占比
"""
sum_ = sum(x)
ratios = []
for i in x:
ratio = i / sum_
ratios.append(ratio)
return ratios | 计算每一类数据的占比 | Below is the the instruction that describes the task:
### Input:
计算每一类数据的占比
### Response:
def compute_ratio(x):
"""
计算每一类数据的占比
"""
sum_ = sum(x)
ratios = []
for i in x:
ratio = i / sum_
ratios.append(ratio)
return ratios |
def _parse_game_date_and_location(self, boxscore):
"""
Retrieve the game's date and location.
The games' meta information, such as date, location, attendance, and
duration, follow a complex parsing scheme that changes based on the
layout of the page. The information should be ab... | Retrieve the game's date and location.
The games' meta information, such as date, location, attendance, and
duration, follow a complex parsing scheme that changes based on the
layout of the page. The information should be able to be parsed and set
regardless of the order and how much in... | Below is the the instruction that describes the task:
### Input:
Retrieve the game's date and location.
The games' meta information, such as date, location, attendance, and
duration, follow a complex parsing scheme that changes based on the
layout of the page. The information should be able... |
def _parse_pages(self, unicode=False):
"""Auxiliary function to parse and format page range of a document."""
if self.pageRange:
pages = 'pp. {}'.format(self.pageRange)
elif self.startingPage:
pages = 'pp. {}-{}'.format(self.startingPage, self.endingPage)
else:
pages = '(no pages... | Auxiliary function to parse and format page range of a document. | Below is the the instruction that describes the task:
### Input:
Auxiliary function to parse and format page range of a document.
### Response:
def _parse_pages(self, unicode=False):
"""Auxiliary function to parse and format page range of a document."""
if self.pageRange:
pages = 'pp. {}'.format(se... |
def command(self, cluster_id, command, *args):
"""Call a ShardedCluster method."""
cluster = self._storage[cluster_id]
try:
return getattr(cluster, command)(*args)
except AttributeError:
raise ValueError("Cannot issue the command %r to ShardedCluster %s"
... | Call a ShardedCluster method. | Below is the the instruction that describes the task:
### Input:
Call a ShardedCluster method.
### Response:
def command(self, cluster_id, command, *args):
"""Call a ShardedCluster method."""
cluster = self._storage[cluster_id]
try:
return getattr(cluster, command)(*args)
... |
def getParticleInfos(self, swarmId=None, genIdx=None, completed=None,
matured=None, lastDescendent=False):
"""Return a list of particleStates for all particles we know about in
the given swarm, their model Ids, and metric results.
Parameters:
-------------------------------------... | Return a list of particleStates for all particles we know about in
the given swarm, their model Ids, and metric results.
Parameters:
---------------------------------------------------------------------
swarmId: A string representation of the sorted list of encoders in this
swarm. For... | Below is the the instruction that describes the task:
### Input:
Return a list of particleStates for all particles we know about in
the given swarm, their model Ids, and metric results.
Parameters:
---------------------------------------------------------------------
swarmId: A string representati... |
def update(self, data_set):
"""
Refresh the time of all specified elements in the supplied data set.
"""
now = time.time()
for d in data_set:
self.timed_data[d] = now
self._expire_data() | Refresh the time of all specified elements in the supplied data set. | Below is the the instruction that describes the task:
### Input:
Refresh the time of all specified elements in the supplied data set.
### Response:
def update(self, data_set):
"""
Refresh the time of all specified elements in the supplied data set.
"""
now = time.time()
for... |
def _get_esxi_proxy_details():
'''
Returns the running esxi's proxy details
'''
det = __proxy__['esxi.get_details']()
host = det.get('host')
if det.get('vcenter'):
host = det['vcenter']
esxi_hosts = None
if det.get('esxi_host'):
esxi_hosts = [det['esxi_host']]
return ... | Returns the running esxi's proxy details | Below is the the instruction that describes the task:
### Input:
Returns the running esxi's proxy details
### Response:
def _get_esxi_proxy_details():
'''
Returns the running esxi's proxy details
'''
det = __proxy__['esxi.get_details']()
host = det.get('host')
if det.get('vcenter'):
... |
def _construct_body_s3_dict(self):
"""Constructs the RestApi's `BodyS3Location property`_, from the SAM Api's DefinitionUri property.
:returns: a BodyS3Location dict, containing the S3 Bucket, Key, and Version of the Swagger definition
:rtype: dict
"""
if isinstance(self.definit... | Constructs the RestApi's `BodyS3Location property`_, from the SAM Api's DefinitionUri property.
:returns: a BodyS3Location dict, containing the S3 Bucket, Key, and Version of the Swagger definition
:rtype: dict | Below is the the instruction that describes the task:
### Input:
Constructs the RestApi's `BodyS3Location property`_, from the SAM Api's DefinitionUri property.
:returns: a BodyS3Location dict, containing the S3 Bucket, Key, and Version of the Swagger definition
:rtype: dict
### Response:
def _con... |
def keep_types_s(s, types):
"""
Keep the given types from a string
Same as :meth:`keep_types` but does not use the :attr:`params`
dictionary
Parameters
----------
s: str
The string of the returns like section
types: list of str
Th... | Keep the given types from a string
Same as :meth:`keep_types` but does not use the :attr:`params`
dictionary
Parameters
----------
s: str
The string of the returns like section
types: list of str
The type identifiers to keep
Returns
... | Below is the the instruction that describes the task:
### Input:
Keep the given types from a string
Same as :meth:`keep_types` but does not use the :attr:`params`
dictionary
Parameters
----------
s: str
The string of the returns like section
types: list ... |
def safe_pdist(arr, *args, **kwargs):
"""
Kwargs:
metric = ut.absdiff
SeeAlso:
scipy.spatial.distance.pdist
TODO: move to vtool
"""
if arr is None or len(arr) < 2:
return None
else:
import vtool as vt
arr_ = vt.atleast_nd(arr, 2)
return spdis... | Kwargs:
metric = ut.absdiff
SeeAlso:
scipy.spatial.distance.pdist
TODO: move to vtool | Below is the the instruction that describes the task:
### Input:
Kwargs:
metric = ut.absdiff
SeeAlso:
scipy.spatial.distance.pdist
TODO: move to vtool
### Response:
def safe_pdist(arr, *args, **kwargs):
"""
Kwargs:
metric = ut.absdiff
SeeAlso:
scipy.spatial.dist... |
def on_setup_ssh(self, b):
"""ATTENTION: modifying the order of operations in this function can lead to unexpected problems"""
with self._setup_ssh_out:
clear_output()
self._ssh_keygen()
#temporary passwords
password = self.__password
proxy_pa... | ATTENTION: modifying the order of operations in this function can lead to unexpected problems | Below is the the instruction that describes the task:
### Input:
ATTENTION: modifying the order of operations in this function can lead to unexpected problems
### Response:
def on_setup_ssh(self, b):
"""ATTENTION: modifying the order of operations in this function can lead to unexpected problems"""
... |
def _Open(self, path_spec, mode='rb'):
"""Opens the file system defined by path specification.
Args:
path_spec (PathSpec): a path specification.
mode (Optional[str]): file access mode. The default is 'rb' which
represents read-only binary.
Raises:
AccessError: if the access to ... | Opens the file system defined by path specification.
Args:
path_spec (PathSpec): a path specification.
mode (Optional[str]): file access mode. The default is 'rb' which
represents read-only binary.
Raises:
AccessError: if the access to open the file was denied.
IOError: if th... | Below is the the instruction that describes the task:
### Input:
Opens the file system defined by path specification.
Args:
path_spec (PathSpec): a path specification.
mode (Optional[str]): file access mode. The default is 'rb' which
represents read-only binary.
Raises:
AccessE... |
def xml_to_namespace(xmlstr):
'''Converts xml response to service bus namespace
The xml format for namespace:
<entry>
<id>uuid:00000000-0000-0000-0000-000000000000;id=0000000</id>
<title type="text">myunittests</title>
<updated>2012-08-22T16:48:10Z</updated>
<content type="application/xml">
<Namesp... | Converts xml response to service bus namespace
The xml format for namespace:
<entry>
<id>uuid:00000000-0000-0000-0000-000000000000;id=0000000</id>
<title type="text">myunittests</title>
<updated>2012-08-22T16:48:10Z</updated>
<content type="application/xml">
<NamespaceDescription
xmlns="http://sche... | Below is the the instruction that describes the task:
### Input:
Converts xml response to service bus namespace
The xml format for namespace:
<entry>
<id>uuid:00000000-0000-0000-0000-000000000000;id=0000000</id>
<title type="text">myunittests</title>
<updated>2012-08-22T16:48:10Z</updated>
<content type="a... |
def delete(self, using=None, **kwargs):
"""
Deletes the index in elasticsearch.
Any additional keyword arguments will be passed to
``Elasticsearch.indices.delete`` unchanged.
"""
return self._get_connection(using).indices.delete(index=self._name, **kwargs) | Deletes the index in elasticsearch.
Any additional keyword arguments will be passed to
``Elasticsearch.indices.delete`` unchanged. | Below is the the instruction that describes the task:
### Input:
Deletes the index in elasticsearch.
Any additional keyword arguments will be passed to
``Elasticsearch.indices.delete`` unchanged.
### Response:
def delete(self, using=None, **kwargs):
"""
Deletes the index in elastic... |
def workon(ctx, issue_id, new, base_branch):
"""
Start work on a given issue.
This command retrieves the issue from the issue tracker, creates and checks
out a new aptly-named branch, puts the issue in the configured active,
status, assigns it to you and starts a correctly linked Harvest timer.
... | Start work on a given issue.
This command retrieves the issue from the issue tracker, creates and checks
out a new aptly-named branch, puts the issue in the configured active,
status, assigns it to you and starts a correctly linked Harvest timer.
If a branch with the same name as the one to be created... | Below is the the instruction that describes the task:
### Input:
Start work on a given issue.
This command retrieves the issue from the issue tracker, creates and checks
out a new aptly-named branch, puts the issue in the configured active,
status, assigns it to you and starts a correctly linked Harves... |
def delete(name, root=None):
'''
Remove the named group
name
Name group to delete
root
Directory to chroot into
CLI Example:
.. code-block:: bash
salt '*' group.delete foo
'''
cmd = ['groupdel']
if root is not None:
cmd.extend(('-R', root))
... | Remove the named group
name
Name group to delete
root
Directory to chroot into
CLI Example:
.. code-block:: bash
salt '*' group.delete foo | Below is the the instruction that describes the task:
### Input:
Remove the named group
name
Name group to delete
root
Directory to chroot into
CLI Example:
.. code-block:: bash
salt '*' group.delete foo
### Response:
def delete(name, root=None):
'''
Remove the ... |
def process_pulls(self, testpulls=None, testarchive=None, expected=None):
"""Runs self.find_pulls() *and* processes the pull requests unit tests,
status updates and wiki page creations.
:arg expected: for unit testing the output results that would be returned
from running the tests in... | Runs self.find_pulls() *and* processes the pull requests unit tests,
status updates and wiki page creations.
:arg expected: for unit testing the output results that would be returned
from running the tests in real time. | Below is the the instruction that describes the task:
### Input:
Runs self.find_pulls() *and* processes the pull requests unit tests,
status updates and wiki page creations.
:arg expected: for unit testing the output results that would be returned
from running the tests in real time.
### ... |
def load_case(adapter, case_obj, update=False):
"""Load a case to the database
Args:
adapter: Connection to database
case_obj: dict
update(bool): If existing case should be updated
Returns:
case_obj(models.Case)
"""
# Check if the case already exists in database.
... | Load a case to the database
Args:
adapter: Connection to database
case_obj: dict
update(bool): If existing case should be updated
Returns:
case_obj(models.Case) | Below is the the instruction that describes the task:
### Input:
Load a case to the database
Args:
adapter: Connection to database
case_obj: dict
update(bool): If existing case should be updated
Returns:
case_obj(models.Case)
### Response:
def load_case(adapter, case_obj, ... |
def AppendFlagsIntoFile(self, filename):
"""Appends all flags assignments from this FlagInfo object to a file.
Output will be in the format of a flagfile.
NOTE: MUST mirror the behavior of the C++ AppendFlagsIntoFile
from http://code.google.com/p/google-gflags
Args:
filename: string, name o... | Appends all flags assignments from this FlagInfo object to a file.
Output will be in the format of a flagfile.
NOTE: MUST mirror the behavior of the C++ AppendFlagsIntoFile
from http://code.google.com/p/google-gflags
Args:
filename: string, name of the file. | Below is the the instruction that describes the task:
### Input:
Appends all flags assignments from this FlagInfo object to a file.
Output will be in the format of a flagfile.
NOTE: MUST mirror the behavior of the C++ AppendFlagsIntoFile
from http://code.google.com/p/google-gflags
Args:
fil... |
def reshape(self, input_shapes):
"""Change the input shape of the predictor.
Parameters
----------
input_shapes : dict of str to tuple
The new shape of input data.
Examples
--------
>>> predictor.reshape({'data':data_shape_tuple})
"""
... | Change the input shape of the predictor.
Parameters
----------
input_shapes : dict of str to tuple
The new shape of input data.
Examples
--------
>>> predictor.reshape({'data':data_shape_tuple}) | Below is the the instruction that describes the task:
### Input:
Change the input shape of the predictor.
Parameters
----------
input_shapes : dict of str to tuple
The new shape of input data.
Examples
--------
>>> predictor.reshape({'data':data_shape_tu... |
def pix2vec(nside, ipix, nest=False):
"""Drop-in replacement for healpy `~healpy.pixelfunc.pix2vec`."""
lon, lat = healpix_to_lonlat(ipix, nside, order='nested' if nest else 'ring')
return ang2vec(*_lonlat_to_healpy(lon, lat)) | Drop-in replacement for healpy `~healpy.pixelfunc.pix2vec`. | Below is the the instruction that describes the task:
### Input:
Drop-in replacement for healpy `~healpy.pixelfunc.pix2vec`.
### Response:
def pix2vec(nside, ipix, nest=False):
"""Drop-in replacement for healpy `~healpy.pixelfunc.pix2vec`."""
lon, lat = healpix_to_lonlat(ipix, nside, order='nested' if nest... |
def free(self, connection):
"""Free the connection from use by the session that was using it.
:param connection: The connection to free
:type connection: psycopg2.extensions.connection
:raises: ConnectionNotFoundError
"""
LOGGER.debug('Pool %s freeing connection %s', se... | Free the connection from use by the session that was using it.
:param connection: The connection to free
:type connection: psycopg2.extensions.connection
:raises: ConnectionNotFoundError | Below is the the instruction that describes the task:
### Input:
Free the connection from use by the session that was using it.
:param connection: The connection to free
:type connection: psycopg2.extensions.connection
:raises: ConnectionNotFoundError
### Response:
def free(self, connectio... |
def to_key_val_list(value):
"""Take an object and test to see if it can be represented as a
dictionary. If it can be, return a list of tuples, e.g.,
::
>>> to_key_val_list([('key', 'val')])
[('key', 'val')]
>>> to_key_val_list({'key': 'val'})
[('key', 'val')]
>>> to... | Take an object and test to see if it can be represented as a
dictionary. If it can be, return a list of tuples, e.g.,
::
>>> to_key_val_list([('key', 'val')])
[('key', 'val')]
>>> to_key_val_list({'key': 'val'})
[('key', 'val')]
>>> to_key_val_list('string')
Val... | Below is the the instruction that describes the task:
### Input:
Take an object and test to see if it can be represented as a
dictionary. If it can be, return a list of tuples, e.g.,
::
>>> to_key_val_list([('key', 'val')])
[('key', 'val')]
>>> to_key_val_list({'key': 'val'})
... |
def logjacobian(self, **params):
r"""Returns the log of the jacobian needed to transform pdfs in the
``variable_params`` parameter space to the ``sampling_params``
parameter space.
Let :math:`\mathbf{x}` be the set of variable parameters,
:math:`\mathbf{y} = f(\mathbf{x})` the s... | r"""Returns the log of the jacobian needed to transform pdfs in the
``variable_params`` parameter space to the ``sampling_params``
parameter space.
Let :math:`\mathbf{x}` be the set of variable parameters,
:math:`\mathbf{y} = f(\mathbf{x})` the set of sampling parameters, and
:m... | Below is the the instruction that describes the task:
### Input:
r"""Returns the log of the jacobian needed to transform pdfs in the
``variable_params`` parameter space to the ``sampling_params``
parameter space.
Let :math:`\mathbf{x}` be the set of variable parameters,
:math:`\math... |
def set_xticks(self, row, column, ticks):
"""Manually specify the x-axis tick values.
:param row,column: specify the subplot.
:param ticks: list of tick values.
"""
subplot = self.get_subplot_at(row, column)
subplot.set_xticks(ticks) | Manually specify the x-axis tick values.
:param row,column: specify the subplot.
:param ticks: list of tick values. | Below is the the instruction that describes the task:
### Input:
Manually specify the x-axis tick values.
:param row,column: specify the subplot.
:param ticks: list of tick values.
### Response:
def set_xticks(self, row, column, ticks):
"""Manually specify the x-axis tick values.
... |
def verifyZeroInteractions(*objs):
"""Verify that no methods have been called on given objs.
Note that strict mocks usually throw early on unexpected, unstubbed
invocations. Partial mocks ('monkeypatched' objects or modules) do not
support this functionality at all, bc only for the stubbed invocations
... | Verify that no methods have been called on given objs.
Note that strict mocks usually throw early on unexpected, unstubbed
invocations. Partial mocks ('monkeypatched' objects or modules) do not
support this functionality at all, bc only for the stubbed invocations
the actual usage gets recorded. So thi... | Below is the the instruction that describes the task:
### Input:
Verify that no methods have been called on given objs.
Note that strict mocks usually throw early on unexpected, unstubbed
invocations. Partial mocks ('monkeypatched' objects or modules) do not
support this functionality at all, bc only f... |
def is_supported(value, check_all=False, filters=None, iterate=False):
"""Return True if the value is supported, False otherwise"""
assert filters is not None
if value is None:
return True
if not is_editable_type(value):
return False
elif not isinstance(value, filters):
retur... | Return True if the value is supported, False otherwise | Below is the the instruction that describes the task:
### Input:
Return True if the value is supported, False otherwise
### Response:
def is_supported(value, check_all=False, filters=None, iterate=False):
"""Return True if the value is supported, False otherwise"""
assert filters is not None
if value i... |
def assert_script_in_current_directory():
"""Assert fail if current directory is different from location of the script"""
script = sys.argv[0]
assert os.path.abspath(os.path.dirname(script)) == os.path.abspath(
'.'), f"Change into directory of script {script} and run again." | Assert fail if current directory is different from location of the script | Below is the the instruction that describes the task:
### Input:
Assert fail if current directory is different from location of the script
### Response:
def assert_script_in_current_directory():
"""Assert fail if current directory is different from location of the script"""
script = sys.argv[0]
assert os.pa... |
def _does_require_deprecation(self):
"""
Check if we have to put the previous version into the deprecated list.
"""
for index, version_number in enumerate(self.current_version[0][:2]):
# We loop through the 2 last elements of the version.
if version_number > sel... | Check if we have to put the previous version into the deprecated list. | Below is the the instruction that describes the task:
### Input:
Check if we have to put the previous version into the deprecated list.
### Response:
def _does_require_deprecation(self):
"""
Check if we have to put the previous version into the deprecated list.
"""
for index, versi... |
def id(self, obj):
"""
The method is to be used to assign an integer variable ID for a
given new object. If the object already has an ID, no new ID is
created and the old one is returned instead.
An object can be anything. In some cases it is convenient to use
... | The method is to be used to assign an integer variable ID for a
given new object. If the object already has an ID, no new ID is
created and the old one is returned instead.
An object can be anything. In some cases it is convenient to use
string variable names.
... | Below is the the instruction that describes the task:
### Input:
The method is to be used to assign an integer variable ID for a
given new object. If the object already has an ID, no new ID is
created and the old one is returned instead.
An object can be anything. In some cases ... |
def scan_resource(self, pkg, path):
r"""Scan a resource directory for colortable files and add them to the registry.
Parameters
----------
pkg : str
The package containing the resource directory
path : str
The path to the directory with the color tables
... | r"""Scan a resource directory for colortable files and add them to the registry.
Parameters
----------
pkg : str
The package containing the resource directory
path : str
The path to the directory with the color tables | Below is the the instruction that describes the task:
### Input:
r"""Scan a resource directory for colortable files and add them to the registry.
Parameters
----------
pkg : str
The package containing the resource directory
path : str
The path to the director... |
def __prepare_domain(data):
"""Prepare domainpart of the JID.
:Parameters:
- `data`: Domain part of the JID
:Types:
- `data`: `unicode`
:raise JIDError: if the domain name is too long.
"""
# pylint: disable=R0912
if not data:
... | Prepare domainpart of the JID.
:Parameters:
- `data`: Domain part of the JID
:Types:
- `data`: `unicode`
:raise JIDError: if the domain name is too long. | Below is the the instruction that describes the task:
### Input:
Prepare domainpart of the JID.
:Parameters:
- `data`: Domain part of the JID
:Types:
- `data`: `unicode`
:raise JIDError: if the domain name is too long.
### Response:
def __prepare_domain(data):
... |
def get_profile():
""" Prefetch the profile module, to fill some holes in the help text."""
argument_parser = ThrowingArgumentParser(add_help=False)
argument_parser.add_argument('profile')
try:
args, _ = argument_parser.parse_known_args()
except ArgumentParserError:
# silently fails, the main parser w... | Prefetch the profile module, to fill some holes in the help text. | Below is the the instruction that describes the task:
### Input:
Prefetch the profile module, to fill some holes in the help text.
### Response:
def get_profile():
""" Prefetch the profile module, to fill some holes in the help text."""
argument_parser = ThrowingArgumentParser(add_help=False)
argument_parser... |
def _dump_cnt(self):
'''Dump counters to file'''
self._cnt['1h'].dump(os.path.join(self.data_path, 'scheduler.1h'))
self._cnt['1d'].dump(os.path.join(self.data_path, 'scheduler.1d'))
self._cnt['all'].dump(os.path.join(self.data_path, 'scheduler.all')) | Dump counters to file | Below is the the instruction that describes the task:
### Input:
Dump counters to file
### Response:
def _dump_cnt(self):
'''Dump counters to file'''
self._cnt['1h'].dump(os.path.join(self.data_path, 'scheduler.1h'))
self._cnt['1d'].dump(os.path.join(self.data_path, 'scheduler.1d'))
... |
def check_arguments(cls, conf):
"""
Sanity checks for options needed for configfile mode.
"""
try:
# Check we have access to the config file
f = open(conf['file'], "r")
f.close()
except IOError as e:
raise ArgsError("Cannot open co... | Sanity checks for options needed for configfile mode. | Below is the the instruction that describes the task:
### Input:
Sanity checks for options needed for configfile mode.
### Response:
def check_arguments(cls, conf):
"""
Sanity checks for options needed for configfile mode.
"""
try:
# Check we have access to the config f... |
def delete(cls, object_version, key=None):
"""Delete tags.
:param object_version: The object version instance or id.
:param key: Key of the tag to delete.
Default: delete all tags.
"""
with db.session.begin_nested():
q = cls.query.filter_by(
... | Delete tags.
:param object_version: The object version instance or id.
:param key: Key of the tag to delete.
Default: delete all tags. | Below is the the instruction that describes the task:
### Input:
Delete tags.
:param object_version: The object version instance or id.
:param key: Key of the tag to delete.
Default: delete all tags.
### Response:
def delete(cls, object_version, key=None):
"""Delete tags.
... |
def run_jar(self, mem=None):
"""
Special case of run() when the executable is a JAR file.
"""
cmd = config.get_command('java')
if mem:
cmd.append('-Xmx%s' % mem)
cmd.append('-jar')
cmd += self.cmd
self.run(cmd) | Special case of run() when the executable is a JAR file. | Below is the the instruction that describes the task:
### Input:
Special case of run() when the executable is a JAR file.
### Response:
def run_jar(self, mem=None):
"""
Special case of run() when the executable is a JAR file.
"""
cmd = config.get_command('java')
if mem:
... |
def invert_node_predicate(node_predicate: NodePredicate) -> NodePredicate: # noqa: D202
"""Build a node predicate that is the inverse of the given node predicate."""
def inverse_predicate(graph: BELGraph, node: BaseEntity) -> bool:
"""Return the inverse of the enclosed node predicate applied to the gr... | Build a node predicate that is the inverse of the given node predicate. | Below is the the instruction that describes the task:
### Input:
Build a node predicate that is the inverse of the given node predicate.
### Response:
def invert_node_predicate(node_predicate: NodePredicate) -> NodePredicate: # noqa: D202
"""Build a node predicate that is the inverse of the given node predica... |
def get_file(original_file):
"""
original file should be s3://bucketname/path/to/file.txt
returns a Buffer with the file in it
"""
import cStringIO
import boto3
s3 = boto3.resource('s3')
bucket_name, object_key = _parse_s3_file(original_file)
logger.debug("Downloading {0} from {1}".... | original file should be s3://bucketname/path/to/file.txt
returns a Buffer with the file in it | Below is the the instruction that describes the task:
### Input:
original file should be s3://bucketname/path/to/file.txt
returns a Buffer with the file in it
### Response:
def get_file(original_file):
"""
original file should be s3://bucketname/path/to/file.txt
returns a Buffer with the file in ... |
def serve():
"""main entry point"""
logging.getLogger().setLevel(logging.DEBUG)
logging.info('Python Tornado Crossdock Server Starting ...')
tracer = Tracer(
service_name='python',
reporter=NullReporter(),
sampler=ConstSampler(decision=True))
opentracing.tracer = tracer
... | main entry point | Below is the the instruction that describes the task:
### Input:
main entry point
### Response:
def serve():
"""main entry point"""
logging.getLogger().setLevel(logging.DEBUG)
logging.info('Python Tornado Crossdock Server Starting ...')
tracer = Tracer(
service_name='python',
repor... |
def filter_factory(global_conf, **local_conf):
"""Returns a WSGI filter app for use with paste.deploy."""
conf = global_conf.copy()
conf.update(local_conf)
def blacklist(app):
return BlacklistFilter(app, conf)
return blacklist | Returns a WSGI filter app for use with paste.deploy. | Below is the the instruction that describes the task:
### Input:
Returns a WSGI filter app for use with paste.deploy.
### Response:
def filter_factory(global_conf, **local_conf):
"""Returns a WSGI filter app for use with paste.deploy."""
conf = global_conf.copy()
conf.update(local_conf)
def blackl... |
def _save_image(self, name, format='PNG'):
""" Shows a save dialog for the ImageResource with 'name'.
"""
dialog = QtGui.QFileDialog(self._control, 'Save Image')
dialog.setAcceptMode(QtGui.QFileDialog.AcceptSave)
dialog.setDefaultSuffix(format.lower())
dialog.setNameFilte... | Shows a save dialog for the ImageResource with 'name'. | Below is the the instruction that describes the task:
### Input:
Shows a save dialog for the ImageResource with 'name'.
### Response:
def _save_image(self, name, format='PNG'):
""" Shows a save dialog for the ImageResource with 'name'.
"""
dialog = QtGui.QFileDialog(self._control, 'Save Ima... |
def wait_actions_on_objects(self, objects, wait_interval=None,
wait_time=None):
"""
.. versionadded:: 0.2.0
Poll the server periodically until the most recent action on each
resource in ``objects`` has finished, yielding each resource's fin... | .. versionadded:: 0.2.0
Poll the server periodically until the most recent action on each
resource in ``objects`` has finished, yielding each resource's final
state when the corresponding action is done.
If ``wait_time`` is exceeded, a `WaitTimeoutError` (containing any
remaini... | Below is the the instruction that describes the task:
### Input:
.. versionadded:: 0.2.0
Poll the server periodically until the most recent action on each
resource in ``objects`` has finished, yielding each resource's final
state when the corresponding action is done.
If ``wait_tim... |
def overload(fn):
"""
Overload a given callable object to be used with ``|`` operator
overloading.
This is especially used for composing a pipeline of
transformation over a single data set.
Arguments:
fn (function): target function to decorate.
Raises:
TypeError: if functi... | Overload a given callable object to be used with ``|`` operator
overloading.
This is especially used for composing a pipeline of
transformation over a single data set.
Arguments:
fn (function): target function to decorate.
Raises:
TypeError: if function or coroutine function is no... | Below is the the instruction that describes the task:
### Input:
Overload a given callable object to be used with ``|`` operator
overloading.
This is especially used for composing a pipeline of
transformation over a single data set.
Arguments:
fn (function): target function to decorate.
... |
def _bind(self):
"""Bind events to handlers"""
main_window = self.main_window
handlers = self.handlers
c_handlers = self.cell_handlers
# Non wx.Grid events
self.Bind(wx.EVT_MOUSEWHEEL, handlers.OnMouseWheel)
self.Bind(wx.EVT_KEY_DOWN, handlers.OnKey)
... | Bind events to handlers | Below is the the instruction that describes the task:
### Input:
Bind events to handlers
### Response:
def _bind(self):
"""Bind events to handlers"""
main_window = self.main_window
handlers = self.handlers
c_handlers = self.cell_handlers
# Non wx.Grid events
self... |
def dmlc_opts(opts):
"""convert from mxnet's opts to dmlc's opts
"""
args = ['--num-workers', str(opts.num_workers),
'--num-servers', str(opts.num_servers),
'--cluster', opts.launcher,
'--host-file', opts.hostfile,
'--sync-dst-dir', opts.sync_dst_dir]
# c... | convert from mxnet's opts to dmlc's opts | Below is the the instruction that describes the task:
### Input:
convert from mxnet's opts to dmlc's opts
### Response:
def dmlc_opts(opts):
"""convert from mxnet's opts to dmlc's opts
"""
args = ['--num-workers', str(opts.num_workers),
'--num-servers', str(opts.num_servers),
'-... |
def complementTab(seq=[]):
"""returns a list of complementary sequence without inversing it"""
complement = {'A': 'T', 'C': 'G', 'G': 'C', 'T': 'A', 'R': 'Y', 'Y': 'R', 'M': 'K', 'K': 'M',
'W': 'W', 'S': 'S', 'B': 'V', 'D': 'H', 'H': 'D', 'V': 'B', 'N': 'N', 'a': 't',
'c': 'g... | returns a list of complementary sequence without inversing it | Below is the the instruction that describes the task:
### Input:
returns a list of complementary sequence without inversing it
### Response:
def complementTab(seq=[]):
"""returns a list of complementary sequence without inversing it"""
complement = {'A': 'T', 'C': 'G', 'G': 'C', 'T': 'A', 'R': 'Y', 'Y': 'R... |
def kill(timeout=15):
'''
Kill the salt minion.
timeout
int seconds to wait for the minion to die.
If you have a monitor that restarts ``salt-minion`` when it dies then this is
a great way to restart after a minion upgrade.
CLI example::
>$ salt minion[12] minion.kill
... | Kill the salt minion.
timeout
int seconds to wait for the minion to die.
If you have a monitor that restarts ``salt-minion`` when it dies then this is
a great way to restart after a minion upgrade.
CLI example::
>$ salt minion[12] minion.kill
minion1:
----------
... | Below is the the instruction that describes the task:
### Input:
Kill the salt minion.
timeout
int seconds to wait for the minion to die.
If you have a monitor that restarts ``salt-minion`` when it dies then this is
a great way to restart after a minion upgrade.
CLI example::
>$ ... |
def export_gcm_encrypted_private_key(self, password: str, salt: str, n: int = 16384) -> str:
"""
This interface is used to export an AES algorithm encrypted private key with the mode of GCM.
:param password: the secret pass phrase to generate the keys from.
:param salt: A string to use ... | This interface is used to export an AES algorithm encrypted private key with the mode of GCM.
:param password: the secret pass phrase to generate the keys from.
:param salt: A string to use for better protection from dictionary attacks.
This value does not need to be kept secret, ... | Below is the the instruction that describes the task:
### Input:
This interface is used to export an AES algorithm encrypted private key with the mode of GCM.
:param password: the secret pass phrase to generate the keys from.
:param salt: A string to use for better protection from dictionary attack... |
def CreateTaskStorage(self, task):
"""Creates a task storage.
Args:
task (Task): task.
Returns:
FakeStorageWriter: storage writer.
Raises:
IOError: if the task storage already exists.
OSError: if the task storage already exists.
"""
if task.identifier in self._task_sto... | Creates a task storage.
Args:
task (Task): task.
Returns:
FakeStorageWriter: storage writer.
Raises:
IOError: if the task storage already exists.
OSError: if the task storage already exists. | Below is the the instruction that describes the task:
### Input:
Creates a task storage.
Args:
task (Task): task.
Returns:
FakeStorageWriter: storage writer.
Raises:
IOError: if the task storage already exists.
OSError: if the task storage already exists.
### Response:
def Cr... |
def adjacent(self, node_a, node_b):
"""Determines whether there is an edge from node_a to node_b.
Returns True if such an edge exists, otherwise returns False."""
neighbors = self.neighbors(node_a)
return node_b in neighbors | Determines whether there is an edge from node_a to node_b.
Returns True if such an edge exists, otherwise returns False. | Below is the the instruction that describes the task:
### Input:
Determines whether there is an edge from node_a to node_b.
Returns True if such an edge exists, otherwise returns False.
### Response:
def adjacent(self, node_a, node_b):
"""Determines whether there is an edge from node_a to node_b.
... |
def create_user(self, instance, name, password, database_names, host=None):
"""
Creates a user with the specified name and password, and gives that
user access to the specified database(s).
"""
return instance.create_user(name=name, password=password,
database_nam... | Creates a user with the specified name and password, and gives that
user access to the specified database(s). | Below is the the instruction that describes the task:
### Input:
Creates a user with the specified name and password, and gives that
user access to the specified database(s).
### Response:
def create_user(self, instance, name, password, database_names, host=None):
"""
Creates a user with th... |
def getDescription(self):
"""Returns a description of the dataset"""
description = {'name':self.name, 'fields':[f.name for f in self.fields], \
'numRecords by field':[f.numRecords for f in self.fields]}
return description | Returns a description of the dataset | Below is the the instruction that describes the task:
### Input:
Returns a description of the dataset
### Response:
def getDescription(self):
"""Returns a description of the dataset"""
description = {'name':self.name, 'fields':[f.name for f in self.fields], \
'numRecords by field':[f.numRecords for ... |
def update(self):
"""Update the data from the thermostat. Always sets the current time."""
_LOGGER.debug("Querying the device..")
time = datetime.now()
value = struct.pack('BBBBBBB', PROP_INFO_QUERY,
time.year % 100, time.month, time.day,
... | Update the data from the thermostat. Always sets the current time. | Below is the the instruction that describes the task:
### Input:
Update the data from the thermostat. Always sets the current time.
### Response:
def update(self):
"""Update the data from the thermostat. Always sets the current time."""
_LOGGER.debug("Querying the device..")
time = datetime... |
def date_in_past(self):
"""Is the block's date in the past?
(Has it not yet happened?)
"""
now = datetime.datetime.now()
return (now.date() > self.date) | Is the block's date in the past?
(Has it not yet happened?) | Below is the the instruction that describes the task:
### Input:
Is the block's date in the past?
(Has it not yet happened?)
### Response:
def date_in_past(self):
"""Is the block's date in the past?
(Has it not yet happened?)
"""
now = datetime.datetime.now()
retu... |
def series_lstrip(series, startswith='http://', ignorecase=True):
""" Strip a suffix str (`endswith` str) from a `df` columns or pd.Series of type str """
return series_strip(series, startswith=startswith, endswith=None, startsorendswith=None, ignorecase=ignorecase) | Strip a suffix str (`endswith` str) from a `df` columns or pd.Series of type str | Below is the the instruction that describes the task:
### Input:
Strip a suffix str (`endswith` str) from a `df` columns or pd.Series of type str
### Response:
def series_lstrip(series, startswith='http://', ignorecase=True):
""" Strip a suffix str (`endswith` str) from a `df` columns or pd.Series of type str ... |
def get_cf_distribution_class():
"""Return the correct troposphere CF distribution class."""
if LooseVersion(troposphere.__version__) == LooseVersion('2.4.0'):
cf_dist = cloudfront.Distribution
cf_dist.props['DistributionConfig'] = (DistributionConfig, True)
return cf_dist
return clo... | Return the correct troposphere CF distribution class. | Below is the the instruction that describes the task:
### Input:
Return the correct troposphere CF distribution class.
### Response:
def get_cf_distribution_class():
"""Return the correct troposphere CF distribution class."""
if LooseVersion(troposphere.__version__) == LooseVersion('2.4.0'):
cf_dis... |
def _iso_name_and_parent_from_path(self, iso_path):
# type: (bytes) -> Tuple[bytes, dr.DirectoryRecord]
'''
An internal method to find the parent directory record and name given an
ISO path. If the parent is found, return a tuple containing the
basename of the path and the paren... | An internal method to find the parent directory record and name given an
ISO path. If the parent is found, return a tuple containing the
basename of the path and the parent directory record object.
Parameters:
iso_path - The absolute ISO path to the entry on the ISO.
Returns:
... | Below is the the instruction that describes the task:
### Input:
An internal method to find the parent directory record and name given an
ISO path. If the parent is found, return a tuple containing the
basename of the path and the parent directory record object.
Parameters:
iso_pa... |
def thread_exception(self, raised_exception):
""" Callback for handling exception, that are raised inside :meth:`.WThreadTask.thread_started`
:param raised_exception: raised exception
:return: None
"""
print('Thread execution was stopped by the exception. Exception: %s' % str(raised_exception))
print('Trac... | Callback for handling exception, that are raised inside :meth:`.WThreadTask.thread_started`
:param raised_exception: raised exception
:return: None | Below is the the instruction that describes the task:
### Input:
Callback for handling exception, that are raised inside :meth:`.WThreadTask.thread_started`
:param raised_exception: raised exception
:return: None
### Response:
def thread_exception(self, raised_exception):
""" Callback for handling exception... |
def source_sum_err(self):
"""
The uncertainty of `~photutils.SourceProperties.source_sum`,
propagated from the input ``error`` array.
``source_sum_err`` is the quadrature sum of the total errors
over the non-masked pixels within the source segment:
.. math:: \\Delta F =... | The uncertainty of `~photutils.SourceProperties.source_sum`,
propagated from the input ``error`` array.
``source_sum_err`` is the quadrature sum of the total errors
over the non-masked pixels within the source segment:
.. math:: \\Delta F = \\sqrt{\\sum_{i \\in S}
\\s... | Below is the the instruction that describes the task:
### Input:
The uncertainty of `~photutils.SourceProperties.source_sum`,
propagated from the input ``error`` array.
``source_sum_err`` is the quadrature sum of the total errors
over the non-masked pixels within the source segment:
... |
def job_not_running(self, jid, tgt, tgt_type, minions, is_finished):
'''
Return a future which will complete once jid (passed in) is no longer
running on tgt
'''
ping_pub_data = yield self.saltclients['local'](tgt,
'saltutil... | Return a future which will complete once jid (passed in) is no longer
running on tgt | Below is the the instruction that describes the task:
### Input:
Return a future which will complete once jid (passed in) is no longer
running on tgt
### Response:
def job_not_running(self, jid, tgt, tgt_type, minions, is_finished):
'''
Return a future which will complete once jid (passed i... |
def get_levels_of_description(self):
"""
Returns an array of all levels of description defined in this AtoM instance.
"""
if not hasattr(self, "levels_of_description"):
self.levels_of_description = [
item["name"]
for item in self._get(urljoin(s... | Returns an array of all levels of description defined in this AtoM instance. | Below is the the instruction that describes the task:
### Input:
Returns an array of all levels of description defined in this AtoM instance.
### Response:
def get_levels_of_description(self):
"""
Returns an array of all levels of description defined in this AtoM instance.
"""
if no... |
def set_resolving(self, **kw):
"""
Certain log fields can be individually resolved. Use this
method to set these fields. Valid keyword arguments:
:param str timezone: string value to set timezone for audits
:param bool time_show_zone: show the time zone in the audit.
... | Certain log fields can be individually resolved. Use this
method to set these fields. Valid keyword arguments:
:param str timezone: string value to set timezone for audits
:param bool time_show_zone: show the time zone in the audit.
:param bool time_show_millis: show timezone in... | Below is the the instruction that describes the task:
### Input:
Certain log fields can be individually resolved. Use this
method to set these fields. Valid keyword arguments:
:param str timezone: string value to set timezone for audits
:param bool time_show_zone: show the time zone... |
def chunks(seq, size=None, dfmt="f", byte_order=None, padval=0.):
"""
Chunk generator based on the array module (Python standard library).
See chunk.struct for more help. This strategy uses array.array (random access
by indexing management) instead of struct.Struct and blocks/deque (circular
queue appending)... | Chunk generator based on the array module (Python standard library).
See chunk.struct for more help. This strategy uses array.array (random access
by indexing management) instead of struct.Struct and blocks/deque (circular
queue appending) from the chunks.struct strategy.
Hint
----
Try each one to find th... | Below is the the instruction that describes the task:
### Input:
Chunk generator based on the array module (Python standard library).
See chunk.struct for more help. This strategy uses array.array (random access
by indexing management) instead of struct.Struct and blocks/deque (circular
queue appending) from... |
def __encryptKeyTransportMessage(
self,
bare_jids,
encryption_callback,
bundles = None,
expect_problems = None,
ignore_trust = False
):
"""
bare_jids: iterable<string>
encryption_callback: A function which is called using an instance of cryptog... | bare_jids: iterable<string>
encryption_callback: A function which is called using an instance of cryptography.hazmat.primitives.ciphers.CipherContext, which you can use to encrypt any sort of data. You don't have to return anything.
bundles: { [bare_jid: string] => { [device_id: int] => ExtendedPublicBu... | Below is the the instruction that describes the task:
### Input:
bare_jids: iterable<string>
encryption_callback: A function which is called using an instance of cryptography.hazmat.primitives.ciphers.CipherContext, which you can use to encrypt any sort of data. You don't have to return anything.
bu... |
def unwrap_aliases(data_type):
"""
Convenience method to unwrap all Alias(es) from around a DataType.
Args:
data_type (DataType): The target to unwrap.
Return:
Tuple[DataType, bool]: The underlying data type and a bool indicating
whether the input type had at least one alia... | Convenience method to unwrap all Alias(es) from around a DataType.
Args:
data_type (DataType): The target to unwrap.
Return:
Tuple[DataType, bool]: The underlying data type and a bool indicating
whether the input type had at least one alias layer. | Below is the the instruction that describes the task:
### Input:
Convenience method to unwrap all Alias(es) from around a DataType.
Args:
data_type (DataType): The target to unwrap.
Return:
Tuple[DataType, bool]: The underlying data type and a bool indicating
whether the input ... |
def run_sim(morphology='patdemo/cells/j4a.hoc',
cell_rotation=dict(x=4.99, y=-4.33, z=3.14),
closest_idx=dict(x=-200., y=0., z=800.)):
'''set up simple cell simulation with LFPs in the plane'''
# Create cell
cell = LFPy.Cell(morphology=morphology, **cell_parameters)
# Align cell... | set up simple cell simulation with LFPs in the plane | Below is the the instruction that describes the task:
### Input:
set up simple cell simulation with LFPs in the plane
### Response:
def run_sim(morphology='patdemo/cells/j4a.hoc',
cell_rotation=dict(x=4.99, y=-4.33, z=3.14),
closest_idx=dict(x=-200., y=0., z=800.)):
'''set up simple cel... |
def get_parent_info(brain_or_object, endpoint=None):
"""Generate url information for the parent object
:param brain_or_object: A single catalog brain or content object
:type brain_or_object: ATContentType/DexterityContentType/CatalogBrain
:param endpoint: The named URL endpoint for the root of the item... | Generate url information for the parent object
:param brain_or_object: A single catalog brain or content object
:type brain_or_object: ATContentType/DexterityContentType/CatalogBrain
:param endpoint: The named URL endpoint for the root of the items
:type endpoint: str/unicode
:returns: URL informat... | Below is the the instruction that describes the task:
### Input:
Generate url information for the parent object
:param brain_or_object: A single catalog brain or content object
:type brain_or_object: ATContentType/DexterityContentType/CatalogBrain
:param endpoint: The named URL endpoint for the root of... |
def get_comments(self):
"""Gets all comments.
return: (osid.commenting.CommentList) - a list of comments
raise: OperationFailed - unable to complete request
raise: PermissionDenied - authorization failure
*compliance: mandatory -- This method must be implemented.*
"""... | Gets all comments.
return: (osid.commenting.CommentList) - a list of comments
raise: OperationFailed - unable to complete request
raise: PermissionDenied - authorization failure
*compliance: mandatory -- This method must be implemented.* | Below is the the instruction that describes the task:
### Input:
Gets all comments.
return: (osid.commenting.CommentList) - a list of comments
raise: OperationFailed - unable to complete request
raise: PermissionDenied - authorization failure
*compliance: mandatory -- This method ... |
def _parseExpression(self, src, returnList=False):
"""
expr
: term [ operator term ]*
;
"""
src, term = self._parseExpressionTerm(src)
operator = None
while src[:1] not in ('', ';', '{', '}', '[', ']', ')'):
for operator in self.ExpressionOpera... | expr
: term [ operator term ]*
; | Below is the the instruction that describes the task:
### Input:
expr
: term [ operator term ]*
;
### Response:
def _parseExpression(self, src, returnList=False):
"""
expr
: term [ operator term ]*
;
"""
src, term = self._parseExpressionTerm(src)
... |
def deployment_check_existence(name, resource_group, **kwargs):
'''
.. versionadded:: 2019.2.0
Check the existence of a deployment.
:param name: The name of the deployment to query.
:param resource_group: The resource group name assigned to the
deployment.
CLI Example:
.. code-b... | .. versionadded:: 2019.2.0
Check the existence of a deployment.
:param name: The name of the deployment to query.
:param resource_group: The resource group name assigned to the
deployment.
CLI Example:
.. code-block:: bash
salt-call azurearm_resource.deployment_check_existence ... | Below is the the instruction that describes the task:
### Input:
.. versionadded:: 2019.2.0
Check the existence of a deployment.
:param name: The name of the deployment to query.
:param resource_group: The resource group name assigned to the
deployment.
CLI Example:
.. code-block:: ... |
def tags(
self):
"""*The list of tags associated with this taskpaper object*
**Usage:**
..
project and task objects can have associated tags. To get a list of tags assigned to an object use:
.. code-block:: python
projectTag = aProject.t... | *The list of tags associated with this taskpaper object*
**Usage:**
..
project and task objects can have associated tags. To get a list of tags assigned to an object use:
.. code-block:: python
projectTag = aProject.tags
taskTags = aTasks.ta... | Below is the the instruction that describes the task:
### Input:
*The list of tags associated with this taskpaper object*
**Usage:**
..
project and task objects can have associated tags. To get a list of tags assigned to an object use:
.. code-block:: python
... |
def dcm(self, dcm):
"""
Set the DCM
:param dcm: Matrix3
"""
assert(isinstance(dcm, Matrix3))
self._dcm = dcm.copy()
# mark other representations as outdated, will get generated on next
# read
self._q = None
self._euler = None | Set the DCM
:param dcm: Matrix3 | Below is the the instruction that describes the task:
### Input:
Set the DCM
:param dcm: Matrix3
### Response:
def dcm(self, dcm):
"""
Set the DCM
:param dcm: Matrix3
"""
assert(isinstance(dcm, Matrix3))
self._dcm = dcm.copy()
# mark other represent... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.