Best Python code snippet using refurb_python
multi_fosphor_example.py
Source:multi_fosphor_example.py  
...854    parser.add_argument("--channel_type", nargs="+", default=["RX2"], type=str)855    return parser.parse_args()856# Takes a list of values and the index within that list to return. If that index857# is out of range, the element at index 0 of the list is returned instead.858def index_or_default(parameter, index):859    assert len(parameter) > 0860    return parameter[index] if index < len(parameter) else parameter[0]861def wf_mode_check(wf_mode):862    return {"max_hold": 0, "average": 1}.get(wf_mode)863def main():864    if StrictVersion("4.5.0") <= StrictVersion(Qt.qVersion()) < StrictVersion("5.0.0"):865        style = gr.prefs().get_string("qtgui", "style", "raster")866        Qt.QApplication.setGraphicsSystem(style)867    qapp = Qt.QApplication(sys.argv)868    # Parse the command-line parameters and populate the dictionary holding869    # application-wide (i.e., non-channel-specific) settings.870    args = parse_args()871    if args.channel_freq is None:872        logger.error("Please specify --channel_freq")873        return False874    settings_dict = {875        "global": {876            "fft_size": args.fft_size,877            "bandwidth": parse_si_value(args.bandwidth),878            "args": args.args,879            "power_bins": args.power_bins,880            "frame_rate": args.frame_rate,881            "max_noutput_items": args.max_noutput_items,882            "channel_select": args.channel_select,883            "no_gui": args.no_gui884        },885        "channels": [],886    }887    # Attempt to locate Fosphor-enabled channels on the RFNoC image of the888    # radio889    fosphor_chains_strings = find_fosphor_chains(settings_dict)890    if len(fosphor_chains_strings) < 1:891        logger.error("No fosphor chains found")892        return False893    if (settings_dict["global"]["channel_select"] != [0, 1, 2, 3]) and (894        max(settings_dict["global"]["channel_select"]) >= len(fosphor_chains_strings)895    ):896        logger.error(897            "Channel "898            + str(max(settings_dict["global"]["channel_select"]))899            + " not detected"900        )901        return False902    # Create an RFNoC graph for use in connecting the RFNoC blocks on the903    # radio to form the Fosphor channels904    rfnoc_graph = ettus.rfnoc_graph(905        gnuradio.uhd.device_addr(settings_dict["global"]["args"])906    )907    settings_dict["global"]["rfnoc_graph"] = rfnoc_graph908    settings_dict["global"]["rfnoc_block_refs"] = dict()909    # For each detected Fosphor channels, populate the channel-specific settings910    # dictionary from the appropriate command-line options911    for (chain_index, _) in enumerate(fosphor_chains_strings):912        channel_settings = {913            "freq": parse_si_value(index_or_default(args.channel_freq, chain_index)),914            "gain": index_or_default(args.channel_gain, chain_index),915            "max_hold_decay": index_or_default(args.max_hold_decay, chain_index),916            "randomization": index_or_default(args.randomization_enable, chain_index),917            "dither": index_or_default(args.dither_enable, chain_index),918            "wf_mode": wf_mode_check(index_or_default(args.wf_mode, chain_index)),919            "alpha": index_or_default(args.averaging_alpha, chain_index),920            "rise": index_or_default(args.rise, chain_index),921            "decay": index_or_default(args.decay, chain_index),922            "offset": index_or_default(args.offset, chain_index),923            "scale": index_or_default(args.scale, chain_index),924            "color": index_or_default(args.color, chain_index),925            "channel_type": index_or_default(args.channel_type, chain_index),926        }927        settings_dict["channels"][chain_index].update(channel_settings)928    # Build all the GNU Radio flowgraphs and GUI elements for each Fosphor929    # channel930    mfe = multi_fosphor_example(settings_dict, fosphor_chains_strings)931    mfe.show()932    # Start the Fosphor channel flowgraphs933    mfe.go()934    def sig_handler(sig=None, frame=None):935        Qt.QApplication.quit()936    signal.signal(signal.SIGINT, sig_handler)937    signal.signal(signal.SIGTERM, sig_handler)938    timer = Qt.QTimer()939    timer.start(500)...ini.py
Source:ini.py  
...4from itertools import chain5from operator import index6from typing import Any, NamedTuple, SupportsIndex, TypeVar7T = TypeVar("T")8def index_or_default(9    lst: list[T],10    value: SupportsIndex,11    start: int = None,12    end: int = None,13    default: T | None = None,14):15    try:16        return lst.index(value, start, end)17    except ValueError:18        return default19def comment_to_string(comment: str):20    return "" if comment == "" else f"#{comment}"21@dataclass22class Directive:23    key: str24    value: str25    def __init__(self, key: Any, value: Any) -> None:26        self.key = str(key)27        self.value = str(value)28# Should have been a @staticmethod, but that failed because of the self-referencing isinstance check29def directive_from_tuple(tuple_: tuple | Directive):30    if isinstance(tuple_, Directive):31        return tuple_32    return Directive(*tuple_)33@dataclass34class IniFileLine:35    comment: str36    space_between: str37    def __init__(self, comment="", space_between="") -> None:38        self.comment = comment39        self.space_between = space_between40    @abstractproperty41    def pre_comment_text(self) -> str:42        pass43    def to_string(self):44        string = ""45        if (pre_comment_text := self.pre_comment_text) != "":46            string += pre_comment_text47        if self.comment != "":48            if string != "" and self.space_between:49                string += " "50            string += comment_to_string(self.comment)51        return string52    def add_comment(self, _comment: str, add_space_before_comment: bool = True):53        if self.comment != "":54            raise Exception("Comment already set")55        if add_space_before_comment:56            _comment = f" {_comment}"57        self.comment = _comment58        self.space_between = " "59class PreCommentLine(IniFileLine):60    pre_comment_spaces: str61    def __init__(self, comment="", pre_comment_spaces=""):62        super().__init__(comment, space_between=False)63        self.pre_comment_spaces = pre_comment_spaces64    @property65    def pre_comment_text(self):66        return self.comment67@dataclass68class SectionTitleLine(IniFileLine):69    title: str70    def __init__(self, title: str, comment="", space_between=""):71        super().__init__(comment, space_between)72        self.title = title73    @property74    def pre_comment_text(self):75        return f"[{self.title}]"76@dataclass77class SectionLine(IniFileLine):78    directive: Directive | None79    delimiter: str80    def __init__(81        self, directive: str, comment="", space_between="", delimiter: str = "="82    ):83        super().__init__(comment, space_between)84        self.directive = directive85        self.delimiter = delimiter86    @staticmethod87    def from_directive(directive_or_kv: tuple | Directive):88        return SectionLine(directive_from_tuple(directive_or_kv), "")89    @property90    def pre_comment_text(self):91        if self.directive is None:92            return ""93        return f"{self.directive.key}{self.delimiter}{self.directive.value}"94@dataclass95class Section:96    titleLine: SectionTitleLine97    lines: list[SectionLine]98    @property99    def directives(self):100        return (line.directive for line in self.lines if line.directive is not None)101    @property102    def directive_tuples(self):103        return (directive.tuple for directive in self.directives)104    def add_directive(self, directive_or_kv: Directive | tuple[str, str]):105        directive = directive_from_tuple(directive_or_kv)106        self.lines.append(SectionLine(directive, ""))107    def add_if_not_present(self, directive_or_kv: Directive | tuple[str, str]):108        directive = directive_from_tuple(directive_or_kv)109        if directive not in self.directives:110            self.lines.append(SectionLine(directive, ""))111    def add_or_replace(self, directive_or_kv: Directive | tuple[str, str]):112        directive = directive_from_tuple(directive_or_kv)113        self.lines = [114            line115            for line in self.lines116            if line.directive is None or line.directive.key != directive.key117        ]118        self.lines.append(SectionLine(directive, ""))119    def add_all_if_not_present(120        self, directives_or_kvs: list[Directive | tuple[str, str]]121    ):122        for directive_or_kv in directives_or_kvs:123            self.add_if_not_present(directive_or_kv)124    def to_lines(self):125        return [126            self.titleLine.to_string(),127            *(line.to_string() for line in self.lines),128        ]129    @staticmethod130    def from_directives(131        title: str, directives_or_kvs: list[Directive | tuple[str, str]]132    ):133        return Section(134            SectionTitleLine(title),135            [136                SectionLine.from_directive(directive_or_kv)137                for directive_or_kv in directives_or_kvs138            ],139        )140class IniFileParseException(Exception):141    pass142class IniConfig:143    _pre_comments: list[PreCommentLine]144    _sections: list[Section]145    def __init__(self, sections: list[Section] = None):146        self._pre_comments = []147        if sections is None:148            sections = []149        self._sections = sections150    def sections_by_title(self, title: str):151        return (152            section for section in self._sections if section.titleLine.title == title153        )154    def single_section_by_title(self, title: str):155        sections = self.sections_by_title(title)156        section = next(sections, None)157        if next(sections, None) != None:158            raise ValueError(f"Found multiple sections with title {title}")159        return section160    def sections_by_directive(self, title: str, directive: Directive):161        return (162            section163            for section in self._sections164            if directive in section.directives and section.titleLine.title == title165        )166    def single_section_by_directive(167        self, title: str, directive_or_kv: Directive | tuple[str, str]168    ):169        directive = directive_from_tuple(directive_or_kv)170        sections = self.sections_by_directive(title, directive)171        section = next(sections, None)172        if next(sections, None) != None:173            raise ValueError(f"Found multiple sections with directive {directive}")174        return section175    def add_section(self, section: Section, add_newline_if_not_first: bool = True):176        if len(self._sections) != 0 and add_newline_if_not_first:177            self._sections[-1].lines.append(SectionLine(None, ""))178        self._sections.append(section)179    def to_lines(self):180        return [181            *(pre_comment.to_string() for pre_comment in self._pre_comments),182            *(chain(*(section.to_lines() for section in self._sections))),183        ]184    def to_string(self):185        return "\n".join(self.to_lines()) + "\n"186    def to_string_io(self):187        return StringIO(self.to_string())188    def write(self, file: Any):189        file.write(self.to_string())190    @staticmethod191    def from_section_directives(192        sections: list[tuple[str, list[Directive | tuple[str, str]]]]193    ):194        return IniConfig(195            [196                Section.from_directives(title, directives)197                for title, directives in sections198            ]199        )200    @staticmethod201    def from_lines(lines: list[str]):202        pre_comments = []203        sections = []204        section = None205        for index, line in enumerate(lines):206            def create_error(message):207                return IniFileParseException(208                    f"Error parsing line {index + 1}: {message} \n"209                    + f"{index + 1}: {line}"210                )211            comment_index = index_or_default(line, "#")212            line_has_comment = comment_index != None213            comment = line[comment_index + 1 :] if line_has_comment else ""214            opening_bracket_index = index_or_default(line, "[", 0, comment_index)215            is_title_line = opening_bracket_index != None216            delimiter_index = index_or_default(line, "=", 0, comment_index)217            is_directive_line = delimiter_index != None218            if line_has_comment:219                if is_title_line and opening_bracket_index > comment_index:220                    is_title_line = False221                if is_directive_line and delimiter_index > comment_index:222                    is_directive_line = False223            if is_title_line and is_directive_line:224                delimiter_after_opening_bracket = (225                    delimiter_index > opening_bracket_index226                )227                is_title_line = not delimiter_after_opening_bracket228                is_directive_line = delimiter_after_opening_bracket229            if is_title_line:230                if opening_bracket_index != 0:...simplify_return.py
Source:simplify_return.py  
...15    """16    Sometimes a return statement can be written more succinctly:17    Bad:18    ```19    def index_or_default(nums: list[Any], index: int, default: Any):20        if index >= len(nums):21            return default22        else:23            return nums[index]24    def is_on_axis(position: tuple[int, int]) -> bool:25        match position:26            case (0, _) | (_, 0):27                return True28            case _:29                return False30    ```31    Good:32    ```33    def index_or_default(nums: list[Any], index: int, default: Any):34        if index >= len(nums):35            return default36        return nums[index]37    def is_on_axis(position: tuple[int, int]) -> bool:38        match position:39            case (0, _) | (_, 0):40                return True41        return False42    ```43    """44    code = 12645def get_trailing_return(node: Statement) -> Statement | None:46    match node:47        case ReturnStmt(expr=Expression()):...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!!
