INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
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)} ).get('functions', [])
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 = None archive = fu...
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: return self.client.execute_query('ge...
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( self.session.get_default_proj...
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() try: client.execute_command('get', {'topic': topic}) excep...
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') policy = client.execute_command('getIamPolicy', {'resource': topic})...
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 = "%s/%s" % (log_info.scope_type, log_info.scop...
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) try: sink = client.execute_c...
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 = self.session.client( 'logging', 'v2',...
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 for context (20s window) timestamps = [e...
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 for easier reuse. """ # Lazy import to avoid runtime dependency from c7n.mu import ( ...
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 'eventName' not in event['detail']: return False k = event['detail']['eventName'] ...
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', []): if not isinstance(e, dict): ...
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 policies or arbitrary scripts across accounts. """ session = get_session(assume, 'c7n-org', profile) client = session.client('organizat...
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 info in config['accounts']: if info['name'] == a...
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, region), last in last_index.items(): ...
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 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 """ with op...
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_name event['_index'] = con...
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 are *really after* the config date """ key_date = "/".join(key.split("/")[4:7]) return parse_date(key_date) > parse_date(config_date)
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: assumes a daily traildb file in s3 with dated key path """ logging.basicConfig(level=(verbose and logging.DEBUG or lo...
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 Auth 3. Azure CLI Auth """ # Only run once if self.credentials is not None: return tenant_auth_...
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 + resource_type if cache_id in self._pr...
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 Azure Functions. Look for dedicated Functions environment variables or fall back to normal Service Principal variables. """ self._initialize_session() ...
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 = m.enum_spec if ex...
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.filter_type == 'list': ...
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: params.update(extra_ar...
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] return buf.append appr = app(wsgi_env, start_response) ...
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['requestContext']['stage'] or '').encode('utf8') query ...
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, lambda_arn): # type: (TypedAWSClient, str) -> LogRetriever """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 AR...
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...
def retrieve_logs(self, include_lambda_messages=True, max_entries=None): # type: (bool, Optional[int]) -> Iterator[Dict[str, Any]] """Retrieve logs from a log group. :type include_lambda_messages: boolean :param include_lambda_messages: Include logs generated by the AWS Lamb...
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 """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. ""...
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...
def validate_python_version(config, actual_py_version=None): # type: (Config, Optional[str]) -> None """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. ...
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, bytes, bytes] """Execute a pip command with ...
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 not compile_c: env_vars...
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', arguments) # When downloadi...
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. Since we # are only interested in all the ones we can down...
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) -> str """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 appropr...
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 = json.load(f) except IOError: # If there ...
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 deployed values. """ final_values = {} # type: Dict[str, Any] if os.path.isfile(filename): with op...
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: (str, str) -> None """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...
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, # type: str zip_contents, # type: str environment_variables=None, # type: StrMap runtime=None, # type: OptStr tags...
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'] for policy_name in inline_policies: ...
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] """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...
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 except client.exceptions.NotFoundException: ...
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, region_name, account_id, rest_api_id, random_id=None): # type: (str, str, str, str, Optional[str]) -> None """Authorize API gateway to invoke a lambda function is needed. ...
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 lambda function. This function will extract the policy string as a json document and return the json.loads(...) version of the policy. """ client = self._cl...
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(self, rest_api_id, output_dir, api_gateway_stage=DEFAULT_STAGE_NAME, sdk_type='javascript'): # type: (str, str, str, str) -> None """Download an SDK to a directory. This will generate an SDK and download it to the provided ``out...
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: (str, str, str) -> file """Generate an SDK for a given SDK. Returns a file like object that streams a zip contents...
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_arn): # type: (str, str, str) -> bool """Verify a subscription arn matches the topic and function name. Given a subscription arn, verify that the associated topic name ...
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 ...
def connect_s3_bucket_to_lambda(self, bucket, function_arn, events, prefix=None, suffix=None): # type: (str, str, List[str], OptStr, OptStr) -> None """Configure S3 bucket to invoke a lambda function. The S3 bucket must already have permission to invoke 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...
def verify_event_source_current(self, event_uuid, resource_name, service_name, function_arn): # type: (str, str, str, str) -> bool """Check if the uuid matches the resource and function arn provided. Given a uuid representing an event source mapping for a lam...
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 config file. """ config_file = os.path.join(self.project_dir, '.chalice', 'config.json') with open(confi...
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_lambda_invoke_handler(name, stage) pa...
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...
def generate_pipeline(ctx, codebuild_image, source, buildspec_file, filename): # type: (click.Context, str, str, str, str) -> None """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 CodeC...
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. If a deployment to a given stage has never happened, this method will return a value of None. """ # This is arguably the wrong level o...
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, # which files need to analyzed and th...
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 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"])} """ ...
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. This is similar to ``get_client_calls`` except it will automatically traverse into chalice views with the assumption that they will be called. """ parsed = parse_code(source_code)...
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(self, url): # type: (str) -> MatchResult """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 exam...
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' try: authorizer_event[...
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.modulators) != 1 or len(self.table_model.protocol.messages) == 0: return modulator = s...
: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: """ self.ui.prBarGeneration.show() self.ui.prBarGeneration.setValue(0) self.ui.prBarGenerat...
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 for msg in self.table_model.protocol.messages: i = next((i for i, d in enumerate(e...
: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(group.all_protocols) return result
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 self.proto_analyzer.messages: i = next((i for i, d in enumerate(self.decodings) if d.name ==...
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 """ if self.ui.chkBoxShowOnlyDiffs.isChecked() and not self.ui.cbShowDiffs.isChecked(): self.ui.cbShowDiffs.setCh...
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...
def find_field(self, messages): """ 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 ...
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...
def assign_messagetypes(self, messages, clusters): """ 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 ove...
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 Fourier transform of the given signal """ window = self.window_function(self.window_size) hop_size = self.hop_size if le...
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 (nanosecond) is uint32, Amplitude is float32 :return: """ spectrogram = self.__calculate_spectrogram(self.samples) ...
Create QImage from ARGB array. The ARGB must have shape (width, height, 4) and dtype=ubyte. NOTE: The order of values in the 3rd axis must be (blue, green, red, alpha). :return:
def create_image(data: np.ndarray, colormap, data_min=None, data_max=None, normalize=True) -> QImage: """ Create QImage from ARGB array. The ARGB must have shape (width, height, 4) and dtype=ubyte. NOTE: The order of values in the 3rd axis must be (blue, green, red, alpha). :retu...
Estimate the frequency of the baseband signal using FFT :param start: Start of the area that shall be investigated :param end: End of the area that shall be investigated :param sample_rate: Sample rate of the signal :return:
def estimate_frequency(self, start: int, end: int, sample_rate: float): """ Estimate the frequency of the baseband signal using FFT :param start: Start of the area that shall be investigated :param end: End of the area that shall be investigated :param sample_rate: Sample rate o...
0 - "ASK", 1 - "FSK", 2 - "PSK", 3 - "APSK (QAM)" :param value: :return:
def modulation_type(self, value: int): """ 0 - "ASK", 1 - "FSK", 2 - "PSK", 3 - "APSK (QAM)" :param value: :return: """ if self.__modulation_type != value: self.__modulation_type = value self._qad = None self.modulation_type_changed.e...
:rtype: int, int, int, int
def selection_range(self): """ :rtype: int, int, int, int """ selected = self.selectionModel().selection() """:type: QItemSelection """ if selected.isEmpty(): return -1, -1, -1, -1 min_row = numpy.min([rng.top() for rng in selected]) max_row ...
Processes can't write to stdout/stderr on frozen windows apps because they do not exist here if process tries it anyway we get a nasty dialog window popping up, so we redirect the streams to a dummy see https://github.com/jopohl/urh/issues/370
def fix_windows_stdout_stderr(): """ Processes can't write to stdout/stderr on frozen windows apps because they do not exist here if process tries it anyway we get a nasty dialog window popping up, so we redirect the streams to a dummy see https://github.com/jopohl/urh/issues/370 """ if hasattr...
Build the order of component based on their priority and predecessors :rtype: list of Component
def build_component_order(self): """ Build the order of component based on their priority and predecessors :rtype: list of Component """ present_components = [item for item in self.__dict__.values() if isinstance(item, Component) and item.enabled] result = [None] * len(p...
This method clusters some bitvectors based on their length. An example output is 2: [0.5, 1] 4: [1, 0.75, 1, 1] Meaning there were two message lengths: 2 and 4 bit. (0.5, 1) means, the first bit was equal in 50% of cases (meaning maximum difference) and bit 2 was equal in all messages ...
def cluster_lengths(self): """ This method clusters some bitvectors based on their length. An example output is 2: [0.5, 1] 4: [1, 0.75, 1, 1] Meaning there were two message lengths: 2 and 4 bit. (0.5, 1) means, the first bit was equal in 50% of cases (meaning maximum d...
Find candidate addresses using LCS algorithm perform a scoring based on how often a candidate appears in a longer candidate Input is something like ------------------------ ['1b6033', '1b6033fd57', '701b603378e289', '20701b603378e289000c62', '1b603300', '78e289757e', '7078e2891b...
def find_candidates(candidates): """ Find candidate addresses using LCS algorithm perform a scoring based on how often a candidate appears in a longer candidate Input is something like ------------------------ ['1b6033', '1b6033fd57', '701b603378e289', '20701b603378e2890...
Choose a pair of address candidates ensuring they have the same length and starting with the highest scored ones :type candidates: dict[str, int] :param candidates: Count how often the longest common substrings appeared in the messages :return:
def choose_candidate_pair(candidates): """ Choose a pair of address candidates ensuring they have the same length and starting with the highest scored ones :type candidates: dict[str, int] :param candidates: Count how often the longest common substrings appeared in the messages ...
Extract each archive from the list of filenames. Normal files stay untouched. Add all files to the Recent Files. :type file_names: list of str :type temp_dir: str :rtype: list of str
def uncompress_archives(file_names, temp_dir): """ Extract each archive from the list of filenames. Normal files stay untouched. Add all files to the Recent Files. :type file_names: list of str :type temp_dir: str :rtype: list of str """ result = [] for filename in file_names: ...
:type modulators: list of Modulator :return:
def write_modulators_to_project_file(self, tree=None): """ :type modulators: list of Modulator :return: """ if self.project_file is None or not self.modulators: return if tree is None: tree = ET.parse(self.project_file) root = tree.getroo...
continuous haar wavelet transform based on the paper "A practical guide to wavelet analysis" by Christopher Torrence and Gilbert P Compo
def cwt_haar(x: np.ndarray, scale=10): """ continuous haar wavelet transform based on the paper "A practical guide to wavelet analysis" by Christopher Torrence and Gilbert P Compo """ next_power_two = 2 ** int(np.log2(len(x))) x = x[0:next_power_two] num_data = len(x) # get FFT of x (...
Finding the synchronization works by finding the first difference between two messages. This is performed for all messages and the most frequent first difference is chosen :type messages: list of Message :param preamble_end: End of preamble = start of search :param search_end: End of se...
def __find_sync_range(self, messages, preamble_end: int, search_end: int): """ Finding the synchronization works by finding the first difference between two messages. This is performed for all messages and the most frequent first difference is chosen :type messages: list of Message ...
Pad message in given row with zeros until given column so user can enter values behind end of message :return:
def __pad_until_index(self, row: int, bit_pos: int): """ Pad message in given row with zeros until given column so user can enter values behind end of message :return: """ try: new_bits = array.array("B", [0] * max(0, bit_pos - len(self.protocol.messages[row]))) ...
Search all differences between protocol messages regarding a reference message :param refindex: index of reference message :rtype: dict[int, set[int]]
def find_differences(self, refindex: int): """ Search all differences between protocol messages regarding a reference message :param refindex: index of reference message :rtype: dict[int, set[int]] """ differences = defaultdict(set) if refindex >= len(self.proto...
Demodulates received IQ data and adds demodulated bits to messages :param data: :return:
def __demodulate_data(self, data): """ Demodulates received IQ data and adds demodulated bits to messages :param data: :return: """ if len(data) == 0: return power_spectrum = data.real ** 2 + data.imag ** 2 is_above_noise = np.sqrt(np.mean(pow...
:type proto_bits: list of str
def create_rectangle(proto_bits, pulse_len=100): """ :type proto_bits: list of str """ ones = np.ones(pulse_len, dtype=np.float32) * 1 zeros = np.ones(pulse_len, dtype=np.float32) * -1 n = 0 y = [] for msg in proto_bits: for bit in msg: ...
Return true if redraw is needed
def set_parameters(self, samples: np.ndarray, window_size, data_min, data_max) -> bool: """ Return true if redraw is needed """ redraw_needed = False if self.samples_need_update: self.spectrogram.samples = samples redraw_needed = True self.samp...
:type parent: QTableView :type undo_stack: QUndoStack :type protocol_analyzers: list of ProtocolAnalyzer
def get_action(self, parent, undo_stack: QUndoStack, sel_range, protocol: ProtocolAnalyzer, view: int): """ :type parent: QTableView :type undo_stack: QUndoStack :type protocol_analyzers: list of ProtocolAnalyzer """ min_row, max_row, start, end = sel_range if min...
Return the length of this message in byte.
def get_byte_length(self, decoded=True) -> int: """ Return the length of this message in byte. """ end = len(self.decoded_bits) if decoded else len(self.__plain_bits) end = self.convert_index(end, 0, 2, decoded=decoded)[0] return int(end)
Return the SRC address of a message if SRC_ADDRESS label is present in message type of the message Return None otherwise :param decoded: :return:
def get_src_address_from_data(self, decoded=True): """ Return the SRC address of a message if SRC_ADDRESS label is present in message type of the message Return None otherwise :param decoded: :return: """ src_address_label = next((lbl for lbl in self.message_type...
Für das Bit-Alignment (neu Ausrichten von Hex, ASCII-View) :rtype: list of array.array
def split(self, decode=True): """ Für das Bit-Alignment (neu Ausrichten von Hex, ASCII-View) :rtype: list of array.array """ start = 0 result = [] message = self.decoded_bits if decode else self.plain_bits bit_alignments = set() if self.align_labe...
:type: encoding
def set_e(self): if self.ui.combobox_decodings.count() < 1: # Empty list return self.e = copy.deepcopy(self.decodings[self.ui.combobox_decodings.currentIndex()]) """:type: encoding """ chain = self.e.get_chain() self.ui.decoderchain.clear() self.chainoptions...
:rtype: dict[int, list of ProtocolAnalyzer]
def protocols(self): """ :rtype: dict[int, list of ProtocolAnalyzer] """ result = {} for i, group in enumerate(self.rootItem.children): result[i] = [child.protocol for child in group.children] return result
:rtype: dict[int, list of ProtocolTreeItem]
def protocol_tree_items(self): """ :rtype: dict[int, list of ProtocolTreeItem] """ result = {} for i, group in enumerate(self.rootItem.children): result[i] = [child for child in group.children] return result
:type items: list of ProtocolTreeItem
def move_to_group(self, items, new_group_id: int): """ :type items: list of ProtocolTreeItem """ group = self.rootItem.child(new_group_id) for item in items: group.appendChild(item) self.controller.refresh()
Set all protocols in copy mode. They will return a copy of their protocol. This is used for writable mode in CFC. :param use_copy: :return:
def set_copy_mode(self, use_copy: bool): """ Set all protocols in copy mode. They will return a copy of their protocol. This is used for writable mode in CFC. :param use_copy: :return: """ for group in self.rootItem.children: for proto in group.childr...