code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def volume_attach(name, server_name, device='/dev/xvdb', **kwargs):
'''
Attach block volume
'''
conn = get_conn()
return conn.volume_attach(
name,
server_name,
device,
timeout=300
) | Attach block volume | Below is the the instruction that describes the task:
### Input:
Attach block volume
### Response:
def volume_attach(name, server_name, device='/dev/xvdb', **kwargs):
'''
Attach block volume
'''
conn = get_conn()
return conn.volume_attach(
name,
server_name,
device,
... |
def encode(self, word, max_length=-1, keep_vowels=False, vowel_char='*'):
r"""Return the Dolby Code of a name.
Parameters
----------
word : str
The word to transform
max_length : int
Maximum length of the returned Dolby code -- this also activates
... | r"""Return the Dolby Code of a name.
Parameters
----------
word : str
The word to transform
max_length : int
Maximum length of the returned Dolby code -- this also activates
the fixed-length code mode if it is greater than 0
keep_vowels : bool... | Below is the the instruction that describes the task:
### Input:
r"""Return the Dolby Code of a name.
Parameters
----------
word : str
The word to transform
max_length : int
Maximum length of the returned Dolby code -- this also activates
the fixe... |
def query_by_entity_uid(idd, kind=''):
'''
Query post2tag by certain post.
'''
if kind == '':
return TabPost2Tag.select(
TabPost2Tag,
TabTag.slug.alias('tag_slug'),
TabTag.name.alias('tag_name')
).join(
... | Query post2tag by certain post. | Below is the the instruction that describes the task:
### Input:
Query post2tag by certain post.
### Response:
def query_by_entity_uid(idd, kind=''):
'''
Query post2tag by certain post.
'''
if kind == '':
return TabPost2Tag.select(
TabPost2Tag,
... |
def dict_contents(self, use_dict=None, as_class=dict):
"""Return the contents of an object as a dict."""
# make/extend the dictionary of content
if use_dict is None:
use_dict = as_class()
# save the content
use_dict.__setitem__('dnet', self.rtDNET)
use_dict._... | Return the contents of an object as a dict. | Below is the the instruction that describes the task:
### Input:
Return the contents of an object as a dict.
### Response:
def dict_contents(self, use_dict=None, as_class=dict):
"""Return the contents of an object as a dict."""
# make/extend the dictionary of content
if use_dict is None:
... |
def _part(self, name, func, args, help, **kwargs):
"""Parses arguments of a single command (e.g. 'v').
If :args: is empty, it assumes that command takes no further arguments.
:name: Name of the command.
:func: Arg method to execute.
:args: Dictionary of CLI arguments pointed at... | Parses arguments of a single command (e.g. 'v').
If :args: is empty, it assumes that command takes no further arguments.
:name: Name of the command.
:func: Arg method to execute.
:args: Dictionary of CLI arguments pointed at Arg method arguments.
:help: Commands' help text.
... | Below is the the instruction that describes the task:
### Input:
Parses arguments of a single command (e.g. 'v').
If :args: is empty, it assumes that command takes no further arguments.
:name: Name of the command.
:func: Arg method to execute.
:args: Dictionary of CLI arguments poi... |
def n_members(self):
"""
Returns the number of members in the domain if it
`is_finite`, otherwise, returns `np.inf`.
:type: ``int`` or ``np.inf``
"""
if self.is_finite:
return reduce(mul, [domain.n_members for domain in self._domains], 1)
else:
... | Returns the number of members in the domain if it
`is_finite`, otherwise, returns `np.inf`.
:type: ``int`` or ``np.inf`` | Below is the the instruction that describes the task:
### Input:
Returns the number of members in the domain if it
`is_finite`, otherwise, returns `np.inf`.
:type: ``int`` or ``np.inf``
### Response:
def n_members(self):
"""
Returns the number of members in the domain if it
... |
def unstash(self):
"""
Pops the last stash if EPAB made a stash before
"""
if not self.stashed:
LOGGER.error('no stash')
else:
LOGGER.info('popping stash')
self.repo.git.stash('pop')
self.stashed = False | Pops the last stash if EPAB made a stash before | Below is the the instruction that describes the task:
### Input:
Pops the last stash if EPAB made a stash before
### Response:
def unstash(self):
"""
Pops the last stash if EPAB made a stash before
"""
if not self.stashed:
LOGGER.error('no stash')
else:
... |
def run_plasmid_extractor(self):
"""
Create and run the plasmid extractor system call
"""
logging.info('Extracting plasmids')
# Define the system call
extract_command = 'PlasmidExtractor.py -i {inf} -o {outf} -p {plasdb} -d {db} -t {cpus} -nc' \
.format(inf=se... | Create and run the plasmid extractor system call | Below is the the instruction that describes the task:
### Input:
Create and run the plasmid extractor system call
### Response:
def run_plasmid_extractor(self):
"""
Create and run the plasmid extractor system call
"""
logging.info('Extracting plasmids')
# Define the system c... |
def execute(connection: connection, statement: str) -> Optional[List[Tuple[str, ...]]]:
"""Execute PGSQL statement and fetches the statement response.
Parameters
----------
connection: psycopg2.extensions.connection
Active connection to a PostGreSQL database.
statement: str
PGSQL st... | Execute PGSQL statement and fetches the statement response.
Parameters
----------
connection: psycopg2.extensions.connection
Active connection to a PostGreSQL database.
statement: str
PGSQL statement to run against the database.
Returns
-------
response: list or None
... | Below is the the instruction that describes the task:
### Input:
Execute PGSQL statement and fetches the statement response.
Parameters
----------
connection: psycopg2.extensions.connection
Active connection to a PostGreSQL database.
statement: str
PGSQL statement to run against the... |
def guess_title(basename):
""" Attempt to guess the title from the filename """
base, _ = os.path.splitext(basename)
return re.sub(r'[ _-]+', r' ', base).title() | Attempt to guess the title from the filename | Below is the the instruction that describes the task:
### Input:
Attempt to guess the title from the filename
### Response:
def guess_title(basename):
""" Attempt to guess the title from the filename """
base, _ = os.path.splitext(basename)
return re.sub(r'[ _-]+', r' ', base).title() |
def as_dict(self):
"""
Json-serializable dict representation of COHP.
"""
d = {"@module": self.__class__.__module__,
"@class": self.__class__.__name__,
"are_coops": self.are_coops,
"efermi": self.efermi,
"energies": self.energies.tolist... | Json-serializable dict representation of COHP. | Below is the the instruction that describes the task:
### Input:
Json-serializable dict representation of COHP.
### Response:
def as_dict(self):
"""
Json-serializable dict representation of COHP.
"""
d = {"@module": self.__class__.__module__,
"@class": self.__class__.__... |
def _crop_default(x, size, row_pct:uniform=0.5, col_pct:uniform=0.5):
"Crop `x` to `size` pixels. `row_pct`,`col_pct` select focal point of crop."
rows,cols = tis2hw(size)
row_pct,col_pct = _minus_epsilon(row_pct,col_pct)
row = int((x.size(1)-rows+1) * row_pct)
col = int((x.size(2)-cols+1) * col_pct... | Crop `x` to `size` pixels. `row_pct`,`col_pct` select focal point of crop. | Below is the the instruction that describes the task:
### Input:
Crop `x` to `size` pixels. `row_pct`,`col_pct` select focal point of crop.
### Response:
def _crop_default(x, size, row_pct:uniform=0.5, col_pct:uniform=0.5):
"Crop `x` to `size` pixels. `row_pct`,`col_pct` select focal point of crop."
rows,c... |
def _track(self, class_name):
"""Keep track of which test cases have executed."""
if self._test_cases.get(class_name) is None:
if self.streaming and self.header:
self._write_test_case_header(class_name, self.stream)
self._test_cases[class_name] = []
i... | Keep track of which test cases have executed. | Below is the the instruction that describes the task:
### Input:
Keep track of which test cases have executed.
### Response:
def _track(self, class_name):
"""Keep track of which test cases have executed."""
if self._test_cases.get(class_name) is None:
if self.streaming and self.header:
... |
def cleanup_subprocesses():
"""On python exit: find possibly running subprocesses and kill them."""
# pylint: disable=redefined-outer-name, reimported
# atexit functions tends to loose global imports sometimes so reimport
# everything what is needed again here:
import os
import errno
from mi... | On python exit: find possibly running subprocesses and kill them. | Below is the the instruction that describes the task:
### Input:
On python exit: find possibly running subprocesses and kill them.
### Response:
def cleanup_subprocesses():
"""On python exit: find possibly running subprocesses and kill them."""
# pylint: disable=redefined-outer-name, reimported
# atexi... |
def decrypt_verify(encrypted, session_keys=None):
"""Decrypts the given ciphertext string and returns both the
signatures (if any) and the plaintext.
:param bytes encrypted: the mail to decrypt
:param list[str] session_keys: a list OpenPGP session keys
:returns: the signatures and decrypted plainte... | Decrypts the given ciphertext string and returns both the
signatures (if any) and the plaintext.
:param bytes encrypted: the mail to decrypt
:param list[str] session_keys: a list OpenPGP session keys
:returns: the signatures and decrypted plaintext data
:rtype: tuple[list[gpg.resuit.Signature], str... | Below is the the instruction that describes the task:
### Input:
Decrypts the given ciphertext string and returns both the
signatures (if any) and the plaintext.
:param bytes encrypted: the mail to decrypt
:param list[str] session_keys: a list OpenPGP session keys
:returns: the signatures and decry... |
def load_password(self):
"""Load the hashed password from the Glances folder."""
# Read the password file, if it exists
with open(self.password_file, 'r') as file_pwd:
hashed_password = file_pwd.read()
return hashed_password | Load the hashed password from the Glances folder. | Below is the the instruction that describes the task:
### Input:
Load the hashed password from the Glances folder.
### Response:
def load_password(self):
"""Load the hashed password from the Glances folder."""
# Read the password file, if it exists
with open(self.password_file, 'r') as file... |
def hashDictOneLevel(myDict):
'''
A function which can generate a hash of a one-level
dict containing strings (like REDIS_CONNECTION_PARAMS)
@param myDict <dict> - Dict with string keys and values
@return <long> - Hash of myDict
'''
keys = [str(x) for x in myDict.keys()]
keys.sort()
lst = []
for key... | A function which can generate a hash of a one-level
dict containing strings (like REDIS_CONNECTION_PARAMS)
@param myDict <dict> - Dict with string keys and values
@return <long> - Hash of myDict | Below is the the instruction that describes the task:
### Input:
A function which can generate a hash of a one-level
dict containing strings (like REDIS_CONNECTION_PARAMS)
@param myDict <dict> - Dict with string keys and values
@return <long> - Hash of myDict
### Response:
def hashDictOneLevel(myDict):
... |
def commit(self):
"""Commit mutations to the database.
:rtype: datetime
:returns: timestamp of the committed changes.
:raises ValueError: if there are no mutations to commit.
"""
self._check_state()
database = self._session._database
api = database.spann... | Commit mutations to the database.
:rtype: datetime
:returns: timestamp of the committed changes.
:raises ValueError: if there are no mutations to commit. | Below is the the instruction that describes the task:
### Input:
Commit mutations to the database.
:rtype: datetime
:returns: timestamp of the committed changes.
:raises ValueError: if there are no mutations to commit.
### Response:
def commit(self):
"""Commit mutations to the data... |
def new(self):
# type: () -> None
'''
Create a new Rock Ridge Platform Dependent record.
Parameters:
None.
Returns:
Nothing.
'''
if self._initialized:
raise pycdlibexception.PyCdlibInternalError('PD record already initialized!')
... | Create a new Rock Ridge Platform Dependent record.
Parameters:
None.
Returns:
Nothing. | Below is the the instruction that describes the task:
### Input:
Create a new Rock Ridge Platform Dependent record.
Parameters:
None.
Returns:
Nothing.
### Response:
def new(self):
# type: () -> None
'''
Create a new Rock Ridge Platform Dependent record.
... |
def main(unused_argv):
"""Run SC2 to play a game or a replay."""
stopwatch.sw.enabled = FLAGS.profile or FLAGS.trace
stopwatch.sw.trace = FLAGS.trace
if (FLAGS.map and FLAGS.replay) or (not FLAGS.map and not FLAGS.replay):
sys.exit("Must supply either a map or replay.")
if FLAGS.replay and not FLAGS.rep... | Run SC2 to play a game or a replay. | Below is the the instruction that describes the task:
### Input:
Run SC2 to play a game or a replay.
### Response:
def main(unused_argv):
"""Run SC2 to play a game or a replay."""
stopwatch.sw.enabled = FLAGS.profile or FLAGS.trace
stopwatch.sw.trace = FLAGS.trace
if (FLAGS.map and FLAGS.replay) or (not F... |
def get_extreme(self, target_prop, maximize=True, min_temp=None,
max_temp=None, min_doping=None, max_doping=None,
isotropy_tolerance=0.05, use_average=True):
"""
This method takes in eigenvalues over a range of carriers,
temperatures, and doping levels, a... | This method takes in eigenvalues over a range of carriers,
temperatures, and doping levels, and tells you what is the "best"
value that can be achieved for the given target_property. Note that
this method searches the doping dict only, not the full mu dict.
Args:
target_prop... | Below is the the instruction that describes the task:
### Input:
This method takes in eigenvalues over a range of carriers,
temperatures, and doping levels, and tells you what is the "best"
value that can be achieved for the given target_property. Note that
this method searches the doping di... |
def get_meta_attributes(self, **kwargs):
"""Determine the form attributes for the meta field."""
superuser = kwargs.get('superuser', False)
if (self.untl_object.qualifier == 'recordStatus'
or self.untl_object.qualifier == 'system'):
if superuser:
self.... | Determine the form attributes for the meta field. | Below is the the instruction that describes the task:
### Input:
Determine the form attributes for the meta field.
### Response:
def get_meta_attributes(self, **kwargs):
"""Determine the form attributes for the meta field."""
superuser = kwargs.get('superuser', False)
if (self.untl_object.q... |
def Pipe(self, *sequence, **kwargs):
"""
`Pipe` runs any `phi.dsl.Expression`. Its highly inspired by Elixir's [|> (pipe)](https://hexdocs.pm/elixir/Kernel.html#%7C%3E/2) operator.
**Arguments**
* ***sequence**: any variable amount of expressions. All expressions inside of `sequence` will be composed together... | `Pipe` runs any `phi.dsl.Expression`. Its highly inspired by Elixir's [|> (pipe)](https://hexdocs.pm/elixir/Kernel.html#%7C%3E/2) operator.
**Arguments**
* ***sequence**: any variable amount of expressions. All expressions inside of `sequence` will be composed together using `phi.dsl.Expression.Seq`.
* ****kwargs**: ... | Below is the the instruction that describes the task:
### Input:
`Pipe` runs any `phi.dsl.Expression`. Its highly inspired by Elixir's [|> (pipe)](https://hexdocs.pm/elixir/Kernel.html#%7C%3E/2) operator.
**Arguments**
* ***sequence**: any variable amount of expressions. All expressions inside of `sequence` will ... |
def security_rule_present(name, access, direction, priority, protocol, security_group, resource_group,
destination_address_prefix=None, destination_port_range=None, source_address_prefix=None,
source_port_range=None, description=None, destination_address_prefixes=None... | .. versionadded:: 2019.2.0
Ensure a security rule exists.
:param name:
Name of the security rule.
:param access:
'allow' or 'deny'
:param direction:
'inbound' or 'outbound'
:param priority:
Integer between 100 and 4096 used for ordering rule application.
:pa... | Below is the the instruction that describes the task:
### Input:
.. versionadded:: 2019.2.0
Ensure a security rule exists.
:param name:
Name of the security rule.
:param access:
'allow' or 'deny'
:param direction:
'inbound' or 'outbound'
:param priority:
Inte... |
def info(name):
'''
Return information for the specified user
This is just returns dummy data so that salt states can work.
:param str name: The name of the user account to show.
CLI Example:
.. code-block:: bash
salt '*' shadow.info root
'''
info = __salt__['user.info'](name... | Return information for the specified user
This is just returns dummy data so that salt states can work.
:param str name: The name of the user account to show.
CLI Example:
.. code-block:: bash
salt '*' shadow.info root | Below is the the instruction that describes the task:
### Input:
Return information for the specified user
This is just returns dummy data so that salt states can work.
:param str name: The name of the user account to show.
CLI Example:
.. code-block:: bash
salt '*' shadow.info root
### ... |
def get_relationship_key(self, context):
"""Return the configured relationship key or generate a new one
"""
if not self.relationship:
return context.portal_type + self.getName()
return self.relationship | Return the configured relationship key or generate a new one | Below is the the instruction that describes the task:
### Input:
Return the configured relationship key or generate a new one
### Response:
def get_relationship_key(self, context):
"""Return the configured relationship key or generate a new one
"""
if not self.relationship:
retu... |
def sg_flatten(tensor, opt):
r"""Reshapes a tensor to `batch_size x -1`.
See `tf.reshape()` in tensorflow.
Args:
tensor: A `Tensor` (automatically given by chain).
opt:
name: If provided, it replaces current tensor's name.
Returns:
A 2-D tensor.
"""
dim = np.pro... | r"""Reshapes a tensor to `batch_size x -1`.
See `tf.reshape()` in tensorflow.
Args:
tensor: A `Tensor` (automatically given by chain).
opt:
name: If provided, it replaces current tensor's name.
Returns:
A 2-D tensor. | Below is the the instruction that describes the task:
### Input:
r"""Reshapes a tensor to `batch_size x -1`.
See `tf.reshape()` in tensorflow.
Args:
tensor: A `Tensor` (automatically given by chain).
opt:
name: If provided, it replaces current tensor's name.
Returns:
A 2... |
def resolve_content_type(type_resolvers, request):
# type: (Iterable[Callable[[Any], str]], Any) -> Optional[str]
"""
Resolve content types from a request.
"""
for resolver in type_resolvers:
content_type = parse_content_type(resolver(request))
if content_type:
return con... | Resolve content types from a request. | Below is the the instruction that describes the task:
### Input:
Resolve content types from a request.
### Response:
def resolve_content_type(type_resolvers, request):
# type: (Iterable[Callable[[Any], str]], Any) -> Optional[str]
"""
Resolve content types from a request.
"""
for resolver in ty... |
def union_update(self, other, ignore_conflicts=False):
"""Update the definition with the union of the ``other``."""
if not ignore_conflicts:
ensure_compatible(self, other)
self._objects |= other._objects
self._properties |= other._properties
self._pairs |= other._pair... | Update the definition with the union of the ``other``. | Below is the the instruction that describes the task:
### Input:
Update the definition with the union of the ``other``.
### Response:
def union_update(self, other, ignore_conflicts=False):
"""Update the definition with the union of the ``other``."""
if not ignore_conflicts:
ensure_compa... |
def run(self, until: float) -> None:
"""
Run simulation until specified time
:note: can be used to run simulation again after it ends from time when it ends
"""
assert until > self.now
events = self._events
schedule = events.push
next_event = events.pop
... | Run simulation until specified time
:note: can be used to run simulation again after it ends from time when it ends | Below is the the instruction that describes the task:
### Input:
Run simulation until specified time
:note: can be used to run simulation again after it ends from time when it ends
### Response:
def run(self, until: float) -> None:
"""
Run simulation until specified time
:note: can ... |
def _attr_data_(self):
"Special property containing the memoized data."
try:
return self.__attr_data
except AttributeError:
self.__attr_data = type(
''.join([type(self).__name__, 'EmptyData']),
(),
{
'__... | Special property containing the memoized data. | Below is the the instruction that describes the task:
### Input:
Special property containing the memoized data.
### Response:
def _attr_data_(self):
"Special property containing the memoized data."
try:
return self.__attr_data
except AttributeError:
self.__attr_data... |
def setup(options):
"""Initialize debug/logging in third party libraries correctly.
Args:
options (:class:`nyawc.Options`): The options to use for the current crawling runtime.
"""
if not options.misc.debug:
requests.packages.urllib3.disable_warnings(
... | Initialize debug/logging in third party libraries correctly.
Args:
options (:class:`nyawc.Options`): The options to use for the current crawling runtime. | Below is the the instruction that describes the task:
### Input:
Initialize debug/logging in third party libraries correctly.
Args:
options (:class:`nyawc.Options`): The options to use for the current crawling runtime.
### Response:
def setup(options):
"""Initialize debug/logging in th... |
def get_available_themes():
""" Iterator on available themes
"""
for d in settings.TEMPLATE_DIRS:
for _d in os.listdir(d):
if os.path.isdir(os.path.join(d, _d)) and is_theme_dir(_d):
yield _d | Iterator on available themes | Below is the the instruction that describes the task:
### Input:
Iterator on available themes
### Response:
def get_available_themes():
""" Iterator on available themes
"""
for d in settings.TEMPLATE_DIRS:
for _d in os.listdir(d):
if os.path.isdir(os.path.join(d, _d)) and is_theme_d... |
def besj(self, x, n):
'''
Function BESJ calculates Bessel function of first kind of order n
Arguments:
n - an integer (>=0), the order
x - value at which the Bessel function is required
--------------------
C++ Mathematical Library
Converted from e... | Function BESJ calculates Bessel function of first kind of order n
Arguments:
n - an integer (>=0), the order
x - value at which the Bessel function is required
--------------------
C++ Mathematical Library
Converted from equivalent FORTRAN library
Converte... | Below is the the instruction that describes the task:
### Input:
Function BESJ calculates Bessel function of first kind of order n
Arguments:
n - an integer (>=0), the order
x - value at which the Bessel function is required
--------------------
C++ Mathematical Libra... |
def encode(data):
'''
bytes -> str
'''
if riemann.network.CASHADDR_PREFIX is None:
raise ValueError('Network {} does not support cashaddresses.'
.format(riemann.get_current_network_name()))
data = convertbits(data, 8, 5)
checksum = calculate_checksum(riemann.net... | bytes -> str | Below is the the instruction that describes the task:
### Input:
bytes -> str
### Response:
def encode(data):
'''
bytes -> str
'''
if riemann.network.CASHADDR_PREFIX is None:
raise ValueError('Network {} does not support cashaddresses.'
.format(riemann.get_current_n... |
def decode(s):
"""Decodes a single string to a list of strings.
:type s: str
:rtype: List[str]
"""
strs = []
i = 0
while i < len(s):
index = s.find(":", i)
size = int(s[i:index])
strs.append(s[index+1: index+1+size])
i = index+1+size
return strs | Decodes a single string to a list of strings.
:type s: str
:rtype: List[str] | Below is the the instruction that describes the task:
### Input:
Decodes a single string to a list of strings.
:type s: str
:rtype: List[str]
### Response:
def decode(s):
"""Decodes a single string to a list of strings.
:type s: str
:rtype: List[str]
"""
strs = []
i = 0
while i ... |
def temporary_eject_device(self, name, controller_port, device, temporary_eject):
"""Sets the behavior for guest-triggered medium eject. In some situations
it is desirable that such ejects update the VM configuration, and in
others the eject should keep the VM configuration. The device must
... | Sets the behavior for guest-triggered medium eject. In some situations
it is desirable that such ejects update the VM configuration, and in
others the eject should keep the VM configuration. The device must
already exist; see :py:func:`IMachine.attach_device` for how to
attach a new dev... | Below is the the instruction that describes the task:
### Input:
Sets the behavior for guest-triggered medium eject. In some situations
it is desirable that such ejects update the VM configuration, and in
others the eject should keep the VM configuration. The device must
already exist; see :... |
def to_html(self, codebase):
"""
Convert this to HTML.
"""
html = ''
def build_line(key, include_pred, format_fn):
val = getattr(self, key)
if include_pred(val):
return '<dt>%s</dt><dd>%s</dd>\n' % (printable(key), format_fn(val))
... | Convert this to HTML. | Below is the the instruction that describes the task:
### Input:
Convert this to HTML.
### Response:
def to_html(self, codebase):
"""
Convert this to HTML.
"""
html = ''
def build_line(key, include_pred, format_fn):
val = getattr(self, key)
if include... |
def parseCmdline(rh):
"""
Parse the request command input.
Input:
Request Handle
Output:
Request Handle updated with parsed input.
Return code - 0: ok, non-zero: error
"""
rh.printSysLog("Enter cmdVM.parseCmdline")
if rh.totalParms >= 2:
rh.userid = rh.reques... | Parse the request command input.
Input:
Request Handle
Output:
Request Handle updated with parsed input.
Return code - 0: ok, non-zero: error | Below is the the instruction that describes the task:
### Input:
Parse the request command input.
Input:
Request Handle
Output:
Request Handle updated with parsed input.
Return code - 0: ok, non-zero: error
### Response:
def parseCmdline(rh):
"""
Parse the request command inp... |
def delete_empty_children(self):
"""
Walk through the children of this node and delete any that are empty.
"""
for child in self.children:
child.delete_empty_children()
try:
if os.path.exists(child.full_path):
os.rmdir(child.ful... | Walk through the children of this node and delete any that are empty. | Below is the the instruction that describes the task:
### Input:
Walk through the children of this node and delete any that are empty.
### Response:
def delete_empty_children(self):
"""
Walk through the children of this node and delete any that are empty.
"""
for child in self.child... |
def put(self, account_id, user_id):
""" Only the primary on the account can add or remove user's access to an account
:param account_id: int of the account_id for the account
:param user_id: int of the user_id to grant access
:return: Access dict
"""
return s... | Only the primary on the account can add or remove user's access to an account
:param account_id: int of the account_id for the account
:param user_id: int of the user_id to grant access
:return: Access dict | Below is the the instruction that describes the task:
### Input:
Only the primary on the account can add or remove user's access to an account
:param account_id: int of the account_id for the account
:param user_id: int of the user_id to grant access
:return: Access dict
### Res... |
def do_cld_check(self, cld):
"""
Do the "clause :math:`D`" check. This method receives a list of
literals, which serves a "clause :math:`D`" [1]_, and checks
whether the formula conjoined with :math:`D` is satisfiable.
If clause :math:`D` cannot be satisfied toge... | Do the "clause :math:`D`" check. This method receives a list of
literals, which serves a "clause :math:`D`" [1]_, and checks
whether the formula conjoined with :math:`D` is satisfiable.
If clause :math:`D` cannot be satisfied together with the formula,
then negations of ... | Below is the the instruction that describes the task:
### Input:
Do the "clause :math:`D`" check. This method receives a list of
literals, which serves a "clause :math:`D`" [1]_, and checks
whether the formula conjoined with :math:`D` is satisfiable.
If clause :math:`D` cannot b... |
def wrap_text(text, width=80):
"""Wrap text lines to maximum *width* characters.
Wrapped text is aligned against the left text border.
Args:
text (str): Text to wrap.
width (int): Maximum number of characters per line.
Returns:
str: Wrapped text.
"""
text =... | Wrap text lines to maximum *width* characters.
Wrapped text is aligned against the left text border.
Args:
text (str): Text to wrap.
width (int): Maximum number of characters per line.
Returns:
str: Wrapped text. | Below is the the instruction that describes the task:
### Input:
Wrap text lines to maximum *width* characters.
Wrapped text is aligned against the left text border.
Args:
text (str): Text to wrap.
width (int): Maximum number of characters per line.
Returns:
str: Wrap... |
def set_stringprep_cache_size(size):
"""Modify stringprep cache size.
:Parameters:
- `size`: new cache size
"""
# pylint: disable-msg=W0603
global _stringprep_cache_size
_stringprep_cache_size = size
if len(Profile.cache_items) > size:
remove = Profile.cache_items[:-size]
... | Modify stringprep cache size.
:Parameters:
- `size`: new cache size | Below is the the instruction that describes the task:
### Input:
Modify stringprep cache size.
:Parameters:
- `size`: new cache size
### Response:
def set_stringprep_cache_size(size):
"""Modify stringprep cache size.
:Parameters:
- `size`: new cache size
"""
# pylint: disable-... |
def flush(self, save_index=False, save_model=False, clear_buffer=False):
"""Commit all changes, clear all caches."""
if save_index:
if self.fresh_index is not None:
self.fresh_index.save(self.location('index_fresh'))
if self.opt_index is not None:
... | Commit all changes, clear all caches. | Below is the the instruction that describes the task:
### Input:
Commit all changes, clear all caches.
### Response:
def flush(self, save_index=False, save_model=False, clear_buffer=False):
"""Commit all changes, clear all caches."""
if save_index:
if self.fresh_index is not None:
... |
def _summarize_result(result, config):
""" Trim out some data to return for the index page """
timing_var = config['scaling_var']
summary = LIVVDict()
for size, res in result.items():
proc_counts = []
bench_times = []
model_times = []
for proc, data in res.items():
... | Trim out some data to return for the index page | Below is the the instruction that describes the task:
### Input:
Trim out some data to return for the index page
### Response:
def _summarize_result(result, config):
""" Trim out some data to return for the index page """
timing_var = config['scaling_var']
summary = LIVVDict()
for size, res in resu... |
def execute(self):
"""
Starts a new cluster.
"""
cluster_template = self.params.cluster
if self.params.cluster_name:
cluster_name = self.params.cluster_name
else:
cluster_name = self.params.cluster
creator = make_creator(self.params.confi... | Starts a new cluster. | Below is the the instruction that describes the task:
### Input:
Starts a new cluster.
### Response:
def execute(self):
"""
Starts a new cluster.
"""
cluster_template = self.params.cluster
if self.params.cluster_name:
cluster_name = self.params.cluster_name
... |
def rareness2(self, password, min_word_fragment_length=3, commonness_of_non_word=50000):
"""
A logical way to calculate rareness, but the speed is illogical for length > 40.
(length 45: 60 sec per test)
:param password:
:param int min_word_fragment_length:
:param int com... | A logical way to calculate rareness, but the speed is illogical for length > 40.
(length 45: 60 sec per test)
:param password:
:param int min_word_fragment_length:
:param int commonness_of_non_word: an arbitrary value to improve commonness of 'poison'
:return int: in range 0-1
... | Below is the the instruction that describes the task:
### Input:
A logical way to calculate rareness, but the speed is illogical for length > 40.
(length 45: 60 sec per test)
:param password:
:param int min_word_fragment_length:
:param int commonness_of_non_word: an arbitrary value ... |
def quote(code):
"""Returns quoted code if not already quoted and if possible
Parameters
----------
code: String
\tCode thta is quoted
"""
try:
code = code.rstrip()
except AttributeError:
# code is not a string, may be None --> There is no code to quote
retur... | Returns quoted code if not already quoted and if possible
Parameters
----------
code: String
\tCode thta is quoted | Below is the the instruction that describes the task:
### Input:
Returns quoted code if not already quoted and if possible
Parameters
----------
code: String
\tCode thta is quoted
### Response:
def quote(code):
"""Returns quoted code if not already quoted and if possible
Parameters
-... |
def open(self, **params):
"""Open telnet connection
Args:
params (dict), must contain two parameters "ip" - ip address or hostname and "port" - port number
Example:
params = {'port': 23, 'ip': 'localhost'}
"""
logger.info('opening telnet')
self.p... | Open telnet connection
Args:
params (dict), must contain two parameters "ip" - ip address or hostname and "port" - port number
Example:
params = {'port': 23, 'ip': 'localhost'} | Below is the the instruction that describes the task:
### Input:
Open telnet connection
Args:
params (dict), must contain two parameters "ip" - ip address or hostname and "port" - port number
Example:
params = {'port': 23, 'ip': 'localhost'}
### Response:
def open(self, **... |
def _parse_sparkml(spark, scope, model, global_inputs, output_dict):
'''
This is a delegate function. It doesn't nothing but invoke the correct parsing function according to the input
model's type.
:param scope: Scope object
:param model: A spark-ml object (e.g., OneHotEncoder and LogisticRegression... | This is a delegate function. It doesn't nothing but invoke the correct parsing function according to the input
model's type.
:param scope: Scope object
:param model: A spark-ml object (e.g., OneHotEncoder and LogisticRegression)
:param inputs: A list of variables
:return: The output variables produc... | Below is the the instruction that describes the task:
### Input:
This is a delegate function. It doesn't nothing but invoke the correct parsing function according to the input
model's type.
:param scope: Scope object
:param model: A spark-ml object (e.g., OneHotEncoder and LogisticRegression)
:param... |
def convert_symbol_to_entrezid(self, symbol):
"""Convert Symbol to Entrez Gene Id"""
entrezdict = {}
server = "http://rest.genenames.org/fetch/symbol/{0}".format(symbol)
r = requests.get(server, headers={"Content-Type": "application/json"})
if not r.ok:
r.raise_for_st... | Convert Symbol to Entrez Gene Id | Below is the the instruction that describes the task:
### Input:
Convert Symbol to Entrez Gene Id
### Response:
def convert_symbol_to_entrezid(self, symbol):
"""Convert Symbol to Entrez Gene Id"""
entrezdict = {}
server = "http://rest.genenames.org/fetch/symbol/{0}".format(symbol)
r... |
def import_corpus(self, corpus_name, local_path=None, branch='master'): # pylint: disable=R0912
"""Download a remote or load local corpus into dir ``~/cltk_data``.
TODO: maybe add ``from git import RemoteProgress``
TODO: refactor this, it's getting kinda long
:type corpus_name: str
... | Download a remote or load local corpus into dir ``~/cltk_data``.
TODO: maybe add ``from git import RemoteProgress``
TODO: refactor this, it's getting kinda long
:type corpus_name: str
:param corpus_name: The name of an available corpus.
:param local_path: str
:param local... | Below is the the instruction that describes the task:
### Input:
Download a remote or load local corpus into dir ``~/cltk_data``.
TODO: maybe add ``from git import RemoteProgress``
TODO: refactor this, it's getting kinda long
:type corpus_name: str
:param corpus_name: The name of an ... |
def FrameworkDir64(self):
"""
Microsoft .NET Framework 64bit directory.
"""
# Default path
guess_fw = os.path.join(self.WinDir, r'Microsoft.NET\Framework64')
# Try to get path from registry, if fail use default path
return self.ri.lookup(self.ri.vc, 'frameworkdir... | Microsoft .NET Framework 64bit directory. | Below is the the instruction that describes the task:
### Input:
Microsoft .NET Framework 64bit directory.
### Response:
def FrameworkDir64(self):
"""
Microsoft .NET Framework 64bit directory.
"""
# Default path
guess_fw = os.path.join(self.WinDir, r'Microsoft.NET\Framework6... |
def delete_cluster_role_binding(self, name, **kwargs): # noqa: E501
"""delete_cluster_role_binding # noqa: E501
delete a ClusterRoleBinding # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>... | delete_cluster_role_binding # noqa: E501
delete a ClusterRoleBinding # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.delete_cluster_role_binding(name, async_req=True)
>>> re... | Below is the the instruction that describes the task:
### Input:
delete_cluster_role_binding # noqa: E501
delete a ClusterRoleBinding # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread =... |
def get_rsa_key(path, passphrase):
'''
Read a private key off the disk. Poor man's simple cache in effect here,
we memoize the result of calling _get_rsa_with_evict. This means the first
time _get_key_with_evict is called with a path and a timestamp the result
is cached. If the file (the private ... | Read a private key off the disk. Poor man's simple cache in effect here,
we memoize the result of calling _get_rsa_with_evict. This means the first
time _get_key_with_evict is called with a path and a timestamp the result
is cached. If the file (the private key) does not change then its
timestamp wil... | Below is the the instruction that describes the task:
### Input:
Read a private key off the disk. Poor man's simple cache in effect here,
we memoize the result of calling _get_rsa_with_evict. This means the first
time _get_key_with_evict is called with a path and a timestamp the result
is cached. If ... |
def error_router(self, original_handler, e):
"""This function decides whether the error occured in a flask-restful
endpoint or not. If it happened in a flask-restful endpoint, our
handler will be dispatched. If it happened in an unrelated view, the
app's original error handler will be di... | This function decides whether the error occured in a flask-restful
endpoint or not. If it happened in a flask-restful endpoint, our
handler will be dispatched. If it happened in an unrelated view, the
app's original error handler will be dispatched.
In the event that the error occurred i... | Below is the the instruction that describes the task:
### Input:
This function decides whether the error occured in a flask-restful
endpoint or not. If it happened in a flask-restful endpoint, our
handler will be dispatched. If it happened in an unrelated view, the
app's original error handl... |
def _MergeMessageField(self, tokenizer, message, field):
"""Merges a single scalar field into a message.
Args:
tokenizer: A tokenizer to parse the field value.
message: The message of which field is a member.
field: The descriptor of the field to be merged.
Raises:
ParseError: In c... | Merges a single scalar field into a message.
Args:
tokenizer: A tokenizer to parse the field value.
message: The message of which field is a member.
field: The descriptor of the field to be merged.
Raises:
ParseError: In case of text parsing problems. | Below is the the instruction that describes the task:
### Input:
Merges a single scalar field into a message.
Args:
tokenizer: A tokenizer to parse the field value.
message: The message of which field is a member.
field: The descriptor of the field to be merged.
Raises:
ParseError:... |
def makefig(code, code_path, output_dir, output_base, config):
"""
Run a pyplot script *code* and save the images under *output_dir*
with file names derived from *output_base*
"""
# -- Parse format list
default_dpi = {'png': 80, 'hires.png': 200, 'pdf': 50}
formats = []
for fmt in conf... | Run a pyplot script *code* and save the images under *output_dir*
with file names derived from *output_base* | Below is the the instruction that describes the task:
### Input:
Run a pyplot script *code* and save the images under *output_dir*
with file names derived from *output_base*
### Response:
def makefig(code, code_path, output_dir, output_base, config):
"""
Run a pyplot script *code* and save the images u... |
def _cost_gp(self,x):
"""
Predicts the time cost of evaluating the function at x.
"""
m, _, _, _ = self.cost_model.predict_withGradients(x)
return np.exp(m) | Predicts the time cost of evaluating the function at x. | Below is the the instruction that describes the task:
### Input:
Predicts the time cost of evaluating the function at x.
### Response:
def _cost_gp(self,x):
"""
Predicts the time cost of evaluating the function at x.
"""
m, _, _, _ = self.cost_model.predict_withGradients(x)
... |
def authenticate_storage(client_secrets, read_only=False):
"""Authenticates a service account for reading and/or writing on a bucket.
TODO: docstring"""
if read_only:
scopes = ['https://www.googleapis.com/auth/devstorage.read_only']
else:
scopes = ['https://www.googleapis.com/auth/d... | Authenticates a service account for reading and/or writing on a bucket.
TODO: docstring | Below is the the instruction that describes the task:
### Input:
Authenticates a service account for reading and/or writing on a bucket.
TODO: docstring
### Response:
def authenticate_storage(client_secrets, read_only=False):
"""Authenticates a service account for reading and/or writing on a bucket.
... |
def should_particle_exist(absent_err, present_err, absent_d, present_d,
im_change_frac=0.2, min_derr=0.1):
"""
Checks whether or not adding a particle should be present.
Parameters
----------
absent_err : Float
The state error without the particle.
present_err ... | Checks whether or not adding a particle should be present.
Parameters
----------
absent_err : Float
The state error without the particle.
present_err : Float
The state error with the particle.
absent_d : numpy.ndarray
The state residuals without the particle.
present_d :... | Below is the the instruction that describes the task:
### Input:
Checks whether or not adding a particle should be present.
Parameters
----------
absent_err : Float
The state error without the particle.
present_err : Float
The state error with the particle.
absent_d : numpy.ndar... |
def high(self):
"""Gets highest priority. Performance: O(1)"""
with self.lock:
try:
return self.data[0][1]
except IndexError as ex:
ex.args = ('DEPQ is empty',)
raise | Gets highest priority. Performance: O(1) | Below is the the instruction that describes the task:
### Input:
Gets highest priority. Performance: O(1)
### Response:
def high(self):
"""Gets highest priority. Performance: O(1)"""
with self.lock:
try:
return self.data[0][1]
except IndexError as ex:
... |
def spark_shape(points, shapes, fill=None, color='blue', width=5, yindex=0, heights=None):
"""TODO: Docstring for spark.
Parameters
----------
points : array-like
shapes : array-like
fill : array-like, optional
Returns
-------
Chart
"""
assert len(points) == len(shapes) + ... | TODO: Docstring for spark.
Parameters
----------
points : array-like
shapes : array-like
fill : array-like, optional
Returns
-------
Chart | Below is the the instruction that describes the task:
### Input:
TODO: Docstring for spark.
Parameters
----------
points : array-like
shapes : array-like
fill : array-like, optional
Returns
-------
Chart
### Response:
def spark_shape(points, shapes, fill=None, color='blue', width=... |
def hex(self):
"""Hexideciaml representation of the message in bytes."""
props = self._message_properties()
msg = bytearray([MESSAGE_START_CODE_0X02, self._code])
for prop in props:
# pylint: disable=unused-variable
for key, val in prop.items():
i... | Hexideciaml representation of the message in bytes. | Below is the the instruction that describes the task:
### Input:
Hexideciaml representation of the message in bytes.
### Response:
def hex(self):
"""Hexideciaml representation of the message in bytes."""
props = self._message_properties()
msg = bytearray([MESSAGE_START_CODE_0X02, self._code... |
def rollback(self, date):
"""Roll date backward to nearest end of year"""
if self.onOffset(date):
return date
else:
return date - YearEnd(month=self.month) | Roll date backward to nearest end of year | Below is the the instruction that describes the task:
### Input:
Roll date backward to nearest end of year
### Response:
def rollback(self, date):
"""Roll date backward to nearest end of year"""
if self.onOffset(date):
return date
else:
return date - YearEnd(month=se... |
def generate_simpleaccount(self):
"""make a simple account with a easier way
如果当前user中没有创建portfolio, 则创建一个portfolio,并用此portfolio创建一个account
如果已有一个或多个portfolio,则使用第一个portfolio来创建一个account
"""
if len(self.portfolio_list.keys()) < 1:
po = self.new_portfolio()
els... | make a simple account with a easier way
如果当前user中没有创建portfolio, 则创建一个portfolio,并用此portfolio创建一个account
如果已有一个或多个portfolio,则使用第一个portfolio来创建一个account | Below is the the instruction that describes the task:
### Input:
make a simple account with a easier way
如果当前user中没有创建portfolio, 则创建一个portfolio,并用此portfolio创建一个account
如果已有一个或多个portfolio,则使用第一个portfolio来创建一个account
### Response:
def generate_simpleaccount(self):
"""make a simple account wit... |
def db_value(self, value):
"""Convert the Pendulum instance to a datetime for saving in the db."""
if isinstance(value, pendulum.Pendulum):
value = datetime.datetime(
value.year, value.month, value.day, value.hour, value.minute,
value.second, value.microsecond... | Convert the Pendulum instance to a datetime for saving in the db. | Below is the the instruction that describes the task:
### Input:
Convert the Pendulum instance to a datetime for saving in the db.
### Response:
def db_value(self, value):
"""Convert the Pendulum instance to a datetime for saving in the db."""
if isinstance(value, pendulum.Pendulum):
va... |
def _get_key_internal(self, *args, **kwargs):
"""Return None if key is not in the bucket set.
Pass 'force' in the headers to check S3 for the key, and after fetching
the key from S3, save the metadata and key to the bucket set.
"""
if args[1] is not None and 'force' in args[1]:
... | Return None if key is not in the bucket set.
Pass 'force' in the headers to check S3 for the key, and after fetching
the key from S3, save the metadata and key to the bucket set. | Below is the the instruction that describes the task:
### Input:
Return None if key is not in the bucket set.
Pass 'force' in the headers to check S3 for the key, and after fetching
the key from S3, save the metadata and key to the bucket set.
### Response:
def _get_key_internal(self, *args, **kwa... |
def sample(self, n, mass_min=0.1, mass_max=10., steps=10000, seed=None):
"""
Sample initial mass values between mass_min and mass_max,
following the IMF distribution.
ADW: Should this be `sample` or `simulate`?
Parameters:
-----------
n : number of samples to dr... | Sample initial mass values between mass_min and mass_max,
following the IMF distribution.
ADW: Should this be `sample` or `simulate`?
Parameters:
-----------
n : number of samples to draw
mass_min : minimum mass to sample from
mass_max : maximum mass to sample f... | Below is the the instruction that describes the task:
### Input:
Sample initial mass values between mass_min and mass_max,
following the IMF distribution.
ADW: Should this be `sample` or `simulate`?
Parameters:
-----------
n : number of samples to draw
mass_min : mi... |
def mouseDoubleClickEvent( self, event ):
"""
Handles the mouse double click event.
:param event | <QMouseEvent>
"""
scene_point = self.mapToScene(event.pos())
date = self.scene().dateAt(scene_point)
date_time = self.scene().dateTime... | Handles the mouse double click event.
:param event | <QMouseEvent> | Below is the the instruction that describes the task:
### Input:
Handles the mouse double click event.
:param event | <QMouseEvent>
### Response:
def mouseDoubleClickEvent( self, event ):
"""
Handles the mouse double click event.
:param event | <QMo... |
def _input_as_dict(self, data):
"""Takes dictionary that sets input and output files.
Valid keys for the dictionary are specified in the subclasses. File
paths must be absolute.
"""
# clear self._input; ready to receive new input and output files
self._input = {}
... | Takes dictionary that sets input and output files.
Valid keys for the dictionary are specified in the subclasses. File
paths must be absolute. | Below is the the instruction that describes the task:
### Input:
Takes dictionary that sets input and output files.
Valid keys for the dictionary are specified in the subclasses. File
paths must be absolute.
### Response:
def _input_as_dict(self, data):
"""Takes dictionary that sets input ... |
def cornerbound(results, it=None, idx=None, prior_transform=None,
periodic=None, ndraws=5000, color='gray', plot_kwargs=None,
labels=None, label_kwargs=None, max_n_ticks=5,
use_math_text=False, show_live=False, live_color='darkviolet',
live_kwargs=None, sp... | Return the bounding distribution used to propose either (1) live points
at a given iteration or (2) a specific dead point during
the course of a run, projected onto all pairs of dimensions.
Parameters
----------
results : :class:`~dynesty.results.Results` instance
A :class:`~dynesty.results... | Below is the the instruction that describes the task:
### Input:
Return the bounding distribution used to propose either (1) live points
at a given iteration or (2) a specific dead point during
the course of a run, projected onto all pairs of dimensions.
Parameters
----------
results : :class:`... |
def _post_action(self, action):
"""Do any housekeeping after taking an action."""
reward = self.reward(action)
# done if number of elapsed timesteps is greater than horizon
self.done = (self.timestep >= self.horizon) and not self.ignore_done
return reward, self.done, {} | Do any housekeeping after taking an action. | Below is the the instruction that describes the task:
### Input:
Do any housekeeping after taking an action.
### Response:
def _post_action(self, action):
"""Do any housekeeping after taking an action."""
reward = self.reward(action)
# done if number of elapsed timesteps is greater than ho... |
def from_events(self, instance, ev_args, ctx):
"""
Like :meth:`.ChildList.from_events`, but the object is appended to the
list associated with its tag in the dict.
"""
tag = ev_args[0], ev_args[1]
cls = self._tag_map[tag]
obj = yield from cls.parse_events(ev_args... | Like :meth:`.ChildList.from_events`, but the object is appended to the
list associated with its tag in the dict. | Below is the the instruction that describes the task:
### Input:
Like :meth:`.ChildList.from_events`, but the object is appended to the
list associated with its tag in the dict.
### Response:
def from_events(self, instance, ev_args, ctx):
"""
Like :meth:`.ChildList.from_events`, but the obj... |
def is_not_exist_or_allow_overwrite(self, overwrite=False):
"""
Test whether a file target is not exists or it exists but allow
overwrite.
"""
if self.exists() and overwrite is False:
return False
else: # pragma: no cover
return True | Test whether a file target is not exists or it exists but allow
overwrite. | Below is the the instruction that describes the task:
### Input:
Test whether a file target is not exists or it exists but allow
overwrite.
### Response:
def is_not_exist_or_allow_overwrite(self, overwrite=False):
"""
Test whether a file target is not exists or it exists but allow
o... |
def _refresh_converters(self):
""" Refresh all of the converters in the py4j library
@return: True if all converters were succesfully updated
"""
self._converters.clear()
return reduce(lambda a, b: a and b, [self._add_converter(k) for k in list(self._xsltLibrary.keys())], True) | Refresh all of the converters in the py4j library
@return: True if all converters were succesfully updated | Below is the the instruction that describes the task:
### Input:
Refresh all of the converters in the py4j library
@return: True if all converters were succesfully updated
### Response:
def _refresh_converters(self):
""" Refresh all of the converters in the py4j library
@return: True if all... |
def pop(self, index=None):
"""Removes an element at the tail of the OrderedSet or at a dedicated
position.
This implementation is meant for the OrderedSet from the ordered_set
package only.
"""
if not self.items:
raise KeyError('Set is empty')
def remove_index(i):
elem = se... | Removes an element at the tail of the OrderedSet or at a dedicated
position.
This implementation is meant for the OrderedSet from the ordered_set
package only. | Below is the the instruction that describes the task:
### Input:
Removes an element at the tail of the OrderedSet or at a dedicated
position.
This implementation is meant for the OrderedSet from the ordered_set
package only.
### Response:
def pop(self, index=None):
"""Removes an element at the tai... |
def makefractalCIJ(mx_lvl, E, sz_cl, seed=None):
'''
This function generates a directed network with a hierarchical modular
organization. All modules are fully connected and connection density
decays as 1/(E^n), with n = index of hierarchical level.
Parameters
----------
mx_lvl : int
... | This function generates a directed network with a hierarchical modular
organization. All modules are fully connected and connection density
decays as 1/(E^n), with n = index of hierarchical level.
Parameters
----------
mx_lvl : int
number of hierarchical levels, N = 2^mx_lvl
E : int
... | Below is the the instruction that describes the task:
### Input:
This function generates a directed network with a hierarchical modular
organization. All modules are fully connected and connection density
decays as 1/(E^n), with n = index of hierarchical level.
Parameters
----------
mx_lvl : in... |
def _sending_task(self, backend):
"""
Used internally to safely increment `backend`s task count. Returns the
overall count of tasks for `backend`.
"""
with self.backend_mutex:
self.backends[backend] += 1
self.task_counter[backend] += 1
this_ta... | Used internally to safely increment `backend`s task count. Returns the
overall count of tasks for `backend`. | Below is the the instruction that describes the task:
### Input:
Used internally to safely increment `backend`s task count. Returns the
overall count of tasks for `backend`.
### Response:
def _sending_task(self, backend):
"""
Used internally to safely increment `backend`s task count. Retur... |
def get_all_credit_notes(self, params=None):
"""
Get all credit notes
This will iterate over all pages until it gets all elements.
So if the rate limit exceeded it will throw an Exception and you will get nothing
:param params: search params
:return: list
"""
... | Get all credit notes
This will iterate over all pages until it gets all elements.
So if the rate limit exceeded it will throw an Exception and you will get nothing
:param params: search params
:return: list | Below is the the instruction that describes the task:
### Input:
Get all credit notes
This will iterate over all pages until it gets all elements.
So if the rate limit exceeded it will throw an Exception and you will get nothing
:param params: search params
:return: list
### Respons... |
def concentric_circles_path(size):
"""
Yields a set of paths that are concentric circles, moving outwards, about the center of the image.
:param size: The (width, height) of the image
:return: Yields individual circles, where each circle is a generator that yields pixel coordinates.
"""
width, ... | Yields a set of paths that are concentric circles, moving outwards, about the center of the image.
:param size: The (width, height) of the image
:return: Yields individual circles, where each circle is a generator that yields pixel coordinates. | Below is the the instruction that describes the task:
### Input:
Yields a set of paths that are concentric circles, moving outwards, about the center of the image.
:param size: The (width, height) of the image
:return: Yields individual circles, where each circle is a generator that yields pixel coordinates... |
def write_equations_code(path, name, laser, omega, gamma, r, Lij, states=None,
excluded_mu=[], verbose=1):
r"""Write code for the equations."""
Ne = len(omega[0])
Nl = len(laser)
N_excluded_mu = len(excluded_mu)
if states is None: states = range(1, Ne+1)
omega_rescaled... | r"""Write code for the equations. | Below is the the instruction that describes the task:
### Input:
r"""Write code for the equations.
### Response:
def write_equations_code(path, name, laser, omega, gamma, r, Lij, states=None,
excluded_mu=[], verbose=1):
r"""Write code for the equations."""
Ne = len(omega[0])
Nl... |
def _commits(self, head='HEAD'):
"""Returns a list of the commits reachable from head.
:return: List of commit objects. the first of which will be the commit
of head, then following theat will be the parents.
:raise: RepoError if any no commits are referenced, including if the
... | Returns a list of the commits reachable from head.
:return: List of commit objects. the first of which will be the commit
of head, then following theat will be the parents.
:raise: RepoError if any no commits are referenced, including if the
head parameter isn't the sha of a commit. | Below is the the instruction that describes the task:
### Input:
Returns a list of the commits reachable from head.
:return: List of commit objects. the first of which will be the commit
of head, then following theat will be the parents.
:raise: RepoError if any no commits are referenced, ... |
def symmetrize_image(image):
"""
Use registration and reflection to make an image symmetric
ANTsR function: N/A
Arguments
---------
image : ANTsImage
image to make symmetric
Returns
-------
ANTsImage
Example
-------
>>> import ants
>>> image = ants.image_r... | Use registration and reflection to make an image symmetric
ANTsR function: N/A
Arguments
---------
image : ANTsImage
image to make symmetric
Returns
-------
ANTsImage
Example
-------
>>> import ants
>>> image = ants.image_read( ants.get_ants_data('r16') , 'float')... | Below is the the instruction that describes the task:
### Input:
Use registration and reflection to make an image symmetric
ANTsR function: N/A
Arguments
---------
image : ANTsImage
image to make symmetric
Returns
-------
ANTsImage
Example
-------
>>> import ants
... |
def generate_zip_data(M, L, n_cells, cluster_probs=None):
"""
Generates zero-inflated poisson-distributed data, given a set of means and zero probs for each cluster.
Args:
M (array): genes x clusters matrix
L (array): genes x clusters matrix - zero-inflation parameters
n_cells (int)... | Generates zero-inflated poisson-distributed data, given a set of means and zero probs for each cluster.
Args:
M (array): genes x clusters matrix
L (array): genes x clusters matrix - zero-inflation parameters
n_cells (int): number of output cells
cluster_probs (array): prior probabil... | Below is the the instruction that describes the task:
### Input:
Generates zero-inflated poisson-distributed data, given a set of means and zero probs for each cluster.
Args:
M (array): genes x clusters matrix
L (array): genes x clusters matrix - zero-inflation parameters
n_cells (int):... |
def add_summaries(self, step, *tags_and_values):
"""Adds summaries to the writer and prints a log statement."""
values = []
to_print = []
for tag, value in tags_and_values:
values.append(tf.Summary.Value(tag=tag, simple_value=float(value)))
to_print.append('%s=%g' % (tag, value))
if self... | Adds summaries to the writer and prints a log statement. | Below is the the instruction that describes the task:
### Input:
Adds summaries to the writer and prints a log statement.
### Response:
def add_summaries(self, step, *tags_and_values):
"""Adds summaries to the writer and prints a log statement."""
values = []
to_print = []
for tag, value in tags_an... |
def run(self, service_id, user_id, email, **kwargs):
"""
Create and Retrieve a token from remote service. Save to DB.
"""
log = self.get_logger(**kwargs)
log.info("Loading Service for token creation")
try:
service = Service.objects.get(id=service_id)
... | Create and Retrieve a token from remote service. Save to DB. | Below is the the instruction that describes the task:
### Input:
Create and Retrieve a token from remote service. Save to DB.
### Response:
def run(self, service_id, user_id, email, **kwargs):
"""
Create and Retrieve a token from remote service. Save to DB.
"""
log = self.get_logger... |
def chbder(cp, degp, x2s, x, nderiv):
"""
Given the coefficients for the Chebyshev expansion of a
polynomial, this returns the value of the polynomial and its
first nderiv derivatives evaluated at the input X.
https://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/chbder_c.html
:para... | Given the coefficients for the Chebyshev expansion of a
polynomial, this returns the value of the polynomial and its
first nderiv derivatives evaluated at the input X.
https://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/chbder_c.html
:param cp: degp+1 Chebyshev polynomial coefficients.
... | Below is the the instruction that describes the task:
### Input:
Given the coefficients for the Chebyshev expansion of a
polynomial, this returns the value of the polynomial and its
first nderiv derivatives evaluated at the input X.
https://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/chbder_c.... |
def info(self, *args, **kwargs):
"""Logs the line of the current thread owns the underlying lock, or
blocks."""
self.lock()
try:
return logger.info(*args, **kwargs)
finally:
self.unlock() | Logs the line of the current thread owns the underlying lock, or
blocks. | Below is the the instruction that describes the task:
### Input:
Logs the line of the current thread owns the underlying lock, or
blocks.
### Response:
def info(self, *args, **kwargs):
"""Logs the line of the current thread owns the underlying lock, or
blocks."""
self.lock()
... |
def get_fno_lot_sizes(self, cached=True, as_json=False):
"""
returns a dictionary with key as stock code and value as stock name.
It also implements cache functionality and hits the server only
if user insists or cache is empty
:return: dict
"""
url = self.fno_lot... | returns a dictionary with key as stock code and value as stock name.
It also implements cache functionality and hits the server only
if user insists or cache is empty
:return: dict | Below is the the instruction that describes the task:
### Input:
returns a dictionary with key as stock code and value as stock name.
It also implements cache functionality and hits the server only
if user insists or cache is empty
:return: dict
### Response:
def get_fno_lot_sizes(self, cac... |
def reduce_annotations(self, annotations, options):
"""Reduce annotations to ones used to identify enrichment (normally exclude ND and NOT)."""
getfnc_qual_ev = options.getfnc_qual_ev()
return [nt for nt in annotations if getfnc_qual_ev(nt.Qualifier, nt.Evidence_Code)] | Reduce annotations to ones used to identify enrichment (normally exclude ND and NOT). | Below is the the instruction that describes the task:
### Input:
Reduce annotations to ones used to identify enrichment (normally exclude ND and NOT).
### Response:
def reduce_annotations(self, annotations, options):
"""Reduce annotations to ones used to identify enrichment (normally exclude ND and NOT).""... |
def TerminateFlow(client_id,
flow_id,
reason=None,
flow_state=rdf_flow_objects.Flow.FlowState.ERROR):
"""Terminates a flow and all of its children.
Args:
client_id: Client ID of a flow to terminate.
flow_id: Flow ID of a flow to terminate.
reason: S... | Terminates a flow and all of its children.
Args:
client_id: Client ID of a flow to terminate.
flow_id: Flow ID of a flow to terminate.
reason: String with a termination reason.
flow_state: Flow state to be assigned to a flow after termination. Defaults
to FlowState.ERROR. | Below is the the instruction that describes the task:
### Input:
Terminates a flow and all of its children.
Args:
client_id: Client ID of a flow to terminate.
flow_id: Flow ID of a flow to terminate.
reason: String with a termination reason.
flow_state: Flow state to be assigned to a flow after t... |
def list_teams(profile="github", ignore_cache=False):
'''
Lists all teams with the organization.
profile
The name of the profile configuration to use. Defaults to ``github``.
ignore_cache
Bypasses the use of cached teams.
CLI Example:
.. code-block:: bash
salt mymini... | Lists all teams with the organization.
profile
The name of the profile configuration to use. Defaults to ``github``.
ignore_cache
Bypasses the use of cached teams.
CLI Example:
.. code-block:: bash
salt myminion github.list_teams
.. versionadded:: 2016.11.0 | Below is the the instruction that describes the task:
### Input:
Lists all teams with the organization.
profile
The name of the profile configuration to use. Defaults to ``github``.
ignore_cache
Bypasses the use of cached teams.
CLI Example:
.. code-block:: bash
salt mym... |
def _parse_metafiles(self, metafile_input):
"""
Parses class input and verifies metadata file names.
:param metafile_input: class input parameter `metafiles`
:type metafile_input: str or list(str) or None
:return: verified list of metadata files
:rtype: list(str)
... | Parses class input and verifies metadata file names.
:param metafile_input: class input parameter `metafiles`
:type metafile_input: str or list(str) or None
:return: verified list of metadata files
:rtype: list(str) | Below is the the instruction that describes the task:
### Input:
Parses class input and verifies metadata file names.
:param metafile_input: class input parameter `metafiles`
:type metafile_input: str or list(str) or None
:return: verified list of metadata files
:rtype: list(str)
##... |
def __patch_pipe_methods(tango_device_klass, pipe):
"""
Checks if the read and write methods have the correct signature.
If a read/write method doesn't have a parameter (the traditional
Pipe), then the method is wrapped into another method to make
this work.
:param tango_device_klass: a DeviceI... | Checks if the read and write methods have the correct signature.
If a read/write method doesn't have a parameter (the traditional
Pipe), then the method is wrapped into another method to make
this work.
:param tango_device_klass: a DeviceImpl class
:type tango_device_klass: class
:param pipe: t... | Below is the the instruction that describes the task:
### Input:
Checks if the read and write methods have the correct signature.
If a read/write method doesn't have a parameter (the traditional
Pipe), then the method is wrapped into another method to make
this work.
:param tango_device_klass: a De... |
def main():
"""
Run through simple demonstration of alarm concept
"""
alarm = XBeeAlarm('/dev/ttyUSB0', '\x56\x78')
routine = SimpleWakeupRoutine(alarm)
from time import sleep
while True:
"""
Run the routine with 10 second delays
"""
try:
print "W... | Run through simple demonstration of alarm concept | Below is the the instruction that describes the task:
### Input:
Run through simple demonstration of alarm concept
### Response:
def main():
"""
Run through simple demonstration of alarm concept
"""
alarm = XBeeAlarm('/dev/ttyUSB0', '\x56\x78')
routine = SimpleWakeupRoutine(alarm)
from tim... |
def _set_protocol_vrrp(self, v, load=False):
"""
Setter method for protocol_vrrp, mapped from YANG variable /protocol_vrrp (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_protocol_vrrp is considered as a private
method. Backends looking to populate this v... | Setter method for protocol_vrrp, mapped from YANG variable /protocol_vrrp (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_protocol_vrrp is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_protoco... | Below is the the instruction that describes the task:
### Input:
Setter method for protocol_vrrp, mapped from YANG variable /protocol_vrrp (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_protocol_vrrp is considered as a private
method. Backends looking to pop... |
def redefineBuffer(self, newBuffer ):
"""!
\~english
Redefine frame of Screen
@param newFrame: a new fram data
@note
newFrame can be:
* PIL Image
* PIL ImageFile
* Dictionary, eg. { "size":(width, height), "color_mode":"1" } or { "... | !
\~english
Redefine frame of Screen
@param newFrame: a new fram data
@note
newFrame can be:
* PIL Image
* PIL ImageFile
* Dictionary, eg. { "size":(width, height), "color_mode":"1" } or { "size":(width, height), "color_mode":"RGB" }
... | Below is the the instruction that describes the task:
### Input:
!
\~english
Redefine frame of Screen
@param newFrame: a new fram data
@note
newFrame can be:
* PIL Image
* PIL ImageFile
* Dictionary, eg. { "size":(width, height), "colo... |
def get_initial(self):
"""
Returns the initial data to use for forms on this view.
"""
initial = super(ProjectCopy, self).get_initial()
if self.copy_object:
initial.update({'name': '%s copy' % self.copy_object.name,
'description': self.copy... | Returns the initial data to use for forms on this view. | Below is the the instruction that describes the task:
### Input:
Returns the initial data to use for forms on this view.
### Response:
def get_initial(self):
"""
Returns the initial data to use for forms on this view.
"""
initial = super(ProjectCopy, self).get_initial()
if s... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.