code
stringlengths
1
18.2k
def _get_event_source_status(awsclient, evt_source, lambda_arn): """ Given an event_source dictionary, create the object and get the event source status. """ event_source_obj = _get_event_source_obj(awsclient, evt_source) return event_source_obj.status(lambda_arn)
def unwire(awsclient, events, lambda_name, alias_name=ALIAS_NAME): """Unwire a list of event from an AWS Lambda function. 'events' is a list of dictionaries, where the dict must contains the 'schedule' of the event as string, and an optional 'name' and 'description'. :param awsclient: :param events: list of events :par...
doesn\'t ' + 'exist... Bailing out...')) return 1 client_lambda = awsclient.get_client('lambda') lambda_function = client_lambda.get_function(FunctionName=lambda_name) lambda_arn = client_lambda.get_alias(FunctionName=lambda_name, Name=alias_name)['AliasArn'] log.info('UN-wiring lambda_arn %s ' % lambda_arn) # TODO why...
#_unschedule_events(awsclient, events, lambda_arn) for event in events: evt_source = event['event_source'] _remove_event_source(awsclient, evt_source, lambda_arn) return 0
def wire_deprecated(awsclient, function_name, s3_event_sources=None, time_event_sources=None, alias_name=ALIAS_NAME): """Deprecated! Please use wire! :param awsclient: :param function_name: :param s3_event_sources: dictionary :param time_event_sources: :param alias_name: :return: exit_code """ if not lambda_exists(awsc...
s3_events_ensure_exists, s3_events_ensure_absent = filter_events_ensure( s3_event_sources) cloudwatch_events_ensure_exists, cloudwatch_events_ensure_absent = \ filter_events_ensure(time_event_sources) for s3_event_source in s3_events_ensure_absent: _ensure_s3_event(awsclient, s3_event_source, function_name, alias_name,...
def unwire_deprecated(awsclient, function_name, s3_event_sources=None, time_event_sources=None, alias_name=ALIAS_NAME): """Deprecated! Please use unwire! :param awsclient: :param function_name: :param s3_event_sources: dictionary :param time_event_sources: :param alias_name: :return: exit_code """ if not lambda_exists(...
= client_lambda.get_policy(FunctionName=function_name, Qualifier=alias_name) policies = json.loads(result['Policy']) except ClientError as e: if e.response['Error']['Code'] == 'ResourceNotFoundException': log.warn("Permission policies not found") else: raise e if lambda_function is not None: #### S3 Events # for every ...
function_name, statement['Sid'], alias_name) log.info('\tRemoving All S3 events {} invoking {}'.format( source_bucket, lambda_arn)) _remove_events_from_s3_bucket(awsclient, source_bucket, lambda_arn) # Case: s3 events without permissions active "safety measure" for s3_event_source in s3_event_sources: bucket_name = s3_...
'\tRemoving Cloudwatch permission {} invoking {}'.format( rule_name, lambda_arn)) _remove_permission(awsclient, function_name, statement['Sid'], alias_name) log.info('\tRemoving Cloudwatch rule {} invoking {}'.format( rule_name, lambda_arn)) _remove_cloudwatch_rule_event(awsclient, rule_name, lambda_arn) # Case: rules ...
def _lambda_add_s3_event_source(awsclient, arn, event, bucket, prefix, suffix): """Use only prefix OR suffix :param arn: :param event: :param bucket: :param prefix: :param suffix: :return: """ json_data = { 'LambdaFunctionConfigurations': [{ 'LambdaFunctionArn': arn, 'Id': str(uuid.uuid1()), 'Events': [event] }] } filt...
'LambdaFunctionConfigurations' in bucket_configurations: bucket_configurations['LambdaFunctionConfigurations'].append( json_data['LambdaFunctionConfigurations'][0] ) else: bucket_configurations['LambdaFunctionConfigurations'] = json_data[ 'LambdaFunctionConfigurations'] response = client_s3.put_bucket_notification_conf...
def find_eigen(hint=None): r''' Try to find the Eigen library. If successful the include directory is returned. ''' # search with pkgconfig # --------------------- try: import pkgconfig if pkgconfig.installed('eigen3','>3.0.0'): return pkgconfig.parse('eigen3')['include_dirs'][0] except: pass # manual search # --------...
"Eigen", "Dense") if os.path.exists(path): vf = os.path.join(d, "Eigen", "src", "Core", "util", "Macros.h") if not os.path.exists(vf): continue src = open(vf, "r").read() v1 = re.findall("#define EIGEN_WORLD_VERSION (.+)", src) v2 = re.findall("#define EIGEN_MAJOR_VERSION (.+)", src) v3 = re.findall("#define EIGEN_MINO...
def check_and_format_logs_params(start, end, tail): """Helper to read the params for the logs command""" def _decode_duration_type(duration_type): durations = {'m': 'minutes', 'h': 'hours', 'd': 'days', 'w': 'weeks'} return durations[duration_type] if not start: if tail: start_dt = maya.now().subtract(seconds=300).date...
end[-1] in ['m', 'h', 'd', 'w']: value = int(end[:-1]) end_dt = maya.now().subtract( **{_decode_duration_type(end[-1]): value}).datetime(naive=True) elif end: end_dt = maya.parse(end).datetime(naive=True) else: end_dt = None return start_dt, end_dt
def upload_file_to_s3(awsclient, bucket, key, filename): """Upload a file to AWS S3 bucket. :param awsclient: :param bucket: :param key: :param filename: :return: """ client_s3 = awsclient.get_client('s3') transfer = S3Transfer(client_s3) # Upload /tmp/myfile to s3://bucket/key and print upload progress. transfer.uploa...
def remove_file_from_s3(awsclient, bucket, key): """Remove a file from an AWS S3 bucket. :param awsclient: :param bucket: :param key: :return: """ client_s3 = awsclient.get_client('s3') response = client_s3.delete_object(Bucket=bucket, Key=key)
def ls(awsclient, bucket, prefix=None): """List bucket contents :param awsclient: :param bucket: :param prefix: :return: """ # this works until 1000 keys! params = {'Bucket': bucket} if prefix: params['Prefix'] = prefix client_s3 = awsclient.get_client('s3') objects = client_s3.list_objects_v2(**params) if objects['Key...
def ORRS(self, params): """ ORRS [Ra,] Ra, Rb OR Ra and Rb together and store the result in Ra The equivalent of `Ra = Ra | Rc` Updates NZ flags Ra and Rb must be low registers The first register is optional """ # This instruction allows for an optional destination register # If it is omitted, then it is assumed to be ...
# As defined in http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.dui0662b/index.html try: Ra, Rb, Rc = self.get_three_parameters(self.THREE_PARAMETER_COMMA_SEPARATED, params) except iarm.exceptions.ParsingError: Rb, Rc = self.get_two_parameters(self.TWO_PARAMETER_COMMA_SEPARATED, params) Ra = Rb self.check_a...
def TST(self, params): """ TST Ra, Rb AND Ra and Rb together and update the NZ flag. The result is not set The equivalent of `Ra & Rc` Ra and Rb must be low registers """ Ra, Rb = self.get_two_parameters(self.TWO_PARAMETER_COMMA_SEPARATED, params) self.check_arguments(low_registers=(Ra, Rb)) def TST_func(): result = se...
def render_to_mail(template, context, **kwargs): """ Renders a mail and returns the resulting ``EmailMultiAlternatives`` instance * ``template``: The base name of the text and HTML (optional) version of the mail. * ``context``: The context used to render the mail. This context instance should contain everything require...
Usage example:: # Render the template myproject/hello_mail.txt (first non-empty line # contains the subject, third to last the body) and optionally the # template myproject/hello_mail.html containing the alternative HTML # representation. message = render_to_mail('myproject/hello_mail', {}, to=[email]) message.send() "...
break except StopIteration: # if lines is empty pass body = "\n".join(lines).strip("\n") message = EmailMultiAlternatives(subject=subject, body=body, **kwargs) try: message.attach_alternative( render_to_string("%s.html" % template, context), "text/html" ) except TemplateDoesNotExist: pass return message
def get_confirmation_url(email, request, name="email_registration_confirm", **kwargs): """ Returns the confirmation URL """ return request.build_absolute_uri( reverse(name, kwargs={"code": get_confirmation_code(email, request, **kwargs)}) )
def send_registration_mail(email, *, request, **kwargs): """send_registration_mail(email, *, request, **kwargs) Sends the registration mail * ``email``: The email address where the registration link should be sent to. * ``request``: A HTTP request instance, used to construct the complete URL (including protocol and dom...
``registration/email_registration_email.txt``: The first line of this template will be the subject, the third to the last line the body of the email. * ``registration/email_registration_email.html``: The body of the HTML version of the mail. This template is **NOT** available by default and is not required either. """ ...
def decode(code, *, max_age): """decode(code, *, max_age) Decodes the code from the registration link and returns a tuple consisting of the verified email address and the payload which was passed through to ``get_confirmation_code``. The maximum age in seconds of the link has to be specified as ``max_age``. This method...
""" try: data = get_signer().unsign(code, max_age=max_age) except signing.SignatureExpired: raise ValidationError( _("The link is expired. Please request another registration link."), code="email_registration_expired", ) except signing.BadSignature: raise ValidationError( _( "Unable to verify the signature. Please requ...
def do_some_work( self, work_dict): """do_some_work :param work_dict: dictionary for key/values """ label = "do_some_work" log.info(("task - {} - start " "work_dict={}") .format(label, work_dict)) ret_data = { "job_results": ("some response key={}").format( str(uuid.uuid4())) } log.info(("task - {} - result={} done") ....
def create_record(awsclient, name_prefix, instance_reference, type="A", host_zone_name=None): """ Builds route53 record entries enabling DNS names for services Note: gcdt.route53 create_record(awsclient, ...) is used in dataplatform cloudformation.py templates! :param name_prefix: The sub domain prefix to use :param in...
name to use (like preprod.ds.glomex.cloud. - DO NOT FORGET THE DOT!) :return: RecordSetType """ # Only fetch the host zone from the COPS stack if nessary if host_zone_name is None: host_zone_name = _retrieve_stack_host_zone_name(awsclient) if not (type == "A" or type == "CNAME"): raise Exception("Record set type is not...
EC2 instance automatically to their private IP if isinstance(instance_reference, Instance): resource_record = troposphere.GetAtt( instance_reference, "PrivateIp" ) else: resource_record = instance_reference return RecordSetType( name_of_record, HostedZoneName=host_zone_name, Name=troposphere.Join("", [ name_prefix + "....
def _retrieve_stack_host_zone_name(awsclient, default_stack_name=None): """ Use service discovery to get the host zone name from the default stack :return: Host zone name as string """ global _host_zone_name if _host_zone_name is not None: return _host_zone_name env = get_env() if env is None: print("Please set environ...
'dp-<env>'? - this should not be hardcoded! default_stack_name = 'dp-%s' % env default_stack_output = get_outputs_for_stack(awsclient, default_stack_name) if HOST_ZONE_NAME__STACK_OUTPUT_NAME not in default_stack_output: print("Please debug why default stack '{}' does not contain '{}'...".format( default_stack_name, HO...
def load_plugins(group='gcdt10'): """Load and register installed gcdt plugins. """ # on using entrypoints: # http://stackoverflow.com/questions/774824/explain-python-entry-points # TODO: make sure we do not have conflicting generators installed! for ep in pkg_resources.iter_entry_points(group, name=None): plugin = ep.l...
def get_plugin_versions(group='gcdt10'): """Load and register installed gcdt plugins. """ versions = {} for ep in pkg_resources.iter_entry_points(group, name=None): versions[ep.dist.project_name] = ep.dist.version return versions
def delete_log_group(awsclient, log_group_name): """Delete the specified log group :param log_group_name: log group name :return: """ client_logs = awsclient.get_client('logs') response = client_logs.delete_log_group( logGroupName=log_group_name )
def put_retention_policy(awsclient, log_group_name, retention_in_days): """Sets the retention of the specified log group if the log group does not yet exist than it will be created first. :param log_group_name: log group name :param retention_in_days: log group name :return: """ try: # Note: for AWS Lambda the log_grou...
it create_log_group(awsclient, log_group_name) except GracefulExit: raise except Exception: # TODO check that it is really a ResourceAlreadyExistsException pass client_logs = awsclient.get_client('logs') response = client_logs.put_retention_policy( logGroupName=log_group_name, retentionInDays=retention_in_days )
def filter_log_events(awsclient, log_group_name, start_ts, end_ts=None): """ Note: this is used to retrieve logs in ramuda. :param log_group_name: log group name :param start_ts: timestamp :param end_ts: timestamp :return: list of log entries """ client_logs = awsclient.get_client('logs') # TODO use all_pages instead! ...
= next_token response = client_logs.filter_log_events(**request) logs.extend( [{'timestamp': e['timestamp'], 'message': e['message']} for e in response['events']] ) if 'nextToken' not in response: break next_token = response['nextToken'] return logs
def describe_log_group(awsclient, log_group_name): """Get info on the specified log group :param log_group_name: log group name :return: """ client_logs = awsclient.get_client('logs') request = { 'logGroupNamePrefix': log_group_name, 'limit': 1 } response = client_logs.describe_log_groups(**request) if response['logGro...
def describe_log_stream(awsclient, log_group_name, log_stream_name): """Get info on the specified log stream :param log_group_name: log group name :param log_stream_name: log stream :return: """ client_logs = awsclient.get_client('logs') response = client_logs.describe_log_streams( logGroupName=log_group_name, logStrea...
def create_log_group(awsclient, log_group_name): """Creates a log group with the specified name. :param log_group_name: log group name :return: """ client_logs = awsclient.get_client('logs') response = client_logs.create_log_group( logGroupName=log_group_name, )
def create_log_stream(awsclient, log_group_name, log_stream_name): """Creates a log stream for the specified log group. :param log_group_name: log group name :param log_stream_name: log stream name :return: """ client_logs = awsclient.get_client('logs') response = client_logs.create_log_stream( logGroupName=log_group_n...
def put_log_events(awsclient, log_group_name, log_stream_name, log_events, sequence_token=None): """Put log events for the specified log group and stream. :param log_group_name: log group name :param log_stream_name: log stream name :param log_events: [{'timestamp': 123, 'message': 'string'}, ...] :param sequence_token...
in response: log.warn(response['rejectedLogEventsInfo']) if 'nextSequenceToken' in response: return response['nextSequenceToken']
def get_log_events(awsclient, log_group_name, log_stream_name, start_ts=None): """Get log events for the specified log group and stream. this is used in tenkai output instance diagnostics :param log_group_name: log group name :param log_stream_name: log stream name :param start_ts: timestamp :return: """ client_logs = ...
response = client_logs.get_log_events(**request) if 'events' in response and response['events']: return [{'timestamp': e['timestamp'], 'message': e['message']} for e in response['events']]
def check_log_stream_exists(awsclient, log_group_name, log_stream_name): """Check :param log_group_name: log group name :param log_stream_name: log stream name :return: True / False """ lg = describe_log_group(awsclient, log_group_name) if lg and lg['logGroupName'] == log_group_name: stream = describe_log_stream(awscli...
def decode_format_timestamp(timestamp): """Convert unix timestamp (millis) into date & time we use in logs output. :param timestamp: unix timestamp in millis :return: date, time in UTC """ dt = maya.MayaDT(timestamp / 1000).datetime(naive=True) return dt.strftime('%Y-%m-%d'), dt.strftime('%H:%M:%S')
def reload(self): """Reload the configuration from disk returning True if the configuration has changed from the previous values. """ config = self._default_configuration() if self._file_path: config.update(self._load_config_file()) if config != self._values: self._values = config return True return False
def _load_config_file(self): """Load the configuration file into memory, returning the content. """ LOGGER.info('Loading configuration from %s', self._file_path) if self._file_path.endswith('json'): config = self._load_json_config() else: config = self._load_yaml_config() for key, value in [(k, v) for k, v in config.it...
def _load_json_config(self): """Load the configuration file in JSON format :rtype: dict """ try: return json.loads(self._read_config()) except ValueError as error: raise ValueError( 'Could not read configuration file: {}'.format(error))
def _load_yaml_config(self): """Loads the configuration file from a .yaml or .yml file :type: dict """ try: config = self._read_config() except OSError as error: raise ValueError('Could not read configuration file: %s' % error) try: return yaml.safe_load(config) except yaml.YAMLError as error: message = '\n'.join([' > ...
file.\n') sys.stderr.write(' YAML format validation available at ' 'http://yamllint.com\n') raise ValueError(error)
def _normalize_file_path(file_path): """Normalize the file path value. :param str file_path: The file path as passed in :rtype: str """ if not file_path: return None elif file_path.startswith('s3://') or \ file_path.startswith('http://') or \ file_path.startswith('https://'): return file_path return path.abspath(file_p...
def _read_config(self): """Read the configuration from the various places it may be read from. :rtype: str :raises: ValueError """ if not self._file_path: return None elif self._file_path.startswith('s3://'): return self._read_s3_config() elif self._file_path.startswith('http://') or \ self._file_path.startswith('https...
def _read_remote_config(self): """Read a remote config via URL. :rtype: str :raises: ValueError """ try: import requests except ImportError: requests = None if not requests: raise ValueError( 'Remote config URL specified but requests not installed') result = requests.get(self._file_path) if not result.ok: raise ValueEr...
def _read_s3_config(self): """Read in the value of the configuration file in Amazon S3. :rtype: str :raises: ValueError """ try: import boto3 import botocore.exceptions except ImportError: boto3, botocore = None, None if not boto3: raise ValueError( 's3 URL specified for configuration but boto3 not installed') parsed =...
configuration from S3: {}'.format(e)) return response['Body'].read().decode('utf-8')
def update(self, configuration, debug=None): """Update the internal configuration values, removing debug_only handlers if debug is False. Returns True if the configuration has changed from previous configuration values. :param dict configuration: The logging configuration :param bool debug: Toggles use of debug_only lo...
def configure(self): """Configure the Python stdlib logger""" if self.debug is not None and not self.debug: self._remove_debug_handlers() self._remove_debug_only() logging.config.dictConfig(self.config) try: logging.captureWarnings(True) except AttributeError: pass
def _remove_debug_handlers(self): """Remove any handlers with an attribute of debug_only that is True and remove the references to said handlers from any loggers that are referencing them. """ remove = list() for handler in self.config[self.HANDLERS]: if self.config[self.HANDLERS][handler].get('debug_only'): remove.app...
def _remove_debug_only(self): """Iterate through each handler removing the invalid dictConfig key of debug_only. """ LOGGER.debug('Removing debug only from handlers') for handler in self.config[self.HANDLERS]: if self.DEBUG_ONLY in self.config[self.HANDLERS][handler]: del self.config[self.HANDLERS][handler][self.DEBUG_...
def as_dictionary(self): """ Convert this object to a dictionary with formatting appropriate for a PIF. :returns: Dictionary with the content of this object formatted for a PIF. """ return {to_camel_case(i): Serializable._convert_to_dictionary(self.__dict__[i]) for i in self.__dict__ if self.__dict__[i] is not None}
def _convert_to_dictionary(obj): """ Convert obj to a dictionary with formatting appropriate for a PIF. This function attempts to treat obj as a Pio object and otherwise returns obj. :param obj: Object to convert to a dictionary. :returns: Input object as a dictionary or the original object. """ if isinstance(obj, list...
def _get_object(class_, obj): """ Helper function that returns an object, or if it is a dictionary, initializes it from class_. :param class_: Class to use to instantiate object. :param obj: Object to process. :return: One or more objects. """ if isinstance(obj, list): return [Serializable._get_object(class_, i) for i ...
def damping(temp, relhum, freq, pres=101325): """ Calculates the damping factor for sound in dB/m depending on temperature, humidity and sound frequency. Source: http://www.sengpielaudio.com/LuftdaempfungFormel.htm temp: Temperature in degrees celsius relhum: Relative humidity as percentage, e.g. 50 freq: Sound frequen...
= 4.6151 - 6.8346 * pow((273.15 / temp), 1.261) hum = relhum * pow(10.0, c_humid) * pres tempr = temp / 293.15 # convert to relative air temp (re 20 deg C) frO = pres * (24.0 + 4.04e4 * hum * (0.02 + hum) / (0.391 + hum)) frN = (pres * pow(tempr, -0.5) * (9.0 + 280.0 * hum * math.exp(-4.17 *
(pow(tempr, (-1.0 / 3.0)) - 1.0)))) damp = (8.686 * freq * freq * ( 1.84e-11 * (1.0 / pres) * math.sqrt(tempr) + pow(tempr, -2.5) * ( 0.01275 * (math.exp(-2239.1 / temp) * 1.0 / (frO + freq * freq / frO)) + 0.1068 * ( math.exp(-3352 / temp) * 1.0 / (frN + freq * freq / frN) ) ) ) ) return
damp
def total_level(source_levels): """ Calculates the total sound pressure level based on multiple source levels """ sums = 0.0 for l in source_levels: if l is None: continue if l == 0: continue sums += pow(10.0, float(l) / 10.0) level = 10.0 * math.log10(sums) return level
def total_rated_level(octave_frequencies): """ Calculates the A-rated total sound pressure level based on octave band frequencies """ sums = 0.0 for band in OCTAVE_BANDS.keys(): if band not in octave_frequencies: continue if octave_frequencies[band] is None: continue if octave_frequencies[band] == 0: continue sums += p...
def leq3(levels): """ Calculates the energy-equivalent (Leq3) value given a regular measurement interval. """ n = float(len(levels)) sums = 0.0 if sum(levels) == 0.0: return 0.0 for l in levels: if l == 0: continue sums += pow(10.0, float(l) / 10.0) leq3 = 10.0 * math.log10((1.0 / n) * sums) leq3 = max(0.0, leq3) retur...
def distant_level(reference_level, distance, reference_distance=1.0): """ Calculates the sound pressure level in dependence of a distance where a perfect ball-shaped source and spread is assumed. reference_level: Sound pressure level in reference distance in dB distance: Distance to calculate sound pressure level for, ...
/ math.log(10)) return level
def distant_total_damped_rated_level( octave_frequencies, distance, temp, relhum, reference_distance=1.0): """ Calculates the damped, A-rated total sound pressure level in a given distance, temperature and relative humidity from octave frequency sound pressure levels in a reference distance """ damping_distance = dista...
= distant_level( reference_level=float(octave_frequencies[band]), distance=distance, reference_distance=reference_distance ) # damping damp_per_meter = damping( temp=temp, relhum=relhum, freq=OCTAVE_BANDS[band][0]) distant_val = distant_val - (damping_distance * damp_per_meter) # applyng A-rating distant_val += OCTAVE_...
def ASRS(self, params): """ ASRS [Ra,] Ra, Rc ASRS [Ra,] Rb, #imm5_counting Arithmetic shift right Rb by Rc or imm5_counting and store the result in Ra imm5 counting is [1, 32] In the register shift, the first two operands must be the same register Ra, Rb, and Rc must be low registers If Ra is omitted, then it is assum...
# This instruction allows for an optional destination register # If it is omitted, then it is assumed to be Rb # As defined in http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.dui0662b/index.html try: Ra, Rb, Rc = self.get_three_parameters(self.THREE_PARAMETER_COMMA_SEPARATED, params) except iarm.exceptions....
shifted out bit if (self.register[Rc] > 0) and (self.register[Rb] & (1 << (self.register[Rc] - 1))): self.set_APSR_flag_to_value('C', 1) else: self.set_APSR_flag_to_value('C', 0) if self.register[Ra] & (1 << (self._bit_width - 1)): self.register[Ra] = (self.register[Ra] >> self.register[Rc]) | ( int('1' * self.register...
# Set the C flag, or the last shifted out bit if self.register[Rb] & (1 << (shift_amount - 1)): self.set_APSR_flag_to_value('C', 1) else: self.set_APSR_flag_to_value('C', 0) if self.register[Ra] & (1 << (self._bit_width - 1)): self.register[Ra] = (self.register[Ra] >> shift_amount) | ( int('1' * shift_amount, 2) << (se...
def LSLS(self, params): """ LSLS [Ra,] Ra, Rc LSLS [Ra,] Rb, #imm5 Logical shift left Rb by Rc or imm5 and store the result in Ra imm5 is [0, 31] In the register shift, the first two operands must be the same register Ra, Rb, and Rc must be low registers If Ra is omitted, then it is assumed to be Rb """ #
This instruction allows for an optional destination register # If it is omitted, then it is assumed to be Rb # As defined in http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.dui0662b/index.html try: Ra, Rb, Rc = self.get_three_parameters(self.THREE_PARAMETER_COMMA_SEPARATED, params) except iarm.exceptions.Pa...
out bit if (self.register[Rc] < self._bit_width) and (self.register[Ra] & (1 << (self._bit_width - self.register[Rc]))): self.set_APSR_flag_to_value('C', 1) else: self.set_APSR_flag_to_value('C', 0) self.register[Ra] = self.register[Ra] << self.register[Rc] self.set_NZ_flags(self.register[Ra]) else: # LSLS Ra, Rb, #imm...
else: self.set_APSR_flag_to_value('C', 0) self.register[Ra] = self.register[Rb] << shift_amount self.set_NZ_flags(self.register[Ra]) return LSLS_func
def LSRS(self, params): """ LSRS [Ra,] Ra, Rc LSRS [Ra,] Rb, #imm5_counting Logical shift right Rb by Rc or imm5 and store the result in Ra imm5 counting is [1, 32] In the register shift, the first two operands must be the same register Ra, Rb, and Rc must be low registers If Ra is omitted, then it is assumed to be Rb ...
# This instruction allows for an optional destination register # If it is omitted, then it is assumed to be Rb # As defined in http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.dui0662b/index.html try: Ra, Rb, Rc = self.get_three_parameters(self.THREE_PARAMETER_COMMA_SEPARATED, params) except iarm.exceptions....
shifted out bit if (self.register[Rc] > 0) and (self.register[Rb] & (1 << (self.register[Rc] - 1))): self.set_APSR_flag_to_value('C', 1) else: self.set_APSR_flag_to_value('C', 0) self.register[Ra] = self.register[Ra] >> self.register[Rc] self.set_NZ_flags(self.register[Ra]) else: # LSRS Ra, Rb, #imm5_counting self.chec...
self.register[Ra] = self.register[Rb] >> shift_amount self.set_NZ_flags(self.register[Ra]) return LSRS_func
def RORS(self, params): """ RORS [Ra,] Ra, Rc Rotate shift right Rb by Rc or imm5 and store the result in Ra The first two operands must be the same register Ra and Rc must be low registers The first register is optional """ # This instruction allows for an optional destination register # If it is omitted, then it is a...
Rb # As defined in http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.dui0662b/index.html try: Ra, Rb, Rc = self.get_three_parameters(self.THREE_PARAMETER_COMMA_SEPARATED, params) except iarm.exceptions.ParsingError: Rb, Rc = self.get_two_parameters(self.TWO_PARAMETER_COMMA_SEPARATED, params) Ra = Rb # TODO im...
def _parse_topic_table(self, xml, tds='title,created,comment,group', selector='//table[@class="olt"]//tr'): """ 解析话题列表 :internal :param xml: 页面XML :param tds: 每列的含义,可以是title, created, comment, group, updated, author, time, rec :param selector: 表在页面中的位置 :return: """ xml_results = xml.xpath(selector) results = [] tds = t...
xml_title.get('href') tid = int(slash_right(url)) title = xml_title.text result.update({'id': tid, 'url': url, 'title': title}) elif td == 'created': xml_created = item.xpath('.//td[position()=%s]/a' % index) \ or item.xpath('.//td[position()=%s]' % index) created_at = xml_created[0].get('title') result['created_at'] =...
= xml_group.get('href') group_alias = slash_right(group_url) group_name = xml_group.text result.update({'group_alias': group_alias, 'group_url': group_url, 'group_name': group_name}) elif td == 'author': xml_author = item.xpath('.//td[position()=%s]/a' % index)[0] author_url = xml_author.get('href') author_alias = slas...
item.xpath('.//td[position()=%s]//a[@class="lnk-remove"]/@href' % (index - 1))[0] result['rec_id'] = re.search(r'rec_id=(\d+)', xml_rec).groups()[0] results.append(result) except Exception as e: self.api.api.logger.exception('parse topic table exception: %s' % e) return results
def search_groups(self, keyword, start=0): """ 搜索小组 :param keyword: 搜索的关键字 :param start: 翻页 :return: 含总数的列表 """ xml = self.api.xml(API_GROUP_SEARCH_GROUPS % (start, keyword)) xml_results = xml.xpath('//div[@class="groups"]/div[@class="result"]') results = [] for item in xml_results: try: url = item.xpath('.//h3/a/@href...