code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def preprocess_abstract_list(self, abstract_list):
"""Preprocess abstracts in database pickle dump format for ISI reader.
For each abstract, creates a plain text file with one sentence per
line, and stores metadata to be included with each statement from
that abstract.
Paramete... | Preprocess abstracts in database pickle dump format for ISI reader.
For each abstract, creates a plain text file with one sentence per
line, and stores metadata to be included with each statement from
that abstract.
Parameters
----------
abstract_list : list[dict]
... |
def print_state(self):
"""Prints the current state."""
def tile_string(value):
"""Concert value to string."""
if value > 0:
return '% 5d' % (2 ** value,)
return " "
separator_line = '-' * 25
print(separator_line)
for row i... | Prints the current state. |
def add_service(self, zeroconf, service_type, name):
"""Handle callback from zeroconf when a service has been discovered."""
self.lock.acquire()
try:
self._internal_add(zeroconf, service_type, name)
finally:
self.lock.release() | Handle callback from zeroconf when a service has been discovered. |
def set_file(self, file=None, is_modified=False, is_untitled=False):
"""
Sets the editor file.
:param File: File to set.
:type File: unicode
:param is_modified: File modified state.
:type is_modified: bool
:param is_untitled: File untitled state.
:type is... | Sets the editor file.
:param File: File to set.
:type File: unicode
:param is_modified: File modified state.
:type is_modified: bool
:param is_untitled: File untitled state.
:type is_untitled: bool
:return: Method success.
:rtype: bool |
def katex_rendering_options(app):
"""Strip katex_options from enclosing {} and append ,"""
options = trim(app.config.katex_options)
# Remove surrounding {}
if options.startswith('{') and options.endswith('}'):
options = trim(options[1:-1])
# If options is not empty, ensure it ends with ','
... | Strip katex_options from enclosing {} and append , |
def get_profile_model():
"""
Returns configured user profile model or None if not found
"""
user_profile_module = getattr(settings, 'USER_PROFILE_MODULE', None)
if user_profile_module:
app_label, model_name = user_profile_module.split('.')
return get_model(app_label, model_name)
... | Returns configured user profile model or None if not found |
def successful(self):
"""Return True if the job finished with a COMPLETED status, False if it
finished with a CANCELLED or FAILED status. Raise an `AssertionError`
if the job has not completed"""
status = self.status
assert status >= COMPLETED, "status is %s" % status
ret... | Return True if the job finished with a COMPLETED status, False if it
finished with a CANCELLED or FAILED status. Raise an `AssertionError`
if the job has not completed |
def get_int_value(self, section, option, default=0):
"""Get the int value of an option, if it exists."""
try:
return self.parser.getint(section, option)
except NoOptionError:
return int(default) | Get the int value of an option, if it exists. |
def __merge_json_values(current, previous):
"""Merges the values between the current and previous run of the script."""
for value in current:
name = value['name']
# Find the previous value
previous_value = __find_and_remove_value(previous, value)
if previous_value is not None:
... | Merges the values between the current and previous run of the script. |
def with_argparser_and_unknown_args(argparser: argparse.ArgumentParser, preserve_quotes: bool = False) -> \
Callable[[argparse.Namespace, List], Optional[bool]]:
"""A decorator to alter a cmd2 method to populate its ``args`` argument by parsing arguments with the given
instance of argparse.ArgumentParse... | A decorator to alter a cmd2 method to populate its ``args`` argument by parsing arguments with the given
instance of argparse.ArgumentParser, but also returning unknown args as a list.
:param argparser: unique instance of ArgumentParser
:param preserve_quotes: if True, then arguments passed to argparse mai... |
def is_valid_device_id(device_id):
""" Check if device identifier is valid.
A valid device identifier contains only ascii word characters or dashes.
:param device_id: Device identifier
:returns: Valid or not.
"""
valid = valid_device_id.match(device_id)
if not valid:
logging.error(... | Check if device identifier is valid.
A valid device identifier contains only ascii word characters or dashes.
:param device_id: Device identifier
:returns: Valid or not. |
def create_property(self, model, name, description=None, property_type=PropertyType.CHAR_VALUE, default_value=None,
unit=None, options=None):
"""Create a new property model under a given model.
Use the :class:`enums.PropertyType` to select which property type to create to ensure... | Create a new property model under a given model.
Use the :class:`enums.PropertyType` to select which property type to create to ensure that you
provide the correct values to the KE-chain backend. The default is a `PropertyType.CHAR_VALUE` which is a
single line text in KE-chain.
:param... |
def do_macro(self, args: argparse.Namespace) -> None:
"""Manage macros"""
func = getattr(args, 'func', None)
if func is not None:
# Call whatever sub-command function was selected
func(self, args)
else:
# No sub-command was provided, so call help
... | Manage macros |
def insert_data(self, data, include_index=False, index_name=None):
""" Insert the contents of a Pandas DataFrame or a list of dictionaries into the table.
The insertion will be performed using at most 500 rows per POST, and at most 10 POSTs per
second, as BigQuery has some limits on streaming rates.
A... | Insert the contents of a Pandas DataFrame or a list of dictionaries into the table.
The insertion will be performed using at most 500 rows per POST, and at most 10 POSTs per
second, as BigQuery has some limits on streaming rates.
Args:
data: the DataFrame or list to insert.
include_index: whet... |
def traverse_extract_fetch(config, wukey, stop_after_extraction=False):
'''Given a config and a
`wukey=cbor.dumps((folder_name,subfolder_name))`, traverse the
folders to generate queries, issue them to Google, fetch the
results, and ingest them.
'''
config.kvlclient.setup_namespace({'openquery... | Given a config and a
`wukey=cbor.dumps((folder_name,subfolder_name))`, traverse the
folders to generate queries, issue them to Google, fetch the
results, and ingest them. |
def example_lchab_to_lchuv():
"""
This function shows very complex chain of conversions in action.
LCHab to LCHuv involves four different calculations, making this the
conversion requiring the most steps.
"""
print("=== Complex Example: LCHab->LCHuv ===")
# Instantiate an LCHab color objec... | This function shows very complex chain of conversions in action.
LCHab to LCHuv involves four different calculations, making this the
conversion requiring the most steps. |
def does_row_exist(self, table: str, field: str, value: Any) -> bool:
"""Checks for the existence of a record by a single field (typically a
PK)."""
sql = ("SELECT COUNT(*) FROM " + self.delimit(table) +
" WHERE " + self.delimit(field) + "=?")
row = self.fetchone(sql, valu... | Checks for the existence of a record by a single field (typically a
PK). |
def issubset(list1, list2):
"""
Examples:
>>> issubset([], [65, 66, 67])
True
>>> issubset([65], [65, 66, 67])
True
>>> issubset([65, 66], [65, 66, 67])
True
>>> issubset([65, 67], [65, 66, 67])
False
"""
n = len(list1)
for startpos in range(len(list2) - n + 1):
... | Examples:
>>> issubset([], [65, 66, 67])
True
>>> issubset([65], [65, 66, 67])
True
>>> issubset([65, 66], [65, 66, 67])
True
>>> issubset([65, 67], [65, 66, 67])
False |
def restore_state(self, state):
"""Restore the current state of this emulated device.
Args:
state (dict): A previously dumped state produced by dump_state.
"""
tile_states = state.get('tile_states', {})
for address, tile_state in tile_states.items():
ad... | Restore the current state of this emulated device.
Args:
state (dict): A previously dumped state produced by dump_state. |
def sort_tags_by_date(self, tags):
"""
Sort all tags by date.
:param list(dict) tags: All tags.
:rtype: list(dict)
:return: Sorted list of tags.
"""
if self.options.verbose:
print("Sorting tags...")
tags.sort(key=lambda x: self.get_time_of_ta... | Sort all tags by date.
:param list(dict) tags: All tags.
:rtype: list(dict)
:return: Sorted list of tags. |
def deps_status(self):
"""Returns a list with the status of the dependencies."""
if not self.deps:
return [self.S_OK]
return [d.status for d in self.deps] | Returns a list with the status of the dependencies. |
def xml(self, indent = ""):
"""This methods renders an XML representation of this parameter, along with
its selected value, and feedback on validation errors"""
xml = indent + "<" + self.__class__.__name__
xml += ' id="'+self.id + '"'
xml += ' name="'+xmlescape(self.name) + '"'
... | This methods renders an XML representation of this parameter, along with
its selected value, and feedback on validation errors |
def resolve(self, current_file, rel_path):
"""Search the filesystem."""
search_path = [path.dirname(current_file)] + self.search_path
target_path = None
for search in search_path:
if self.exists(path.join(search, rel_path)):
target_path = path.normpath(path.join(search, rel_path))
... | Search the filesystem. |
def BBI(Series, N1, N2, N3, N4):
'多空指标'
bbi = (MA(Series, N1) + MA(Series, N2) +
MA(Series, N3) + MA(Series, N4)) / 4
DICT = {'BBI': bbi}
VAR = pd.DataFrame(DICT)
return VAR | 多空指标 |
def edge_nei_overlap_bu(CIJ):
'''
This function determines the neighbors of two nodes that are linked by
an edge, and then computes their overlap. Connection matrix must be
binary and directed. Entries of 'EC' that are 'inf' indicate that no
edge is present. Entries of 'EC' that are 0 denote "loc... | This function determines the neighbors of two nodes that are linked by
an edge, and then computes their overlap. Connection matrix must be
binary and directed. Entries of 'EC' that are 'inf' indicate that no
edge is present. Entries of 'EC' that are 0 denote "local bridges", i.e.
edges that link comp... |
def translate(cls, val):
"""Translate each of the standard json/yaml types to appropiate objects."""
if val is None:
return cls.translate_none(val)
elif isinstance(val, string_types):
return cls.translate_str(val)
# Needs to be before integer checks
elif i... | Translate each of the standard json/yaml types to appropiate objects. |
def action_log_delete(sender, instance, **kwargs):
"""
Signal receiver that creates a log entry when a model instance is deleted from the database.
Direct use is discouraged, connect your model through :py:func:`actionslog.registry.register` instead.
"""
if instance.pk is not None:
changes ... | Signal receiver that creates a log entry when a model instance is deleted from the database.
Direct use is discouraged, connect your model through :py:func:`actionslog.registry.register` instead. |
def predict_f_samples(self, Xnew, num_samples):
"""
Produce samples from the posterior latent function(s) at the points
Xnew.
"""
mu, var = self._build_predict(Xnew, full_cov=True) # N x P, # P x N x N
jitter = tf.eye(tf.shape(mu)[0], dtype=settings.float_type) * setting... | Produce samples from the posterior latent function(s) at the points
Xnew. |
def get_interfaces(impls):
"""Get interfaces from their implementations."""
if impls is None:
return None
elif isinstance(impls, OrderMixin):
result = OrderedDict()
for name in impls.order:
result[name] = impls[name].interface
return result
elif isinstance(i... | Get interfaces from their implementations. |
def parse_relation(obj: dict) -> BioCRelation:
"""Deserialize a dict obj to a BioCRelation object"""
rel = BioCRelation()
rel.id = obj['id']
rel.infons = obj['infons']
for node in obj['nodes']:
rel.add_node(BioCNode(node['refid'], node['role']))
return rel | Deserialize a dict obj to a BioCRelation object |
def read_creds_from_environment_variables():
"""
Read credentials from environment variables
:return:
"""
creds = init_creds()
# Check environment variables
if 'AWS_ACCESS_KEY_ID' in os.environ and 'AWS_SECRET_ACCESS_KEY' in os.environ:
creds['AccessKeyId'] = os.environ['AWS_ACCESS_... | Read credentials from environment variables
:return: |
def _get_file_size(file_path):
"""Returns the size of the file at the specified file path, formatted as a 4-byte unsigned
integer bytearray.
"""
size = getsize(file_path)
file_size = bytearray(4)
pack_into(b"I", file_size, 0, size)
return file_size | Returns the size of the file at the specified file path, formatted as a 4-byte unsigned
integer bytearray. |
def parseFile(self, fil) :
"""Opens a file and parses it"""
f = open(fil)
self.parseStr(f.read())
f.close() | Opens a file and parses it |
def reserve_bits(self, num_bits, stream):
"""Used to "reserve" ``num_bits`` amount of bits in order to keep track
of consecutive bitfields (or are the called bitfield groups?).
E.g. ::
struct {
char a:8, b:8;
char c:4, d:4, e:8;
}
... | Used to "reserve" ``num_bits`` amount of bits in order to keep track
of consecutive bitfields (or are the called bitfield groups?).
E.g. ::
struct {
char a:8, b:8;
char c:4, d:4, e:8;
}
:param int num_bits: The number of bits to claim
... |
def learn(self,
runs,
dir=1,
periodic=False,
recurrent=True,
randomSpeed=False,
learnRecurrent=False,
envelope=True,):
"""
Traverses a sinusoidal trajectory across the environment, learning during
the process. A pair... | Traverses a sinusoidal trajectory across the environment, learning during
the process. A pair of runs across the environment (one in each direction)
takes 10 seconds if in a periodic larger environment, and 4 seconds in a
smaller nonperiodic environment.
:param runs: How many runs across the environmen... |
def CDPP(flux, mask=[], cadence='lc'):
'''
Compute the proxy 6-hr CDPP metric.
:param array_like flux: The flux array to compute the CDPP for
:param array_like mask: The indices to be masked
:param str cadence: The light curve cadence. Default `lc`
'''
# 13 cadences is 6.5 hours
rmswi... | Compute the proxy 6-hr CDPP metric.
:param array_like flux: The flux array to compute the CDPP for
:param array_like mask: The indices to be masked
:param str cadence: The light curve cadence. Default `lc` |
def add_root(self, id_):
"""Adds a root node.
arg: id (osid.id.Id): the ``Id`` of the node
raise: AlreadyExists - ``id`` is already in hierarchy
raise: NotFound - ``id`` not found
raise: NullArgument - ``id`` is ``null``
raise: OperationFailed - unable to complete... | Adds a root node.
arg: id (osid.id.Id): the ``Id`` of the node
raise: AlreadyExists - ``id`` is already in hierarchy
raise: NotFound - ``id`` not found
raise: NullArgument - ``id`` is ``null``
raise: OperationFailed - unable to complete request
raise: PermissionD... |
async def do_connect(self, args):
"""Connect to the PLM device.
Usage:
connect [device [workdir]]
Arguments:
device: PLM device (default /dev/ttyUSB0)
workdir: Working directory to save and load device information
"""
params = args.split()
... | Connect to the PLM device.
Usage:
connect [device [workdir]]
Arguments:
device: PLM device (default /dev/ttyUSB0)
workdir: Working directory to save and load device information |
def write_pdf(matrix, version, out, scale=1, border=None, color='#000',
background=None, compresslevel=9):
"""\
Serializes the QR Code as PDF document.
:param matrix: The matrix to serialize.
:param int version: The (Micro) QR code version
:param out: Filename or a file-like object su... | \
Serializes the QR Code as PDF document.
:param matrix: The matrix to serialize.
:param int version: The (Micro) QR code version
:param out: Filename or a file-like object supporting to write bytes.
:param scale: Indicates the size of a single module (default: 1 which
corresponds to 1 ... |
def dkron(A,dA,B,dB, operation='prod'):
"""
Function computes the derivative of Kronecker product A*B
(or Kronecker sum A+B).
Input:
-----------------------
A: 2D matrix
Some matrix
dA: 3D (or 2D matrix)
Derivarives of A
B: 2D matrix
Some matrix
dB: 3D (or 2... | Function computes the derivative of Kronecker product A*B
(or Kronecker sum A+B).
Input:
-----------------------
A: 2D matrix
Some matrix
dA: 3D (or 2D matrix)
Derivarives of A
B: 2D matrix
Some matrix
dB: 3D (or 2D matrix)
Derivarives of B
operation: s... |
def IntegerAddition(left: vertex_constructor_param_types, right: vertex_constructor_param_types, label: Optional[str]=None) -> Vertex:
"""
Adds one vertex to another
:param left: a vertex to add
:param right: a vertex to add
"""
return Integer(context.jvm_view().IntegerAdditionVertex, label... | Adds one vertex to another
:param left: a vertex to add
:param right: a vertex to add |
def clean_pip_env() -> Generator[None, None, None]:
"""A context manager for temporarily removing 'PIP_REQUIRE_VIRTUALENV' from the environment.
Since shiv installs via `--target`, we need to ignore venv requirements if they exist.
"""
require_venv = os.environ.pop(PIP_REQUIRE_VIRTUALENV, None)
t... | A context manager for temporarily removing 'PIP_REQUIRE_VIRTUALENV' from the environment.
Since shiv installs via `--target`, we need to ignore venv requirements if they exist. |
def mac_address(value,
allow_empty = False,
**kwargs):
"""Validate that ``value`` is a valid MAC address.
:param value: The value to validate.
:type value: :class:`str <python:str>` / :obj:`None <python:None>`
:param allow_empty: If ``True``, returns :obj:`None <python:... | Validate that ``value`` is a valid MAC address.
:param value: The value to validate.
:type value: :class:`str <python:str>` / :obj:`None <python:None>`
:param allow_empty: If ``True``, returns :obj:`None <python:None>` if
``value`` is empty. If ``False``, raises a
:class:`EmptyValueError <vali... |
def get_ieee_rotation(structure, refine_rotation=True):
"""
Given a structure associated with a tensor, determines
the rotation matrix for IEEE conversion according to
the 1987 IEEE standards.
Args:
structure (Structure): a structure associated with the
... | Given a structure associated with a tensor, determines
the rotation matrix for IEEE conversion according to
the 1987 IEEE standards.
Args:
structure (Structure): a structure associated with the
tensor to be converted to the IEEE standard
refine_rotation (... |
def get_distance(self, other, lbda=0.5, min_overlap=4):
"""
Return the Euclidean distance between vectors v of
two trees. Must have the same leaf set (too lazy to check).
"""
if self.tree ^ other.tree:
if len(self.tree & other.tree) < min_overlap:
retu... | Return the Euclidean distance between vectors v of
two trees. Must have the same leaf set (too lazy to check). |
def NRM(f,a,b,best):
WARN = True # Warn, rather than stop if I encounter a NaN...
"""
Calculate NRM expected lab field and estimated ancient field
NRM(blab,best)= (best/blab)*TRM(blab)
"""
if float(f)==0:
print('ERROR: NRM: f==0.')
if not WARN : sys.exit()
m = (old_div(float(... | Calculate NRM expected lab field and estimated ancient field
NRM(blab,best)= (best/blab)*TRM(blab) |
def stats(self, name, value):
"""
Calculates min/average/max statistics based on the current and previous values.
:param name: a counter name of Statistics type
:param value: a value to update statistics
"""
counter = self.get(name, CounterType.Statistics)
self.... | Calculates min/average/max statistics based on the current and previous values.
:param name: a counter name of Statistics type
:param value: a value to update statistics |
def normalize(self):
"""
Rearrange the conjunction to a conventional form.
This puts any coreference(s) first, followed by type terms,
then followed by AVM(s) (including lists). AVMs are
normalized via :meth:`AVM.normalize`.
"""
corefs = []
types = []
... | Rearrange the conjunction to a conventional form.
This puts any coreference(s) first, followed by type terms,
then followed by AVM(s) (including lists). AVMs are
normalized via :meth:`AVM.normalize`. |
def _parse(self):
"""Parses the input file's content and generates a list of its elements/docstrings.
:returns: the list of elements
"""
#TODO manage decorators
#TODO manage default params with strings escaping chars as (, ), ', ', #, ...
#TODO manage elements ending wi... | Parses the input file's content and generates a list of its elements/docstrings.
:returns: the list of elements |
def sign_rsa_sha1(base_string, rsa_private_key):
"""**RSA-SHA1**
Per `section 3.4.3`_ of the spec.
The "RSA-SHA1" signature method uses the RSASSA-PKCS1-v1_5 signature
algorithm as defined in `RFC3447, Section 8.2`_ (also known as
PKCS#1), using SHA-1 as the hash function for EMSA-PKCS1-v1_5. To
... | **RSA-SHA1**
Per `section 3.4.3`_ of the spec.
The "RSA-SHA1" signature method uses the RSASSA-PKCS1-v1_5 signature
algorithm as defined in `RFC3447, Section 8.2`_ (also known as
PKCS#1), using SHA-1 as the hash function for EMSA-PKCS1-v1_5. To
use this method, the client MUST have established cl... |
def log_pdf(self, y, mu, weights=None):
"""
computes the log of the pdf or pmf of the values under the current distribution
Parameters
----------
y : array-like of length n
target values
mu : array-like of length n
expected values
weights ... | computes the log of the pdf or pmf of the values under the current distribution
Parameters
----------
y : array-like of length n
target values
mu : array-like of length n
expected values
weights : array-like shape (n,) or None, default: None
c... |
async def send_code_request(self, phone, *, force_sms=False):
"""
Sends a code request to the specified phone number.
Args:
phone (`str` | `int`):
The phone to which the code will be sent.
force_sms (`bool`, optional):
Whether to force se... | Sends a code request to the specified phone number.
Args:
phone (`str` | `int`):
The phone to which the code will be sent.
force_sms (`bool`, optional):
Whether to force sending as SMS.
Returns:
An instance of :tl:`SentCode`. |
def process_children(self, node, parent, pmod):
"""Process all children of `node`, except "rpc" and "notification".
"""
for ch in node.i_children:
if ch.keyword in ["rpc", "notification"]: continue
if ch.keyword in ["choice", "case"]:
self.process_children... | Process all children of `node`, except "rpc" and "notification". |
def update(ctx, opts, owner_repo_identifier, show_tokens, name, token):
"""
Update (set) a entitlement in a repository.
- OWNER/REPO/IDENTIFIER: Specify the OWNER namespace (i.e. user or org),
and the REPO name that has an entitlement identified by IDENTIFIER. All
separated by a slash.
... | Update (set) a entitlement in a repository.
- OWNER/REPO/IDENTIFIER: Specify the OWNER namespace (i.e. user or org),
and the REPO name that has an entitlement identified by IDENTIFIER. All
separated by a slash.
Example: 'your-org/your-repo/abcdef123456'
Full CLI example:
$ cloudsmi... |
def set_namespace_view_settings(self):
"""Set the namespace view settings"""
if self.namespacebrowser:
settings = to_text_string(
self.namespacebrowser.get_view_settings())
code =(u"get_ipython().kernel.namespace_view_settings = %s" %
settings)
... | Set the namespace view settings |
def write(self, filename, entities, sortkey=None, columns=None):
"""Write entities out to filename in csv format.
Note: this doesn't write directly into a Zip archive, because this behavior
is difficult to achieve with Zip archives. Use make_zip() to create a new
GTFS Zip archive.
"""
if os.pat... | Write entities out to filename in csv format.
Note: this doesn't write directly into a Zip archive, because this behavior
is difficult to achieve with Zip archives. Use make_zip() to create a new
GTFS Zip archive. |
def get_path(name, scheme=_get_default_scheme(), vars=None, expand=True):
"""Return a path corresponding to the scheme.
``scheme`` is the install scheme name.
"""
return get_paths(scheme, vars, expand)[name] | Return a path corresponding to the scheme.
``scheme`` is the install scheme name. |
def search(self,q):
""" Search. """
import re
pattern = re.compile("%s" % q)
result = {}
for i in self.allstockno:
b = re.search(pattern, self.allstockno[i])
try:
b.group()
result[i] = self.allstockno[i]
except:
pass
return result | Search. |
def get_store(logger: Logger=None) -> 'Store':
"""Get and configure the storage backend"""
from trading_bots.conf import settings
store_settings = settings.storage
store = store_settings.get('name', 'json')
if store == 'json':
store = 'trading_bots.core.storage.JSONStore'
elif store == '... | Get and configure the storage backend |
def interrupt (aggregate):
"""Interrupt execution and shutdown, ignoring any subsequent
interrupts."""
while True:
try:
log.warn(LOG_CHECK,
_("interrupt; waiting for active threads to finish"))
log.warn(LOG_CHECK,
_("another interrupt will exit i... | Interrupt execution and shutdown, ignoring any subsequent
interrupts. |
def UpsertTrigger(self, collection_link, trigger, options=None):
"""Upserts a trigger in a collection.
:param str collection_link:
The link to the document collection.
:param dict trigger:
:param dict options:
The request options for the request.
:return... | Upserts a trigger in a collection.
:param str collection_link:
The link to the document collection.
:param dict trigger:
:param dict options:
The request options for the request.
:return:
The upserted Trigger.
:rtype:
dict |
def download_image(self):
"""
Download the image and return the
local path to the image file.
"""
split = urlsplit(self.url)
filename = split.path.split("/")[-1]
# Ensure the directory to store the image cache exists
if not os.path.exists(self.cache_direc... | Download the image and return the
local path to the image file. |
def remove_hyperedge(self, hyperedge_id):
"""Removes a hyperedge and its attributes from the hypergraph.
:param hyperedge_id: ID of the hyperedge to be removed.
:raises: ValueError -- No such hyperedge exists.
Examples:
::
>>> H = UndirectedHypergraph()
... | Removes a hyperedge and its attributes from the hypergraph.
:param hyperedge_id: ID of the hyperedge to be removed.
:raises: ValueError -- No such hyperedge exists.
Examples:
::
>>> H = UndirectedHypergraph()
>>> hyperedge_list = (["A", "B", "C"],
... |
def indication(self, apdu):
"""This function is called for each downstream packet related to
the transaction."""
if _debug: ServerSSM._debug("indication %r", apdu)
if self.state == IDLE:
self.idle(apdu)
elif self.state == SEGMENTED_REQUEST:
self.segmented... | This function is called for each downstream packet related to
the transaction. |
def _cleanup(self, to_clean, allow=()):
""" Remove keys we added for internal use
"""
# this item's been retrieved from the API, we only need the 'data'
# entry
if to_clean.keys() == ["links", "library", "version", "meta", "key", "data"]:
to_clean = to_clean["data"]
... | Remove keys we added for internal use |
def sinterstore(self, destination, *keys):
"""This command is equal to :meth:`~tredis.RedisClient.sinter`, but
instead of returning the resulting set, it is stored in destination.
If destination already exists, it is overwritten.
.. note::
**Time complexity**: ``O(N*M)`` wo... | This command is equal to :meth:`~tredis.RedisClient.sinter`, but
instead of returning the resulting set, it is stored in destination.
If destination already exists, it is overwritten.
.. note::
**Time complexity**: ``O(N*M)`` worst case where ``N`` is the
cardinality of ... |
def _op(self, line, op=None, offset=0):
"""
Returns the gate name for placing a gate on a line.
:param int line: Line number.
:param int op: Operation number or, by default, uses the current op count.
:return: Gate name.
:rtype: string
"""
if op is None:
... | Returns the gate name for placing a gate on a line.
:param int line: Line number.
:param int op: Operation number or, by default, uses the current op count.
:return: Gate name.
:rtype: string |
def action(source, func):
"""Perform an action for each element of an asynchronous sequence
without modifying it.
The given function can be synchronous or asynchronous.
"""
if asyncio.iscoroutinefunction(func):
async def innerfunc(arg):
await func(arg)
return arg
... | Perform an action for each element of an asynchronous sequence
without modifying it.
The given function can be synchronous or asynchronous. |
def linkify_hostgroups_realms_hosts(self, realms, hosts, forced_realms_hostgroups=True):
# pylint: disable=too-many-locals, too-many-nested-blocks, too-many-branches
"""Link between an hostgroup and a realm is already done in the configuration parsing
function that defines and checks the default... | Link between an hostgroup and a realm is already done in the configuration parsing
function that defines and checks the default satellites, realms, hosts and hosts groups
consistency.
This function will only raise some alerts if hosts groups and hosts that are contained
do not belong th... |
def splitOnWords(self, transaction, addrOffset=0):
"""
:return: generator of TransPart instance
"""
wordWidth = self.wordWidth
end = addrOffset
for tmp in transaction.walkFlatten(offset=addrOffset):
if isinstance(tmp, OneOfTransaction):
split =... | :return: generator of TransPart instance |
def daily_periods(self, range_start=datetime.date.min, range_end=datetime.date.max, exclude_dates=tuple()):
"""Returns an iterator of Period tuples for every day this schedule is in effect, between range_start
and range_end."""
tz = self.timezone
period = self.period
weekdays = s... | Returns an iterator of Period tuples for every day this schedule is in effect, between range_start
and range_end. |
def write_file(path, content, mode='w'):
# type: (Text, Union[Text,bytes], Text) -> None
""" --pretend aware file writing.
You can always write files manually but you should always handle the
--pretend case.
Args:
path (str):
content (str):
mode (str):
"""
from pelt... | --pretend aware file writing.
You can always write files manually but you should always handle the
--pretend case.
Args:
path (str):
content (str):
mode (str): |
def sign(self, data, nonce = None):
"""
Sign data using the Montgomery private key stored by this XEdDSA instance.
:param data: A bytes-like object containing the data to sign.
:param nonce: A bytes-like object with length 64 or None.
:returns: A bytes-like object encoding the s... | Sign data using the Montgomery private key stored by this XEdDSA instance.
:param data: A bytes-like object containing the data to sign.
:param nonce: A bytes-like object with length 64 or None.
:returns: A bytes-like object encoding the signature with length SIGNATURE_SIZE.
If the non... |
def properties_operator(cls, name):
"""Wraps a container operator to ensure container class is maintained"""
def wrapper(self, *args, **kwargs):
"""Perform operation and cast to container class"""
output = getattr(super(cls, self), name)(*args, **kwargs)
return cls(output)
wrapped ... | Wraps a container operator to ensure container class is maintained |
def render_publ_template(template, **kwargs):
""" Render out a template, providing the image function based on the args.
Returns tuple of (rendered text, etag)
"""
text = render_template(
template.filename,
template=template,
image=image_function(
template=template,
... | Render out a template, providing the image function based on the args.
Returns tuple of (rendered text, etag) |
def pop(self, amount=1) -> Union[BitVec, List[BitVec]]:
"""Pops amount elements from the stack.
:param amount:
:return:
"""
if amount > len(self.stack):
raise StackUnderflowException
values = self.stack[-amount:][::-1]
del self.stack[-amount:]
... | Pops amount elements from the stack.
:param amount:
:return: |
def get_rrset(self, section, name, rdclass, rdtype,
covers=dns.rdatatype.NONE, deleting=None, create=False,
force_unique=False):
"""Get the RRset with the given attributes in the specified section.
If the RRset is not found, None is returned.
@param section:... | Get the RRset with the given attributes in the specified section.
If the RRset is not found, None is returned.
@param section: the section of the message to look in, e.g.
self.answer.
@type section: list of dns.rrset.RRset objects
@param name: the name of the RRset
@typ... |
def merge(self, sample):
"""
Use bbmerge to merge paired FASTQ files for use in metagenomics pipelines. Create a report with the
total number of reads, and the number of reads that could be paired
:param sample: metadata sample object flagged as a metagenome
"""
# Set the... | Use bbmerge to merge paired FASTQ files for use in metagenomics pipelines. Create a report with the
total number of reads, and the number of reads that could be paired
:param sample: metadata sample object flagged as a metagenome |
def aryule(X, order, norm='biased', allow_singularity=True):
r"""Compute AR coefficients using Yule-Walker method
:param X: Array of complex data values, X(1) to X(N)
:param int order: Order of autoregressive process to be fitted (integer)
:param str norm: Use a biased or unbiased correlation.
:par... | r"""Compute AR coefficients using Yule-Walker method
:param X: Array of complex data values, X(1) to X(N)
:param int order: Order of autoregressive process to be fitted (integer)
:param str norm: Use a biased or unbiased correlation.
:param bool allow_singularity:
:return:
* AR coefficient... |
def digit(uni_char, default_value=None):
"""Returns the digit value assigned to the Unicode character uni_char as
integer. If no such value is defined, default is returned, or, if not
given, ValueError is raised."""
uni_char = unicod(uni_char) # Force to Unicode.
if default_value is not None:
... | Returns the digit value assigned to the Unicode character uni_char as
integer. If no such value is defined, default is returned, or, if not
given, ValueError is raised. |
def _read_bytes_from_socket(self, msglen):
""" Read bytes from the socket. """
chunks = []
bytes_recd = 0
while bytes_recd < msglen:
if self.stop.is_set():
raise InterruptLoop("Stopped while reading from socket")
try:
chunk = self.s... | Read bytes from the socket. |
def print_stats(self, header=True, file=sys.stdout):
"""Pretty print stats table."""
if header:
print("CACHE {:*^18} {:*^18} {:*^18} {:*^18} {:*^18}".format(
"HIT", "MISS", "LOAD", "STORE", "EVICT"), file=file)
for s in self.stats():
print("{name:>5} {HIT_... | Pretty print stats table. |
def __get_initial_center(self, return_index):
"""!
@brief Choose randomly first center.
@param[in] return_index (bool): If True then return center's index instead of point.
@return (array_like) First center.<br>
(uint) Index of first center.
"""
index_... | !
@brief Choose randomly first center.
@param[in] return_index (bool): If True then return center's index instead of point.
@return (array_like) First center.<br>
(uint) Index of first center. |
def SensorsTriggersGet(self, sensor_id, trigger_id = -1):
"""
Obtain either all triggers connected to a sensor, or the details of a specific trigger connected to a sensor.
If successful, result can be obtained from getResponse(), and should be a json string.
... | Obtain either all triggers connected to a sensor, or the details of a specific trigger connected to a sensor.
If successful, result can be obtained from getResponse(), and should be a json string.
@param sensor_id (int) - Sensor id of the sensor to retrieve triggers from.
... |
def write(self, oprot):
'''
Write this object to the given output protocol and return self.
:type oprot: thryft.protocol._output_protocol._OutputProtocol
:rtype: pastpy.gen.database.impl.online.online_database_object_detail.OnlineDatabaseObjectDetail
'''
oprot.write_str... | Write this object to the given output protocol and return self.
:type oprot: thryft.protocol._output_protocol._OutputProtocol
:rtype: pastpy.gen.database.impl.online.online_database_object_detail.OnlineDatabaseObjectDetail |
def _check_time_range(time_range, now):
'''
Check time range
'''
if _TIME_SUPPORTED:
_start = dateutil_parser.parse(time_range['start'])
_end = dateutil_parser.parse(time_range['end'])
return bool(_start <= now <= _end)
else:
log.error('Dateutil is required.')
... | Check time range |
def _size(self):
"""
:return: how many bits is this slice selecting
"""
assert isinstance(self, Value)
return int(self.val[0]) - int(self.val[1]) | :return: how many bits is this slice selecting |
def compile_command(context, backend, config):
"""
Compile Sass project sources to CSS
"""
logger = logging.getLogger("boussole")
logger.info(u"Building project")
# Discover settings file
try:
discovering = Discover(backends=[SettingsBackendJson,
... | Compile Sass project sources to CSS |
def lessThanOrEqual(self, value):
"""
Sets the operator type to Query.Op.LessThanOrEqual and sets
the value to the inputted value.
:param value <variant>
:return <Query>
:sa lessThanOrEqual
:usage |>... | Sets the operator type to Query.Op.LessThanOrEqual and sets
the value to the inputted value.
:param value <variant>
:return <Query>
:sa lessThanOrEqual
:usage |>>> from orb import Query as Q
|>>>... |
def _find_advisory_targets(name=None,
advisory_ids=None,
**kwargs):
'''
Inspect the arguments to pkg.patch_installed and discover what advisory
patches need to be installed. Return a dict of advisory patches to install.
'''
cur_patches = __salt__... | Inspect the arguments to pkg.patch_installed and discover what advisory
patches need to be installed. Return a dict of advisory patches to install. |
def _isobject(self, name, exist):
"""Test whether the name is an object."""
if exist in [2, 5]:
return False
cmd = 'isobject(%s)' % name
resp = self._engine.eval(cmd, silent=True).strip()
return resp == 'ans = 1' | Test whether the name is an object. |
def forward_committor_sensitivity(T, A, B, index):
"""
calculate the sensitivity matrix for index of the forward committor from A to B given transition matrix T.
Parameters
----------
T : numpy.ndarray shape = (n, n)
Transition matrix
A : array like
List of integer state labels f... | calculate the sensitivity matrix for index of the forward committor from A to B given transition matrix T.
Parameters
----------
T : numpy.ndarray shape = (n, n)
Transition matrix
A : array like
List of integer state labels for set A
B : array like
List of integer state label... |
def parse_form(self, req, name, field):
"""Pull a form value from the request."""
return core.get_value(req.POST, name, field) | Pull a form value from the request. |
def startLogging(console=True, filepath=None):
'''
Starts the global Twisted logger subsystem with maybe
stdout and/or a file specified in the config file
'''
global logLevelFilterPredicate
observers = []
if console:
observers.append( FilteringLogObserver(observer=textFileLogObse... | Starts the global Twisted logger subsystem with maybe
stdout and/or a file specified in the config file |
def buffer(self, byte_offset=0):
"""Get a copy of the map buffer"""
contents = self.ptr.contents
ptr = addressof(contents.buffer.contents) + byte_offset
length = contents.length * 4 - byte_offset
return buffer((c_char * length).from_address(ptr).raw) \
if length else ... | Get a copy of the map buffer |
def as_text(self):
"""
Return a textual representation of this key.
"""
if self.secret_exponent():
return self.wif()
sec_hex = self.sec_as_hex()
if sec_hex:
return sec_hex
return self.address() | Return a textual representation of this key. |
def read_all_from_datastore(self):
"""Reads all work pieces from the datastore."""
self._work = {}
client = self._datastore_client
parent_key = client.key(KIND_WORK_TYPE, self._work_type_entity_id)
for entity in client.query_fetch(kind=KIND_WORK, ancestor=parent_key):
work_id = entity.key.flat... | Reads all work pieces from the datastore. |
def SignFiles(self, filenames):
"""Signs multiple files at once."""
file_list = " ".join(filenames)
subprocess.check_call("%s %s" % (self._signing_cmdline, file_list))
if self._verification_cmdline:
subprocess.check_call("%s %s" % (self._verification_cmdline, file_list)) | Signs multiple files at once. |
def soup(self):
'''
Running plugins and adding an HTML doctype to the
generated Tag HTML.
'''
dom = BeautifulSoup('<!DOCTYPE html>')
# BeautifulSoup behaves differently if lxml is installed or not,
# and will create a basic HTML structure if lxml is insta... | Running plugins and adding an HTML doctype to the
generated Tag HTML. |
def slice(string, start=None, end=None):
"""
Returns a substring of the given string, counting graphemes instead of codepoints.
Negative indices is currently not supported.
>>> string = "tamil நி (ni)"
>>> string[:7]
'tamil ந'
>>> grapheme.slice(string, end=7)
'tamil நி'
>>> string... | Returns a substring of the given string, counting graphemes instead of codepoints.
Negative indices is currently not supported.
>>> string = "tamil நி (ni)"
>>> string[:7]
'tamil ந'
>>> grapheme.slice(string, end=7)
'tamil நி'
>>> string[7:]
'ி (ni)'
>>> grapheme.slice(string, 7)
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.