_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q256900 | parse_course_key | validation | def parse_course_key(course_identifier):
"""
Return the serialized course key given either a course run ID or course key.
"""
try:
course_run_key = CourseKey.from_string(course_identifier)
except InvalidKeyError:
# Assume we already have a course key.
return course_identifier... | python | {
"resource": ""
} |
q256901 | EnterpriseXAPIClient.lrs | validation | def lrs(self):
"""
LRS client instance to be used for sending statements.
"""
return RemoteLRS(
version=self.lrs_configuration.version,
endpoint=self.lrs_configuration.endpoint,
auth=self.lrs_configuration.authorization_header,
) | python | {
"resource": ""
} |
q256902 | EnterpriseXAPIClient.save_statement | validation | def save_statement(self, statement):
"""
Save xAPI statement.
Arguments:
statement (EnterpriseStatement): xAPI Statement to send to the LRS.
Raises:
ClientError: If xAPI statement fails to save.
"""
response = self.lrs.save_statement(statement)
... | python | {
"resource": ""
} |
q256903 | SapSuccessFactorsLearnerExporter.get_learner_data_records | validation | def get_learner_data_records(self, enterprise_enrollment, completed_date=None, grade=None, is_passing=False):
"""
Return a SapSuccessFactorsLearnerDataTransmissionAudit with the given enrollment and course completion data.
If completed_date is None and the learner isn't passing, then course com... | python | {
"resource": ""
} |
q256904 | SapSuccessFactorsLearnerManger.unlink_learners | validation | def unlink_learners(self):
"""
Iterate over each learner and unlink inactive SAP channel learners.
This method iterates over each enterprise learner and unlink learner
from the enterprise if the learner is marked inactive in the related
integrated channel.
"""
sa... | python | {
"resource": ""
} |
q256905 | has_implicit_access_to_dashboard | validation | def has_implicit_access_to_dashboard(user, obj): # pylint: disable=unused-argument
"""
Check that if request user has implicit access to `ENTERPRISE_DASHBOARD_ADMIN_ROLE` feature role.
Returns:
boolean: whether the request user has access or not
"""
request = get_request_or_stub()
deco... | python | {
"resource": ""
} |
q256906 | has_implicit_access_to_catalog | validation | def has_implicit_access_to_catalog(user, obj): # pylint: disable=unused-argument
"""
Check that if request user has implicit access to `ENTERPRISE_CATALOG_ADMIN_ROLE` feature role.
Returns:
boolean: whether the request user has access or not
"""
request = get_request_or_stub()
decoded_... | python | {
"resource": ""
} |
q256907 | has_implicit_access_to_enrollment_api | validation | def has_implicit_access_to_enrollment_api(user, obj): # pylint: disable=unused-argument
"""
Check that if request user has implicit access to `ENTERPRISE_ENROLLMENT_API_ADMIN_ROLE` feature role.
Returns:
boolean: whether the request user has access or not
"""
request = get_request_or_stub(... | python | {
"resource": ""
} |
q256908 | EnterpriseCustomerEntitlementInline.ecommerce_coupon_url | validation | def ecommerce_coupon_url(self, instance):
"""
Instance is EnterpriseCustomer. Return e-commerce coupon urls.
"""
if not instance.entitlement_id:
return "N/A"
return format_html(
'<a href="{base_url}/coupons/{id}" target="_blank">View coupon "{id}" details... | python | {
"resource": ""
} |
q256909 | dropHistoricalTable | validation | def dropHistoricalTable(apps, schema_editor):
"""
Drops the historical sap_success_factors table named herein.
"""
table_name = 'sap_success_factors_historicalsapsuccessfactorsenterprisecus80ad'
if table_name in connection.introspection.table_names():
migrations.DeleteModel(
name... | python | {
"resource": ""
} |
q256910 | export_as_csv_action | validation | def export_as_csv_action(description="Export selected objects as CSV file", fields=None, header=True):
"""
Return an export csv action.
Arguments:
description (string): action description
fields ([string]): list of model fields to include
header (bool): whether or not to output the ... | python | {
"resource": ""
} |
q256911 | get_clear_catalog_id_action | validation | def get_clear_catalog_id_action(description=None):
"""
Return the action method to clear the catalog ID for a EnterpriseCustomer.
"""
description = description or _("Unlink selected objects from existing course catalogs")
def clear_catalog_id(modeladmin, request, queryset): # pylint: disable=unuse... | python | {
"resource": ""
} |
q256912 | Account._login | validation | def _login(self, email, password):
"""
Login to pybotvac account using provided email and password.
:param email: email for pybotvac account
:param password: Password for pybotvac account
:return:
"""
response = requests.post(urljoin(self.ENDPOINT, 'sessions'),
... | python | {
"resource": ""
} |
q256913 | Account.refresh_maps | validation | def refresh_maps(self):
"""
Get information about maps of the robots.
:return:
"""
for robot in self.robots:
resp2 = (
requests.get(urljoin(self.ENDPOINT, 'users/me/robots/{}/maps'.format(robot.serial)),
headers=self._head... | python | {
"resource": ""
} |
q256914 | Account.refresh_robots | validation | def refresh_robots(self):
"""
Get information about robots connected to account.
:return:
"""
resp = requests.get(urljoin(self.ENDPOINT, 'dashboard'),
headers=self._headers)
resp.raise_for_status()
for robot in resp.json()['robots']:
... | python | {
"resource": ""
} |
q256915 | Account.get_map_image | validation | def get_map_image(url, dest_path=None):
"""
Return a requested map from a robot.
:return:
"""
image = requests.get(url, stream=True, timeout=10)
if dest_path:
image_url = url.rsplit('/', 2)[1] + '-' + url.rsplit('/', 1)[1]
image_filename = image_... | python | {
"resource": ""
} |
q256916 | Account.refresh_persistent_maps | validation | def refresh_persistent_maps(self):
"""
Get information about persistent maps of the robots.
:return:
"""
for robot in self._robots:
resp2 = (requests.get(urljoin(
self.ENDPOINT,
'users/me/robots/{}/persistent_maps'.format(robot.serial)... | python | {
"resource": ""
} |
q256917 | _calculate_distance | validation | def _calculate_distance(latlon1, latlon2):
"""Calculates the distance between two points on earth.
"""
lat1, lon1 = latlon1
lat2, lon2 = latlon2
dlon = lon2 - lon1
dlat = lat2 - lat1
R = 6371 # radius of the earth in kilometers
a = np.sin(dlat / 2)**2 + np.cos(lat1) * np.cos(lat2) * (np... | python | {
"resource": ""
} |
q256918 | graph2dict | validation | def graph2dict(g, return_dict_of_dict=True):
"""Takes a graph and returns an adjacency list.
Parameters
----------
g : :any:`networkx.DiGraph`, :any:`networkx.Graph`, etc.
Any object that networkx can turn into a
:any:`DiGraph<networkx.DiGraph>`.
return_dict_of_dict : bool (optional... | python | {
"resource": ""
} |
q256919 | _matrix2dict | validation | def _matrix2dict(matrix, etype=False):
"""Takes an adjacency matrix and returns an adjacency list."""
n = len(matrix)
adj = {k: {} for k in range(n)}
for k in range(n):
for j in range(n):
if matrix[k, j] != 0:
adj[k][j] = {} if not etype else matrix[k, j]
return ... | python | {
"resource": ""
} |
q256920 | _dict2dict | validation | def _dict2dict(adj_dict):
"""Takes a dictionary based representation of an adjacency list
and returns a dict of dicts based representation.
"""
item = adj_dict.popitem()
adj_dict[item[0]] = item[1]
if not isinstance(item[1], dict):
new_dict = {}
for key, value in adj_dict.items()... | python | {
"resource": ""
} |
q256921 | adjacency2graph | validation | def adjacency2graph(adjacency, edge_type=None, adjust=1, **kwargs):
"""Takes an adjacency list, dict, or matrix and returns a graph.
The purpose of this function is take an adjacency list (or matrix)
and return a :class:`.QueueNetworkDiGraph` that can be used with a
:class:`.QueueNetwork` instance. The... | python | {
"resource": ""
} |
q256922 | QueueNetworkDiGraph.get_edge_type | validation | def get_edge_type(self, edge_type):
"""Returns all edges with the specified edge type.
Parameters
----------
edge_type : int
An integer specifying what type of edges to return.
Returns
-------
out : list of 2-tuples
A list of 2-tuples rep... | python | {
"resource": ""
} |
q256923 | QueueNetworkDiGraph.draw_graph | validation | def draw_graph(self, line_kwargs=None, scatter_kwargs=None, **kwargs):
"""Draws the graph.
Uses matplotlib, specifically
:class:`~matplotlib.collections.LineCollection` and
:meth:`~matplotlib.axes.Axes.scatter`. Gets the default
keyword arguments for both methods by calling
... | python | {
"resource": ""
} |
q256924 | QueueNetworkDiGraph.lines_scatter_args | validation | def lines_scatter_args(self, line_kwargs=None, scatter_kwargs=None, pos=None):
"""Returns the arguments used when plotting.
Takes any keyword arguments for
:class:`~matplotlib.collections.LineCollection` and
:meth:`~matplotlib.axes.Axes.scatter` and returns two
dictionaries with... | python | {
"resource": ""
} |
q256925 | poisson_random_measure | validation | def poisson_random_measure(t, rate, rate_max):
"""A function that returns the arrival time of the next arrival for
a Poisson random measure.
Parameters
----------
t : float
The start time from which to simulate the next arrival time.
rate : function
The *intensity function* for ... | python | {
"resource": ""
} |
q256926 | QueueServer._current_color | validation | def _current_color(self, which=0):
"""Returns a color for the queue.
Parameters
----------
which : int (optional, default: ``0``)
Specifies the type of color to return.
Returns
-------
color : list
Returns a RGBA color that is represented... | python | {
"resource": ""
} |
q256927 | QueueServer.fetch_data | validation | def fetch_data(self, return_header=False):
"""Fetches data from the queue.
Parameters
----------
return_header : bool (optonal, default: ``False``)
Determines whether the column headers are returned.
Returns
-------
data : :class:`~numpy.ndarray`
... | python | {
"resource": ""
} |
q256928 | QueueServer.next_event_description | validation | def next_event_description(self):
"""Returns an integer representing whether the next event is
an arrival, a departure, or nothing.
Returns
-------
out : int
An integer representing whether the next event is an
arrival or a departure: ``1`` corresponds to... | python | {
"resource": ""
} |
q256929 | QueueServer.set_num_servers | validation | def set_num_servers(self, n):
"""Change the number of servers in the queue to ``n``.
Parameters
----------
n : int or :const:`numpy.infty`
A positive integer (or ``numpy.infty``) to set the number
of queues in the system to.
Raises
------
... | python | {
"resource": ""
} |
q256930 | QueueServer.simulate | validation | def simulate(self, n=1, t=None, nA=None, nD=None):
"""This method simulates the queue forward for a specified
amount of simulation time, or for a specific number of
events.
Parameters
----------
n : int (optional, default: ``1``)
The number of events to simul... | python | {
"resource": ""
} |
q256931 | _get_queues | validation | def _get_queues(g, queues, edge, edge_type):
"""Used to specify edge indices from different types of arguments."""
INT = numbers.Integral
if isinstance(queues, INT):
queues = [queues]
elif queues is None:
if edge is not None:
if isinstance(edge, tuple):
if is... | python | {
"resource": ""
} |
q256932 | QueueNetwork.animate | validation | def animate(self, out=None, t=None, line_kwargs=None,
scatter_kwargs=None, **kwargs):
"""Animates the network as it's simulating.
The animations can be saved to disk or viewed in interactive
mode. Closing the window ends the animation if viewed in
interactive mode. This ... | python | {
"resource": ""
} |
q256933 | QueueNetwork.clear | validation | def clear(self):
"""Resets the queue to its initial state.
The attributes ``t``, ``num_events``, ``num_agents`` are set to
zero, :meth:`.reset_colors` is called, and the
:meth:`.QueueServer.clear` method is called for each queue in
the network.
Notes
-----
... | python | {
"resource": ""
} |
q256934 | QueueNetwork.clear_data | validation | def clear_data(self, queues=None, edge=None, edge_type=None):
"""Clears data from all queues.
If none of the parameters are given then every queue's data is
cleared.
Parameters
----------
queues : int or an iterable of int (optional)
The edge index (or an it... | python | {
"resource": ""
} |
q256935 | QueueNetwork.copy | validation | def copy(self):
"""Returns a deep copy of itself."""
net = QueueNetwork(None)
net.g = self.g.copy()
net.max_agents = copy.deepcopy(self.max_agents)
net.nV = copy.deepcopy(self.nV)
net.nE = copy.deepcopy(self.nE)
net.num_agents = copy.deepcopy(self.num_agents)
... | python | {
"resource": ""
} |
q256936 | QueueNetwork.draw | validation | def draw(self, update_colors=True, line_kwargs=None,
scatter_kwargs=None, **kwargs):
"""Draws the network. The coloring of the network corresponds
to the number of agents at each queue.
Parameters
----------
update_colors : ``bool`` (optional, default: ``True``).
... | python | {
"resource": ""
} |
q256937 | QueueNetwork.get_agent_data | validation | def get_agent_data(self, queues=None, edge=None, edge_type=None, return_header=False):
"""Gets data from queues and organizes it by agent.
If none of the parameters are given then data from every
:class:`.QueueServer` is retrieved.
Parameters
----------
queues : int or ... | python | {
"resource": ""
} |
q256938 | QueueNetwork.get_queue_data | validation | def get_queue_data(self, queues=None, edge=None, edge_type=None, return_header=False):
"""Gets data from all the queues.
If none of the parameters are given then data from every
:class:`.QueueServer` is retrieved.
Parameters
----------
queues : int or an *array_like* of... | python | {
"resource": ""
} |
q256939 | QueueNetwork.initialize | validation | def initialize(self, nActive=1, queues=None, edges=None, edge_type=None):
"""Prepares the ``QueueNetwork`` for simulation.
Each :class:`.QueueServer` in the network starts inactive,
which means they do not accept arrivals from outside the
network, and they have no agents in their system... | python | {
"resource": ""
} |
q256940 | QueueNetwork.next_event_description | validation | def next_event_description(self):
"""Returns whether the next event is an arrival or a departure
and the queue the event is accuring at.
Returns
-------
des : str
Indicates whether the next event is an arrival, a
departure, or nothing; returns ``'Arrival'... | python | {
"resource": ""
} |
q256941 | QueueNetwork.reset_colors | validation | def reset_colors(self):
"""Resets all edge and vertex colors to their default values."""
for k, e in enumerate(self.g.edges()):
self.g.set_ep(e, 'edge_color', self.edge2queue[k].colors['edge_color'])
for v in self.g.nodes():
self.g.set_vp(v, 'vertex_fill_color', self.colo... | python | {
"resource": ""
} |
q256942 | QueueNetwork.set_transitions | validation | def set_transitions(self, mat):
"""Change the routing transitions probabilities for the
network.
Parameters
----------
mat : dict or :class:`~numpy.ndarray`
A transition routing matrix or transition dictionary. If
passed a dictionary, the keys are source ... | python | {
"resource": ""
} |
q256943 | QueueNetwork.show_active | validation | def show_active(self, **kwargs):
"""Draws the network, highlighting active queues.
The colored vertices represent vertices that have at least one
queue on an in-edge that is active. Dark edges represent
queues that are active, light edges represent queues that are
inactive.
... | python | {
"resource": ""
} |
q256944 | QueueNetwork.show_type | validation | def show_type(self, edge_type, **kwargs):
"""Draws the network, highlighting queues of a certain type.
The colored vertices represent self loops of type ``edge_type``.
Dark edges represent queues of type ``edge_type``.
Parameters
----------
edge_type : int
T... | python | {
"resource": ""
} |
q256945 | QueueNetwork.simulate | validation | def simulate(self, n=1, t=None):
"""Simulates the network forward.
Simulates either a specific number of events or for a specified
amount of simulation time.
Parameters
----------
n : int (optional, default: 1)
The number of events to simulate. If ``t`` is n... | python | {
"resource": ""
} |
q256946 | QueueNetwork.start_collecting_data | validation | def start_collecting_data(self, queues=None, edge=None, edge_type=None):
"""Tells the queues to collect data on agents' arrival, service
start, and departure times.
If none of the parameters are given then every
:class:`.QueueServer` will start collecting data.
Parameters
... | python | {
"resource": ""
} |
q256947 | QueueNetwork.stop_collecting_data | validation | def stop_collecting_data(self, queues=None, edge=None, edge_type=None):
"""Tells the queues to stop collecting data on agents.
If none of the parameters are given then every
:class:`.QueueServer` will stop collecting data.
Parameters
----------
queues : int, *array_like... | python | {
"resource": ""
} |
q256948 | QueueNetwork.transitions | validation | def transitions(self, return_matrix=True):
"""Returns the routing probabilities for each vertex in the
graph.
Parameters
----------
return_matrix : bool (optional, the default is ``True``)
Specifies whether an :class:`~numpy.ndarray` is returned.
If ``Fal... | python | {
"resource": ""
} |
q256949 | UnionFind.size | validation | def size(self, s):
"""Returns the number of elements in the set that ``s`` belongs to.
Parameters
----------
s : object
An object
Returns
-------
out : int
The number of elements in the set that ``s`` belongs to.
"""
leade... | python | {
"resource": ""
} |
q256950 | UnionFind.find | validation | def find(self, s):
"""Locates the leader of the set to which the element ``s`` belongs.
Parameters
----------
s : object
An object that the ``UnionFind`` contains.
Returns
-------
object
The leader of the set that contains ``s``.
... | python | {
"resource": ""
} |
q256951 | UnionFind.union | validation | def union(self, a, b):
"""Merges the set that contains ``a`` with the set that contains ``b``.
Parameters
----------
a, b : objects
Two objects whose sets are to be merged.
"""
s1, s2 = self.find(a), self.find(b)
if s1 != s2:
r1, r2 = sel... | python | {
"resource": ""
} |
q256952 | generate_transition_matrix | validation | def generate_transition_matrix(g, seed=None):
"""Generates a random transition matrix for the graph ``g``.
Parameters
----------
g : :any:`networkx.DiGraph`, :class:`numpy.ndarray`, dict, etc.
Any object that :any:`DiGraph<networkx.DiGraph>` accepts.
seed : int (optional)
An integer... | python | {
"resource": ""
} |
q256953 | generate_random_graph | validation | def generate_random_graph(num_vertices=250, prob_loop=0.5, **kwargs):
"""Creates a random graph where the edges have different types.
This method calls :func:`.minimal_random_graph`, and then adds
a loop to each vertex with ``prob_loop`` probability. It then
calls :func:`.set_types_random` on the resul... | python | {
"resource": ""
} |
q256954 | generate_pagerank_graph | validation | def generate_pagerank_graph(num_vertices=250, **kwargs):
"""Creates a random graph where the vertex types are
selected using their pagerank.
Calls :func:`.minimal_random_graph` and then
:func:`.set_types_rank` where the ``rank`` keyword argument
is given by :func:`networkx.pagerank`.
Parameter... | python | {
"resource": ""
} |
q256955 | minimal_random_graph | validation | def minimal_random_graph(num_vertices, seed=None, **kwargs):
"""Creates a connected graph with random vertex locations.
Parameters
----------
num_vertices : int
The number of vertices in the graph.
seed : int (optional)
An integer used to initialize numpy's psuedorandom number
... | python | {
"resource": ""
} |
q256956 | get_class_traits | validation | def get_class_traits(klass):
""" Yield all of the documentation for trait definitions on a class object.
"""
# FIXME: gracefully handle errors here or in the caller?
source = inspect.getsource(klass)
cb = CommentBlocker()
cb.process_file(StringIO(source))
mod_ast = compiler.parse(source)
... | python | {
"resource": ""
} |
q256957 | NonComment.add | validation | def add(self, string, start, end, line):
""" Add lines to the block.
"""
if string.strip():
# Only add if not entirely whitespace.
self.start_lineno = min(self.start_lineno, start[0])
self.end_lineno = max(self.end_lineno, end[0]) | python | {
"resource": ""
} |
q256958 | CommentBlocker.process_file | validation | def process_file(self, file):
""" Process a file object.
"""
if sys.version_info[0] >= 3:
nxt = file.__next__
else:
nxt = file.next
for token in tokenize.generate_tokens(nxt):
self.process_token(*token)
self.make_index() | python | {
"resource": ""
} |
q256959 | CommentBlocker.process_token | validation | def process_token(self, kind, string, start, end, line):
""" Process a single token.
"""
if self.current_block.is_comment:
if kind == tokenize.COMMENT:
self.current_block.add(string, start, end, line)
else:
self.new_noncomment(start[0], end... | python | {
"resource": ""
} |
q256960 | CommentBlocker.new_noncomment | validation | def new_noncomment(self, start_lineno, end_lineno):
""" We are transitioning from a noncomment to a comment.
"""
block = NonComment(start_lineno, end_lineno)
self.blocks.append(block)
self.current_block = block | python | {
"resource": ""
} |
q256961 | CommentBlocker.new_comment | validation | def new_comment(self, string, start, end, line):
""" Possibly add a new comment.
Only adds a new comment if this comment is the only thing on the line.
Otherwise, it extends the noncomment block.
"""
prefix = line[:start[1]]
if prefix.strip():
# Oops! Trailin... | python | {
"resource": ""
} |
q256962 | CommentBlocker.make_index | validation | def make_index(self):
""" Make the index mapping lines of actual code to their associated
prefix comments.
"""
for prev, block in zip(self.blocks[:-1], self.blocks[1:]):
if not block.is_comment:
self.index[block.start_lineno] = prev | python | {
"resource": ""
} |
q256963 | CommentBlocker.search_for_comment | validation | def search_for_comment(self, lineno, default=None):
""" Find the comment block just before the given line number.
Returns None (or the specified default) if there is no such block.
"""
if not self.index:
self.make_index()
block = self.index.get(lineno, None)
... | python | {
"resource": ""
} |
q256964 | BaseBackend._load | validation | def _load(self, config):
"""
Loads config from string or dict
"""
if isinstance(config, six.string_types):
try:
config = json.loads(config)
except ValueError:
pass
if not isinstance(config, dict):
raise TypeError... | python | {
"resource": ""
} |
q256965 | BaseBackend._merge_config | validation | def _merge_config(self, config, templates):
"""
Merges config with templates
"""
if not templates:
return config
# type check
if not isinstance(templates, list):
raise TypeError('templates argument must be an instance of list')
# merge temp... | python | {
"resource": ""
} |
q256966 | BaseBackend.render | validation | def render(self, files=True):
"""
Converts the configuration dictionary into the corresponding configuration format
:param files: whether to include "additional files" in the output or not;
defaults to ``True``
:returns: string with output
"""
self.... | python | {
"resource": ""
} |
q256967 | BaseBackend.generate | validation | def generate(self):
"""
Returns a ``BytesIO`` instance representing an in-memory tar.gz archive
containing the native router configuration.
:returns: in-memory tar.gz archive, instance of ``BytesIO``
"""
tar_bytes = BytesIO()
tar = tarfile.open(fileobj=tar_bytes,... | python | {
"resource": ""
} |
q256968 | BaseBackend.write | validation | def write(self, name, path='./'):
"""
Like ``generate`` but writes to disk.
:param name: file name, the tar.gz extension will be added automatically
:param path: directory where the file will be written to, defaults to ``./``
:returns: None
"""
byte_object = self... | python | {
"resource": ""
} |
q256969 | BaseBackend._add_file | validation | def _add_file(self, tar, name, contents, mode=DEFAULT_FILE_MODE):
"""
Adds a single file in tarfile instance.
:param tar: tarfile instance
:param name: string representing filename or path
:param contents: string representing file contents
:param mode: string representin... | python | {
"resource": ""
} |
q256970 | BaseBackend.parse | validation | def parse(self, native):
"""
Parses a native configuration and converts
it to a NetJSON configuration dictionary
"""
if not hasattr(self, 'parser') or not self.parser:
raise NotImplementedError('Parser class not specified')
parser = self.parser(native)
... | python | {
"resource": ""
} |
q256971 | merge_config | validation | def merge_config(template, config, list_identifiers=None):
"""
Merges ``config`` on top of ``template``.
Conflicting keys are handled in the following way:
* simple values (eg: ``str``, ``int``, ``float``, ecc) in ``config`` will
overwrite the ones in ``template``
* values of type ``list`` i... | python | {
"resource": ""
} |
q256972 | merge_list | validation | def merge_list(list1, list2, identifiers=None):
"""
Merges ``list2`` on top of ``list1``.
If both lists contain dictionaries which have keys specified
in ``identifiers`` which have equal values, those dicts will
be merged (dicts in ``list2`` will override dicts in ``list1``).
The remaining elem... | python | {
"resource": ""
} |
q256973 | evaluate_vars | validation | def evaluate_vars(data, context=None):
"""
Evaluates variables in ``data``
:param data: data structure containing variables, may be
``str``, ``dict`` or ``list``
:param context: ``dict`` containing variables
:returns: modified data structure
"""
context = context or {}
... | python | {
"resource": ""
} |
q256974 | get_copy | validation | def get_copy(dict_, key, default=None):
"""
Looks for a key in a dictionary, if found returns
a deepcopied value, otherwise returns default value
"""
value = dict_.get(key, default)
if value:
return deepcopy(value)
return value | python | {
"resource": ""
} |
q256975 | BaseConverter.type_cast | validation | def type_cast(self, item, schema=None):
"""
Loops over item and performs type casting
according to supplied schema fragment
"""
if schema is None:
schema = self._schema
properties = schema['properties']
for key, value in item.items():
if ke... | python | {
"resource": ""
} |
q256976 | OpenWisp._get_install_context | validation | def _get_install_context(self):
"""
returns the template context for install.sh and uninstall.sh
"""
config = self.config
# layer2 VPN list
l2vpn = []
for vpn in self.config.get('openvpn', []):
if vpn.get('dev_type') != 'tap':
continue
... | python | {
"resource": ""
} |
q256977 | OpenWisp._add_install | validation | def _add_install(self, context):
"""
generates install.sh and adds it to included files
"""
contents = self._render_template('install.sh', context)
self.config.setdefault('files', []) # file list might be empty
# add install.sh to list of included files
self._add... | python | {
"resource": ""
} |
q256978 | OpenWisp._add_uninstall | validation | def _add_uninstall(self, context):
"""
generates uninstall.sh and adds it to included files
"""
contents = self._render_template('uninstall.sh', context)
self.config.setdefault('files', []) # file list might be empty
# add uninstall.sh to list of included files
s... | python | {
"resource": ""
} |
q256979 | OpenWisp._add_tc_script | validation | def _add_tc_script(self):
"""
generates tc_script.sh and adds it to included files
"""
# fill context
context = dict(tc_options=self.config.get('tc_options', []))
# import pdb; pdb.set_trace()
contents = self._render_template('tc_script.sh', context)
self.... | python | {
"resource": ""
} |
q256980 | BaseRenderer.render | validation | def render(self):
"""
Renders configuration by using the jinja2 templating engine
"""
# get jinja2 template
template_name = '{0}.jinja2'.format(self.get_name())
template = self.template_env.get_template(template_name)
# render template and cleanup
context ... | python | {
"resource": ""
} |
q256981 | Interfaces.__intermediate_addresses | validation | def __intermediate_addresses(self, interface):
"""
converts NetJSON address to
UCI intermediate data structure
"""
address_list = self.get_copy(interface, 'addresses')
# do not ignore interfaces if they do not contain any address
if not address_list:
r... | python | {
"resource": ""
} |
q256982 | Interfaces.__intermediate_interface | validation | def __intermediate_interface(self, interface, uci_name):
"""
converts NetJSON interface to
UCI intermediate data structure
"""
interface.update({
'.type': 'interface',
'.name': uci_name,
'ifname': interface.pop('name')
})
if 'ne... | python | {
"resource": ""
} |
q256983 | Interfaces.__intermediate_address | validation | def __intermediate_address(self, address):
"""
deletes NetJSON address keys
"""
for key in self._address_keys:
if key in address:
del address[key]
return address | python | {
"resource": ""
} |
q256984 | Interfaces.__intermediate_bridge | validation | def __intermediate_bridge(self, interface, i):
"""
converts NetJSON bridge to
UCI intermediate data structure
"""
# ensure type "bridge" is only given to one logical interface
if interface['type'] == 'bridge' and i < 2:
bridge_members = ' '.join(interface.pop(... | python | {
"resource": ""
} |
q256985 | Interfaces.__intermediate_proto | validation | def __intermediate_proto(self, interface, address):
"""
determines UCI interface "proto" option
"""
# proto defaults to static
address_proto = address.pop('proto', 'static')
if 'proto' not in interface:
return address_proto
else:
# allow ov... | python | {
"resource": ""
} |
q256986 | Interfaces.__intermediate_dns_servers | validation | def __intermediate_dns_servers(self, uci, address):
"""
determines UCI interface "dns" option
"""
# allow override
if 'dns' in uci:
return uci['dns']
# ignore if using DHCP or if "proto" is none
if address['proto'] in ['dhcp', 'dhcpv6', 'none']:
... | python | {
"resource": ""
} |
q256987 | Interfaces.__intermediate_dns_search | validation | def __intermediate_dns_search(self, uci, address):
"""
determines UCI interface "dns_search" option
"""
# allow override
if 'dns_search' in uci:
return uci['dns_search']
# ignore if "proto" is none
if address['proto'] == 'none':
return None... | python | {
"resource": ""
} |
q256988 | Radios.__intermediate_htmode | validation | def __intermediate_htmode(self, radio):
"""
only for mac80211 driver
"""
protocol = radio.pop('protocol')
channel_width = radio.pop('channel_width')
# allow overriding htmode
if 'htmode' in radio:
return radio['htmode']
if protocol == '802.11n'... | python | {
"resource": ""
} |
q256989 | Radios.__netjson_protocol | validation | def __netjson_protocol(self, radio):
"""
determines NetJSON protocol radio attribute
"""
htmode = radio.get('htmode')
hwmode = radio.get('hwmode', None)
if htmode.startswith('HT'):
return '802.11n'
elif htmode.startswith('VHT'):
return '802... | python | {
"resource": ""
} |
q256990 | Radios.__netjson_channel_width | validation | def __netjson_channel_width(self, radio):
"""
determines NetJSON channel_width radio attribute
"""
htmode = radio.pop('htmode')
if htmode == 'NONE':
return 20
channel_width = htmode.replace('VHT', '').replace('HT', '')
# we need to override htmode
... | python | {
"resource": ""
} |
q256991 | OpenVpn.auto_client | validation | def auto_client(cls, host, server, ca_path=None, ca_contents=None,
cert_path=None, cert_contents=None, key_path=None,
key_contents=None):
"""
Returns a configuration dictionary representing an OpenVPN client configuration
that is compatible with the passed... | python | {
"resource": ""
} |
q256992 | OpenVpn._auto_client_files | validation | def _auto_client_files(cls, client, ca_path=None, ca_contents=None, cert_path=None,
cert_contents=None, key_path=None, key_contents=None):
"""
returns a list of NetJSON extra files for automatically generated clients
produces side effects in ``client`` dictionary
... | python | {
"resource": ""
} |
q256993 | get_install_requires | validation | def get_install_requires():
"""
parse requirements.txt, ignore links, exclude comments
"""
requirements = []
for line in open('requirements.txt').readlines():
# skip to next iteration if comment or empty line
if line.startswith('#') or line == '' or line.startswith('http') or line.st... | python | {
"resource": ""
} |
q256994 | Report.events | validation | def events(self, **kwargs):
"""Get all events for this report. Additional arguments may also be
specified that will be passed to the query function.
"""
return self.__api.events(query=EqualsOperator("report", self.hash_),
**kwargs) | python | {
"resource": ""
} |
q256995 | Node.facts | validation | def facts(self, **kwargs):
"""Get all facts of this node. Additional arguments may also be
specified that will be passed to the query function.
"""
return self.__api.facts(query=EqualsOperator("certname", self.name),
**kwargs) | python | {
"resource": ""
} |
q256996 | Node.fact | validation | def fact(self, name):
"""Get a single fact from this node."""
facts = self.facts(name=name)
return next(fact for fact in facts) | python | {
"resource": ""
} |
q256997 | Node.resources | validation | def resources(self, type_=None, title=None, **kwargs):
"""Get all resources of this node or all resources of the specified
type. Additional arguments may also be specified that will be passed
to the query function.
"""
if type_ is None:
resources = self.__api.resource... | python | {
"resource": ""
} |
q256998 | Node.resource | validation | def resource(self, type_, title, **kwargs):
"""Get a resource matching the supplied type and title. Additional
arguments may also be specified that will be passed to the query
function.
"""
resources = self.__api.resources(
type_=type_,
title=title,
... | python | {
"resource": ""
} |
q256999 | Node.reports | validation | def reports(self, **kwargs):
"""Get all reports for this node. Additional arguments may also be
specified that will be passed to the query function.
"""
return self.__api.reports(
query=EqualsOperator("certname", self.name),
**kwargs) | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.