code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def send(self, data):
"""Sends the eAPI request to the destination node
This method is responsible for sending an eAPI request to the
destination node and returning a response based on the eAPI response
object. eAPI responds to request messages with either a success
message or ... | Sends the eAPI request to the destination node
This method is responsible for sending an eAPI request to the
destination node and returning a response based on the eAPI response
object. eAPI responds to request messages with either a success
message or failure message.
eAPI Re... | Below is the the instruction that describes the task:
### Input:
Sends the eAPI request to the destination node
This method is responsible for sending an eAPI request to the
destination node and returning a response based on the eAPI response
object. eAPI responds to request messages with ... |
def terminal_states(data, vkey='velocity', groupby=None, groups=None, self_transitions=False, basis=None,
weight_diffusion=0, scale_diffusion=1, eps=1e-3, copy=False):
"""Computes terminal states (root and end points).
Arguments
---------
data: :class:`~anndata.AnnData`
Anno... | Computes terminal states (root and end points).
Arguments
---------
data: :class:`~anndata.AnnData`
Annotated data matrix.
vkey: `str` (default: `'velocity'`)
Name of velocity estimates to be used.
self_transitions: `bool` (default: `False`)
Allow transitions from one node t... | Below is the the instruction that describes the task:
### Input:
Computes terminal states (root and end points).
Arguments
---------
data: :class:`~anndata.AnnData`
Annotated data matrix.
vkey: `str` (default: `'velocity'`)
Name of velocity estimates to be used.
self_transitions... |
def get_file(self, commit, path, offset_bytes=0, size_bytes=0, extract_value=True):
"""
Returns an iterator of the contents contents of a file at a specific Commit.
Params:
* commit: A tuple, string, or Commit object representing the commit.
* path: The path of the file.
... | Returns an iterator of the contents contents of a file at a specific Commit.
Params:
* commit: A tuple, string, or Commit object representing the commit.
* path: The path of the file.
* offset_bytes: Optional. specifies a number of bytes that should be
skipped in the beginning o... | Below is the the instruction that describes the task:
### Input:
Returns an iterator of the contents contents of a file at a specific Commit.
Params:
* commit: A tuple, string, or Commit object representing the commit.
* path: The path of the file.
* offset_bytes: Optional. specifie... |
def revision(self):
"""Revision number"""
rev = self._p4dict.get('haveRev', -1)
if rev == 'none':
rev = 0
return int(rev) | Revision number | Below is the the instruction that describes the task:
### Input:
Revision number
### Response:
def revision(self):
"""Revision number"""
rev = self._p4dict.get('haveRev', -1)
if rev == 'none':
rev = 0
return int(rev) |
def command_msg(housecode, command):
"""Create an X10 message to send the house code and a command code."""
house_byte = 0
if isinstance(housecode, str):
house_byte = insteonplm.utils.housecode_to_byte(housecode) << 4
elif isinstance(housecode, int) and housecode < 16:
... | Create an X10 message to send the house code and a command code. | Below is the the instruction that describes the task:
### Input:
Create an X10 message to send the house code and a command code.
### Response:
def command_msg(housecode, command):
"""Create an X10 message to send the house code and a command code."""
house_byte = 0
if isinstance(housecode,... |
def FilesBelongToSameModule(filename_cc, filename_h):
"""Check if these two filenames belong to the same module.
The concept of a 'module' here is a as follows:
foo.h, foo-inl.h, foo.cc, foo_test.cc and foo_unittest.cc belong to the
same 'module' if they are in the same directory.
some/path/public/xyzzy and ... | Check if these two filenames belong to the same module.
The concept of a 'module' here is a as follows:
foo.h, foo-inl.h, foo.cc, foo_test.cc and foo_unittest.cc belong to the
same 'module' if they are in the same directory.
some/path/public/xyzzy and some/path/internal/xyzzy are also considered
to belong to... | Below is the the instruction that describes the task:
### Input:
Check if these two filenames belong to the same module.
The concept of a 'module' here is a as follows:
foo.h, foo-inl.h, foo.cc, foo_test.cc and foo_unittest.cc belong to the
same 'module' if they are in the same directory.
some/path/public/... |
def read_namespaced_pod_status(self, name, namespace, **kwargs): # noqa: E501
"""read_namespaced_pod_status # noqa: E501
read status of the specified Pod # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=... | read_namespaced_pod_status # noqa: E501
read status of the specified Pod # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.read_namespaced_pod_status(name, namespace, async_req=True)
... | Below is the the instruction that describes the task:
### Input:
read_namespaced_pod_status # noqa: E501
read status of the specified Pod # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thre... |
def elements(self):
"""Return the identifier's elements as tuple."""
offset = self.EXTRA_DIGITS
if offset:
return (self._id[:offset], self.company_prefix, self._reference,
self.check_digit)
else:
return (self.company_prefix, self._reference, se... | Return the identifier's elements as tuple. | Below is the the instruction that describes the task:
### Input:
Return the identifier's elements as tuple.
### Response:
def elements(self):
"""Return the identifier's elements as tuple."""
offset = self.EXTRA_DIGITS
if offset:
return (self._id[:offset], self.company_prefix, se... |
def listen(self, func):
"""
Listen to parameters change.
Parameters
----------
func : callable
Function to be called when a parameter changes.
"""
self._C0.listen(func)
self._C1.listen(func) | Listen to parameters change.
Parameters
----------
func : callable
Function to be called when a parameter changes. | Below is the the instruction that describes the task:
### Input:
Listen to parameters change.
Parameters
----------
func : callable
Function to be called when a parameter changes.
### Response:
def listen(self, func):
"""
Listen to parameters change.
Pa... |
def __search_obj(self,
obj,
item,
parent,
parents_ids=frozenset({}),
is_namedtuple=False):
"""Search objects"""
found = False
if obj == item:
found = True
# We report ... | Search objects | Below is the the instruction that describes the task:
### Input:
Search objects
### Response:
def __search_obj(self,
obj,
item,
parent,
parents_ids=frozenset({}),
is_namedtuple=False):
"""Search objects... |
def remove_handler(self, handler: Handler, group: int = 0):
"""Removes a previously-added update handler.
Make sure to provide the right group that the handler was added in. You can use
the return value of the :meth:`add_handler` method, a tuple of (handler, group), and
pass it directly... | Removes a previously-added update handler.
Make sure to provide the right group that the handler was added in. You can use
the return value of the :meth:`add_handler` method, a tuple of (handler, group), and
pass it directly.
Args:
handler (``Handler``):
The... | Below is the the instruction that describes the task:
### Input:
Removes a previously-added update handler.
Make sure to provide the right group that the handler was added in. You can use
the return value of the :meth:`add_handler` method, a tuple of (handler, group), and
pass it directly.
... |
def replace_namespaced_controller_revision(self, name, namespace, body, **kwargs): # noqa: E501
"""replace_namespaced_controller_revision # noqa: E501
replace the specified ControllerRevision # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronou... | replace_namespaced_controller_revision # noqa: E501
replace the specified ControllerRevision # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.replace_namespaced_controller_revision(n... | Below is the the instruction that describes the task:
### Input:
replace_namespaced_controller_revision # noqa: E501
replace the specified ControllerRevision # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=T... |
def updateButtonText(self, lst):
"""Update the list of selected axes in the menu button"""
axis_txt = ''
for e in lst:
axis_txt += '%d,' % (e+1)
# remove trailing ',' and add to button string
self.SetLabel("Axes: %s" % axis_txt[:-1]) | Update the list of selected axes in the menu button | Below is the the instruction that describes the task:
### Input:
Update the list of selected axes in the menu button
### Response:
def updateButtonText(self, lst):
"""Update the list of selected axes in the menu button"""
axis_txt = ''
for e in lst:
axis_txt += '%d,' % (e+1)
... |
def _deserialize_class(cls, input_cls_name, trusted, strict):
"""Returns the HasProperties class to use for deserialization"""
if not input_cls_name or input_cls_name == cls.__name__:
return cls
if trusted and input_cls_name in cls._REGISTRY:
return cls._REGISTRY[input_cl... | Returns the HasProperties class to use for deserialization | Below is the the instruction that describes the task:
### Input:
Returns the HasProperties class to use for deserialization
### Response:
def _deserialize_class(cls, input_cls_name, trusted, strict):
"""Returns the HasProperties class to use for deserialization"""
if not input_cls_name or input_cls... |
def run_with_pmids(model_path, pmids):
"""Run with given list of PMIDs."""
from indra.tools.machine.machine import run_with_pmids_helper
run_with_pmids_helper(model_path, pmids) | Run with given list of PMIDs. | Below is the the instruction that describes the task:
### Input:
Run with given list of PMIDs.
### Response:
def run_with_pmids(model_path, pmids):
"""Run with given list of PMIDs."""
from indra.tools.machine.machine import run_with_pmids_helper
run_with_pmids_helper(model_path, pmids) |
def push_concurrency_history_item(self, state, number_concurrent_threads):
"""Adds a new concurrency-history-item to the history item list
A concurrent history item stores information about the point in time where a certain number of states is
launched concurrently
(e.g. in a barrier co... | Adds a new concurrency-history-item to the history item list
A concurrent history item stores information about the point in time where a certain number of states is
launched concurrently
(e.g. in a barrier concurrency state).
:param state: the state that launches the state group
... | Below is the the instruction that describes the task:
### Input:
Adds a new concurrency-history-item to the history item list
A concurrent history item stores information about the point in time where a certain number of states is
launched concurrently
(e.g. in a barrier concurrency state).... |
def write_gsd(structure, filename, ref_distance=1.0, ref_mass=1.0,
ref_energy=1.0, rigid_bodies=None, shift_coords=True,
write_special_pairs=True):
"""Output a GSD file (HOOMD v2 default data format).
Parameters
----------
structure : parmed.Structure
ParmEd Structur... | Output a GSD file (HOOMD v2 default data format).
Parameters
----------
structure : parmed.Structure
ParmEd Structure object
filename : str
Path of the output file.
ref_distance : float, optional, default=1.0
Reference distance for conversion to reduced units
ref_mass : ... | Below is the the instruction that describes the task:
### Input:
Output a GSD file (HOOMD v2 default data format).
Parameters
----------
structure : parmed.Structure
ParmEd Structure object
filename : str
Path of the output file.
ref_distance : float, optional, default=1.0
... |
def buffer(self, data):
'''
Buffer unused bytes from the input stream.
'''
self._read_lock.acquire()
try:
return super(GeventTransport, self).buffer(data)
finally:
self._read_lock.release() | Buffer unused bytes from the input stream. | Below is the the instruction that describes the task:
### Input:
Buffer unused bytes from the input stream.
### Response:
def buffer(self, data):
'''
Buffer unused bytes from the input stream.
'''
self._read_lock.acquire()
try:
return super(GeventTransport, self)... |
def push(self, read_time, next_resume_token):
"""
Assembles a new snapshot from the current set of changes and invokes
the user's callback. Clears the current changes on completion.
"""
deletes, adds, updates = Watch._extract_changes(
self.doc_map, self.change_map, re... | Assembles a new snapshot from the current set of changes and invokes
the user's callback. Clears the current changes on completion. | Below is the the instruction that describes the task:
### Input:
Assembles a new snapshot from the current set of changes and invokes
the user's callback. Clears the current changes on completion.
### Response:
def push(self, read_time, next_resume_token):
"""
Assembles a new snapshot from ... |
def _merge_flags(new_flags, old_flags=None, conf='any'):
'''
Merges multiple lists of flags removing duplicates and resolving conflicts
giving priority to lasts lists.
'''
if not old_flags:
old_flags = []
args = [old_flags, new_flags]
if conf == 'accept_keywords':
tmp = new_f... | Merges multiple lists of flags removing duplicates and resolving conflicts
giving priority to lasts lists. | Below is the the instruction that describes the task:
### Input:
Merges multiple lists of flags removing duplicates and resolving conflicts
giving priority to lasts lists.
### Response:
def _merge_flags(new_flags, old_flags=None, conf='any'):
'''
Merges multiple lists of flags removing duplicates and r... |
def image(self, raw_url, title='', alt=''):
"""
Filters the ``src`` attribute of an image.
Note that filtering the source URL of an ``<img>`` tag is only a very
basic protection, and it's mostly useless in modern browsers (they block
JavaScript in there by default). An example o... | Filters the ``src`` attribute of an image.
Note that filtering the source URL of an ``<img>`` tag is only a very
basic protection, and it's mostly useless in modern browsers (they block
JavaScript in there by default). An example of attack that filtering
does not thwart is phishing base... | Below is the the instruction that describes the task:
### Input:
Filters the ``src`` attribute of an image.
Note that filtering the source URL of an ``<img>`` tag is only a very
basic protection, and it's mostly useless in modern browsers (they block
JavaScript in there by default). An exam... |
def to_pod(self):
"""
Example (in yaml):
type: per_family
orderers:
- packages: ['foo', 'bah']
type: version_split
first_version: '4.0.5'
- packages: ['python']
type: sorted
descending: false
... | Example (in yaml):
type: per_family
orderers:
- packages: ['foo', 'bah']
type: version_split
first_version: '4.0.5'
- packages: ['python']
type: sorted
descending: false
default_order:
type... | Below is the the instruction that describes the task:
### Input:
Example (in yaml):
type: per_family
orderers:
- packages: ['foo', 'bah']
type: version_split
first_version: '4.0.5'
- packages: ['python']
type: sorted
... |
def close( self ):
"""
Close the db and release memory
"""
if self.db is not None:
self.db.commit()
self.db.close()
self.db = None
return | Close the db and release memory | Below is the the instruction that describes the task:
### Input:
Close the db and release memory
### Response:
def close( self ):
"""
Close the db and release memory
"""
if self.db is not None:
self.db.commit()
self.db.close()
self.db = None
... |
def _parse_statistic(data, scale):
"""Parse binary statistics returned from the history API"""
i = 0
for byte in bytearray(data):
i = (i << 8) + byte
if i == 32768:
return None
if scale == 0:
return i
return float(i) / (scale * 10) | Parse binary statistics returned from the history API | Below is the the instruction that describes the task:
### Input:
Parse binary statistics returned from the history API
### Response:
def _parse_statistic(data, scale):
"""Parse binary statistics returned from the history API"""
i = 0
for byte in bytearray(data):
i = (i << 8) + b... |
def getHelpAsString(docstring=False, show_ver=True):
"""
Return useful help from a file in the script directory called
``__taskname__.help``
"""
install_dir = os.path.dirname(__file__)
taskname = util.base_taskname(__taskname__, __package__)
htmlfile = os.path.join(install_dir, 'htmlhelp', ... | Return useful help from a file in the script directory called
``__taskname__.help`` | Below is the the instruction that describes the task:
### Input:
Return useful help from a file in the script directory called
``__taskname__.help``
### Response:
def getHelpAsString(docstring=False, show_ver=True):
"""
Return useful help from a file in the script directory called
``__taskname__.he... |
def get_req_resp_record(self, resp_obj):
""" get request and response info from Response() object.
"""
def log_print(req_resp_dict, r_type):
msg = "\n================== {} details ==================\n".format(r_type)
for key, value in req_resp_dict[r_type].items():
... | get request and response info from Response() object. | Below is the the instruction that describes the task:
### Input:
get request and response info from Response() object.
### Response:
def get_req_resp_record(self, resp_obj):
""" get request and response info from Response() object.
"""
def log_print(req_resp_dict, r_type):
msg =... |
def retry_target(target, predicate, sleep_generator, deadline, on_error=None):
"""Call a function and retry if it fails.
This is the lowest-level retry helper. Generally, you'll use the
higher-level retry helper :class:`Retry`.
Args:
target(Callable): The function to call and retry. This must ... | Call a function and retry if it fails.
This is the lowest-level retry helper. Generally, you'll use the
higher-level retry helper :class:`Retry`.
Args:
target(Callable): The function to call and retry. This must be a
nullary function - apply arguments with `functools.partial`.
... | Below is the the instruction that describes the task:
### Input:
Call a function and retry if it fails.
This is the lowest-level retry helper. Generally, you'll use the
higher-level retry helper :class:`Retry`.
Args:
target(Callable): The function to call and retry. This must be a
... |
def compute_cardinalities(self):
""" This will count the number of distinct values for each dimension in
the dataset and add that count to the model so that it can be used as a
hint by UI components. """
for dimension in self.model.dimensions:
result = self.members(dimension.... | This will count the number of distinct values for each dimension in
the dataset and add that count to the model so that it can be used as a
hint by UI components. | Below is the the instruction that describes the task:
### Input:
This will count the number of distinct values for each dimension in
the dataset and add that count to the model so that it can be used as a
hint by UI components.
### Response:
def compute_cardinalities(self):
""" This will co... |
def relative_readlink(self, relpath):
"""Execute `readlink` for the given path, which may result in a relative path.
Raises exception if path is ignored.
"""
if self.isignored(self._append_slash_if_dir_path(relpath)):
self._raise_access_ignored(relpath)
return self._relative_readlink_raw(relp... | Execute `readlink` for the given path, which may result in a relative path.
Raises exception if path is ignored. | Below is the the instruction that describes the task:
### Input:
Execute `readlink` for the given path, which may result in a relative path.
Raises exception if path is ignored.
### Response:
def relative_readlink(self, relpath):
"""Execute `readlink` for the given path, which may result in a relative pat... |
def load_session_from_file(self, username: str, filename: Optional[str] = None) -> None:
"""Internally stores :class:`requests.Session` object loaded from file.
If filename is None, the file with the default session path is loaded.
:raises FileNotFoundError: If the file does not exist.
... | Internally stores :class:`requests.Session` object loaded from file.
If filename is None, the file with the default session path is loaded.
:raises FileNotFoundError: If the file does not exist. | Below is the the instruction that describes the task:
### Input:
Internally stores :class:`requests.Session` object loaded from file.
If filename is None, the file with the default session path is loaded.
:raises FileNotFoundError: If the file does not exist.
### Response:
def load_session_from_f... |
def verify_response(self, response, otp, nonce, return_response=False):
"""
Returns True if the OTP is valid (status=OK) and return_response=False,
otherwise (return_response = True) it returns the server response as a
dictionary.
Throws an exception if the OTP is replayed, the ... | Returns True if the OTP is valid (status=OK) and return_response=False,
otherwise (return_response = True) it returns the server response as a
dictionary.
Throws an exception if the OTP is replayed, the server response message
verification failed or the client id is invalid, returns Fal... | Below is the the instruction that describes the task:
### Input:
Returns True if the OTP is valid (status=OK) and return_response=False,
otherwise (return_response = True) it returns the server response as a
dictionary.
Throws an exception if the OTP is replayed, the server response message... |
def register_message_callback(self, type_, from_, cb):
"""
Register a callback to be called when a message is received.
:param type_: Message type to listen for, or :data:`None` for a
wildcard match.
:type type_: :class:`~.MessageType` or :data:`None`
:para... | Register a callback to be called when a message is received.
:param type_: Message type to listen for, or :data:`None` for a
wildcard match.
:type type_: :class:`~.MessageType` or :data:`None`
:param from_: Sender JID to listen for, or :data:`None` for a wildcard
... | Below is the the instruction that describes the task:
### Input:
Register a callback to be called when a message is received.
:param type_: Message type to listen for, or :data:`None` for a
wildcard match.
:type type_: :class:`~.MessageType` or :data:`None`
:param from... |
def data(self):
"""Return the examples in the dataset in order, sorted, or shuffled."""
if self.sort:
xs = sorted(self.dataset, key=self.sort_key)
elif self.shuffle:
xs = [self.dataset[i] for i in self.random_shuffler(range(len(self.dataset)))]
else:
x... | Return the examples in the dataset in order, sorted, or shuffled. | Below is the the instruction that describes the task:
### Input:
Return the examples in the dataset in order, sorted, or shuffled.
### Response:
def data(self):
"""Return the examples in the dataset in order, sorted, or shuffled."""
if self.sort:
xs = sorted(self.dataset, key=self.sort_... |
def constructPrimaryIdentifier(self, data, ordered_identifier_candidates):
"""
Construct and return a primary identifier value from the
data asserted by the IdP using the ordered list of candidates
from the configuration.
"""
logprefix = PrimaryIdentifier.logprefix
... | Construct and return a primary identifier value from the
data asserted by the IdP using the ordered list of candidates
from the configuration. | Below is the the instruction that describes the task:
### Input:
Construct and return a primary identifier value from the
data asserted by the IdP using the ordered list of candidates
from the configuration.
### Response:
def constructPrimaryIdentifier(self, data, ordered_identifier_candidates):
... |
def clone_to(self, target_repo):
"""stub"""
new_asset = target_repo.duplicate_asset(self.my_osid_object.ident)
form = target_repo.get_asset_form_for_update(new_asset.ident)
form.set_provenance(str(self.my_osid_object.ident))
return target_repo.update_asset(form) | stub | Below is the the instruction that describes the task:
### Input:
stub
### Response:
def clone_to(self, target_repo):
"""stub"""
new_asset = target_repo.duplicate_asset(self.my_osid_object.ident)
form = target_repo.get_asset_form_for_update(new_asset.ident)
form.set_provenance(str(se... |
def _encrypt(key_data, derived_key_information):
"""
Encrypt 'key_data' using the Advanced Encryption Standard (AES-256) algorithm.
'derived_key_information' should contain a key strengthened by PBKDF2. The
key size is 256 bits and AES's mode of operation is set to CTR (CounTeR Mode).
The HMAC of the ciphert... | Encrypt 'key_data' using the Advanced Encryption Standard (AES-256) algorithm.
'derived_key_information' should contain a key strengthened by PBKDF2. The
key size is 256 bits and AES's mode of operation is set to CTR (CounTeR Mode).
The HMAC of the ciphertext is generated to ensure the ciphertext has not been
... | Below is the the instruction that describes the task:
### Input:
Encrypt 'key_data' using the Advanced Encryption Standard (AES-256) algorithm.
'derived_key_information' should contain a key strengthened by PBKDF2. The
key size is 256 bits and AES's mode of operation is set to CTR (CounTeR Mode).
The HMAC of... |
def date_decoder(dic):
"""Add python types decoding. See JsonEncoder"""
if '__date__' in dic:
try:
d = datetime.date(**{c: v for c, v in dic.items() if not c == "__date__"})
except (TypeError, ValueError):
raise json.JSONDecodeError("Corrupted date format !", str(dic), 1)... | Add python types decoding. See JsonEncoder | Below is the the instruction that describes the task:
### Input:
Add python types decoding. See JsonEncoder
### Response:
def date_decoder(dic):
"""Add python types decoding. See JsonEncoder"""
if '__date__' in dic:
try:
d = datetime.date(**{c: v for c, v in dic.items() if not c == "__d... |
def splice(self, new_str, start, end=None):
"""Returns a new FmtStr with the input string spliced into the
the original FmtStr at start and end.
If end is provided, new_str will replace the substring self.s[start:end-1].
"""
if len(new_str) == 0:
return self
n... | Returns a new FmtStr with the input string spliced into the
the original FmtStr at start and end.
If end is provided, new_str will replace the substring self.s[start:end-1]. | Below is the the instruction that describes the task:
### Input:
Returns a new FmtStr with the input string spliced into the
the original FmtStr at start and end.
If end is provided, new_str will replace the substring self.s[start:end-1].
### Response:
def splice(self, new_str, start, end=None):
... |
def find(self, asset_id, query=None, **kwargs):
"""
Gets a single asset by ID.
"""
if query is None:
query = {}
normalize_select(query)
return super(AssetsProxy, self).find(asset_id, query=query, **kwargs) | Gets a single asset by ID. | Below is the the instruction that describes the task:
### Input:
Gets a single asset by ID.
### Response:
def find(self, asset_id, query=None, **kwargs):
"""
Gets a single asset by ID.
"""
if query is None:
query = {}
normalize_select(query)
return sup... |
def status(name, sig=None):
'''
Return the status for a service.
If the name contains globbing, a dict mapping service name to True/False
values is returned.
.. versionchanged:: 2018.3.0
The service name can now be a glob (e.g. ``salt*``)
Args:
name (str): The name of the servi... | Return the status for a service.
If the name contains globbing, a dict mapping service name to True/False
values is returned.
.. versionchanged:: 2018.3.0
The service name can now be a glob (e.g. ``salt*``)
Args:
name (str): The name of the service to check
sig (str): Signature... | Below is the the instruction that describes the task:
### Input:
Return the status for a service.
If the name contains globbing, a dict mapping service name to True/False
values is returned.
.. versionchanged:: 2018.3.0
The service name can now be a glob (e.g. ``salt*``)
Args:
name... |
def _press_special_key(self, key, down):
""" Helper method for special keys.
Source: http://stackoverflow.com/questions/11045814/emulate-media-key-press-on-mac
"""
key_code = special_key_translate_table[key]
ev = NSEvent.otherEventWithType_location_modifierFlags_timestamp_wind... | Helper method for special keys.
Source: http://stackoverflow.com/questions/11045814/emulate-media-key-press-on-mac | Below is the the instruction that describes the task:
### Input:
Helper method for special keys.
Source: http://stackoverflow.com/questions/11045814/emulate-media-key-press-on-mac
### Response:
def _press_special_key(self, key, down):
""" Helper method for special keys.
Source: http://s... |
def intersect(self, other):
""" Computes the multiset intersection, between the current Multicolor and the supplied Multicolor
:param other: another Multicolor object to compute a multiset intersection with
:return:
:raise TypeError: an intersection can be computed only between two Mult... | Computes the multiset intersection, between the current Multicolor and the supplied Multicolor
:param other: another Multicolor object to compute a multiset intersection with
:return:
:raise TypeError: an intersection can be computed only between two Multicolor objects | Below is the the instruction that describes the task:
### Input:
Computes the multiset intersection, between the current Multicolor and the supplied Multicolor
:param other: another Multicolor object to compute a multiset intersection with
:return:
:raise TypeError: an intersection can be c... |
def allow_request(self, request, view):
"""
Modify throttling for service users.
Updates throttling rate if the request is coming from the service user, and
defaults to UserRateThrottle's configured setting otherwise.
Updated throttling rate comes from `DEFAULT_THROTTLE_RATES` ... | Modify throttling for service users.
Updates throttling rate if the request is coming from the service user, and
defaults to UserRateThrottle's configured setting otherwise.
Updated throttling rate comes from `DEFAULT_THROTTLE_RATES` key in `REST_FRAMEWORK`
setting. service user thrott... | Below is the the instruction that describes the task:
### Input:
Modify throttling for service users.
Updates throttling rate if the request is coming from the service user, and
defaults to UserRateThrottle's configured setting otherwise.
Updated throttling rate comes from `DEFAULT_THROTTL... |
def positions(self):
"""
TimeSeries of positions.
"""
# if accessing and stale - update first
if self._needupdate:
self.update(self.root.now)
if self.root.stale:
self.root.update(self.root.now, None)
return self._positions.loc[:self.now] | TimeSeries of positions. | Below is the the instruction that describes the task:
### Input:
TimeSeries of positions.
### Response:
def positions(self):
"""
TimeSeries of positions.
"""
# if accessing and stale - update first
if self._needupdate:
self.update(self.root.now)
if self.r... |
def on_timer(self):
"""Executes flush(). Ignores any errors to make sure one exception
doesn't halt the whole flushing process.
"""
try:
self.flush()
except Exception as e:
log.exception('Error while flushing: %s', e)
self._set_timer() | Executes flush(). Ignores any errors to make sure one exception
doesn't halt the whole flushing process. | Below is the the instruction that describes the task:
### Input:
Executes flush(). Ignores any errors to make sure one exception
doesn't halt the whole flushing process.
### Response:
def on_timer(self):
"""Executes flush(). Ignores any errors to make sure one exception
doesn't halt the who... |
def _get_attribute(self, attribute, name):
"""Device attribute getter"""
try:
if attribute is None:
attribute = self._attribute_file_open( name )
else:
attribute.seek(0)
return attribute, attribute.read().strip().decode()
except... | Device attribute getter | Below is the the instruction that describes the task:
### Input:
Device attribute getter
### Response:
def _get_attribute(self, attribute, name):
"""Device attribute getter"""
try:
if attribute is None:
attribute = self._attribute_file_open( name )
else:
... |
def get_plugin_from_string(plugin_name):
"""
Returns plugin or plugin point class from given ``plugin_name`` string.
Example of ``plugin_name``::
'my_app.MyPlugin'
"""
modulename, classname = plugin_name.rsplit('.', 1)
module = import_module(modulename)
return getattr(module, clas... | Returns plugin or plugin point class from given ``plugin_name`` string.
Example of ``plugin_name``::
'my_app.MyPlugin' | Below is the the instruction that describes the task:
### Input:
Returns plugin or plugin point class from given ``plugin_name`` string.
Example of ``plugin_name``::
'my_app.MyPlugin'
### Response:
def get_plugin_from_string(plugin_name):
"""
Returns plugin or plugin point class from given ``... |
def _poly_eval(self, u, ids, der=0):
"""Evaluate internal polynomial."""
if der == 0:
return self._poly_eval_0(u, ids)
elif der == 1:
return self._poly_eval_1(u, ids)
elif der == 2:
return self._poly_eval_2(u, ids)
elif der == 3:
re... | Evaluate internal polynomial. | Below is the the instruction that describes the task:
### Input:
Evaluate internal polynomial.
### Response:
def _poly_eval(self, u, ids, der=0):
"""Evaluate internal polynomial."""
if der == 0:
return self._poly_eval_0(u, ids)
elif der == 1:
return self._poly_eval_1... |
def rahukaalam_utc(self, date, latitude, longitude, observer_elevation=0):
"""Calculate ruhakaalam times in the UTC timezone.
:param date: Date to calculate for.
:type date: :class:`datetime.date`
:param latitude: Latitude - Northern latitudes should be positive
:... | Calculate ruhakaalam times in the UTC timezone.
:param date: Date to calculate for.
:type date: :class:`datetime.date`
:param latitude: Latitude - Northern latitudes should be positive
:type latitude: float
:param longitude: Longitude - Eastern longitudes shou... | Below is the the instruction that describes the task:
### Input:
Calculate ruhakaalam times in the UTC timezone.
:param date: Date to calculate for.
:type date: :class:`datetime.date`
:param latitude: Latitude - Northern latitudes should be positive
:type latitude: ... |
def get_next_types(self, n=None):
"""Gets the next set of ``Types`` in this list.
The specified amount must be less than or equal to the return
from ``available()``.
arg: n (cardinal): the number of ``Type`` elements requested
which must be less than or equal to ``av... | Gets the next set of ``Types`` in this list.
The specified amount must be less than or equal to the return
from ``available()``.
arg: n (cardinal): the number of ``Type`` elements requested
which must be less than or equal to ``available()``
return: (osid.type.Type) ... | Below is the the instruction that describes the task:
### Input:
Gets the next set of ``Types`` in this list.
The specified amount must be less than or equal to the return
from ``available()``.
arg: n (cardinal): the number of ``Type`` elements requested
which must be le... |
def _from_dict(cls, _dict):
"""Initialize a RuntimeEntity object from a json dictionary."""
args = {}
if 'entity' in _dict:
args['entity'] = _dict.get('entity')
else:
raise ValueError(
'Required property \'entity\' not present in RuntimeEntity JSON... | Initialize a RuntimeEntity object from a json dictionary. | Below is the the instruction that describes the task:
### Input:
Initialize a RuntimeEntity object from a json dictionary.
### Response:
def _from_dict(cls, _dict):
"""Initialize a RuntimeEntity object from a json dictionary."""
args = {}
if 'entity' in _dict:
args['entity'] = _... |
def export(self, mesh, rlzs_by_gsim, num_ses):
"""
Yield :class:`Rupture` objects, with all the
attributes set, suitable for export in XML format.
"""
rupture = self.rupture
events = self.get_events(rlzs_by_gsim)
events_by_ses = self.get_events_by_ses(events, num_... | Yield :class:`Rupture` objects, with all the
attributes set, suitable for export in XML format. | Below is the the instruction that describes the task:
### Input:
Yield :class:`Rupture` objects, with all the
attributes set, suitable for export in XML format.
### Response:
def export(self, mesh, rlzs_by_gsim, num_ses):
"""
Yield :class:`Rupture` objects, with all the
attributes s... |
def community_topic_subscription_delete(self, topic_id, id, **kwargs):
"https://developer.zendesk.com/rest_api/docs/help_center/subscriptions#delete-topic-subscription"
api_path = "/api/v2/community/topics/{topic_id}/subscriptions/{id}.json"
api_path = api_path.format(topic_id=topic_id, id=id)
... | https://developer.zendesk.com/rest_api/docs/help_center/subscriptions#delete-topic-subscription | Below is the the instruction that describes the task:
### Input:
https://developer.zendesk.com/rest_api/docs/help_center/subscriptions#delete-topic-subscription
### Response:
def community_topic_subscription_delete(self, topic_id, id, **kwargs):
"https://developer.zendesk.com/rest_api/docs/help_center/subs... |
def random_product(iter1, iter2):
"""
Random sampler for equal_splits functions
"""
iter4 = np.concatenate([
np.random.choice(iter1, 2, replace=False),
np.random.choice(iter2, 2, replace=False)
])
return iter4 | Random sampler for equal_splits functions | Below is the the instruction that describes the task:
### Input:
Random sampler for equal_splits functions
### Response:
def random_product(iter1, iter2):
"""
Random sampler for equal_splits functions
"""
iter4 = np.concatenate([
np.random.choice(iter1, 2, replace=False),
np.random... |
def _getDecoratorsName(node):
"""
Return a list with names of decorators attached to this node.
@param node: current node of pylint
"""
# For setter properties pylint fails so we use a custom code.
decorators = []
if not node.decorators:
return decorators
for decorator in node.... | Return a list with names of decorators attached to this node.
@param node: current node of pylint | Below is the the instruction that describes the task:
### Input:
Return a list with names of decorators attached to this node.
@param node: current node of pylint
### Response:
def _getDecoratorsName(node):
"""
Return a list with names of decorators attached to this node.
@param node: current nod... |
def select(soup, selector):
"""
soup should be a BeautifulSoup instance; selector is a CSS selector
specifying the elements you want to retrieve.
"""
tokens = selector.split()
current_context = [soup]
for token in tokens:
m = attribselect_re.match(token)
if m:
# ... | soup should be a BeautifulSoup instance; selector is a CSS selector
specifying the elements you want to retrieve. | Below is the the instruction that describes the task:
### Input:
soup should be a BeautifulSoup instance; selector is a CSS selector
specifying the elements you want to retrieve.
### Response:
def select(soup, selector):
"""
soup should be a BeautifulSoup instance; selector is a CSS selector
spec... |
def periodic(period=60.0, file=sys.stderr):
"""Start a daemon thread which will periodically print GC stats
:param period: Update period in seconds
:param file: A writable file-like object
"""
import threading
import time
S = _StatsThread(period=period, file=file)
T = threading.Thread(t... | Start a daemon thread which will periodically print GC stats
:param period: Update period in seconds
:param file: A writable file-like object | Below is the the instruction that describes the task:
### Input:
Start a daemon thread which will periodically print GC stats
:param period: Update period in seconds
:param file: A writable file-like object
### Response:
def periodic(period=60.0, file=sys.stderr):
"""Start a daemon thread which will p... |
def _workout_filename(filename):
'''
Recursively workout the file name from an augeas change
'''
if os.path.isfile(filename) or filename == '/':
if filename == '/':
filename = None
return filename
else:
return _workout_filename(os.path.dirname(filename)) | Recursively workout the file name from an augeas change | Below is the the instruction that describes the task:
### Input:
Recursively workout the file name from an augeas change
### Response:
def _workout_filename(filename):
'''
Recursively workout the file name from an augeas change
'''
if os.path.isfile(filename) or filename == '/':
if filename... |
def get_version(form='short'):
"""
Returns the version string.
Takes single argument ``form``, which should be one of the following
strings:
* ``short`` Returns major + minor branch version string with the format of
B.b.t.
* ``normal`` Returns human readable version string with the for... | Returns the version string.
Takes single argument ``form``, which should be one of the following
strings:
* ``short`` Returns major + minor branch version string with the format of
B.b.t.
* ``normal`` Returns human readable version string with the format of
B.b.t _type type_num.
* ``v... | Below is the the instruction that describes the task:
### Input:
Returns the version string.
Takes single argument ``form``, which should be one of the following
strings:
* ``short`` Returns major + minor branch version string with the format of
B.b.t.
* ``normal`` Returns human readable v... |
def _process_dataset(name, directory, num_shards, labels_file):
"""Process a complete data set and save it as a TFRecord.
Args:
name: string, unique identifier specifying the data set.
directory: string, root path to the data set.
num_shards: integer number of shards for this data set.
labels_file:... | Process a complete data set and save it as a TFRecord.
Args:
name: string, unique identifier specifying the data set.
directory: string, root path to the data set.
num_shards: integer number of shards for this data set.
labels_file: string, path to the labels file. | Below is the the instruction that describes the task:
### Input:
Process a complete data set and save it as a TFRecord.
Args:
name: string, unique identifier specifying the data set.
directory: string, root path to the data set.
num_shards: integer number of shards for this data set.
labels_file:... |
def _build_connection_pool(cls, session: AppSession):
'''Create connection pool.'''
args = session.args
connect_timeout = args.connect_timeout
read_timeout = args.read_timeout
if args.timeout:
connect_timeout = read_timeout = args.timeout
if args.limit_rate:... | Create connection pool. | Below is the the instruction that describes the task:
### Input:
Create connection pool.
### Response:
def _build_connection_pool(cls, session: AppSession):
'''Create connection pool.'''
args = session.args
connect_timeout = args.connect_timeout
read_timeout = args.read_timeout
... |
def _apply_local_transforms(p, ts):
"""
Given a 2d array of single shot results (outer axis iterates over shots, inner axis over bits)
and a list of assignment probability matrices (one for each bit in the readout, ordered like
the inner axis of results) apply local 2x2 matrices to each bit index.
... | Given a 2d array of single shot results (outer axis iterates over shots, inner axis over bits)
and a list of assignment probability matrices (one for each bit in the readout, ordered like
the inner axis of results) apply local 2x2 matrices to each bit index.
:param np.array p: An array that enumerates a fu... | Below is the the instruction that describes the task:
### Input:
Given a 2d array of single shot results (outer axis iterates over shots, inner axis over bits)
and a list of assignment probability matrices (one for each bit in the readout, ordered like
the inner axis of results) apply local 2x2 matrices to ... |
def _pullMessage(self):
"""Call pull api with seq value to get message data."""
data = {
"msgs_recv": 0,
"sticky_token": self._sticky,
"sticky_pool": self._pool,
"clientid": self._client_id,
"state": "active" if self._markAlive else "offline",
... | Call pull api with seq value to get message data. | Below is the the instruction that describes the task:
### Input:
Call pull api with seq value to get message data.
### Response:
def _pullMessage(self):
"""Call pull api with seq value to get message data."""
data = {
"msgs_recv": 0,
"sticky_token": self._sticky,
... |
def stream_events(self, inputs, ew):
"""This function handles all the action: splunk calls this modular input
without arguments, streams XML describing the inputs to stdin, and waits
for XML on stdout describing events.
If you set use_single_instance to True on the scheme in get_scheme,... | This function handles all the action: splunk calls this modular input
without arguments, streams XML describing the inputs to stdin, and waits
for XML on stdout describing events.
If you set use_single_instance to True on the scheme in get_scheme, it
will pass all the instances of this ... | Below is the the instruction that describes the task:
### Input:
This function handles all the action: splunk calls this modular input
without arguments, streams XML describing the inputs to stdin, and waits
for XML on stdout describing events.
If you set use_single_instance to True on the ... |
def get_files_from_dir(path, recursive=True, depth=0, file_ext='.py'):
"""Retrieve the list of files from a folder.
@param path: file or directory where to search files
@param recursive: if True will search also sub-directories
@param depth: if explore recursively, the depth of sub directories to follo... | Retrieve the list of files from a folder.
@param path: file or directory where to search files
@param recursive: if True will search also sub-directories
@param depth: if explore recursively, the depth of sub directories to follow
@param file_ext: the files extension to get. Default is '.py'
@retur... | Below is the the instruction that describes the task:
### Input:
Retrieve the list of files from a folder.
@param path: file or directory where to search files
@param recursive: if True will search also sub-directories
@param depth: if explore recursively, the depth of sub directories to follow
@pa... |
def collect(package='perch.migrations'):
"""
Import all modules inside the perch.migrations package and return the
registered migrations
"""
package = importlib.import_module(package)
for loader, name, is_pkg in pkgutil.walk_packages(package.__path__):
importlib.import_module(package.__... | Import all modules inside the perch.migrations package and return the
registered migrations | Below is the the instruction that describes the task:
### Input:
Import all modules inside the perch.migrations package and return the
registered migrations
### Response:
def collect(package='perch.migrations'):
"""
Import all modules inside the perch.migrations package and return the
registered mi... |
def prepare_metadata(metadata):
'''prepare a key/value list of metadata for the request. The metadata
object that comes in is only parsed one level.
'''
pairs = {
'metadata': {
'items': [{
'key': 'client',
'value': 'sregistry'
}
... | prepare a key/value list of metadata for the request. The metadata
object that comes in is only parsed one level. | Below is the the instruction that describes the task:
### Input:
prepare a key/value list of metadata for the request. The metadata
object that comes in is only parsed one level.
### Response:
def prepare_metadata(metadata):
'''prepare a key/value list of metadata for the request. The metadata
ob... |
def get_key(self, key, target='in'):
"""Get the name of a key in current style.
e.g.: in javadoc style, the returned key for 'param' is '@param'
:param key: the key wanted (param, type, return, rtype,..)
:param target: the target docstring is 'in' for the input or
'out' for th... | Get the name of a key in current style.
e.g.: in javadoc style, the returned key for 'param' is '@param'
:param key: the key wanted (param, type, return, rtype,..)
:param target: the target docstring is 'in' for the input or
'out' for the output to generate. (Default value = 'in') | Below is the the instruction that describes the task:
### Input:
Get the name of a key in current style.
e.g.: in javadoc style, the returned key for 'param' is '@param'
:param key: the key wanted (param, type, return, rtype,..)
:param target: the target docstring is 'in' for the input or
... |
def requestAvatar(self, avatarId, mind, *interfaces):
"""
Create Adder avatars for any IBoxReceiver request.
"""
if IBoxReceiver in interfaces:
return (IBoxReceiver, Adder(avatarId), lambda: None)
raise NotImplementedError() | Create Adder avatars for any IBoxReceiver request. | Below is the the instruction that describes the task:
### Input:
Create Adder avatars for any IBoxReceiver request.
### Response:
def requestAvatar(self, avatarId, mind, *interfaces):
"""
Create Adder avatars for any IBoxReceiver request.
"""
if IBoxReceiver in interfaces:
... |
def get_dirty_items(item_list, flag_list):
"""
Returns each item in item_list where not flag in flag_list
Args:
item_list (list):
flag_list (list):
Returns:
dirty_items
"""
assert len(item_list) == len(flag_list)
dirty_items = [item for (item, flag) in
... | Returns each item in item_list where not flag in flag_list
Args:
item_list (list):
flag_list (list):
Returns:
dirty_items | Below is the the instruction that describes the task:
### Input:
Returns each item in item_list where not flag in flag_list
Args:
item_list (list):
flag_list (list):
Returns:
dirty_items
### Response:
def get_dirty_items(item_list, flag_list):
"""
Returns each item in item... |
def append(self, item, name=None):
"""
Adds the given item to the end of the pipeline.
"""
with self.condition:
self.queue.append(item)
uuid = self._register_item(name, item)
self.condition.notify_all()
return uuid | Adds the given item to the end of the pipeline. | Below is the the instruction that describes the task:
### Input:
Adds the given item to the end of the pipeline.
### Response:
def append(self, item, name=None):
"""
Adds the given item to the end of the pipeline.
"""
with self.condition:
self.queue.append(item)
... |
def k8s_events_handle_experiment_job_statuses(self: 'celery_app.task', payload: Dict) -> None:
"""Experiment jobs statuses"""
details = payload['details']
job_uuid = details['labels']['job_uuid']
logger.debug('handling events status for job_uuid: %s, status: %s',
job_uuid, payload['stat... | Experiment jobs statuses | Below is the the instruction that describes the task:
### Input:
Experiment jobs statuses
### Response:
def k8s_events_handle_experiment_job_statuses(self: 'celery_app.task', payload: Dict) -> None:
"""Experiment jobs statuses"""
details = payload['details']
job_uuid = details['labels']['job_uuid']
... |
def setup_file_dest(params, clearDestination=True):
"""
Function to set up the file catalog structure for simulation output
Parameters
----------
params : object
e.g., `cellsim16popsParams.multicompartment_params()`
clear_dest : bool
Savefolder will be cleared if al... | Function to set up the file catalog structure for simulation output
Parameters
----------
params : object
e.g., `cellsim16popsParams.multicompartment_params()`
clear_dest : bool
Savefolder will be cleared if already existing.
Returns
-------
None | Below is the the instruction that describes the task:
### Input:
Function to set up the file catalog structure for simulation output
Parameters
----------
params : object
e.g., `cellsim16popsParams.multicompartment_params()`
clear_dest : bool
Savefolder will be cleared ... |
def set_priority(self, p_priority):
"""
Sets the priority of the todo. Must be a single capital letter [A-Z],
or None to unset the priority.
Priority remains unchanged when an invalid priority is given, or when
the task was completed.
"""
if not self.is_completed(... | Sets the priority of the todo. Must be a single capital letter [A-Z],
or None to unset the priority.
Priority remains unchanged when an invalid priority is given, or when
the task was completed. | Below is the the instruction that describes the task:
### Input:
Sets the priority of the todo. Must be a single capital letter [A-Z],
or None to unset the priority.
Priority remains unchanged when an invalid priority is given, or when
the task was completed.
### Response:
def set_priority(... |
def keys_to_string(data):
"""
Function to convert all the unicode keys in string keys
"""
if isinstance(data, dict):
for key in list(data.keys()):
if isinstance(key, six.string_types):
value = data[key]
val = keys_to_string(value)
del d... | Function to convert all the unicode keys in string keys | Below is the the instruction that describes the task:
### Input:
Function to convert all the unicode keys in string keys
### Response:
def keys_to_string(data):
"""
Function to convert all the unicode keys in string keys
"""
if isinstance(data, dict):
for key in list(data.keys()):
... |
def _get_metadata(self):
"""Get header information and store as metadata for the endpoint."""
self.metadata = self.fetch_header()
self.variables = {g.name for g in self.metadata.grids} | Get header information and store as metadata for the endpoint. | Below is the the instruction that describes the task:
### Input:
Get header information and store as metadata for the endpoint.
### Response:
def _get_metadata(self):
"""Get header information and store as metadata for the endpoint."""
self.metadata = self.fetch_header()
self.variables = {g... |
def confirm(self):
"""
Mark the instance's email as verified.
"""
self.email.is_verified = True
self.email.save()
signals.email_verified.send(email=self.email, sender=self.__class__)
logger.info("Verified email address: %s", self.email.email) | Mark the instance's email as verified. | Below is the the instruction that describes the task:
### Input:
Mark the instance's email as verified.
### Response:
def confirm(self):
"""
Mark the instance's email as verified.
"""
self.email.is_verified = True
self.email.save()
signals.email_verified.send(email=... |
def main():
"""
NAME
grab_magic_key.py
DESCRIPTION
picks out key and saves to file
SYNTAX
grab_magic_key.py [command line optins]
OPTIONS
-h prints help message and quits
-f FILE: specify input magic format file
-key KEY: specify key to print to sta... | NAME
grab_magic_key.py
DESCRIPTION
picks out key and saves to file
SYNTAX
grab_magic_key.py [command line optins]
OPTIONS
-h prints help message and quits
-f FILE: specify input magic format file
-key KEY: specify key to print to standard output | Below is the the instruction that describes the task:
### Input:
NAME
grab_magic_key.py
DESCRIPTION
picks out key and saves to file
SYNTAX
grab_magic_key.py [command line optins]
OPTIONS
-h prints help message and quits
-f FILE: specify input magic format file
... |
def print(self, *objects, **options):
"""
Print the given objects to the given file stream.
See https://docs.python.org/3/library/functions.html#print
The only difference to the ``print()`` built-in is that
``Colorful.print()`` formats the string with ``c=self``.
With th... | Print the given objects to the given file stream.
See https://docs.python.org/3/library/functions.html#print
The only difference to the ``print()`` built-in is that
``Colorful.print()`` formats the string with ``c=self``.
With that stylings are possible
:param str sep: the sepe... | Below is the the instruction that describes the task:
### Input:
Print the given objects to the given file stream.
See https://docs.python.org/3/library/functions.html#print
The only difference to the ``print()`` built-in is that
``Colorful.print()`` formats the string with ``c=self``.
... |
def aes_cbc_pkcs7_decrypt(key, data, iv):
"""
Decrypts AES ciphertext in CBC mode using a 128, 192 or 256 bit key
:param key:
The encryption key - a byte string either 16, 24 or 32 bytes long
:param data:
The ciphertext - a byte string
:param iv:
The initialization vector ... | Decrypts AES ciphertext in CBC mode using a 128, 192 or 256 bit key
:param key:
The encryption key - a byte string either 16, 24 or 32 bytes long
:param data:
The ciphertext - a byte string
:param iv:
The initialization vector - a byte string 16-bytes long
:raises:
Va... | Below is the the instruction that describes the task:
### Input:
Decrypts AES ciphertext in CBC mode using a 128, 192 or 256 bit key
:param key:
The encryption key - a byte string either 16, 24 or 32 bytes long
:param data:
The ciphertext - a byte string
:param iv:
The initial... |
def get_cleaned_kwargs(self, kwargs):
"""
Returns concrete field lookups.
"""
cleaned_kwargs = kwargs.copy()
if kwargs is not None:
for k in kwargs:
if self.is_linguist_lookup(k):
del cleaned_kwargs[k]
return cleaned_kwarg... | Returns concrete field lookups. | Below is the the instruction that describes the task:
### Input:
Returns concrete field lookups.
### Response:
def get_cleaned_kwargs(self, kwargs):
"""
Returns concrete field lookups.
"""
cleaned_kwargs = kwargs.copy()
if kwargs is not None:
for k in kwargs:
... |
def rate_limit(limit: int, key=None):
"""
Decorator for configuring rate limit and key in different functions.
:param limit:
:param key:
:return:
"""
def decorator(func):
setattr(func, 'throttling_rate_limit', limit)
if key:
setattr(func, 'throttling_key', key)
... | Decorator for configuring rate limit and key in different functions.
:param limit:
:param key:
:return: | Below is the the instruction that describes the task:
### Input:
Decorator for configuring rate limit and key in different functions.
:param limit:
:param key:
:return:
### Response:
def rate_limit(limit: int, key=None):
"""
Decorator for configuring rate limit and key in different functions.
... |
def rsdl_s(self, Yprev, Y):
"""Compute dual residual vector."""
return self.rho * self.cnst_AT(self.U) | Compute dual residual vector. | Below is the the instruction that describes the task:
### Input:
Compute dual residual vector.
### Response:
def rsdl_s(self, Yprev, Y):
"""Compute dual residual vector."""
return self.rho * self.cnst_AT(self.U) |
def make(self, pnum):
"""
Make a PID file and populate with PID number.
"""
try:
# Create the PID file
self.mkfile(self.pid_file, pnum)
except Exception as e:
self.die('Failed to generate PID file: {}'.format(str(e))) | Make a PID file and populate with PID number. | Below is the the instruction that describes the task:
### Input:
Make a PID file and populate with PID number.
### Response:
def make(self, pnum):
"""
Make a PID file and populate with PID number.
"""
try:
# Create the PID file
self.mkfile(se... |
def write_rk4(path,name,laser,omega,gamma,r,Lij,states=None,verbose=1):
r"""
This function writes the Fortran code needed to calculate the time evolution of the density matrix elements
`\rho_{ij}` using the Runge-Kutta method of order 4.
INPUT:
- ``path`` - A string with the working directory where a... | r"""
This function writes the Fortran code needed to calculate the time evolution of the density matrix elements
`\rho_{ij}` using the Runge-Kutta method of order 4.
INPUT:
- ``path`` - A string with the working directory where all files will be stored. It must end with ``/``.
- ``name`` - A stri... | Below is the the instruction that describes the task:
### Input:
r"""
This function writes the Fortran code needed to calculate the time evolution of the density matrix elements
`\rho_{ij}` using the Runge-Kutta method of order 4.
INPUT:
- ``path`` - A string with the working directory where all f... |
def deblind(rInv,y):
"""
Removes blinding using ephemeral key @rInv on (intermediate result)
@y \in Gt.
"""
# Verify types, then deblind using the values provided.
assertScalarType(rInv)
assertType(y, GtElement)
return y ** rInv | Removes blinding using ephemeral key @rInv on (intermediate result)
@y \in Gt. | Below is the the instruction that describes the task:
### Input:
Removes blinding using ephemeral key @rInv on (intermediate result)
@y \in Gt.
### Response:
def deblind(rInv,y):
"""
Removes blinding using ephemeral key @rInv on (intermediate result)
@y \in Gt.
"""
# Verify types, then de... |
def convex_hull(points):
"""Computes the convex hull of a set of 2D points.
Implements `Andrew's monotone chain algorithm <http://en.wikibooks.org/wiki/Algorithm_Implementation/Geometry/Convex_hull/Monotone_chain>`_.
The algorithm has O(n log n) complexity.
Credit: `<http://en.wikibooks.org/wiki/Algor... | Computes the convex hull of a set of 2D points.
Implements `Andrew's monotone chain algorithm <http://en.wikibooks.org/wiki/Algorithm_Implementation/Geometry/Convex_hull/Monotone_chain>`_.
The algorithm has O(n log n) complexity.
Credit: `<http://en.wikibooks.org/wiki/Algorithm_Implementation/Geometry/Con... | Below is the the instruction that describes the task:
### Input:
Computes the convex hull of a set of 2D points.
Implements `Andrew's monotone chain algorithm <http://en.wikibooks.org/wiki/Algorithm_Implementation/Geometry/Convex_hull/Monotone_chain>`_.
The algorithm has O(n log n) complexity.
Credit:... |
def get_pmid(doc_id):
"""Get PMID from document_chembl_id
Parameters
----------
doc_id : str
Returns
-------
pmid : str
"""
url_pmid = 'https://www.ebi.ac.uk/chembl/api/data/document.json'
params = {'document_chembl_id': doc_id}
res = requests.get(url_pmid, params=params)
... | Get PMID from document_chembl_id
Parameters
----------
doc_id : str
Returns
-------
pmid : str | Below is the the instruction that describes the task:
### Input:
Get PMID from document_chembl_id
Parameters
----------
doc_id : str
Returns
-------
pmid : str
### Response:
def get_pmid(doc_id):
"""Get PMID from document_chembl_id
Parameters
----------
doc_id : str
... |
def decode_offset_response(cls, data):
"""
Decode bytes to an OffsetResponse
Arguments:
data: bytes to decode
"""
((correlation_id, num_topics), cur) = relative_unpack('>ii', data, 0)
for _ in range(num_topics):
(topic, cur) = read_short_string(d... | Decode bytes to an OffsetResponse
Arguments:
data: bytes to decode | Below is the the instruction that describes the task:
### Input:
Decode bytes to an OffsetResponse
Arguments:
data: bytes to decode
### Response:
def decode_offset_response(cls, data):
"""
Decode bytes to an OffsetResponse
Arguments:
data: bytes to decode
... |
def get_subgraph_by_second_neighbors(graph, nodes: Iterable[BaseEntity], filter_pathologies: bool = False):
"""Get a graph around the neighborhoods of the given nodes and expand to the neighborhood of those nodes.
Returns none if none of the nodes are in the graph.
:param pybel.BELGraph graph: A BEL graph... | Get a graph around the neighborhoods of the given nodes and expand to the neighborhood of those nodes.
Returns none if none of the nodes are in the graph.
:param pybel.BELGraph graph: A BEL graph
:param nodes: An iterable of BEL nodes
:param filter_pathologies: Should expansion take place around patho... | Below is the the instruction that describes the task:
### Input:
Get a graph around the neighborhoods of the given nodes and expand to the neighborhood of those nodes.
Returns none if none of the nodes are in the graph.
:param pybel.BELGraph graph: A BEL graph
:param nodes: An iterable of BEL nodes
... |
def _sge_get_mem(xmlstring, queue_name):
""" Get memory information from qhost
"""
rootxml = ET.fromstring(xmlstring)
my_machine_dict = {}
# on some machines rootxml.tag looks like "{...}qhost" where the "{...}" gets prepended to all attributes
rootTag = rootxml.tag.rstrip("qhost")
for host ... | Get memory information from qhost | Below is the the instruction that describes the task:
### Input:
Get memory information from qhost
### Response:
def _sge_get_mem(xmlstring, queue_name):
""" Get memory information from qhost
"""
rootxml = ET.fromstring(xmlstring)
my_machine_dict = {}
# on some machines rootxml.tag looks like "... |
def superdict(arg=()):
"""Recursive defaultdict which can init with other dict """
def update(obj, arg):
return obj.update(arg) or obj
return update(defaultdict(superdict), arg) | Recursive defaultdict which can init with other dict | Below is the the instruction that describes the task:
### Input:
Recursive defaultdict which can init with other dict
### Response:
def superdict(arg=()):
"""Recursive defaultdict which can init with other dict """
def update(obj, arg):
return obj.update(arg) or obj
return update(defaultdict(su... |
def get_path(language):
''' Returns the full path to the language file '''
filename = language.lower() + '.json'
lang_file_path = os.path.join(_DEFAULT_DIR, filename)
if not os.path.exists(lang_file_path):
raise IOError('Could not find {} language file'.format(language))
return lang_file_path | Returns the full path to the language file | Below is the the instruction that describes the task:
### Input:
Returns the full path to the language file
### Response:
def get_path(language):
''' Returns the full path to the language file '''
filename = language.lower() + '.json'
lang_file_path = os.path.join(_DEFAULT_DIR, filename)
if not os.path.exi... |
def load_parameter_file(file_path, name = ''):
"""
Load parameters from a YAML file (or a directory containing YAML files).
:returns: An instance of :any:`ParameterNode` or :any:`Scale` or :any:`Parameter`.
"""
if not os.path.exists(file_path):
raise ValueError("{} doest not exist".format(f... | Load parameters from a YAML file (or a directory containing YAML files).
:returns: An instance of :any:`ParameterNode` or :any:`Scale` or :any:`Parameter`. | Below is the the instruction that describes the task:
### Input:
Load parameters from a YAML file (or a directory containing YAML files).
:returns: An instance of :any:`ParameterNode` or :any:`Scale` or :any:`Parameter`.
### Response:
def load_parameter_file(file_path, name = ''):
"""
Load parameters ... |
def run_hive(args, check_return_code=True):
"""
Runs the `hive` from the command line, passing in the given args, and
returning stdout.
With the apache release of Hive, so of the table existence checks
(which are done using DESCRIBE do not exit with a return code of 0
so we need an option to ig... | Runs the `hive` from the command line, passing in the given args, and
returning stdout.
With the apache release of Hive, so of the table existence checks
(which are done using DESCRIBE do not exit with a return code of 0
so we need an option to ignore the return code and just return stdout for parsing | Below is the the instruction that describes the task:
### Input:
Runs the `hive` from the command line, passing in the given args, and
returning stdout.
With the apache release of Hive, so of the table existence checks
(which are done using DESCRIBE do not exit with a return code of 0
so we need an... |
def renderInTable(self, relpath=""):
"""renderInTable() is called to render FITS images in a table"""
# return from cache if available
cachekey, html = self.checkCache('InTable', relpath)
if html is not None:
return html
# else regenerate
# single image: rende... | renderInTable() is called to render FITS images in a table | Below is the the instruction that describes the task:
### Input:
renderInTable() is called to render FITS images in a table
### Response:
def renderInTable(self, relpath=""):
"""renderInTable() is called to render FITS images in a table"""
# return from cache if available
cachekey, html = s... |
def log(logger=None, start_message='Starting...', end_message='Done...'):
"""
Basic log decorator
Can be used as :
- @log (with default logger)
- @log(mylogger)
- @log(start_message='Hello !", logger=mylogger, end_message='Bye !')
"""
def actual_log(f, real_logger=logger):
logger... | Basic log decorator
Can be used as :
- @log (with default logger)
- @log(mylogger)
- @log(start_message='Hello !", logger=mylogger, end_message='Bye !') | Below is the the instruction that describes the task:
### Input:
Basic log decorator
Can be used as :
- @log (with default logger)
- @log(mylogger)
- @log(start_message='Hello !", logger=mylogger, end_message='Bye !')
### Response:
def log(logger=None, start_message='Starting...', end_message='Done... |
def FindModuleIdDefiningFlag(self, flagname, default=None):
"""Return the ID of the module defining this flag, or default.
Args:
flagname: Name of the flag to lookup.
default: Value to return if flagname is not defined. Defaults
to None.
Returns:
The ID of the module which regi... | Return the ID of the module defining this flag, or default.
Args:
flagname: Name of the flag to lookup.
default: Value to return if flagname is not defined. Defaults
to None.
Returns:
The ID of the module which registered the flag with this name.
If no such module exists (i.e... | Below is the the instruction that describes the task:
### Input:
Return the ID of the module defining this flag, or default.
Args:
flagname: Name of the flag to lookup.
default: Value to return if flagname is not defined. Defaults
to None.
Returns:
The ID of the module which re... |
def rm(hdfs_path, recursive=True, user=None):
"""
Remove a file or directory.
If ``recursive`` is :obj:`True` (the default), directory contents are
removed recursively.
"""
host, port, path_ = path.split(hdfs_path, user)
fs = hdfs(host, port, user)
retval = fs.delete(path_, recursive=re... | Remove a file or directory.
If ``recursive`` is :obj:`True` (the default), directory contents are
removed recursively. | Below is the the instruction that describes the task:
### Input:
Remove a file or directory.
If ``recursive`` is :obj:`True` (the default), directory contents are
removed recursively.
### Response:
def rm(hdfs_path, recursive=True, user=None):
"""
Remove a file or directory.
If ``recursive`` ... |
def to_string_with_default(value, default_value):
"""
Converts value into string or returns default when value is None.
:param value: the value to convert.
:param default_value: the default value.
:return: string value or default when value is null.
"""
result ... | Converts value into string or returns default when value is None.
:param value: the value to convert.
:param default_value: the default value.
:return: string value or default when value is null. | Below is the the instruction that describes the task:
### Input:
Converts value into string or returns default when value is None.
:param value: the value to convert.
:param default_value: the default value.
:return: string value or default when value is null.
### Response:
def to_string... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.