INSTRUCTION stringlengths 1 46.3k | RESPONSE stringlengths 75 80.2k |
|---|---|
When serializing an agent distribution, remove the thresholds, in order
to avoid cluttering the YAML definition file. | def serialize_distribution(network_agents, known_modules=[]):
'''
When serializing an agent distribution, remove the thresholds, in order
to avoid cluttering the YAML definition file.
'''
d = deepcopy(list(network_agents))
for v in d:
if 'threshold' in v:
del v['threshold']
... |
Validate states to avoid ignoring states during initialization | def _validate_states(states, topology):
'''Validate states to avoid ignoring states during initialization'''
states = states or []
if isinstance(states, dict):
for x in states:
assert x in topology.node
else:
assert len(states) <= len(topology)
return states |
Convenience method to allow specifying agents by class or class name. | def _convert_agent_types(ind, to_string=False, **kwargs):
'''Convenience method to allow specifying agents by class or class name.'''
if to_string:
return serialize_distribution(ind, **kwargs)
return deserialize_distribution(ind, **kwargs) |
Used in the initialization of agents given an agent distribution. | def _agent_from_distribution(distribution, value=-1, agent_id=None):
"""Used in the initialization of agents given an agent distribution."""
if value < 0:
value = random.random()
for d in sorted(distribution, key=lambda x: x['threshold']):
threshold = d['threshold']
# Check if the de... |
Get a list of nodes in the ego network of *node* of radius *steps* | def ego_search(self, steps=1, center=False, node=None, **kwargs):
'''Get a list of nodes in the ego network of *node* of radius *steps*'''
node = as_node(node if node is not None else self)
G = self.subgraph(**kwargs)
return nx.ego_graph(G, node, center=center, radius=steps).nodes() |
Get a list of nodes whose coordinates are closer than *radius* to *node*. | def geo_search(self, radius, node=None, center=False, **kwargs):
'''Get a list of nodes whose coordinates are closer than *radius* to *node*.'''
node = as_node(node if node is not None else self)
G = self.subgraph(**kwargs)
pos = nx.get_node_attributes(G, 'pos')
if not pos:
... |
Receiving a message from the websocket, parse, and act accordingly. | def on_message(self, message):
""" Receiving a message from the websocket, parse, and act accordingly. """
msg = tornado.escape.json_decode(message)
if msg['type'] == 'config_file':
if self.application.verbose:
print(msg['data'])
self.config = list(yam... |
Run the app. | def launch(self, port=None):
""" Run the app. """
if port is not None:
self.port = port
url = 'http://127.0.0.1:{PORT}'.format(PORT=self.port)
print('Interface starting at {url}'.format(url=url))
self.listen(self.port)
# webbrowser.open(url)
t... |
Get stats for status codes by date.
Returns:
list: status codes + date grouped by type: 2xx, 3xx, 4xx, 5xx, attacks. | def status_codes_by_date_stats():
"""
Get stats for status codes by date.
Returns:
list: status codes + date grouped by type: 2xx, 3xx, 4xx, 5xx, attacks.
"""
def date_counter(queryset):
return dict(Counter(map(
lambda dt: ms_since_epoch(datetime.combine(
... |
Get stats for most visited pages.
Args:
logs (list): logs data to use.
Returns:
dict: more_than_10 and less_than_10: list of dict (bound + url list). | def most_visited_pages_stats():
"""
Get stats for most visited pages.
Args:
logs (list): logs data to use.
Returns:
dict: more_than_10 and less_than_10: list of dict (bound + url list).
"""
stats = {'more_than_10': [], 'less_than_10': {}}
counter = Counter(list(RequestLog.... |
Agents will try to enter. The pub checks if it is possible | def enter(self, pub_id, *nodes):
'''Agents will try to enter. The pub checks if it is possible'''
try:
pub = self['pubs'][pub_id]
except KeyError:
raise ValueError('Pub {} is not available'.format(pub_id))
if not pub['open'] or (pub['capacity'] < (len(nodes) + pub... |
Agents will notify the pub they want to leave | def exit(self, pub_id, *node_ids):
'''Agents will notify the pub they want to leave'''
try:
pub = self['pubs'][pub_id]
except KeyError:
raise ValueError('Pub {} is not available'.format(pub_id))
for node_id in node_ids:
node = self.get_agent(node_id)
... |
Look for friends to drink with | def looking_for_friends(self):
'''Look for friends to drink with'''
self.info('I am looking for friends')
available_friends = list(self.get_agents(drunk=False,
pub=None,
state_id=self.looking_for_fr... |
Look for a pub that accepts me and my friends | def looking_for_pub(self):
'''Look for a pub that accepts me and my friends'''
if self['pub'] != None:
return self.sober_in_pub
self.debug('I am looking for a pub')
group = list(self.get_neighboring_agents())
for pub in self.env.available_pubs():
self.debu... |
Try to become friends with another agent. The chances of
success depend on both agents' openness. | def befriend(self, other_agent, force=False):
'''
Try to become friends with another agent. The chances of
success depend on both agents' openness.
'''
if force or self['openness'] > random():
self.env.add_edge(self, other_agent)
self.info('Made some frien... |
Look for random agents around me and try to befriend them | def try_friends(self, others):
''' Look for random agents around me and try to befriend them'''
befriended = False
k = int(10*self['openness'])
shuffle(others)
for friend in islice(others, k): # random.choice >= 3.7
if friend == self:
continue
... |
Compute the mean, standard deviation, min, quartile1, quartile2, quartile3, and max of a vector
Parameters
----------
data: array of real values
Returns
-------
features = dictionary containing the min, max, mean, and standard deviation | def profile_distribution(data):
"""
Compute the mean, standard deviation, min, quartile1, quartile2, quartile3, and max of a vector
Parameters
----------
data: array of real values
Returns
-------
features = dictionary containing the min, max, mean, and standard deviation
"""
i... |
Return the value as a dict, raising error if conversion to dict is not possible | def to_native(self, value):
"""Return the value as a dict, raising error if conversion to dict is not possible"""
if isinstance(value, dict):
return value
elif isinstance(value, six.string_types):
native_value = json.loads(value)
if isinstance(native_value, di... |
Load a value as a list, converting items if necessary | def to_native(self, value):
"""Load a value as a list, converting items if necessary"""
if isinstance(value, six.string_types):
value_list = value.split(self.string_delim)
else:
value_list = value
to_native = self.member_type.to_native if self.member_type is not ... |
Validate each member of the list, if member_type exists | def validate_member_type(self, value):
"""Validate each member of the list, if member_type exists"""
if self.member_type:
for item in value:
self.member_type.validate(item) |
Validate the length of value, if min_length or max_length was specified | def validate_length(self, value):
"""Validate the length of value, if min_length or max_length was specified"""
list_len = len(value) if value else 0
if self.max_length is not None and list_len > self.max_length:
raise ValidationError(
u'List has {} values; max lengt... |
Validate the network resource with exponential backoff | def validate_resource(self, value):
"""Validate the network resource with exponential backoff"""
def do_backoff(*args, **kwargs):
"""Call self._test_connection with exponential backoff, for self._max_tries attempts"""
attempts = 0
while True:
try:
... |
登录 | def login(self, **kwargs):
"""登录"""
payload = {
'username': self.username,
'password': self.password,
}
headers = kwargs.setdefault('headers', {})
headers.setdefault(
'Referer',
'https://www.shanbay.com/web/account/login'
)
... |
获取扇贝网服务器时间(UTC 时间) | def server_date_utc(self):
"""获取扇贝网服务器时间(UTC 时间)"""
date_str = self.request('http://www.shanbay.com', 'head'
).headers['date']
date_utc = datetime.datetime.strptime(date_str,
'%a, %d %b %Y %H:%M:%S GMT')
return... |
Returns a list of metafeatures computable by the Metafeatures class. | def list_metafeatures(cls, group="all"):
"""
Returns a list of metafeatures computable by the Metafeatures class.
"""
# todo make group for intractable metafeatures for wide datasets or
# datasets with high cardinality categorical columns:
# PredPCA1, PredPCA2, PredPCA3, ... |
Parameters
----------
X: pandas.DataFrame, the dataset features
Y: pandas.Series, the dataset targets
column_types: Dict[str, str], dict from column name to column type as
"NUMERIC" or "CATEGORICAL" or "TEXT", must include Y column
metafeature_ids: list, the metafeatu... | def compute(
self, X: DataFrame, Y: Series=None,
column_types: Dict[str, str]=None, metafeature_ids: List=None,
exclude: List=None, sample_shape=None, seed=None, n_folds=2,
verbose=False, timeout=None
) -> dict:
"""
Parameters
----------
X: pandas.Data... |
Stratified uniform sampling of rows, according to the classes in Y.
Ensures there are enough samples from each class in Y for cross
validation. | def _sample_rows(self, X, Y, sample_shape, seed):
"""
Stratified uniform sampling of rows, according to the classes in Y.
Ensures there are enough samples from each class in Y for cross
validation.
"""
if sample_shape[0] is None or X.shape[0] <= sample_shape[0]:
... |
Constructor: use token authentication to read secrets from a Vault path
See https://www.vaultproject.io/docs/auth/token.html
Args:
url: Vault url
path: Vault path where secrets are stored
vault_token: token (must have access to vault path) | def from_token(cls, url, path, token):
"""Constructor: use token authentication to read secrets from a Vault path
See https://www.vaultproject.io/docs/auth/token.html
Args:
url: Vault url
path: Vault path where secrets are stored
vault_token: token (must hav... |
Constructor: use AppRole authentication to read secrets from a Vault path
See https://www.vaultproject.io/docs/auth/approle.html
Args:
url: Vault url
path: Vault path where secrets are stored
role_id: Vault RoleID
secret_id: Vault SecretID | def from_app_role(cls, url, path, role_id, secret_id):
"""Constructor: use AppRole authentication to read secrets from a Vault path
See https://www.vaultproject.io/docs/auth/approle.html
Args:
url: Vault url
path: Vault path where secrets are stored
role_id:... |
Read data from the vault path | def _fetch_secrets(vault_url, path, token):
"""Read data from the vault path"""
url = _url_joiner(vault_url, 'v1', path)
resp = requests.get(url, headers=VaultLoader._get_headers(token))
resp.raise_for_status()
data = resp.json()
if data.get('errors'):
raise V... |
Get a Vault token, using the RoleID and SecretID | def _fetch_app_role_token(vault_url, role_id, secret_id):
"""Get a Vault token, using the RoleID and SecretID"""
url = _url_joiner(vault_url, 'v1/auth/approle/login')
resp = requests.post(url, data={'role_id': role_id, 'secret_id': secret_id})
resp.raise_for_status()
data = resp.... |
Reread secrets from the vault path | def reload(self):
"""Reread secrets from the vault path"""
self._source = self._fetch_secrets(self._vault_url, self._path, self._token) |
Convenience method: look up the vault token | def lookup_token(self):
"""Convenience method: look up the vault token"""
url = _url_joiner(self._vault_url, 'v1/auth/token/lookup-self')
resp = requests.get(url, headers=self._headers)
resp.raise_for_status()
data = resp.json()
if data.get('errors'):
raise Va... |
Convenience method: renew Vault token | def renew_token(self):
"""Convenience method: renew Vault token"""
url = _url_joiner(self._vault_url, 'v1/auth/token/renew-self')
resp = requests.get(url, headers=self._headers)
resp.raise_for_status()
data = resp.json()
if data.get('errors'):
raise VaultExcep... |
Sort sort options for display.
:param sort_options: A dictionary containing the field name as key and
asc/desc as value.
:returns: A dictionary with sorting options for Invenio-Search-JS. | def sorted_options(sort_options):
"""Sort sort options for display.
:param sort_options: A dictionary containing the field name as key and
asc/desc as value.
:returns: A dictionary with sorting options for Invenio-Search-JS.
"""
return [
{
'title': v['title'],
... |
Converts html code into formatted plain text. | def html_to_plain_text(html):
"""Converts html code into formatted plain text."""
# Use BeautifulSoup to normalize the html
soup = BeautifulSoup(html, "html.parser")
# Init the parser
parser = HTML2PlainParser()
parser.feed(str(soup.encode('utf-8')))
# Strip the end of the plain text
res... |
Handles every start tag like e.g. <p>. | def handle_starttag(self, tag, attrs):
"""Handles every start tag like e.g. <p>."""
if (tag in self.newline_before_elements):
self.text += '\n'
if (tag in self.stroke_before_elements and not
self.text.endswith(self.stroke_text)):
# Put a stroke in front of... |
Handles data between tags. | def handle_data(self, data):
"""Handles data between tags."""
# Only proceed with unignored elements
if self.lasttag not in self.ignored_elements:
# Remove any predefined linebreaks
text = data.replace('\n', '')
# If there's some text left, proceed!
... |
Handles every end tag like e.g. </p>. | def handle_endtag(self, tag):
"""Handles every end tag like e.g. </p>."""
if tag in self.stroke_after_elements:
if self.text.endswith(self.stroke_text):
# Only add a stroke if there isn't already a stroke posted
# In this case, there was no content between the... |
Starts the thread | def run(self):
""" Starts the thread """
task = None
monitor_task = MonitorTask(
notification_endpoint=self._handle_message)
while True:
if self._terminate:
self._logger.info("scsgate.Reactor exiting")
self._connection.close()
... |
Just a simple generator that creates a network with n nodes and
n_edges edges. Edges are assigned randomly, only avoiding self loops. | def mygenerator(n=5, n_edges=5):
'''
Just a simple generator that creates a network with n nodes and
n_edges edges. Edges are assigned randomly, only avoiding self loops.
'''
G = nx.Graph()
for i in range(n):
G.add_node(i)
for i in range(n_edges):
nodes = list(G.nodes)
... |
Internal method to import instance variables data from a dictionary
:param dict datadict: The dictionary containing variables values. | def _import(self, datadict):
"""
Internal method to import instance variables data from a dictionary
:param dict datadict: The dictionary containing variables values.
"""
self.GUID = datadict.get("GUID", uuid.uuid1())
self.FileName = datadict.get("FileName", "")
... |
Creates a :class:`~vsgen.project.VSGProject` from a :class:`~configparser.ConfigParser` section.
:param ConfigParser config: A :class:`~configparser.ConfigParser` instance.
:param str section: A :class:`~configparser.ConfigParser` section key.
:param kwargs: List of a... | def from_section(cls, config, section, **kwargs):
"""
Creates a :class:`~vsgen.project.VSGProject` from a :class:`~configparser.ConfigParser` section.
:param ConfigParser config: A :class:`~configparser.ConfigParser` instance.
:param str section: A :class:`~configparser.Conf... |
Returns the :attr:`ProjectHome` relative to :attr:`FileName` directory. | def ProjectHomeRelative(self):
"""
Returns the :attr:`ProjectHome` relative to :attr:`FileName` directory.
"""
return os.path.relpath(self.ProjectHome, os.path.dirname(self.FileName)) |
Returns the :attr:`StartupFile` relative to :attr:`ProjectHome` directory. | def StartupFileRelative(self):
"""
Returns the :attr:`StartupFile` relative to :attr:`ProjectHome` directory.
"""
return os.path.relpath(self.StartupFile, self.ProjectHome) if self.StartupFile else self.StartupFile |
Returns a generator iterating over the each file in :attr:`ContentFiles` relative to :attr:`ProjectHome` directory. | def ContentFilesRelative(self):
"""
Returns a generator iterating over the each file in :attr:`ContentFiles` relative to :attr:`ProjectHome` directory.
"""
return (os.path.relpath(path, self.ProjectHome) for path in sorted(self.ContentFiles, key=self.lower)) |
Returns a generator iterating over the each file in :attr:`ContentFiles` relative to :attr:`ProjectHome` directory. | def CompileFilesRelative(self):
"""
Returns a generator iterating over the each file in :attr:`ContentFiles` relative to :attr:`ProjectHome` directory.
"""
return (os.path.relpath(path, self.ProjectHome) for path in sorted(self.CompileFiles, key=self.lower)) |
Returns a generator iterating over the each directory referenced by the project, relative to :attr:`ProjectHome` directory. | def DirectoriesRelative(self):
"""
Returns a generator iterating over the each directory referenced by the project, relative to :attr:`ProjectHome` directory.
"""
# Acquire all directories
directories = itertools.chain(self.Directories, (os.path.dirname(f) for f in itertools.chai... |
Inserts files by recursive traversing the rootpath and inserting files according the addition filter parameters.
:param str rootpath: The absolute path to the root directory.
:param list directoryInFilter: A list of fnmatch expressions to match directories to be included. A `None` value wi... | def insert_files(self, rootpath, directoryInFilter=None, directoryExFilter=None, compileInFilter=None, compileExFilter=None, contentInFilter=None, contentExFilter=None):
"""
Inserts files by recursive traversing the rootpath and inserting files according the addition filter parameters.
:param s... |
Encrypt a third-party caveat.
The third_party_info key holds information about the
third party we're encrypting the caveat for; the key is the
public/private key pair of the party that's adding the caveat.
The caveat will be encoded according to the version information
found in third_party_info.
... | def encode_caveat(condition, root_key, third_party_info, key, ns):
'''Encrypt a third-party caveat.
The third_party_info key holds information about the
third party we're encrypting the caveat for; the key is the
public/private key pair of the party that's adding the caveat.
The caveat will be enc... |
Create a JSON-encoded third-party caveat.
The third_party_pub_key key represents the PublicKey of the third party
we're encrypting the caveat for; the key is the public/private key pair of
the party that's adding the caveat.
@param condition string
@param root_key bytes
@param third_party_pub_... | def _encode_caveat_v1(condition, root_key, third_party_pub_key, key):
'''Create a JSON-encoded third-party caveat.
The third_party_pub_key key represents the PublicKey of the third party
we're encrypting the caveat for; the key is the public/private key pair of
the party that's adding the caveat.
... |
Create a version 2 or version 3 third-party caveat.
The format has the following packed binary fields (note
that all fields up to and including the nonce are the same
as the v2 format):
version 2 or 3 [1 byte]
first 4 bytes of third-party Curve25519 public key [4 bytes]
first-party... | def _encode_caveat_v2_v3(version, condition, root_key, third_party_pub_key,
key, ns):
'''Create a version 2 or version 3 third-party caveat.
The format has the following packed binary fields (note
that all fields up to and including the nonce are the same
as the v2 format):
... |
Creates a version 2 or version 3 secret part of the third party
caveat. The returned data is not encrypted.
The format has the following packed binary fields:
version 2 or 3 [1 byte]
root key length [n: uvarint]
root key [n bytes]
namespace length [n: uvarint] (v3 only)
namespace [n bytes] ... | def _encode_secret_part_v2_v3(version, condition, root_key, ns):
'''Creates a version 2 or version 3 secret part of the third party
caveat. The returned data is not encrypted.
The format has the following packed binary fields:
version 2 or 3 [1 byte]
root key length [n: uvarint]
root key [n byt... |
Decode caveat by decrypting the encrypted part using key.
@param key the nacl private key to decode.
@param caveat bytes.
@return ThirdPartyCaveatInfo | def decode_caveat(key, caveat):
'''Decode caveat by decrypting the encrypted part using key.
@param key the nacl private key to decode.
@param caveat bytes.
@return ThirdPartyCaveatInfo
'''
if len(caveat) == 0:
raise VerificationError('empty third party caveat')
first = caveat[:1]
... |
Decode a base64 encoded JSON id.
@param key the nacl private key to decode.
@param caveat a base64 encoded JSON string. | def _decode_caveat_v1(key, caveat):
'''Decode a base64 encoded JSON id.
@param key the nacl private key to decode.
@param caveat a base64 encoded JSON string.
'''
data = base64.b64decode(caveat).decode('utf-8')
wrapper = json.loads(data)
tp_public_key = nacl.public.PublicKey(
base6... |
Decodes a version 2 or version 3 caveat. | def _decode_caveat_v2_v3(version, key, caveat):
'''Decodes a version 2 or version 3 caveat.
'''
if (len(caveat) < 1 + _PUBLIC_KEY_PREFIX_LEN +
_KEY_LEN + nacl.public.Box.NONCE_SIZE + 16):
raise VerificationError('caveat id too short')
original_caveat = caveat
caveat = caveat[1:] ... |
encodes integer into variable-length format into data. | def encode_uvarint(n, data):
'''encodes integer into variable-length format into data.'''
if n < 0:
raise ValueError('only support positive integer')
while True:
this_byte = n & 127
n >>= 7
if n == 0:
data.append(this_byte)
break
data.append(th... |
Decode a variable-length integer.
Reads a sequence of unsigned integer byte and decodes them into an integer
in variable-length format and returns it and the length read. | def decode_uvarint(data):
'''Decode a variable-length integer.
Reads a sequence of unsigned integer byte and decodes them into an integer
in variable-length format and returns it and the length read.
'''
n = 0
shift = 0
length = 0
for b in data:
if not isinstance(b, int):
... |
Builds type dictionary for user-defined type converters,
used by :mod:`parse` module.
This requires that each type converter has a "name" attribute.
:param converters: List of type converters (parse_types)
:return: Type converter dictionary | def build_type_dict(converters):
"""
Builds type dictionary for user-defined type converters,
used by :mod:`parse` module.
This requires that each type converter has a "name" attribute.
:param converters: List of type converters (parse_types)
:return: Type converter dictionary
"""
more_... |
Create a type converter for a list of items (many := 1..*).
The parser accepts anything and the converter needs to fail on errors.
:param item_converter: Type converter for an item.
:param listsep: List separator to use (as string).
:return: Type converter function object for the list... | def make_list(cls, item_converter=None, listsep=','):
"""
Create a type converter for a list of items (many := 1..*).
The parser accepts anything and the converter needs to fail on errors.
:param item_converter: Type converter for an item.
:param listsep: List separator to use... |
Creates a type converter for an enumeration or text-to-value mapping.
:param enum_mappings: Defines enumeration names and values.
:return: Type converter function object for the enum/mapping. | def make_enum(enum_mappings):
"""
Creates a type converter for an enumeration or text-to-value mapping.
:param enum_mappings: Defines enumeration names and values.
:return: Type converter function object for the enum/mapping.
"""
if (inspect.isclass(enum_mappings) and
... |
Creates a type-converter function to select one from a list of strings.
The type-converter function returns the selected choice_text.
The :param:`transform()` function is applied in the type converter.
It can be used to enforce the case (because parser uses re.IGNORECASE).
:param choice... | def make_choice(cls, choices, transform=None, strict=None):
"""
Creates a type-converter function to select one from a list of strings.
The type-converter function returns the selected choice_text.
The :param:`transform()` function is applied in the type converter.
It can be used... |
Creates a type converter to select one item from a list of strings.
The type converter function returns a tuple (index, choice_text).
:param choices: List of strings as choice.
:param transform: Optional, initial transform function for parsed text.
:return: Type converter function objec... | def make_choice2(cls, choices, transform=None, strict=None):
"""
Creates a type converter to select one item from a list of strings.
The type converter function returns a tuple (index, choice_text).
:param choices: List of strings as choice.
:param transform: Optional, initial t... |
Creates a type converter for a number of type converter alternatives.
The first matching type converter is used.
REQUIRES: type_converter.pattern attribute
:param converters: List of type converters as alternatives.
:param re_opts: Regular expression options zu use (=default_re_opts).... | def make_variant(cls, converters, re_opts=None, compiled=False, strict=True):
"""
Creates a type converter for a number of type converter alternatives.
The first matching type converter is used.
REQUIRES: type_converter.pattern attribute
:param converters: List of type converte... |
Carries out a conversion (represented as a string) and returns the
result as a human-readable string.
Args:
inp (str): Text representing a unit conversion, which should
include a magnitude, a description of the initial units,
and a description of the target u... | def parseUnits(self, inp):
"""Carries out a conversion (represented as a string) and returns the
result as a human-readable string.
Args:
inp (str): Text representing a unit conversion, which should
include a magnitude, a description of the initial units,
... |
Checks if a string represents a valid quantities unit.
Args:
w (str): A string to be tested against the set of valid
quantities units.
Returns:
True if the string can be used as a unit in the quantities
module. | def isValidUnit(self, w):
"""Checks if a string represents a valid quantities unit.
Args:
w (str): A string to be tested against the set of valid
quantities units.
Returns:
True if the string can be used as a unit in the quantities
module.
... |
Collects all the valid units from an inp string. Works by
appending consecutive words from the string and cross-referncing
them with a set of valid units.
Args:
inp (str): Some text which hopefully contains descriptions
of different units.
Returns:
... | def extractUnits(self, inp):
"""Collects all the valid units from an inp string. Works by
appending consecutive words from the string and cross-referncing
them with a set of valid units.
Args:
inp (str): Some text which hopefully contains descriptions
of diff... |
Converts a string representation of some quantity of units into a
quantities object.
Args:
inp (str): A textual representation of some quantity of units,
e.g., "fifty kilograms".
Returns:
A quantities object representing the described quantity and its
... | def convert(self, inp):
"""Converts a string representation of some quantity of units into a
quantities object.
Args:
inp (str): A textual representation of some quantity of units,
e.g., "fifty kilograms".
Returns:
A quantities object representin... |
Allow access to any ACL members that was equal to the user name.
That is, some user u is considered a member of group u and no other. | def allow(self, ctx, acls):
'''Allow access to any ACL members that was equal to the user name.
That is, some user u is considered a member of group u and no other.
'''
for acl in acls:
if self._identity == acl:
return True
return False |
Return an unique list of resources or collections from a list of paths.
Supports fq_name and wilcards resolution.
>>> expand_paths(['virtual-network',
'floating-ip/2a0a54b4-a420-485e-8372-42f70a627ec9'])
[Collection('virtual-network'),
Resource('floating-ip', uuid='2a0a54b4-a420-... | def expand_paths(paths=None, predicate=None, filters=None, parent_uuid=None):
"""Return an unique list of resources or collections from a list of paths.
Supports fq_name and wilcards resolution.
>>> expand_paths(['virtual-network',
'floating-ip/2a0a54b4-a420-485e-8372-42f70a627ec9'])
... |
Renders a Jinja2 template to text. | def render(self, template, filename, context={}, filters={}):
"""
Renders a Jinja2 template to text.
"""
filename = os.path.normpath(filename)
path, file = os.path.split(filename)
try:
os.makedirs(path)
except OSError as exception:
if excep... |
Executes the command. | def execute(self):
"""
Executes the command.
"""
from vsgen.util.logger import VSGLogger
VSGLogger.info(self._logname, self._message)
start = time.clock()
VSGWriter.write(self._writables, self._parallel)
end = time.clock()
VSGLogger.info(self._log... |
Utility method to spawn a VSGWriter for each element in a collection.
:param list pylist: A list of VSG objects (PrProjects, VSGSolutions, etc)
:param bool parallel: Flag to enable asynchronous writing. | def write(pylist, parallel=True):
"""
Utility method to spawn a VSGWriter for each element in a collection.
:param list pylist: A list of VSG objects (PrProjects, VSGSolutions, etc)
:param bool parallel: Flag to enable asynchronous writing.
"""
threads = [VSGWriter(o) ... |
Implement Interactor.interact by opening the browser window
and waiting for the discharge token | def interact(self, ctx, location, ir_err):
'''Implement Interactor.interact by opening the browser window
and waiting for the discharge token'''
p = ir_err.interaction_method(self.kind(), WebBrowserInteractionInfo)
if not location.endswith('/'):
location += '/'
visit_... |
Returns a token from a the wait token URL
@param wait_token_url URL to wait for (string)
:return DischargeToken | def _wait_for_token(self, ctx, wait_token_url):
''' Returns a token from a the wait token URL
@param wait_token_url URL to wait for (string)
:return DischargeToken
'''
resp = requests.get(wait_token_url)
if resp.status_code != 200:
raise InteractionError('cann... |
Create a new instance of WebBrowserInteractionInfo, as expected
by the Error.interaction_method method.
@param info_dict The deserialized JSON object
@return a new WebBrowserInteractionInfo object. | def from_dict(cls, info_dict):
'''Create a new instance of WebBrowserInteractionInfo, as expected
by the Error.interaction_method method.
@param info_dict The deserialized JSON object
@return a new WebBrowserInteractionInfo object.
'''
return WebBrowserInteractionInfo(
... |
Returns a `list` of all the `System` objects to the cluster. Updates every time - no caching.
:return: a `list` of all the `System` objects known to the cluster.
:rtype: list | def get(self):
"""
Returns a `list` of all the `System` objects to the cluster. Updates every time - no caching.
:return: a `list` of all the `System` objects known to the cluster.
:rtype: list
"""
self.conn.connection._check_login()
response = self.conn.connecti... |
Set name for SDS
:param name: Name of SDS
:param sdsObj: ScaleIO SDS object
:return: POST request response
:rtype: Requests POST response object | def set_sds_name(self, name, sdsObj):
"""
Set name for SDS
:param name: Name of SDS
:param sdsObj: ScaleIO SDS object
:return: POST request response
:rtype: Requests POST response object
"""
# TODO:
# Check if object parameters are the correct type... |
Unregister SDS from MDM/SIO Cluster
:param sdsObj: ScaleIO SDS objecty
:return: POST request response
:rtype: Requests POST response object | def unregisterSds(self, sdsObj):
"""
Unregister SDS from MDM/SIO Cluster
:param sdsObj: ScaleIO SDS objecty
:return: POST request response
:rtype: Requests POST response object
"""
self.conn.connection._check_login()
response = self.conn.connection._do_pos... |
Register SDS with MDM/SIO Cluster
:param sdsObj: ScaleIO SDS object
:return: POST request response
:rtype: Requests POST response object | def registerSds(self, sdsObj, **kwargs):
"""
Register SDS with MDM/SIO Cluster
:param sdsObj: ScaleIO SDS object
:return: POST request response
:rtype: Requests POST response object
"""
# Register existing SDS running SDS binary (need to be installed manually but ... |
Get list of SDS objects attached to a specific ScaleIO Faultset
:param faultSetObj: ScaleIO Faultset object
:rtype: list of SDS in specified Faultset | def get_sds_in_faultset(self, faultSetObj):
"""
Get list of SDS objects attached to a specific ScaleIO Faultset
:param faultSetObj: ScaleIO Faultset object
:rtype: list of SDS in specified Faultset
"""
self.conn.connection._check_login()
response = self.conn.conne... |
Get ScaleIO SDS object by its name
:param name: Name of SDS
:return: ScaleIO SDS object
:raise KeyError: No SDS with specified name found
:rtype: SDS object | def get_sds_by_name(self,name):
"""
Get ScaleIO SDS object by its name
:param name: Name of SDS
:return: ScaleIO SDS object
:raise KeyError: No SDS with specified name found
:rtype: SDS object
"""
for sds in self.sds:
if sds.name == name:
... |
Get ScaleIO SDS object by its ip address
:param name: IP address of SDS
:return: ScaleIO SDS object
:raise KeyError: No SDS with specified ip found
:rtype: SDS object | def get_sds_by_ip(self,ip):
"""
Get ScaleIO SDS object by its ip address
:param name: IP address of SDS
:return: ScaleIO SDS object
:raise KeyError: No SDS with specified ip found
:rtype: SDS object
"""
if self.conn.is_ip_addr(ip):
for sds in s... |
Get ScaleIO SDS object by its id
:param name: ID of SDS
:return: ScaleIO SDS object
:raise KeyError: No SDS with specified id found
:rtype: SDS object | def get_sds_by_id(self,id):
"""
Get ScaleIO SDS object by its id
:param name: ID of SDS
:return: ScaleIO SDS object
:raise KeyError: No SDS with specified id found
:rtype: SDS object
"""
for sds in self.sds:
if sds.id == id:
ret... |
Sets a new value for a given configuration parameter.
If it already exists, an Exception is thrown.
To overwrite an existing value, set overwrite to True.
:param name: Unique name of the parameter
:param value: Value of the configuration parameter
:param overwrite: If true, an ... | def set(self, name, value, overwrite=False):
"""
Sets a new value for a given configuration parameter.
If it already exists, an Exception is thrown.
To overwrite an existing value, set overwrite to True.
:param name: Unique name of the parameter
:param value: Value of t... |
Creates missing types for fields with a CardinalityField part.
It is assumed that the primary type converter for cardinality=1
is registered in the type dictionary.
:param schema: Parse schema (or format) for parser (as string).
:param type_dict: Type dictionary with type converters.
... | def create_missing_types(cls, schema, type_dict, type_builder=None):
"""Creates missing types for fields with a CardinalityField part.
It is assumed that the primary type converter for cardinality=1
is registered in the type dictionary.
:param schema: Parse schema (or format) for parse... |
Extract the type names for fields with CardinalityField part.
Selects only the missing type names that are not in the type dictionary.
:param schema: Parse schema to use (as string).
:param type_dict: Type dictionary with type converters.
:return: Generator with missing type names ... | def extract_missing_special_type_names(schema, type_dict):
"""Extract the type names for fields with CardinalityField part.
Selects only the missing type names that are not in the type dictionary.
:param schema: Parse schema to use (as string).
:param type_dict: Type dictionary wit... |
Checks an allow or a deny caveat. The need_ops parameter specifies
whether we require all the operations in the caveat to be declared in
the context. | def _check_operations(ctx, need_ops, arg):
''' Checks an allow or a deny caveat. The need_ops parameter specifies
whether we require all the operations in the caveat to be declared in
the context.
'''
ctx_ops = ctx.get(OP_KEY, [])
if len(ctx_ops) == 0:
if need_ops:
f = arg.sp... |
Checks the caveat against all registered caveat conditions.
:return: error message string if any or None | def check_first_party_caveat(self, ctx, cav):
''' Checks the caveat against all registered caveat conditions.
:return: error message string if any or None
'''
try:
cond, arg = parse_caveat(cav)
except ValueError as ex:
# If we can't parse it, perhaps it's ... |
Returns information on all the registered checkers.
Sorted by namespace and then name
:returns a list of CheckerInfo | def info(self):
''' Returns information on all the registered checkers.
Sorted by namespace and then name
:returns a list of CheckerInfo
'''
return sorted(self._checkers.values(), key=lambda x: (x.ns, x.name)) |
Registers the given condition(string) in the given namespace
uri (string) to be checked with the given check function.
The check function checks a caveat by passing an auth context, a cond
parameter(string) that holds the caveat condition including any
namespace prefix and an arg paramet... | def register(self, cond, uri, check):
''' Registers the given condition(string) in the given namespace
uri (string) to be checked with the given check function.
The check function checks a caveat by passing an auth context, a cond
parameter(string) that holds the caveat condition includi... |
Registers all the standard checkers in the given checker.
If not present already, the standard checkers schema (STD_NAMESPACE) is
added to the checker's namespace with an empty prefix. | def register_std(self):
''' Registers all the standard checkers in the given checker.
If not present already, the standard checkers schema (STD_NAMESPACE) is
added to the checker's namespace with an empty prefix.
'''
self._namespace.register(STD_NAMESPACE, '')
for cond i... |
Implements Authorizer.authorize by calling f with the given identity
for each operation. | def authorize(self, ctx, identity, ops):
'''Implements Authorizer.authorize by calling f with the given identity
for each operation.
'''
allowed = []
caveats = []
for op in ops:
ok, fcaveats = self._f(ctx, identity, op)
allowed.append(ok)
... |
Implements Authorizer.authorize by calling identity.allow to
determine whether the identity is a member of the ACLs associated with
the given operations. | def authorize(self, ctx, identity, ops):
'''Implements Authorizer.authorize by calling identity.allow to
determine whether the identity is a member of the ACLs associated with
the given operations.
'''
if len(ops) == 0:
# Anyone is allowed to do nothing.
r... |
Matches both the subject and action, not necessarily the conditions. | def is_relevant(self, action, subject):
"""
Matches both the subject and action, not necessarily the conditions.
"""
return self.matches_action(action) and self.matches_subject(subject) |
Check that a given HAL id is a valid one.
:param hal_id: The HAL id to be checked.
:returns: Boolean indicating whether the HAL id is valid or not.
>>> is_valid("hal-01258754, version 1")
True
>>> is_valid("hal-01258754")
True
>>> is_valid("hal-01258754v2")
True
>>> is_valid("fo... | def is_valid(hal_id):
"""
Check that a given HAL id is a valid one.
:param hal_id: The HAL id to be checked.
:returns: Boolean indicating whether the HAL id is valid or not.
>>> is_valid("hal-01258754, version 1")
True
>>> is_valid("hal-01258754")
True
>>> is_valid("hal-01258754v... |
Extract HAL ids from a text.
:param text: The text to extract HAL ids from.
:returns: A list of matching HAL ids.
>>> sorted(extract_from_text("hal-01258754 hal-01258754v2 foobar"))
['hal-01258754', 'hal-01258754v2'] | def extract_from_text(text):
"""
Extract HAL ids from a text.
:param text: The text to extract HAL ids from.
:returns: A list of matching HAL ids.
>>> sorted(extract_from_text("hal-01258754 hal-01258754v2 foobar"))
['hal-01258754', 'hal-01258754v2']
"""
return tools.remove_duplicates([... |
Creates a VSG solution from a configparser instance.
:param object config: The instance of the configparser class
:param str section: The section name to read.
:param kwargs: List of additional keyworded arguments to be passed into the VSGSolution.
:return: A valid VSGSolution instance... | def _getsolution(self, config, section, **kwargs):
"""
Creates a VSG solution from a configparser instance.
:param object config: The instance of the configparser class
:param str section: The section name to read.
:param kwargs: List of additional keyworded arguments to be pas... |
Creates a VSG project from a configparser instance.
:param object config: The instance of the configparser class
:param str section: The section name to read.
:param kwargs: List of additional keyworded arguments to be passed into the VSGProject.
:return: A valid VSGProject instance if... | def _getproject(self, config, section, **kwargs):
"""
Creates a VSG project from a configparser instance.
:param object config: The instance of the configparser class
:param str section: The section name to read.
:param kwargs: List of additional keyworded arguments to be passe... |
Creates an VSGSuite instance from a filename.
:param str filename: The fully qualified path to the VSG configuration file. | def from_file(cls, filename):
"""
Creates an VSGSuite instance from a filename.
:param str filename: The fully qualified path to the VSG configuration file.
"""
# Read the configuration file
config = VSGConfigParser()
if filename not in config.read([filename]):
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.