text stringlengths 81 112k |
|---|
index policy metrics
def index_metrics(
config, start, end, incremental=False, concurrency=5, accounts=None,
period=3600, tag=None, index='policy-metrics', verbose=False):
"""index policy metrics"""
logging.basicConfig(level=(verbose and logging.DEBUG or logging.INFO))
logging.getLogger('bo... |
make config revision look like describe output.
def transform_revision(self, revision):
"""make config revision look like describe output."""
config = self.manager.get_source('config')
return config.load_resource(revision) |
meta model subscriber on resource registration.
We watch for new resource types being registered and if they
support aws config, automatically register the jsondiff filter.
def register_resources(klass, registry, resource_class):
""" meta model subscriber on resource registration.
We ... |
Add basic options ot the subparser.
`blacklist` is a list of options to exclude from the default set.
e.g.: ['region', 'log-group']
def _default_options(p, blacklist=""):
""" Add basic options ot the subparser.
`blacklist` is a list of options to exclude from the default set.
e.g.: ['region', 'lo... |
Add options specific to the report subcommand.
def _report_options(p):
""" Add options specific to the report subcommand. """
_default_options(p, blacklist=['cache', 'log-group', 'quiet'])
p.add_argument(
'--days', type=float, default=1,
help="Number of days of history to consider")
p.a... |
Add options specific to metrics subcommand.
def _metrics_options(p):
""" Add options specific to metrics subcommand. """
_default_options(p, blacklist=['log-group', 'output-dir', 'cache', 'quiet'])
p.add_argument(
'--start', type=date_parse,
help='Start date (requires --end, overrides --da... |
Add options specific to logs subcommand.
def _logs_options(p):
""" Add options specific to logs subcommand. """
_default_options(p, blacklist=['cache', 'quiet'])
# default time range is 0 to "now" (to include all log entries)
p.add_argument(
'--start',
default='the beginning', # inval... |
Add options specific to schema subcommand.
def _schema_options(p):
""" Add options specific to schema subcommand. """
p.add_argument(
'resource', metavar='selector', nargs='?',
default=None).completer = _schema_tab_completer
p.add_argument(
'--summary', action="store_true",
... |
Augment rds clusters with their respective tags.
def _rds_cluster_tags(model, dbs, session_factory, generator, retry):
"""Augment rds clusters with their respective tags."""
client = local_session(session_factory).client('rds')
def process_tags(db):
try:
db['Tags'] = retry(
... |
Type convert the csv record, modifies in place.
def process_user_record(cls, info):
"""Type convert the csv record, modifies in place."""
keys = list(info.keys())
# Value conversion
for k in keys:
v = info[k]
if v in ('N/A', 'no_information'):
inf... |
Mimic the format returned by LambdaManager.logs()
def normalized_log_entries(raw_entries):
'''Mimic the format returned by LambdaManager.logs()'''
entry_start = r'([0-9:, \-]+) - .* - (\w+) - (.*)$'
entry = None
# process start/end here - avoid parsing log entries twice
for line in raw_entries:
... |
filter out entries before start and after end
def log_entries_in_range(entries, start, end):
'''filter out entries before start and after end'''
start = _timestamp_from_string(start)
end = _timestamp_from_string(end)
for entry in entries:
log_timestamp = entry.get('timestamp', 0)
if log... |
Get logs for a specific log group
def log_entries_from_group(session, group_name, start, end):
'''Get logs for a specific log group'''
logs = session.client('logs')
log.info("Fetching logs from group: %s" % group_name)
try:
logs.describe_log_groups(logGroupNamePrefix=group_name)
except Clie... |
Builds and returns a cloud API service object.
Args:
credentials (OAuth2Credentials): Credentials that will be used to
authenticate the API calls.
service_name (str): The name of the API.
version (str): The version of the API to use.
developer_key (str): The api key to u... |
Construct an http client suitable for googleapiclient usage w/ user agent.
def _build_http(http=None):
"""Construct an http client suitable for googleapiclient usage w/ user agent.
"""
if not http:
http = httplib2.Http(
timeout=HTTP_REQUEST_TIMEOUT, ca_certs=HTTPLIB_CA_BUNDLE)
user... |
Safely initialize a repository class to a property.
Args:
repository_class (class): The class to initialize.
version (str): The gcp service version for the repository.
Returns:
object: An instance of repository_class.
def client(self, service_name, version, compone... |
A thread local instance of httplib2.Http.
Returns:
httplib2.Http: An Http instance authorized by the credentials.
def http(self):
"""A thread local instance of httplib2.Http.
Returns:
httplib2.Http: An Http instance authorized by the credentials.
"""
if... |
Builds HttpRequest object.
Args:
verb (str): Request verb (ex. insert, update, delete).
verb_arguments (dict): Arguments to be passed with the request.
Returns:
httplib2.HttpRequest: HttpRequest to be sent to the API.
def _build_request(self, verb, verb_arguments):... |
Builds pagination-aware request object.
More details:
https://developers.google.com/api-client-library/python/guide/pagination
Args:
verb (str): Request verb (ex. insert, update, delete).
prior_request (httplib2.HttpRequest): Request that may trigger
p... |
Executes command (ex. add) via a dedicated http object.
Async APIs may take minutes to complete. Therefore, callers are
encouraged to leverage concurrent.futures (or similar) to place long
running commands on a separate threads.
Args:
verb (str): Method to execute on the co... |
Executes query (ex. list) via a dedicated http object.
Args:
verb (str): Method to execute on the component (ex. get, list).
verb_arguments (dict): key-value pairs to be passed to _BuildRequest.
Yields:
dict: Service Response.
Raises:
Pagination... |
Executes query (ex. search) via a dedicated http object.
Args:
verb (str): Method to execute on the component (ex. search).
verb_arguments (dict): key-value pairs to be passed to _BuildRequest.
Yields:
dict: Service Response.
def execute_search_query(self, verb, ve... |
Executes query (ex. get) via a dedicated http object.
Args:
verb (str): Method to execute on the component (ex. get, list).
verb_arguments (dict): key-value pairs to be passed to _BuildRequest.
Returns:
dict: Service Response.
def execute_query(self, verb, verb_arg... |
Run execute with retries and rate limiting.
Args:
request (object): The HttpRequest object to execute.
Returns:
dict: The response from the API.
def _execute(self, request):
"""Run execute with retries and rate limiting.
Args:
request (object): The... |
Check if a resource is locked.
If a resource has an explicit status we use that, else
we defer to the parent resource lock status.
def info(self, account_id, resource_id, parent_id):
"""Check if a resource is locked.
If a resource has an explicit status we use that, else
we de... |
ENI flow stream processor that rollups, enhances,
and indexes the stream by time period.
def process_eni_metrics(
stream_eni, myips, stream,
start, end, period, sample_size,
resolver, sink_uri):
"""ENI flow stream processor that rollups, enhances,
and indexes the stream by tim... |
Analyze flow log records for application and generate metrics per period
def analyze_app(
app, env, account_id,
bucket, prefix, store_dir,
resources, ipdb, ipranges,
start, end, tz,
sink, period, sample_count,
debug):
"""Analyze flow log records for application and g... |
List extant cloud functions.
def list_functions(self, prefix=None):
"""List extant cloud functions."""
return self.client.execute_command(
'list',
{'parent': "projects/{}/locations/{}".format(
self.session.get_default_project(),
self.region)}
... |
publish the given function.
def publish(self, func):
"""publish the given function."""
project = self.session.get_default_project()
func_name = "projects/{}/locations/{}/functions/{}".format(
project, self.region, func.name)
func_info = self.get(func.name)
source_url... |
Get the details on a given function.
def get(self, func_name, qualifier=None):
"""Get the details on a given function."""
project = self.session.get_default_project()
func_name = "projects/{}/locations/{}/functions/{}".format(
project, self.region, func_name)
try:
... |
Upload function source and return source url
def _upload(self, archive, region):
"""Upload function source and return source url
"""
# Generate source upload url
url = self.client.execute_command(
'generateUploadUrl',
{'parent': 'projects/{}/locations/{}'.format(... |
Verify the pub/sub topic exists.
Returns the topic qualified name.
def ensure_topic(self):
"""Verify the pub/sub topic exists.
Returns the topic qualified name.
"""
client = self.session.client('pubsub', 'v1', 'projects.topics')
topic = self.get_topic_param()
t... |
Ensure the given identities are in the iam role bindings for the topic.
def ensure_iam(self, publisher=None):
"""Ensure the given identities are in the iam role bindings for the topic.
"""
topic = self.get_topic_param()
client = self.session.client('pubsub', 'v1', 'projects.topics')
... |
Get the parent container for the log sink
def get_parent(self, log_info):
"""Get the parent container for the log sink"""
if self.data.get('scope', 'log') == 'log':
if log_info.scope_type != 'projects':
raise ValueError("Invalid log subscriber scope")
parent = "%... |
Ensure the log sink and its pub sub topic exist.
def ensure_sink(self):
"""Ensure the log sink and its pub sub topic exist."""
topic_info = self.pubsub.ensure_topic()
scope, sink_path, sink_info = self.get_sink(topic_info)
client = self.session.client('logging', 'v2', '%s.sinks' % scope... |
Remove any provisioned log sink if auto created
def remove(self, func):
"""Remove any provisioned log sink if auto created"""
if not self.data['name'].startswith(self.prefix):
return
parent = self.get_parent(self.get_log())
_, sink_path, _ = self.get_sink()
client = ... |
Format log events and relay via sns/email
def process_log_event(event, context):
"""Format log events and relay via sns/email"""
init()
serialized = event['awslogs'].pop('data')
data = json.loads(zlib.decompress(
base64.b64decode(serialized), 16 + zlib.MAX_WBITS))
# Fetch additional logs f... |
Lambda function provisioning.
Self contained within the component, to allow for easier reuse.
def get_function(session_factory, name, role, sns_topic, log_groups,
subject="Lambda Error", pattern="Traceback"):
"""Lambda function provisioning.
Self contained within the component, to allow ... |
Match a given cwe event as cloudtrail with an api call
That has its information filled out.
def match(cls, event):
"""Match a given cwe event as cloudtrail with an api call
That has its information filled out.
"""
if 'detail' not in event:
return False
if '... |
extract resources ids from a cloud trail event.
def get_trail_ids(cls, event, mode):
"""extract resources ids from a cloud trail event."""
resource_ids = ()
event_name = event['detail']['eventName']
event_source = event['detail']['eventSource']
for e in mode.get('events', []):
... |
Generate a c7n-org accounts config file using AWS Organizations
With c7n-org you can then run policies or arbitrary scripts across
accounts.
def main(role, ou, assume, profile, output, regions, active):
"""Generate a c7n-org accounts config file using AWS Organizations
With c7n-org you can then run p... |
Download a traildb file for a given account/day/region
def download(config, account, day, region, output):
"""Download a traildb file for a given account/day/region"""
with open(config) as fh:
config = yaml.safe_load(fh.read())
jsonschema.validate(config, CONFIG_SCHEMA)
found = None
for ... |
time series lastest record time by account.
def status(config):
"""time series lastest record time by account."""
with open(config) as fh:
config = yaml.safe_load(fh.read())
jsonschema.validate(config, CONFIG_SCHEMA)
last_index = get_incremental_starts(config, None)
accounts = {}
for (a... |
index traildbs directly from s3 for multiple accounts.
context: assumes a daily traildb file in s3 with key path
specified by key_template in config file for each account
def index(config, start, end, incremental=False, concurrency=5, accounts=None,
verbose=False):
"""index traildbs dir... |
Returns a sqlite row factory that returns a dictionary
def dict_factory(cursor, row):
"""Returns a sqlite row factory that returns a dictionary"""
d = {}
for idx, col in enumerate(cursor.description):
d[col[0]] = row[idx]
return d |
Generator that returns the events
def fetch_events(cursor, config, account_name):
"""Generator that returns the events"""
query = config['indexer'].get('query',
'select * from events where user_agent glob \'*CloudCustodian*\'')
for event in cursor.execute(query):
event['account'] = account... |
traildb bucket folders are not zero-padded so this validation
checks that the keys returned by the paginator are
*really after* the config date
def valid_date(key, config_date):
""" traildb bucket folders are not zero-padded so this validation
checks that the keys returned by the paginator ... |
index traildbs directly from s3 for multiple accounts.
context: assumes a daily traildb file in s3 with dated key path
def index(
config, date=None, directory=None, concurrency=5, accounts=None,
tag=None, verbose=False):
"""index traildbs directly from s3 for multiple accounts.
context: a... |
Creates a session using available authentication type.
Auth priority:
1. Token Auth
2. Tenant Auth
3. Azure CLI Auth
def _initialize_session(self):
"""
Creates a session using available authentication type.
Auth priority:
1. Token Auth
2. Tenant... |
latest non-preview api version for resource
def resource_api_version(self, resource_id):
""" latest non-preview api version for resource """
namespace = ResourceIdParser.get_namespace(resource_id)
resource_type = ResourceIdParser.get_resource_type(resource_id)
cache_id = namespace + r... |
Build auth json string for deploying
Azure Functions. Look for dedicated
Functions environment variables or
fall back to normal Service Principal
variables.
def get_functions_auth_string(self, target_subscription_id):
"""
Build auth json string for deploying
Azu... |
Query a set of resources.
def filter(self, resource_manager, **params):
"""Query a set of resources."""
m = self.resolve(resource_manager.resource_type)
client = local_session(self.session_factory).client(
m.service, resource_manager.config.region)
enum_op, path, extra_args ... |
Get resources by identities
def get(self, resource_manager, identities):
"""Get resources by identities
"""
m = self.resolve(resource_manager.resource_type)
params = {}
client_filter = False
# Try to formulate server side query
if m.filter_name:
if m... |
Query a set of resources.
def filter(self, resource_manager, **params):
"""Query a set of resources."""
m = self.resolve(resource_manager.resource_type)
client = local_session(self.session_factory).client(m.service)
enum_op, path, extra_args = m.enum_spec
if extra_args:
... |
Create an api gw response from a wsgi app and environ.
def create_gw_response(app, wsgi_env):
"""Create an api gw response from a wsgi app and environ.
"""
response = {}
buf = []
result = []
def start_response(status, headers, exc_info=None):
result[:] = [status, headers]
retur... |
Create a wsgi environment from an apigw request.
def create_wsgi_request(event, server_name='apigw'):
"""Create a wsgi environment from an apigw request.
"""
path = urllib.url2pathname(event['path'])
script_name = (
event['headers']['Host'].endswith('.amazonaws.com') and
event['requestC... |
Create a LogRetriever from a client and lambda arn.
:type client: botocore.client.Logs
:param client: A ``logs`` client.
:type lambda_arn: str
:param lambda_arn: The ARN of the lambda function.
:return: An instance of ``LogRetriever``.
def create_from_lambda_arn(cls, client, ... |
Retrieve logs from a log group.
:type include_lambda_messages: boolean
:param include_lambda_messages: Include logs generated by the AWS
Lambda service. If this value is False, only chalice logs will be
included.
:type max_entries: int
:param max_entries: Maxim... |
Validate app configuration.
The purpose of this method is to provide a fail fast mechanism
for anything we know is going to fail deployment.
We can detect common error cases and provide the user with helpful
error messages.
def validate_configuration(config):
# type: (Config) -> None
"""Valida... |
Validate configuration matches a specific python version.
If the ``actual_py_version`` is not provided, it will default
to the major/minor version of the currently running python
interpreter.
:param actual_py_version: The major/minor python version in
the form "pythonX.Y", e.g "python2.7", "py... |
Execute a pip command with the given arguments.
def _execute(self,
command, # type: str
args, # type: List[str]
env_vars=None, # type: EnvVars
shim=None # type: OptStr
):
# type: (...) -> Tuple[int, byt... |
Build an sdist into a wheel file.
def build_wheel(self, wheel, directory, compile_c=True):
# type: (str, str, bool) -> None
"""Build an sdist into a wheel file."""
arguments = ['--no-deps', '--wheel-dir', directory, wheel]
env_vars = self._osutils.environ()
shim = ''
if ... |
Download all dependencies as sdist or wheel.
def download_all_dependencies(self, requirements_filename, directory):
# type: (str, str) -> None
"""Download all dependencies as sdist or wheel."""
arguments = ['-r', requirements_filename, '--dest', directory]
rc, out, err = self._execute('... |
Download wheel files for manylinux for all the given packages.
def download_manylinux_wheels(self, abi, packages, directory):
# type: (str, List[str], str) -> None
"""Download wheel files for manylinux for all the given packages."""
# If any one of these dependencies fails pip will bail out. Si... |
Transform a name to a valid cfn name.
This will convert the provided name to a CamelCase name.
It's possible that the conversion to a CFN resource name
can result in name collisions. It's up to the caller
to handle name collisions appropriately.
def to_cfn_resource_name(name):
# type: (str) -> st... |
Delete a top level key from the deployed JSON file.
def remove_stage_from_deployed_values(key, filename):
# type: (str, str) -> None
"""Delete a top level key from the deployed JSON file."""
final_values = {} # type: Dict[str, Any]
try:
with open(filename, 'r') as f:
final_values =... |
Record deployed values to a JSON file.
This allows subsequent deploys to lookup previously deployed values.
def record_deployed_values(deployed_values, filename):
# type: (Dict[str, Any], str) -> None
"""Record deployed values to a JSON file.
This allows subsequent deploys to lookup previously deploy... |
Create a zip file from a source input directory.
This function is intended to be an equivalent to
`zip -r`. You give it a source directory, `source_dir`,
and it will recursively zip up the files into a zipfile
specified by the `outfile` argument.
def create_zip_file(source_dir, outfile):
# type: ... |
Update a Lambda function's code and configuration.
This method only updates the values provided to it. If a parameter
is not provided, no changes will be made for that that parameter on
the targeted lambda function.
def update_function(self,
function_name, ... |
Delete a role by first deleting all inline policies.
def delete_role(self, name):
# type: (str) -> None
"""Delete a role by first deleting all inline policies."""
client = self._client('iam')
inline_policies = client.list_role_policies(
RoleName=name
)['PolicyNames']... |
Get rest api id associated with an API name.
:type name: str
:param name: The name of the rest api.
:rtype: str
:return: If the rest api exists, then the restApiId
is returned, otherwise None.
def get_rest_api_id(self, name):
# type: (str) -> Optional[str]
... |
Check if an an API Gateway REST API exists.
def rest_api_exists(self, rest_api_id):
# type: (str) -> bool
"""Check if an an API Gateway REST API exists."""
client = self._client('apigateway')
try:
client.get_rest_api(restApiId=rest_api_id)
return True
exc... |
Authorize API gateway to invoke a lambda function is needed.
This method will first check if API gateway has permission to call
the lambda function, and only if necessary will it invoke
``self.add_permission_for_apigateway(...).
def add_permission_for_apigateway(self, function_name,
... |
Return the function policy for a lambda function.
This function will extract the policy string as a json document
and return the json.loads(...) version of the policy.
def get_function_policy(self, function_name):
# type: (str) -> Dict[str, Any]
"""Return the function policy for a lamb... |
Download an SDK to a directory.
This will generate an SDK and download it to the provided
``output_dir``. If you're using ``get_sdk_download_stream()``,
you have to handle downloading the stream and unzipping the
contents yourself. This method handles that for you.
def download_sdk(s... |
Generate an SDK for a given SDK.
Returns a file like object that streams a zip contents for the
generated SDK.
def get_sdk_download_stream(self, rest_api_id,
api_gateway_stage=DEFAULT_STAGE_NAME,
sdk_type='javascript'):
# type: (s... |
Verify a subscription arn matches the topic and function name.
Given a subscription arn, verify that the associated topic name
and function arn match up to the parameters passed in.
def verify_sns_subscription_current(self, subscription_arn, topic_name,
function... |
Configure S3 bucket to invoke a lambda function.
The S3 bucket must already have permission to invoke the
lambda function before you call this function, otherwise
the service will return an error. You can add permissions
by using the ``add_permission_for_s3_event`` below. The
... |
Check if the uuid matches the resource and function arn provided.
Given a uuid representing an event source mapping for a lambda
function, verify that the associated source arn
and function arn match up to the parameters passed in.
Instead of providing the event source arn, the resourc... |
Load the chalice config file from the project directory.
:raise: OSError/IOError if unable to load the config file.
def load_project_config(self):
# type: () -> Dict[str, Any]
"""Load the chalice config file from the project directory.
:raise: OSError/IOError if unable to load the con... |
Invoke the deployed lambda function NAME.
def invoke(ctx, name, profile, stage):
# type: (click.Context, str, str, str) -> None
"""Invoke the deployed lambda function NAME."""
factory = ctx.obj['factory'] # type: CLIFactory
factory.profile = profile
try:
invoke_handler = factory.create_la... |
Generate a cloudformation template for a starter CD pipeline.
This command will write a starter cloudformation template to
the filename you provide. It contains a CodeCommit repo,
a CodeBuild stage for packaging your chalice app, and a
CodePipeline stage to deploy your application using cloudformation... |
Return resources associated with a given stage.
If a deployment to a given stage has never happened,
this method will return a value of None.
def deployed_resources(self, chalice_stage_name):
# type: (str) -> DeployedResources
"""Return resources associated with a given stage.
... |
Auto generate policy for an application.
def generate_policy(self, config):
# type: (Config) -> Dict[str, Any]
"""Auto generate policy for an application."""
# Admittedly, this is pretty bare bones logic for the time
# being. All it really does it work out, given a Config instance,
... |
Return all clients calls made in provided source code.
:returns: A dict of service_name -> set([client calls]).
Example: {"s3": set(["list_objects", "create_bucket"]),
"dynamodb": set(["describe_table"])}
def get_client_calls(source_code):
# type: (str) -> APICallT
"""Return all ... |
Return client calls for a chalice app.
This is similar to ``get_client_calls`` except it will
automatically traverse into chalice views with the assumption
that they will be called.
def get_client_calls_for_app(source_code):
# type: (str) -> APICallT
"""Return client calls for a chalice app.
... |
Match the url against known routes.
This method takes a concrete route "/foo/bar", and
matches it against a set of routes. These routes can
use param substitution corresponding to API gateway patterns.
For example::
match_route('/foo/bar') -> '/foo/{name}'
def match_route... |
Translate event for an authorizer input.
def _prepare_authorizer_event(self, arn, lambda_event, lambda_context):
# type: (str, EventType, LambdaContext) -> EventType
"""Translate event for an authorizer input."""
authorizer_event = lambda_event.copy()
authorizer_event['type'] = 'TOKEN'
... |
Set initial parameters for default modulator if it was not edited by user previously
:return:
def bootstrap_modulator(self, protocol: ProtocolAnalyzer):
"""
Set initial parameters for default modulator if it was not edited by user previously
:return:
"""
if len(self.modu... |
:param buffer: Buffer in which the modulated data shall be written, initialized with zeros
:return:
def modulate_data(self, buffer: np.ndarray) -> np.ndarray:
"""
:param buffer: Buffer in which the modulated data shall be written, initialized with zeros
:return:
"""
... |
Refresh existing encodings for messages, when encoding was changed by user in dialog
:return:
def refresh_existing_encodings(self, encodings_from_file):
"""
Refresh existing encodings for messages, when encoding was changed by user in dialog
:return:
"""
update = False... |
:rtype: dict[int, list of ProtocolAnalyzer]
def protocols(self):
"""
:rtype: dict[int, list of ProtocolAnalyzer]
"""
if self.__protocols is None:
self.__protocols = self.proto_tree_model.protocols
return self.__protocols |
:return: visible protocols
:rtype: list of ProtocolAnalyzer
def protocol_list(self):
"""
:return: visible protocols
:rtype: list of ProtocolAnalyzer
"""
result = []
for group in self.groups:
result.extend(group.protocols)
return result |
:return: all protocols including not shown ones
:rtype: list of ProtocolAnalyzer
def full_protocol_list(self):
"""
:return: all protocols including not shown ones
:rtype: list of ProtocolAnalyzer
"""
result = []
for group in self.groups:
result.extend... |
Refresh existing encodings for messages, when encoding was changed by user in dialog
:return:
def refresh_existing_encodings(self):
"""
Refresh existing encodings for messages, when encoding was changed by user in dialog
:return:
"""
update = False
for msg in ... |
Handles the different combinations of the show only checkboxes, namely:
- Show only labels
- Show only Diffs
def set_show_only_status(self):
"""
Handles the different combinations of the show only checkboxes, namely:
- Show only labels
- Show only Diffs
"""
... |
Wrapper method selecting the backend to assign the protocol field.
Various strategies are possible e.g.:
1) Heuristics e.g. for Preamble
2) Scoring based e.g. for Length
3) Fulltext search for addresses based on participant subgroups
:param messages: messages a field shall be se... |
Assign message types based on the clusters. Following rules:
1) Messages from different clusters will get different message types
2) Messages from same clusters will get same message type
3) The new message type will copy over the existing labels
4) No new message type will be set for me... |
Perform Short-time Fourier transform to get the spectrogram for the given samples
:return: short-time Fourier transform of the given signal
def stft(self, samples: np.ndarray):
"""
Perform Short-time Fourier transform to get the spectrogram for the given samples
:return: short-time Four... |
Export to Frequency, Time, Amplitude file.
Frequency is double, Time (nanosecond) is uint32, Amplitude is float32
:return:
def export_to_fta(self, sample_rate, filename: str, include_amplitude=False):
"""
Export to Frequency, Time, Amplitude file.
Frequency is double, Time (nan... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.