_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q35800 | Canvas.get_appointment_groups | train | def get_appointment_groups(self, **kwargs):
"""
List appointment groups.
:calls: `GET /api/v1/appointment_groups \
<https://canvas.instructure.com/doc/api/appointment_groups.html#method.appointment_groups.index>`_
:rtype: :class:`canvasapi.paginated_list.PaginatedList` of
... | python | {
"resource": ""
} |
q35801 | Canvas.get_appointment_group | train | def get_appointment_group(self, appointment_group):
"""
Return single Appointment Group by id
:calls: `GET /api/v1/appointment_groups/:id \
<https://canvas.instructure.com/doc/api/appointment_groups.html#method.appointment_groups.show>`_
:param appointment_group: The ID of the ... | python | {
"resource": ""
} |
q35802 | Canvas.create_appointment_group | train | def create_appointment_group(self, appointment_group, **kwargs):
"""
Create a new Appointment Group.
:calls: `POST /api/v1/appointment_groups \
<https://canvas.instructure.com/doc/api/appointment_groups.html#method.appointment_groups.create>`_
:param appointment_group: The attr... | python | {
"resource": ""
} |
q35803 | Canvas.get_file | train | def get_file(self, file, **kwargs):
"""
Return the standard attachment json object for a file.
:calls: `GET /api/v1/files/:id \
<https://canvas.instructure.com/doc/api/files.html#method.files.api_show>`_
:param file: The object or ID of the file to retrieve.
:type file:... | python | {
"resource": ""
} |
q35804 | Canvas.get_folder | train | def get_folder(self, folder):
"""
Return the details for a folder
:calls: `GET /api/v1/folders/:id \
<https://canvas.instructure.com/doc/api/files.html#method.folders.show>`_
:param folder: The object or ID of the folder to retrieve.
:type folder: :class:`canvasapi.fold... | python | {
"resource": ""
} |
q35805 | Canvas.get_outcome | train | def get_outcome(self, outcome):
"""
Returns the details of the outcome with the given id.
:calls: `GET /api/v1/outcomes/:id \
<https://canvas.instructure.com/doc/api/outcomes.html#method.outcomes_api.show>`_
:param outcome: The outcome object or ID to return.
:type outc... | python | {
"resource": ""
} |
q35806 | Canvas.get_root_outcome_group | train | def get_root_outcome_group(self):
"""
Redirect to root outcome group for context
:calls: `GET /api/v1/global/root_outcome_group \
<https://canvas.instructure.com/doc/api/outcome_groups.html#method.outcome_groups_api.redirect>`_
:returns: The OutcomeGroup of the context.
... | python | {
"resource": ""
} |
q35807 | Canvas.get_outcome_group | train | def get_outcome_group(self, group):
"""
Returns the details of the Outcome Group with the given id.
:calls: `GET /api/v1/global/outcome_groups/:id \
<https://canvas.instructure.com/doc/api/outcome_groups.html#method.outcome_groups_api.show>`_
:param group: The outcome group... | python | {
"resource": ""
} |
q35808 | Canvas.get_progress | train | def get_progress(self, progress, **kwargs):
"""
Get a specific progress.
:calls: `GET /api/v1/progress/:id
<https://canvas.instructure.com/doc/api/progress.html#method.progress.show>`_
:param progress: The object or ID of the progress to retrieve.
:type progress: in... | python | {
"resource": ""
} |
q35809 | Canvas.get_announcements | train | def get_announcements(self, **kwargs):
"""
List announcements.
:calls: `GET /api/v1/announcements \
<https://canvas.instructure.com/doc/api/announcements.html#method.announcements_api.index>`_
:rtype: :class:`canvasapi.paginated_list.PaginatedList` of
:class:`ca... | python | {
"resource": ""
} |
q35810 | is_multivalued | train | def is_multivalued(value):
"""
Determine whether the given value should be treated as a sequence
of multiple values when used as a request parameter.
In general anything that is iterable is multivalued. For example,
`list` and `tuple` instances are multivalued. Generators are
multivalued, as ... | python | {
"resource": ""
} |
q35811 | combine_kwargs | train | def combine_kwargs(**kwargs):
"""
Flatten a series of keyword arguments from complex combinations of
dictionaries and lists into a list of tuples representing
properly-formatted parameters to pass to the Requester object.
:param kwargs: A dictionary containing keyword arguments to be
flatte... | python | {
"resource": ""
} |
q35812 | flatten_kwarg | train | def flatten_kwarg(key, obj):
"""
Recursive call to flatten sections of a kwarg to be combined
:param key: The partial keyword to add to the full keyword
:type key: str
:param obj: The object to translate into a kwarg. If the type is
`dict`, the key parameter will be added to the keyword bet... | python | {
"resource": ""
} |
q35813 | get_institution_url | train | def get_institution_url(base_url):
"""
Clean up a given base URL.
:param base_url: The base URL of the API.
:type base_url: str
:rtype: str
"""
base_url = base_url.rstrip('/')
index = base_url.find('/api/v1')
if index != -1:
return base_url[0:index]
return base_url | python | {
"resource": ""
} |
q35814 | file_or_path | train | def file_or_path(file):
"""
Open a file and return the handler if a path is given.
If a file handler is given, return it directly.
:param file: A file handler or path to a file.
:returns: A tuple with the open file handler and whether it was a path.
:rtype: (file, bool)
"""
is_path = ... | python | {
"resource": ""
} |
q35815 | CalendarEvent.delete | train | def delete(self, **kwargs):
"""
Delete this calendar event.
:calls: `DELETE /api/v1/calendar_events/:id \
<https://canvas.instructure.com/doc/api/calendar_events.html#method.calendar_events_api.destroy>`_
:rtype: :class:`canvasapi.calendar_event.CalendarEvent`
"""
... | python | {
"resource": ""
} |
q35816 | CalendarEvent.edit | train | def edit(self, **kwargs):
"""
Modify this calendar event.
:calls: `PUT /api/v1/calendar_events/:id \
<https://canvas.instructure.com/doc/api/calendar_events.html#method.calendar_events_api.update>`_
:rtype: :class:`canvasapi.calendar_event.CalendarEvent`
"""
res... | python | {
"resource": ""
} |
q35817 | _wrap_layer | train | def _wrap_layer(name, input_layer, build_func, dropout_rate=0.0, trainable=True):
"""Wrap layers with residual, normalization and dropout.
:param name: Prefix of names for internal layers.
:param input_layer: Input layer.
:param build_func: A callable that takes the input tensor and generates the outpu... | python | {
"resource": ""
} |
q35818 | attention_builder | train | def attention_builder(name, head_num, activation, history_only, trainable=True):
"""Get multi-head self-attention builder.
:param name: Prefix of names for internal layers.
:param head_num: Number of heads in multi-head self-attention.
:param activation: Activation for multi-head self-attention.
:p... | python | {
"resource": ""
} |
q35819 | feed_forward_builder | train | def feed_forward_builder(name, hidden_dim, activation, trainable=True):
"""Get position-wise feed-forward layer builder.
:param name: Prefix of names for internal layers.
:param hidden_dim: Hidden dimension of feed forward layer.
:param activation: Activation for feed-forward layer.
:param trainabl... | python | {
"resource": ""
} |
q35820 | get_encoder_component | train | def get_encoder_component(name,
input_layer,
head_num,
hidden_dim,
attention_activation=None,
feed_forward_activation='relu',
dropout_rate=0.0,
... | python | {
"resource": ""
} |
q35821 | get_decoder_component | train | def get_decoder_component(name,
input_layer,
encoded_layer,
head_num,
hidden_dim,
attention_activation=None,
feed_forward_activation='relu',
... | python | {
"resource": ""
} |
q35822 | get_encoders | train | def get_encoders(encoder_num,
input_layer,
head_num,
hidden_dim,
attention_activation=None,
feed_forward_activation='relu',
dropout_rate=0.0,
trainable=True):
"""Get encoders.
:param encoder_n... | python | {
"resource": ""
} |
q35823 | get_decoders | train | def get_decoders(decoder_num,
input_layer,
encoded_layer,
head_num,
hidden_dim,
attention_activation=None,
feed_forward_activation='relu',
dropout_rate=0.0,
trainable=True):
"""Get... | python | {
"resource": ""
} |
q35824 | get_model | train | def get_model(token_num,
embed_dim,
encoder_num,
decoder_num,
head_num,
hidden_dim,
attention_activation=None,
feed_forward_activation='relu',
dropout_rate=0.0,
use_same_embed=True,
... | python | {
"resource": ""
} |
q35825 | decode | train | def decode(model, tokens, start_token, end_token, pad_token, max_len=10000, max_repeat=10, max_repeat_block=10):
"""Decode with the given model and input tokens.
:param model: The trained model.
:param tokens: The input tokens of encoder.
:param start_token: The token that represents the start of a sen... | python | {
"resource": ""
} |
q35826 | gelu | train | def gelu(x):
"""An approximation of gelu.
See: https://arxiv.org/pdf/1606.08415.pdf
"""
return 0.5 * x * (1.0 + K.tanh(math.sqrt(2.0 / math.pi) * (x + 0.044715 * K.pow(x, 3)))) | python | {
"resource": ""
} |
q35827 | Env.prefixed | train | def prefixed(self, prefix):
"""Context manager for parsing envvars with a common prefix."""
old_prefix = self._prefix
if old_prefix is None:
self._prefix = prefix
else:
self._prefix = "{}{}".format(old_prefix, prefix)
yield self
self._prefix = old_... | python | {
"resource": ""
} |
q35828 | Env.add_parser | train | def add_parser(self, name, func):
"""Register a new parser method with the name ``name``. ``func`` must
receive the input value for an environment variable.
"""
self.__parser_map__[name] = _func2method(func, method_name=name)
return None | python | {
"resource": ""
} |
q35829 | Env.parser_for | train | def parser_for(self, name):
"""Decorator that registers a new parser method with the name ``name``.
The decorated function must receive the input value for an environment variable.
"""
def decorator(func):
self.add_parser(name, func)
return func
return d... | python | {
"resource": ""
} |
q35830 | Env.add_parser_from_field | train | def add_parser_from_field(self, name, field_cls):
"""Register a new parser method with name ``name``, given a marshmallow ``Field``."""
self.__parser_map__[name] = _field2method(field_cls, method_name=name) | python | {
"resource": ""
} |
q35831 | NMEAFile.open | train | def open(self, fp, mode='r'):
"""
Open the NMEAFile.
"""
self._file = open(fp, mode=mode)
return self._file | python | {
"resource": ""
} |
q35832 | xml_records | train | def xml_records(filename):
"""
If the second return value is not None, then it is an
Exception encountered during parsing. The first return value
will be the XML string.
@type filename str
@rtype: generator of (etree.Element or str), (None or Exception)
"""
with Evtx(filename) as e... | python | {
"resource": ""
} |
q35833 | RootNode.template_instance | train | def template_instance(self):
'''
parse the template instance node.
this is used to compute the location of the template definition structure.
Returns:
TemplateInstanceNode: the template instance.
'''
ofs = self.offset()
if self.unpack_byte(0x0) & 0x0F =... | python | {
"resource": ""
} |
q35834 | RootNode.template | train | def template(self):
'''
parse the template referenced by this root node.
note, this template structure is not guaranteed to be located within the root node's boundaries.
Returns:
TemplateNode: the template.
'''
instance = self.template_instance()
offset... | python | {
"resource": ""
} |
q35835 | evtx_chunk_xml_view | train | def evtx_chunk_xml_view(chunk):
"""
Generate XML representations of the records in an EVTX chunk.
Does not include the XML <?xml... header.
Records are ordered by chunk.records()
Args:
chunk (Evtx.Chunk): the chunk to render.
Yields:
tuple[str, Evtx.Record]: the rendered XML docum... | python | {
"resource": ""
} |
q35836 | evtx_file_xml_view | train | def evtx_file_xml_view(file_header):
"""
Generate XML representations of the records in an EVTX file.
Does not include the XML <?xml... header.
Records are ordered by file_header.chunks(), and then by chunk.records()
Args:
chunk (Evtx.FileHeader): the file header to render.
Yields:
... | python | {
"resource": ""
} |
q35837 | FileHeader.get_record | train | def get_record(self, record_num):
"""
Get a Record by record number.
@type record_num: int
@param record_num: The record number of the the record to fetch.
@rtype Record or None
@return The record request by record number, or None if the
record is not found.
... | python | {
"resource": ""
} |
q35838 | Record.data | train | def data(self):
"""
Return the raw data block which makes up this record as a bytestring.
@rtype str
@return A string that is a copy of the buffer that makes
up this record.
"""
return self._buf[self.offset():self.offset() + self.size()] | python | {
"resource": ""
} |
q35839 | Record.lxml | train | def lxml(self):
'''
render the record into a lxml document.
this is useful for querying data from the record using xpath, etc.
note: lxml must be installed.
Returns:
lxml.etree.ElementTree: the rendered and parsed xml document.
Raises:
ImportError: ... | python | {
"resource": ""
} |
q35840 | UserList.get | train | def get(self):
"""List all users"""
self.reqparse.add_argument('page', type=int, default=1, required=True)
self.reqparse.add_argument('count', type=int, default=50, choices=[25, 50, 100])
self.reqparse.add_argument('authSystem', type=str, default=None, action='append')
args = sel... | python | {
"resource": ""
} |
q35841 | UserList.options | train | def options(self):
"""Returns metadata information required for User Creation"""
roles = db.Role.all()
return self.make_response({
'roles': roles,
'authSystems': list(current_app.available_auth_systems.keys()),
'activeAuthSystem': current_app.active_auth_syst... | python | {
"resource": ""
} |
q35842 | UserDetails.get | train | def get(self, user_id):
"""Returns a specific user"""
user = db.User.find_one(User.user_id == user_id)
roles = db.Role.all()
if not user:
return self.make_response('Unable to find the user requested, might have been removed', HTTP.NOT_FOUND)
return self.make_respons... | python | {
"resource": ""
} |
q35843 | UserDetails.put | train | def put(self, user_id):
"""Update a user object"""
self.reqparse.add_argument('roles', type=str, action='append')
args = self.reqparse.parse_args()
auditlog(event='user.create', actor=session['user'].username, data=args)
user = db.User.find_one(User.user_id == user_id)
r... | python | {
"resource": ""
} |
q35844 | DomainHijackAuditor.return_resource_name | train | def return_resource_name(self, record, resource_type):
""" Removes the trailing AWS domain from a DNS record
to return the resource name
e.g bucketname.s3.amazonaws.com will return bucketname
Args:
record (str): DNS record
resource_type: AWS Resource typ... | python | {
"resource": ""
} |
q35845 | BaseAccount.to_json | train | def to_json(self, is_admin=False):
"""Returns a dict representation of the object
Args:
is_admin (`bool`): If true, include information about the account that should be avaiable only to admins
Returns:
`dict`
"""
if is_admin:
return {
... | python | {
"resource": ""
} |
q35846 | BaseAccount.get | train | def get(account):
"""Returns the class object identified by `account_id`
Args:
account (`int`, `str`): Unique ID of the account to load from database
Returns:
`Account` object if found, else None
"""
account = Account.get(account)
if not account:... | python | {
"resource": ""
} |
q35847 | BaseAccount.get_all | train | def get_all(cls, include_disabled=True):
"""Returns a list of all accounts of a given type
Args:
include_disabled (`bool`): Include disabled accounts. Default: `True`
Returns:
list of account objects
"""
if cls == BaseAccount:
raise Inquisito... | python | {
"resource": ""
} |
q35848 | BaseAccount.search | train | def search(*, include_disabled=True, account_ids=None, account_type_id=None, properties=None, return_query=False):
"""Search for accounts based on the provided filters
Args:
include_disabled (`bool`): Include disabled accounts (default: True)
account_ids: (`list` of `int`): List... | python | {
"resource": ""
} |
q35849 | SQSScheduler.execute_scheduler | train | def execute_scheduler(self):
"""Main entry point for the scheduler. This method will start two scheduled jobs, `schedule_jobs` which takes
care of scheduling the actual SQS messaging and `process_status_queue` which will track the current status
of the jobs as workers are executing them
... | python | {
"resource": ""
} |
q35850 | SQSScheduler.list_current_jobs | train | def list_current_jobs(self):
"""Return a list of the currently scheduled jobs in APScheduler
Returns:
`dict` of `str`: :obj:`apscheduler/job:Job`
"""
jobs = {}
for job in self.scheduler.get_jobs():
if job.name not in ('schedule_jobs', 'process_status_queu... | python | {
"resource": ""
} |
q35851 | SQSScheduler.send_worker_queue_message | train | def send_worker_queue_message(self, *, batch_id, job_name, entry_point, worker_args, retry_count=0):
"""Send a message to the `worker_queue` for a worker to execute the requests job
Args:
batch_id (`str`): Unique ID of the batch the job belongs to
job_name (`str`): Non-unique ID... | python | {
"resource": ""
} |
q35852 | SQSScheduler.send_status_message | train | def send_status_message(self, object_id, status):
"""Send a message to the `status_queue` to update a job's status.
Returns `True` if the message was sent, else `False`
Args:
object_id (`str`): ID of the job that was executed
status (:obj:`SchedulerStatus`): Status of t... | python | {
"resource": ""
} |
q35853 | SQSScheduler.process_status_queue | train | def process_status_queue(self):
"""Process all messages in the `status_queue` and check for any batches that needs to change status
Returns:
`None`
"""
self.log.debug('Start processing status queue')
while True:
messages = self.status_queue.receive_messag... | python | {
"resource": ""
} |
q35854 | IAMAuditor.run | train | def run(self, *args, **kwargs):
"""Iterate through all AWS accounts and apply roles and policies from Github
Args:
*args: Optional list of arguments
**kwargs: Optional list of keyword arguments
Returns:
`None`
"""
accounts = list(AWSAccount.g... | python | {
"resource": ""
} |
q35855 | IAMAuditor.get_policies_from_git | train | def get_policies_from_git(self):
"""Retrieve policies from the Git repo. Returns a dictionary containing all the roles and policies
Returns:
:obj:`dict` of `str`: `dict`
"""
fldr = mkdtemp()
try:
url = 'https://{token}:x-oauth-basic@{server}/{repo}'.forma... | python | {
"resource": ""
} |
q35856 | IAMAuditor.get_policies_from_aws | train | def get_policies_from_aws(client, scope='Local'):
"""Returns a list of all the policies currently applied to an AWS Account. Returns a list containing all the
policies for the specified scope
Args:
client (:obj:`boto3.session.Session`): A boto3 Session object
scope (`str... | python | {
"resource": ""
} |
q35857 | IAMAuditor.get_roles | train | def get_roles(client):
"""Returns a list of all the roles for an account. Returns a list containing all the roles for the account.
Args:
client (:obj:`boto3.session.Session`): A boto3 Session object
Returns:
:obj:`list` of `dict`
"""
done = False
... | python | {
"resource": ""
} |
q35858 | IAMAuditor.create_policy | train | def create_policy(self, account, client, document, name, arn=None):
"""Create a new IAM policy.
If the policy already exists, a new version will be added and if needed the oldest policy version not in use
will be removed. Returns a dictionary containing the policy or version information
... | python | {
"resource": ""
} |
q35859 | SlackNotifier.notify | train | def notify(self, subsystem, recipient, subject, body_html, body_text):
"""You can send messages either to channels and private groups by using the following formats
#channel-name
@username-direct-message
Args:
subsystem (`str`): Name of the subsystem originating the notific... | python | {
"resource": ""
} |
q35860 | SlackNotifier.send_message | train | def send_message(contacts, message):
"""List of contacts the send the message to. You can send messages either to channels and private groups by
using the following formats
#channel-name
@username-direct-message
If the channel is the name of a private group / channel, you must ... | python | {
"resource": ""
} |
q35861 | _register_default_option | train | def _register_default_option(nsobj, opt):
""" Register default ConfigOption value if it doesn't exist. If does exist, update the description if needed """
item = ConfigItem.get(nsobj.namespace_prefix, opt.name)
if not item:
logger.info('Adding {} ({}) = {} to {}'.format(
opt.name,
... | python | {
"resource": ""
} |
q35862 | _import_templates | train | def _import_templates(force=False):
"""Import templates from disk into database
Reads all templates from disk and adds them to the database. By default, any template that has been modified by
the user will not be updated. This can however be changed by setting `force` to `True`, which causes all templates
... | python | {
"resource": ""
} |
q35863 | initialize | train | def initialize():
"""Initialize the application configuration, adding any missing default configuration or roles
Returns:
`None`
"""
global __initialized
if __initialized:
return
# Setup all the default base settings
try:
for data in DEFAULT_CONFIG_OPTIONS:
... | python | {
"resource": ""
} |
q35864 | before_request | train | def before_request():
"""Checks to ensure that the session is valid and validates the users CSRF token is present
Returns:
`None`
"""
if not request.path.startswith('/saml') and not request.path.startswith('/auth'):
# Validate the session has the items we need
if 'accounts' not ... | python | {
"resource": ""
} |
q35865 | after_request | train | def after_request(response):
"""Modifies the response object prior to sending it to the client. Used to add CORS headers to the request
Args:
response (response): Flask response object
Returns:
`None`
"""
response.headers.add('Access-Control-Allow-Origin', '*')
response.headers... | python | {
"resource": ""
} |
q35866 | CINQFlask.register_auth_system | train | def register_auth_system(self, auth_system):
"""Register a given authentication system with the framework. Returns `True` if the `auth_system` is registered
as the active auth system, else `False`
Args:
auth_system (:obj:`BaseAuthPlugin`): A subclass of the `BaseAuthPlugin` class to... | python | {
"resource": ""
} |
q35867 | CINQFlask.register_menu_item | train | def register_menu_item(self, items):
"""Registers a views menu items into the metadata for the application. Skip if the item is already present
Args:
items (`list` of `MenuItem`): A list of `MenuItem`s
Returns:
`None`
"""
for itm in items:
if... | python | {
"resource": ""
} |
q35868 | CINQFlask.__register_types | train | def __register_types(self):
"""Iterates all entry points for resource types and registers a `resource_type_id` to class mapping
Returns:
`None`
"""
try:
for entry_point in CINQ_PLUGINS['cloud_inquisitor.plugins.types']['plugins']:
cls = entry_poin... | python | {
"resource": ""
} |
q35869 | CINQFlask.__register_notifiers | train | def __register_notifiers(self):
"""Lists all notifiers to be able to provide metadata for the frontend
Returns:
`list` of `dict`
"""
notifiers = {}
for entry_point in CINQ_PLUGINS['cloud_inquisitor.plugins.notifiers']['plugins']:
cls = entry_point.load()
... | python | {
"resource": ""
} |
q35870 | CINQApi.register_views | train | def register_views(self, app):
"""Iterates all entry points for views and auth systems and dynamically load and register the routes with Flask
Args:
app (`CINQFlask`): CINQFlask object to register views for
Returns:
`None`
"""
self.add_resource(LoginRedi... | python | {
"resource": ""
} |
q35871 | DNSCollector.get_axfr_records | train | def get_axfr_records(self, server, domains):
"""Return a `list` of `dict`s containing the zones and their records, obtained from the DNS server
Returns:
:obj:`list` of `dict`
"""
zones = []
for zoneName in domains:
try:
zone = {
... | python | {
"resource": ""
} |
q35872 | DNSCollector.get_cloudflare_records | train | def get_cloudflare_records(self, *, account):
"""Return a `list` of `dict`s containing the zones and their records, obtained from the CloudFlare API
Returns:
account (:obj:`CloudFlareAccount`): A CloudFlare Account object
:obj:`list` of `dict`
"""
zones = []
... | python | {
"resource": ""
} |
q35873 | DNSCollector.__cloudflare_request | train | def __cloudflare_request(self, *, account, path, args=None):
"""Helper function to interact with the CloudFlare API.
Args:
account (:obj:`CloudFlareAccount`): CloudFlare Account object
path (`str`): URL endpoint to communicate with
args (:obj:`dict` of `str`: `str`):... | python | {
"resource": ""
} |
q35874 | DNSCollector.__cloudflare_list_zones | train | def __cloudflare_list_zones(self, *, account, **kwargs):
"""Helper function to list all zones registered in the CloudFlare system. Returns a `list` of the zones
Args:
account (:obj:`CloudFlareAccount`): A CloudFlare Account object
**kwargs (`dict`): Extra arguments to pass to th... | python | {
"resource": ""
} |
q35875 | DNSCollector.__cloudflare_list_zone_records | train | def __cloudflare_list_zone_records(self, *, account, zoneID, **kwargs):
"""Helper function to list all records on a CloudFlare DNS Zone. Returns a `dict` containing the records and
their information.
Args:
account (:obj:`CloudFlareAccount`): A CloudFlare Account object
z... | python | {
"resource": ""
} |
q35876 | CloudTrailAuditor.run | train | def run(self, *args, **kwargs):
"""Entry point for the scheduler
Args:
*args: Optional arguments
**kwargs: Optional keyword arguments
Returns:
None
"""
accounts = list(AWSAccount.get_all(include_disabled=False).values())
# S3 Bucket ... | python | {
"resource": ""
} |
q35877 | CloudTrailAuditor.validate_sqs_policy | train | def validate_sqs_policy(self, accounts):
"""Given a list of accounts, ensures that the SQS policy allows all the accounts to write to the queue
Args:
accounts (`list` of :obj:`Account`): List of accounts
Returns:
`None`
"""
sqs_queue_name = self.dbconfig... | python | {
"resource": ""
} |
q35878 | CloudTrail.run | train | def run(self):
"""Configures and enables a CloudTrail trail and logging on a single AWS Account.
Has the capability to create both single region and multi-region trails.
Will automatically create SNS topics, subscribe to SQS queues and turn on logging for the account in question,
as we... | python | {
"resource": ""
} |
q35879 | CloudTrail.validate_trail_settings | train | def validate_trail_settings(self, ct, aws_region, trail):
"""Validates logging, SNS and S3 settings for the global trail.
Has the capability to:
- start logging for the trail
- create SNS topics & queues
- configure or modify a S3 bucket for logging
"""
self.lo... | python | {
"resource": ""
} |
q35880 | CloudTrail.create_sns_topic | train | def create_sns_topic(self, region):
"""Creates an SNS topic if needed. Returns the ARN if the created SNS topic
Args:
region (str): Region name
Returns:
`str`
"""
sns = self.session.client('sns', region_name=region)
self.log.info('Creating SNS t... | python | {
"resource": ""
} |
q35881 | CloudTrail.validate_sns_topic_subscription | train | def validate_sns_topic_subscription(self, region):
"""Validates SQS subscription to the SNS topic. Returns `True` if subscribed or `False` if not subscribed
or topic is missing
Args:
region (str): Name of AWS Region
Returns:
`bool`
"""
sns = self... | python | {
"resource": ""
} |
q35882 | CloudTrail.subscribe_sns_topic_to_sqs | train | def subscribe_sns_topic_to_sqs(self, region):
"""Subscribe SQS to the SNS topic. Returns the ARN of the SNS Topic subscribed
Args:
region (`str`): Name of the AWS region
Returns:
`str`
"""
sns = self.session.resource('sns', region_name=region)
to... | python | {
"resource": ""
} |
q35883 | CloudTrail.create_cloudtrail | train | def create_cloudtrail(self, region):
"""Creates a new CloudTrail Trail
Args:
region (str): Name of the AWS region
Returns:
`None`
"""
ct = self.session.client('cloudtrail', region_name=region)
# Creating the sns topic for the trail prior to crea... | python | {
"resource": ""
} |
q35884 | CloudTrail.enable_sns_notification | train | def enable_sns_notification(self, region, trailName):
"""Enable SNS notifications for a Trail
Args:
region (`str`): Name of the AWS region
trailName (`str`): Name of the CloudTrail Trail
Returns:
`None`
"""
ct = self.session.client('cloudtrai... | python | {
"resource": ""
} |
q35885 | CloudTrail.start_logging | train | def start_logging(self, region, name):
"""Turn on logging for a CloudTrail Trail
Args:
region (`str`): Name of the AWS region
name (`str`): Name of the CloudTrail Trail
Returns:
`None`
"""
ct = self.session.client('cloudtrail', region_name=re... | python | {
"resource": ""
} |
q35886 | CloudTrail.set_s3_prefix | train | def set_s3_prefix(self, region, name):
"""Sets the S3 prefix for a CloudTrail Trail
Args:
region (`str`): Name of the AWS region
name (`str`): Name of the CloudTrail Trail
Returns:
`None`
"""
ct = self.session.client('cloudtrail', region_name... | python | {
"resource": ""
} |
q35887 | CloudTrail.set_s3_bucket | train | def set_s3_bucket(self, region, name, bucketName):
"""Sets the S3 bucket location for logfile delivery
Args:
region (`str`): Name of the AWS region
name (`str`): Name of the CloudTrail Trail
bucketName (`str`): Name of the S3 bucket to deliver log files to
R... | python | {
"resource": ""
} |
q35888 | CloudTrail.create_s3_bucket | train | def create_s3_bucket(cls, bucket_name, bucket_region, bucket_account, template):
"""Creates the S3 bucket on the account specified as the destination account for log files
Args:
bucket_name (`str`): Name of the S3 bucket
bucket_region (`str`): AWS Region for the bucket
... | python | {
"resource": ""
} |
q35889 | VPCFlowLogsAuditor.run | train | def run(self):
"""Main entry point for the auditor worker.
Returns:
`None`
"""
# Loop through all accounts that are marked as enabled
accounts = list(AWSAccount.get_all(include_disabled=False).values())
for account in accounts:
self.log.debug('Upd... | python | {
"resource": ""
} |
q35890 | VPCFlowLogsAuditor.confirm_iam_role | train | def confirm_iam_role(self, account):
"""Return the ARN of the IAM Role on the provided account as a string. Returns an `IAMRole` object from boto3
Args:
account (:obj:`Account`): Account where to locate the role
Returns:
:obj:`IAMRole`
"""
try:
... | python | {
"resource": ""
} |
q35891 | VPCFlowLogsAuditor.create_iam_role | train | def create_iam_role(self, account):
"""Create a new IAM role. Returns the ARN of the newly created role
Args:
account (:obj:`Account`): Account where to create the IAM role
Returns:
`str`
"""
try:
iam = self.session.client('iam')
... | python | {
"resource": ""
} |
q35892 | VPCFlowLogsAuditor.confirm_cw_log | train | def confirm_cw_log(self, account, region, vpcname):
"""Create a new CloudWatch log group based on the VPC Name if none exists. Returns `True` if succesful
Args:
account (:obj:`Account`): Account to create the log group in
region (`str`): Region to create the log group in
... | python | {
"resource": ""
} |
q35893 | VPCFlowLogsAuditor.create_vpc_flow_logs | train | def create_vpc_flow_logs(self, account, region, vpc_id, iam_role_arn):
"""Create a new VPC Flow log
Args:
account (:obj:`Account`): Account to create the flow in
region (`str`): Region to create the flow in
vpc_id (`str`): ID of the VPC to create the flow for
... | python | {
"resource": ""
} |
q35894 | RequiredTagsAuditor.get_contacts | train | def get_contacts(self, issue):
"""Returns a list of contacts for an issue
Args:
issue (:obj:`RequiredTagsIssue`): Issue record
Returns:
`list` of `dict`
"""
# If the resources has been deleted, just return an empty list, to trigger issue deletion without... | python | {
"resource": ""
} |
q35895 | RequiredTagsAuditor.get_actions | train | def get_actions(self, issues):
"""Returns a list of actions to executed
Args:
issues (`list` of :obj:`RequiredTagsIssue`): List of issues
Returns:
`list` of `dict`
"""
actions = []
try:
for issue in issues:
action_item... | python | {
"resource": ""
} |
q35896 | RequiredTagsAuditor.determine_alert | train | def determine_alert(self, action_schedule, issue_creation_time, last_alert):
"""Determine if we need to trigger an alert
Args:
action_schedule (`list`): A list contains the alert schedule
issue_creation_time (`int`): Time we create the issue
last_alert (`str`): Time ... | python | {
"resource": ""
} |
q35897 | RequiredTagsAuditor.determine_action | train | def determine_action(self, issue):
"""Determine the action we should take for the issue
Args:
issue: Issue to determine action for
Returns:
`dict`
"""
resource_type = self.resource_types[issue.resource.resource_type_id]
issue_alert_schedule = se... | python | {
"resource": ""
} |
q35898 | RequiredTagsAuditor.process_actions | train | def process_actions(self, actions):
"""Process the actions we want to take
Args:
actions (`list`): List of actions we want to take
Returns:
`list` of notifications
"""
notices = {}
notification_contacts = {}
for action in actions:
... | python | {
"resource": ""
} |
q35899 | RequiredTagsAuditor.validate_tag | train | def validate_tag(self, key, value):
"""Check whether a tag value is valid
Args:
key: A tag key
value: A tag value
Returns:
`(True or False)`
A boolean indicating whether or not the value is valid
"""
if key == 'owner':
... | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.