Best Python code snippet using slash
content.py
Source:content.py  
...25from pyparsing import Suppress26from pyparsing import Word27from pyparsing import ZeroOrMore28from tools import verify29def sep(text):30    """Makes a separator."""31    return Suppress(Literal(text))32def key(name):33    """Makes grammar expression for a key."""34    return (35        Literal(name) ^36        (sep('\'') + Literal(name) + sep('\'')) ^37        (sep('"') + Literal(name) + sep('"')))38def list_of(term):39    """Makes a delimited list of terms."""40    return (41        Optional(42            term +43            ZeroOrMore(Suppress(Literal(',')) + term) +44            Optional(Suppress(Literal(',')))45        )46    )47def chunks(l, n):48    """Partitions the list l into disjoint sub-lists of length n."""49    if len(l) % n != 0:50        raise Exception('List length is not a multiple on %s', n)51    return [l[i:i+n] for i in range(0, len(l), n)]52def make_dict(unused_s, unused_l, toks):53    """Makes a dict from the list using even items as keys, odd as values."""54    result = {}55    key_value_pairs = chunks(toks, 2)56    for key_value_pair in key_value_pairs:57        result[key_value_pair[0]] = key_value_pair[1]58    return result59def make_list(unused_s, unused_l, toks):60    """Makes a list out of a token tuple holding a list."""61    result = []62    for item in toks:63        result.append(item.asList())64    return result65def make_bool(value):66    """Makes a boolean value lambda."""67    def make_value():68        return verify.Term(verify.BOOLEAN, value)69    return make_value70def make_int(value):71    """Makes an int value lambda."""72    return int(value[0])73def make_float(value):74    """Makes an float value lambda."""75    return float(value[0])76class AssessmentParser13(object):77    """Grammar and parser for the assessment."""78    string = (79        QuotedString('\'', escChar='\\', multiline=True) ^80        QuotedString('"', escChar='\\', multiline=True))81    boolean = (82        Literal('true').setParseAction(make_bool(True)) ^83        Literal('false').setParseAction(make_bool(False)))84    float = Combine(85        Word(nums) + Optional(Literal('.') + Word(nums))86    ).setParseAction(make_float)87    integer = Word(nums).setParseAction(make_int)88    choice_decl = (89        string ^90        Combine(91            sep('correct(') + string + sep(')')92        ).setParseAction(lambda x: verify.Term(verify.CORRECT, x[0]))93    )94    regex = (95        Regex('/(.*)/i') ^96        Combine(97            sep('regex(') +98            QuotedString('"', escChar='\\') +99            sep(')')100        ).setParseAction(lambda x: verify.Term(verify.REGEX, x[0]))101    )102    question_decl = (103        sep('{') +104        Each(105            Optional(106                key('questionHTML') + sep(':') +107                string + Optional(sep(','))) +108            Optional(109                key('lesson') + sep(':') +110                string + Optional(sep(','))) +111            Optional(112                key('correctAnswerString') + sep(':') +113                string + Optional(sep(','))) +114            Optional(115                key('correctAnswerRegex') + sep(':') +116                regex + Optional(sep(','))) +117            Optional(118                key('correctAnswerNumeric') + sep(':') +119                float + Optional(sep(','))) +120            Optional(121                key('choiceScores') + sep(':') +122                sep('[') +123                Group(list_of(float)).setParseAction(make_list) +124                sep(']') +125                Optional(sep(','))) +126            Optional(127                key('weight') + sep(':') + integer + Optional(sep(','))) +128            Optional(129                key('multiLine') + sep(':') +130                boolean + Optional(sep(','))) +131            Optional(132                key('choices') + sep(':') +133                sep('[') +134                Group(list_of(choice_decl)).setParseAction(make_list) +135                sep(']') +136                Optional(sep(',')))137        ) +138        sep('}')).setParseAction(make_dict)139    assessment_grammar = (140        sep('assessment') +141        sep('=') +142        sep('{') +143        Each(144            Optional(145                key('assessmentName') + sep(':') +146                string + Optional(sep(','))) +147            Optional(148                key('preamble') + sep(':') +149                string + Optional(sep(','))) +150            Optional(151                key('checkAnswers') + sep(':') +152                boolean + Optional(sep(','))) +153            Optional(154                key('questionsList') + sep(':') +155                sep('[') +156                Group(list_of(question_decl)).setParseAction(make_list) +157                sep(']') +158                Optional(sep(',')))159        ) +160        sep('}') +161        Optional(sep(';'))).setParseAction(make_dict)162    @classmethod163    def parse_string(cls, content):164        return cls.assessment_grammar.parseString(content)165    @classmethod166    def parse_string_in_scope(cls, content, scope, root_name):167        """Parses assessment text following grammar."""168        if 'assessment' != root_name:169            raise Exception('Unsupported schema: %s', root_name)170        # we need to extract the results as a dictionary; so we remove the171        # outer array holding it172        ast = cls.parse_string(content).asList()173        if len(ast) == 1:174            ast = ast[0]175        return dict(176            scope.items() +177            {'__builtins__': {}}.items() +178            {root_name: ast}.items())179class ActivityParser13(object):180    """Grammar and parser for the activity."""181    variable = Word(alphas)182    integer = Word(nums).setParseAction(make_int)183    string = (184        QuotedString('\'', escChar='\\', multiline=True) ^185        QuotedString('"', escChar='\\', multiline=True))186    boolean = (187        Literal('true').setParseAction(make_bool(True)) ^188        Literal('false').setParseAction(make_bool(False)))189    regex = (190        Regex('/(.*)/i') ^191        Combine(192            sep('regex(') +193            QuotedString('"', escChar='\\') +194            sep(')')195        ).setParseAction(lambda x: verify.Term(verify.REGEX, x[0]))196    )197    choice_decl = Group(198        sep('[') +199        string + sep(',') +200        boolean + sep(',') +201        string +202        sep(']')203    )204    choices_decl = Group(205        sep('[') +206        Optional(list_of(choice_decl)) +207        sep(']')208    ).setParseAction(make_list)209    multiple_choice_decl = (210        key('questionType') + sep(':') + key('multiple choice') +211        Optional(sep(','))212    )213    multiple_choice = (214        sep('{') +215        multiple_choice_decl +216        Each(217            Optional(218                key('questionHTML') + sep(':') +219                string + Optional(sep(','))) +220            Optional(221                key('choices') + sep(':') +222                choices_decl + Optional(sep(',')))223        ) +224        sep('}')225    ).setParseAction(make_dict)226    free_text_decl = (227        key('questionType') + sep(':') + key('freetext') +228        Optional(sep(','))229    )230    free_text = (231        sep('{') +232        free_text_decl +233        Each(234            Optional(235                key('questionHTML') + sep(':') +236                string + Optional(sep(','))) +237            Optional(238                key('correctAnswerRegex') + sep(':') +239                regex + Optional(sep(','))) +240            Optional(241                key('correctAnswerOutput') + sep(':') +242                string + Optional(sep(','))) +243            Optional(244                key('incorrectAnswerOutput') + sep(':') +245                string + Optional(sep(','))) +246            Optional(247                key('showAnswerPrompt') + sep(':') +248                string + Optional(sep(','))) +249            Optional(250                key('showAnswerOutput') + sep(':') +251                string + Optional(sep(','))) +252            Optional(253                key('outputHeight') + sep(':') +254                string + Optional(sep(',')))255        ) +256        sep('}')257    ).setParseAction(make_dict)258    question_list_decl = (259        sep('{') +260        Each(261            Optional(262                key('questionHTML') + sep(':') +263                string + Optional(sep(','))) +264            Optional(265                key('choices') + sep(':') +266                sep('[') +267                Group(list_of(string)).setParseAction(make_list) +268                sep(']') +269                Optional(sep(','))) +270            Optional(271                key('correctIndex') + sep(':') +272                (integer ^ (273                    sep('[') +274                    Group(list_of(integer)).setParseAction(make_list) +275                    sep(']'))) +276                Optional(sep(','))) +277            Optional(278                key('multiSelect') + sep(':') +279                boolean + Optional(sep(','))),280        ) +281        sep('}')).setParseAction(make_dict)282    questions_list_decl = Group(283        sep('[') +284        Optional(list_of(question_list_decl)) +285        sep(']')286    ).setParseAction(make_list)287    multiple_choice_group_decl = (288        key('questionType') + sep(':') + key('multiple choice group') +289        Optional(sep(','))290    )291    multiple_choice_group = (292        sep('{') +293        multiple_choice_group_decl +294        Each(295            Optional(296                key('questionGroupHTML') + sep(':') +297                string + Optional(sep(','))) +298            Optional(299                key('allCorrectMinCount') + sep(':') +300                integer + Optional(sep(','))) +301            Optional(302                key('allCorrectOutput') + sep(':') +303                string + Optional(sep(','))) +304            Optional(305                key('someIncorrectOutput') + sep(':') +306                string + Optional(sep(','))) +307            Optional(308                key('questionsList') + sep(':') +309                questions_list_decl + Optional(sep(',')))310        ) +311        sep('}')312    ).setParseAction(make_dict)313    activity_grammar = (314        sep('activity') +315        sep('=') +316        sep('[') +317        Optional(list_of(318            string ^ multiple_choice ^ free_text ^ multiple_choice_group)) +319        sep(']') +320        Optional(sep(';')))321    @classmethod322    def parse_string(cls, content):323        return cls.activity_grammar.parseString(content)324    @classmethod325    def parse_string_in_scope(cls, content, scope, root_name):326        """Parses activity text following grammar."""327        if 'activity' != root_name:328            raise Exception('Unsupported schema: %s', root_name)329        return dict(330            scope.items() +331            {'__builtins__': {}}.items() +332            {root_name: cls.parse_string(content).asList()}.items())333# here we register all the parser334SUPPORTED_PARSERS = {...test_print.py
Source:test_print.py  
1"""Test correct operation of the print function.2"""3# In 2.6, this gives us the behavior we want.  In 3.0, it has4#  no function, but it still must parse correctly.5from __future__ import print_function6import unittest7from test import test_support8from StringIO import StringIO9NotDefined = object()10# A dispatch table all 8 combinations of providing11#  sep, end, and file12# I use this machinery so that I'm not just passing default13#  values to print, I'm either passing or not passing in the14#  arguments15dispatch = {16    (False, False, False):17     lambda args, sep, end, file: print(*args),18    (False, False, True):19     lambda args, sep, end, file: print(file=file, *args),20    (False, True,  False):21     lambda args, sep, end, file: print(end=end, *args),22    (False, True,  True):23     lambda args, sep, end, file: print(end=end, file=file, *args),24    (True,  False, False):25     lambda args, sep, end, file: print(sep=sep, *args),26    (True,  False, True):27     lambda args, sep, end, file: print(sep=sep, file=file, *args),28    (True,  True,  False):29     lambda args, sep, end, file: print(sep=sep, end=end, *args),30    (True,  True,  True):31     lambda args, sep, end, file: print(sep=sep, end=end, file=file, *args),32    }33# Class used to test __str__ and print34class ClassWith__str__:35    def __init__(self, x):36        self.x = x37    def __str__(self):38        return self.x39class TestPrint(unittest.TestCase):40    def check(self, expected, args,41            sep=NotDefined, end=NotDefined, file=NotDefined):42        # Capture sys.stdout in a StringIO.  Call print with args,43        #  and with sep, end, and file, if they're defined.  Result44        #  must match expected.45        # Look up the actual function to call, based on if sep, end, and file46        #  are defined47        fn = dispatch[(sep is not NotDefined,48                       end is not NotDefined,49                       file is not NotDefined)]50        with test_support.captured_stdout() as t:51            fn(args, sep, end, file)52        self.assertEqual(t.getvalue(), expected)53    def test_print(self):54        def x(expected, args, sep=NotDefined, end=NotDefined):55            # Run the test 2 ways: not using file, and using56            #  file directed to a StringIO57            self.check(expected, args, sep=sep, end=end)58            # When writing to a file, stdout is expected to be empty59            o = StringIO()60            self.check('', args, sep=sep, end=end, file=o)61            # And o will contain the expected output62            self.assertEqual(o.getvalue(), expected)63        x('\n', ())64        x('a\n', ('a',))65        x('None\n', (None,))66        x('1 2\n', (1, 2))67        x('1   2\n', (1, ' ', 2))68        x('1*2\n', (1, 2), sep='*')69        x('1 s', (1, 's'), end='')70        x('a\nb\n', ('a', 'b'), sep='\n')71        x('1.01', (1.0, 1), sep='', end='')72        x('1*a*1.3+', (1, 'a', 1.3), sep='*', end='+')73        x('a\n\nb\n', ('a\n', 'b'), sep='\n')74        x('\0+ +\0\n', ('\0', ' ', '\0'), sep='+')75        x('a\n b\n', ('a\n', 'b'))76        x('a\n b\n', ('a\n', 'b'), sep=None)77        x('a\n b\n', ('a\n', 'b'), end=None)78        x('a\n b\n', ('a\n', 'b'), sep=None, end=None)79        x('*\n', (ClassWith__str__('*'),))80        x('abc 1\n', (ClassWith__str__('abc'), 1))81        # 2.x unicode tests82        x(u'1 2\n', ('1', u'2'))83        x(u'u\1234\n', (u'u\1234',))84        x(u'  abc 1\n', (' ', ClassWith__str__(u'abc'), 1))85        # errors86        self.assertRaises(TypeError, print, '', sep=3)87        self.assertRaises(TypeError, print, '', end=3)88        self.assertRaises(AttributeError, print, '', file='')89    def test_mixed_args(self):90        # If an unicode arg is passed, sep and end should be unicode, too.91        class Recorder(object):92            def __init__(self, must_be_unicode):93                self.buf = []94                self.force_unicode = must_be_unicode95            def write(self, what):96                if self.force_unicode and not isinstance(what, unicode):97                    raise AssertionError("{0!r} is not unicode".format(what))98                self.buf.append(what)99        buf = Recorder(True)100        print(u'hi', file=buf)101        self.assertEqual(u''.join(buf.buf), 'hi\n')102        del buf.buf[:]103        print(u'hi', u'nothing', file=buf)104        self.assertEqual(u''.join(buf.buf), 'hi nothing\n')105        buf = Recorder(False)106        print('hi', 'bye', end=u'\n', file=buf)107        self.assertIsInstance(buf.buf[1], unicode)108        self.assertIsInstance(buf.buf[3], unicode)109        del buf.buf[:]110        print(sep=u'x', file=buf)111        self.assertIsInstance(buf.buf[-1], unicode)112def test_main():113    test_support.run_unittest(TestPrint)114if __name__ == "__main__":...pprint.py
Source:pprint.py  
1'''2This is a recursive attempt I had at pretty printing.3How many approaches?4'''5# Approach 16def pprint(sequence,sep='\t',start=''):7    def pprintlist(sequence, start=start,sep=sep):8        if isinstance(sequence[0], list):9            string = f'{start}[\n' + pprinter(sequence[0],start=f'{start}{sep}',sep=sep)10        else:11            string = f'{start}[\n{start}{sep}' + str(sequence[0])12        for element in sequence[1:]:13            if isinstance(element, list):14                string += f',\n' + pprinter(element,start=f'{start}{sep}',sep=sep)15            else:16                string += f',\n{start}{sep}' + str(element)17        return string + f'\n{start}]'18    print(pprintlist(sequence))19def pprinter(sequence, start='',sep='\t'):20    if isinstance(sequence[0], list):21        string = f'{start}[\n' + pprinter(sequence[0],start=f'{start}{sep}',sep=sep)22    else:23        string = f'{start}[\n{start}{sep}' + str(sequence[0])24    for element in sequence[1:]:25        if isinstance(element, list):26            string += f',\n' + pprinter(element,start=f'{start}{sep}',sep=sep)27        else:28            string += f',\n{start}{sep}' + str(element)29    return string + f'\n{start}]'30# Approach 231pprint(32    [33        [0,1,2,3,4],34        [0,1,2,3,4],35        [0,1,2,3,4],36        [0,1,2,3,4]37    ]38)39# Testing40def main():41    # x = [1,2,3,4,5]42    # print(pprinter(x,sep='-'))43    # y = [[1,2,3],[4,5,6],[6,7,8]]44    # print(pprinter(y,sep='-'))45    z = [[[1,2,3],[4,5,6],[7,8,9]],[['a','b','c'],['d','e','f'],['g','h','i']]]46    print(pprinter(z))47    # for i in x:48    #     pprint(i)49if __name__ == '__main__':...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!!
