Best Python code snippet using autotest_python
pygenie.py
Source:pygenie.py  
1from collections import namedtuple2from contextlib import contextmanager3from pygenie.lib import *4from pygenie.lib.params._par_type import Parameter5class MeasurementTime(object):6    def __init__(self, live, real):7        self.live = live8        self.real = real9    def serialize(self):10        return {11            "live": self.live,12            "real": self.real13        }14class EnergycalibrationManager(object):15    POLYNOMIAL_CALIBRATION = b"POLY"16    """17    Value of ``EnergyCalibration.TYPE`` parameter which signifies18    polynomial calibration (that we are able to serialize.19    """20    def __init__(self, pygenie):21        super().__init__()22        self.pygenie = pygenie23    @property24    def type(self):25        """26        Calibration type used.27        """28        return self.pygenie.get_param(EnergyCalibration.TYPE)29    @property30    def unit(self):31        """32        Unit (eg. kev) in to which energy is calibrated33        """34        return self.pygenie.get_param(EnergyCalibration.UNIT)35    def get_calibration_coefficients(self):36        """37        If this uses polynomial calibration will return38        numpy array containing polynomial coefficients.39        This polynomial is in format compatible with ``np.polyval``40        call.41        """42        return get_calibration(self.pygenie.dsc)43    def serialize(self):44        serialized_dict = {45            "type" : self.type,46            "unit": self.unit,47        }48        if serialized_dict['type'] == self.POLYNOMIAL_CALIBRATION:49            serialized_dict.update({50                "energy_calibration": list(self.get_calibration_coefficients())51            })52        return serialized_dict53@contextmanager54def open_cam_source(file_name, source_type, open_mode=OpenFlags.ReadOnly, verify_hardware=False, shell_ptr=b""):55    pygenie = PYGenieObj()56    try:57        pygenie.open(file_name, source_type, open_mode, verify_hardware, shell_ptr)58        yield pygenie59    finally:60        pygenie.close()61class PYGenieObj(object):62    ABSOLUTE_TIME_PARAMETERS = {63        "X_ASTIME"64    }65    def __init__(self, autoconvert_absolute_dates=False):66        """67        :param bool autoconvert_absolute_dates: If set to True this object will attempt68                                                to automaticall convert datetime69                                                parameters that70                                                contain absolute intervals to datetime71                                                objects.72        :return:73        """74        super().__init__()75        self.dsc = None76        self.autoconvert_absolute_dates = autoconvert_absolute_dates77    def open(self, file_name, source_type, open_mode=OpenFlags.ReadOnly, verify_hardware=False, shell_ptr=b""):78        """79        Creates and opens a data source.80        Parameters are just like on SadOpenDataSource function.81        :param str file_name: It can be str, bytes or pathlib.Path object. File or datasource to open.82        :param SourceType esource_type: A source type. Specific types depend on the83                                        Library used. Example valid values are:84                                        ``SourceType.NativeSpect`` or ``SourceType.Detector``.85                                        All other constants from header file are accepted,86                                        and are avilable from SourceType without87                                        ``CIF_`` prefix.88        :param OpenFlags open_mode: Open method all constants prefixed with ``ACC_`` are avilable89                                    from this enum. Example valid value90                                    ``SourceType.ReadOnly``.91        :param bool verify_hardware: See  SadOpenDataSource.92        :param bytes shell_ptr:93        :return: None94        """95        self.dsc = create_vdm_connection()96        open_source(self.dsc, file_name, source_type, open_mode, verify_hardware, shell_ptr)97    def close(self):98        """99        Closes the VDM connection. Called automatically on deletion of this object.100        """101        if self.dsc is not None:102            self.flush()103            delete_vdm_connection(self.dsc)104            self.dsc = None105    def flush(self):106        flush(self.dsc)107    def convert_cam_interval_to_datetime(self, interval):108        return convert_interval_to_absolute_date(interval)109    def get_param(self, param, entry=1, record=1):110        """111        Gets a parameter.112        Following type conversions are used:113        * T parameters are converted to byte instances.114        * F parameters are converted to floats.115        * X parameters (datetime) are converted to floats, to convert them to116          datetime use :meth:`convert_cam_interval_to_datetime` (or select:117          ``autoconvert_absolute_dates`` on ``__init__``.)118        * L parameters are converted to int instances.119        :param Parameter param: Parameter to get. This can be either a string (with name120                                of the constant). Or a Parameter instance.121                                Parameters can be obtained from: a PARAM_GENERATOR instance122                                (for example ``PARAM_GENERATOR.T_STITLE``), or from123                                various enums that contain human-readable parameter124                                names, see: :class:`EnergyCalibration`,125                                :class:`SampleDescription`, :class:`ParamAlias`.126        :param int entry: As defined in SadGetParam (yes when I use this form, it means I have no clue)127        :param int record: As defined in SadGetParam128        :return: Parameter value129        """130        value =  get_parameter(self.dsc, param, entry, record)131        if self.autoconvert_absolute_dates and param.name in self.ABSOLUTE_TIME_PARAMETERS:132            value = self.convert_cam_interval_to_datetime(value)133        return value134    def set_param(self, param, value,  entry=1, record=1):135        """136        Sets a parameter. See :meth:`get_param` for description of parameters.137        Data is flushed to the data soure when this object is closed, deleted138        or when call to :meth:`flush` is issued.139        :param value: Value to be set140        """141        set_parameter(self.dsc, param, value, entry, record)142    def get_spectrum(self, channel_from=None, channel_to=None, spectrum_type=SpectrumType.LONG_DATA):143        """144        Returns spectrum from data source as a numpy array.145        Depending on value of ``spectrum_type``,146        either a numpy array containing dtype=np.uint32 (default) entries, or147        a numpy array containing dtype=np.float32.148        :param int channel_from:149        :param int channel_to:150        :param SpectrumType spectrum_type:151        :return: Numpy array containing spectrum channels.152        """153        if channel_from is None:154            channel_from = 0155        if channel_to is None:156            channel_to = self.channel_count157        return get_spectrum(self.dsc, channel_from, channel_to, spectrum_type)158    def __getitem__(self, item):159        """160        Equicalent to:  ``self.get_spectrum(item.start, item.stop)161        :param slice item:162        """163        if not isinstance(item, slice):164            raise ValueError("Pass a slice object")165        if item.step is not None:166            raise ValueError("Step is not supported")167        return self.get_spectrum(item.start, item.stop)168    @property169    def channel_count(self):170        """171        Return number of channels in the detector172        :return:173        """174        return self.get_param(ParamAlias.NUMBER_OF_CHANNELS)175    @property176    def measurement_time(self):177        """178        Returns tuple containing both live and real measurement times.179        """180        return MeasurementTime(181            self.get_param(ParamAlias.TIME_LIVE),182            self.get_param(ParamAlias.TIME_REAL),183        )184    @property185    def title(self):186        return self.get_param(SampleDescription.TITLE)187    @title.setter188    def title(self, value):189        if isinstance(value, str):190            value = value.encode('ascii')191        self.set_param(SampleDescription.TITLE, value)192        self.flush() # Since getter would still return stale value193    @property194    def sample_id(self):195        return self.get_param(SampleDescription.ID)196    @sample_id.setter197    def sample_id(self, value):198        if isinstance(value, str):199            value = value.encode('ascii')200        self.set_param(SampleDescription.ID, value)201        self.flush() # Since getter would still return stale value202    @property203    def energy_calibration(self):204        return EnergycalibrationManager(self)205    def get_description(self, part=0):206        """207        CAM files can contain four parts of description (each 64 bytes long).208        This returns each part209        :param int part: Zero indexed part index210        """211        return self.get_param(SampleDescription.DESCRIPTION[part+1])212    def set_description(self, value, part=0):213        """214        Sets description part.215        """216        if isinstance(value, str):217            value = value.encode('ascii')218        self.set_param(SampleDescription.DESCRIPTION[part+1], value)219    @property220    def measurement_start_time(self):221        """222        Datetime instance containing time when measurement was started.223        """224        return self.convert_cam_interval_to_datetime(225            get_parameter(self.dsc, SampleDescription.MEASURE_START_TIME)226        )227    def serialize(self, convert_absolute_datetime_params=False, additional_metadata = None):228        """229        Returns a dictionary (that can be immediately serialized to JSON)230        (Format should be self-evident).231        :param bool convert_absolute_datetime_params:  if true --- we will convert absolute datetimes and present them232                                                       as strings.233        :return: dict234        """235        additional_metadata = {} if additional_metadata is None else additional_metadata236        # param_list = [] if param_list is None else param_list237        serialized_dict = {238            "metadata": additional_metadata,239            "channel_count": self.channel_count,240            "measurment_start_time": self.measurement_start_time,241            "measurement_time" : self.measurement_time,242            "spectrum": self[:],243            "sample_id": self.sample_id,244            "title": self.title,245            "description": [],246            "energy_calibration": self.energy_calibration.serialize(),247            "params": []248        }249        # for param_list250        for ii in range(4):251            serialized_dict['description'].append(self.get_description(ii))252        return serialized_dict253    def __del__(self):...coral_pi.py
Source:coral_pi.py  
...6    version = platform.python_version()7    (major, minor, patch) = version.split('.')8    if major != '3' or minor != 7:9        raise Exception('Python version must be between 3.7 to use the Google Coral USB Accelerator on a Raspberry Pi')10def verify_hardware():11    uname = os.uname()12    OS = uname[0]13    MACHINE = uname[4]14    is_linux = OS == "Linux"15    is_pi = utility.is_raspberry_pi()16    is_arm7 = MACHINE in "armv7l"17    if not (is_pi and is_linux and is_arm7):18        raise Exception('If using the Google Coral on a Raspberry Pi, the architecture must be armv7l')19def check_lib_edge_tpu_install():20    verify_hardware()21    # https://stackoverflow.com/a/3391589/864383322    with open(os.devnull, "w") as devnull:23        retval = subprocess.call(24            ["dpkg","-s","libedgetpu1-std"],25            stdout=devnull,26            stderr=subprocess.STDOUT27        )28    29    return retval == 030def install_pycoral():31    utility.info('Installing pycoral and tflite-runtime...')32    new_reqs = utility.pip_install('{} {}'.format(constants.tflite_rpi_wheel, constants.pycoral_rpi_wheel))33    utility.info('The following packages have been installed:\n')34    [print('\t{}'.format(req)) for req in new_reqs]35   36def setup_coral():37    utility.info('Checking hardware compatibility...')38    verify_hardware()39    print('\tDevice is compatible!\n')40    utility.info('Checking python version...')41    verify_python_version()42    print('\tPython version is compatible!\n')43    utility.info("Checking if Google Coral lib_edge_tpu has been installed...")44    lib_is_installed = check_lib_edge_tpu_install()45    if not lib_is_installed:46        install_cmd = '\n'.join([47            'echo "deb https://packages.cloud.google.com/apt coral-edgetpu-stable main" | sudo tee /etc/apt/sources.list.d/coral-edgetpu.list',48            'curl https://packages.cloud.google.com/apt/doc/apt-key.gpg | sudo apt-key add -',49            'sudo apt-get update',50            'sudo apt-get install libedgetpu1-std'51        ])52        ...dsc.py
Source:dsc.py  
1import pathlib2from pygenie import init;3init._make_initialized()4from pygenie.utils import extract_defines, hex_int5from pygenie.lib.errors import check_for_error, ReturnErrorCodes6import enum7SourceType = enum.IntEnum(8    "SourceType",9    extract_defines(init.S560_PATH / 'CI_FILES.H', prefix="CIF_",10                    required_names=["NativeSpect", "Detector"], value_mapper=hex_int))11OpenFlags = enum.IntEnum(12    "OpenFlags", extract_defines(13        init.S560_PATH / 'Spasst.h', prefix="ACC_", value_mapper=hex_int,14        required_names=["ReadOnly", "ReadWrite", "Exclusive", 'SysWrite', 'AppWrite', 'Direct']))15def delete_vdm_connection(dsc):16    check_for_error(dsc, init.SAD_LIB.SadDeleteDSC(dsc))17def open_source(dsc, source_location, detector_type, open_mode, verify_hardware=False, shell_id=b""):18    if isinstance(source_location, str):19        source_location = pathlib.Path(source_location)20    check_for_error(dsc, init.SAD_LIB.SadOpenDataSource(dsc, bytes(source_location), int(detector_type), int(open_mode), verify_hardware, shell_id))21def create_vdm_connection():22    dsc = init.ffi.new("void**")23    #Yes these arguments myst allways be zero24    needs_to_delete_dsc = False25    # This is ankward error handling, but here is the rationale26    # If iUtlCreateFileDSC2 returns Error we need to manally delete DSC,27    # This should be done even if some other exception is raised28    # (for example while getting error details)29    init_result = init.SAD_LIB.iUtlCreateFileDSC2(dsc, 0, init.ffi.NULL)30    dsc = dsc[0]31    if init_result == ReturnErrorCodes.Error:32        needs_to_delete_dsc = True33    try:34        check_for_error(dsc, init_result)35    finally:36        if needs_to_delete_dsc:37            delete_vdm_connection(dsc) # In case of this error we are responsible for deleting dsc38    return dsc39def flush(dsc):40    init.SAD_LIB.SadFlush(dsc)...Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
