Best Python code snippet using slash
results_parser_test.py
Source:results_parser_test.py  
...97                    "cpes": ["cpe:/a:openbsd:openssh:6.6.1p1", "cpe:/o:linux:linux_kernel"]98                }99            ),100            # Expect to see the pop and push of the new context for port 80 and pusblish101            call.pop_context(),102            call.push_context({103                "port_str": "80",104                "port_id": "80",105                "protocol": "tcp",106            }),107            call.post_results(108                "ports",109                {110                    "status": "open",111                    "status_reason": "syn-ack",112                    "service": "http",113                    "product": "Apache httpd",114                    "version": "2.4.7",115                    "extra_info": "(Ubuntu)",116                    "os_type": None,117                    "cpes": ["cpe:/a:apache:http_server:2.4.7"],118                    "http-server-header": [119                        "Apache/2.4.7 (Ubuntu)"120                    ]121                }122            ),123            # Now the context that is pushed after popping and is expected to be used in the non temporal key124            # is the os name, since we are expecting to report os level info125            call.pop_context(),126            call.push_context({127                "os_name": "Linux 4.4"128            }),129            call.post_results(130                "os",131                {132                    "os_accuracy": 97,133                    "os_classes": [134                        {135                            "os_class_type": "general purpose",136                            "os_class_vendor": "Linux",137                            "os_class_os_family": "Linux",138                            "os_class_os_gen": "4.X",139                            "os_class_accuracy": "97",140                            "os_cpes": [141                                "cpe:/o:linux:linux_kernel:4.4"142                            ]143                        }144                    ]145                }146            ),147            # Since this accuracy of 97% is the highest seen, we expect the summaries to update148            call.add_summary("most_likely_os", "Linux 4.4"),149            call.add_summary("most_likely_os_accuracy", 97),150            # We expect two os docs in the collection151            call.pop_context(),152            call.push_context({153                "os_name": "Linux 3.11 - 4.1"154            }),155            # then the summaries156            call.post_results(157                "os",158                {159                    "os_accuracy": 93,160                    "os_classes": [161                        {162                            "os_class_type": "general purpose",163                            "os_class_vendor": "Linux",164                            "os_class_os_family": "Linux",165                            "os_class_os_gen": "3.X",166                            "os_class_accuracy": "93",167                            "os_cpes": [168                                "cpe:/o:linux:linux_kernel:3"169                            ]170                        },171                        {172                            "os_class_type": "general purpose",173                            "os_class_vendor": "Linux",174                            "os_class_os_family": "Linux",175                            "os_class_os_gen": "4.X",176                            "os_class_accuracy": "93",177                            "os_cpes": [178                                "cpe:/o:linux:linux_kernel:4"179                            ]180                        }181                    ]182                }183            ),184            # And now finally we expect the big global doc to be published, including summaries185            call.pop_context(),186            call.post_results(187                "data",188                {189                    "host_names": [190                        {191                            "host_name": "scanme.nmap.org",192                            "host_name_type": "user"193                        },194                        {195                            "host_name": "scanme.nmap.org",196                            "host_name_type": "PTR"197                        }198                    ],199                    "ports": [200                        {201                            "port_str": "22",202                            "port_id": "22",203                            "protocol": "tcp",204                            "status": "open",205                            "status_reason": "syn-ack",206                            "service": "ssh",207                            "product": "OpenSSH",208                            "version": "6.6.1p1 Ubuntu 2ubuntu2.11",209                            "extra_info": "Ubuntu Linux; protocol 2.0",210                            "os_type": "Linux",211                            "cpes": ["cpe:/a:openbsd:openssh:6.6.1p1", "cpe:/o:linux:linux_kernel"]212                        },213                        {214                            "port_str": "80",215                            "port_id": "80",216                            "protocol": "tcp",217                            "status": "open",218                            "status_reason": "syn-ack",219                            "service": "http",220                            "product": "Apache httpd",221                            "version": "2.4.7",222                            "extra_info": "(Ubuntu)",223                            "os_type": None,224                            "cpes": ["cpe:/a:apache:http_server:2.4.7"],225                            "http-server-header": [226                                "Apache/2.4.7 (Ubuntu)"227                            ]228                        },229                    ],230                    "os_info": [231                        {232                            "os_name": "Linux 4.4",233                            "os_accuracy": 97,234                            "os_classes": [235                                {236                                    "os_class_type": "general purpose",237                                    "os_class_vendor": "Linux",238                                    "os_class_os_family": "Linux",239                                    "os_class_os_gen": "4.X",240                                    "os_class_accuracy": "97",241                                    "os_cpes": [242                                        "cpe:/o:linux:linux_kernel:4.4"243                                    ]244                                }245                            ]246                        },247                        {248                            "os_name": "Linux 3.11 - 4.1",249                            "os_accuracy": 93,250                            "os_classes": [251                                {252                                    "os_class_type": "general purpose",253                                    "os_class_vendor": "Linux",254                                    "os_class_os_family": "Linux",255                                    "os_class_os_gen": "3.X",256                                    "os_class_accuracy": "93",257                                    "os_cpes": [258                                        "cpe:/o:linux:linux_kernel:3"259                                    ]260                                },261                                {262                                    "os_class_type": "general purpose",263                                    "os_class_vendor": "Linux",264                                    "os_class_os_family": "Linux",265                                    "os_class_os_gen": "4.X",266                                    "os_class_accuracy": "93",267                                    "os_cpes": [268                                        "cpe:/o:linux:linux_kernel:4"269                                    ]270                                }271                            ]272                        }273                    ],274                    "host_scan_start_time": "2019-04-17T12:55:57Z",275                    "host_scan_end_time": "2019-04-17T12:56:27Z",276                    "status": "up",277                    "status_reason": "echo-reply",278                    "uptime": "686432",279                    "last_boot": "Tue Apr  9 14:15:55 2019"280                },281                include_summaries=True282            ),283            # expect the publish method to be called at the finish284            call.publish_results()285        ]286    @resetting_mocks(results_context_constructor)287    @pytest.mark.unit288    def test_parses_tls_info():289        results_parser, mock_mgr, mock_results_context = execute_test_using_results_archive(290            "tls-info-nmap.xml.tar.gz"291        )292        # filter all the calls to those that allow us to inspect the behaviour293        posted_cipher_doc = filter_tested_interactions(294            ["ssl_ciphers", "ssl_protos"],295            ["push_context", "pop_context", "add_summaries"],296            mock_mgr297        )298        expected = [299            call.push_context({300                "port_str": "443",301                "port_id": "443",302                "protocol": "tcp",303            }),304            # first publish all the info in one doc305            call.push_context({"ssl_protocol": "TLSv1.2"}),306            call.post_results("ssl_protos", {307                "ciphers": [308                    {309                        "kex_info": "ecdh_x25519",310                        "strength": "A",311                        "name": "TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256"312                    },313                    {314                        "kex_info": "ecdh_x25519",315                        "strength": "A",316                        "name": "TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384"317                    },318                ],319                "cipher_preference": "server"320            }),321            # Then an entry for each cipher is created322            call.push_context({"name": "TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256"}),323            call.post_results("ssl_ciphers", {"kex_info": "ecdh_x25519", "strength": "A"}),324            call.pop_context(),325            call.push_context({"name": "TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384"}),326            call.post_results("ssl_ciphers", {"kex_info": "ecdh_x25519", "strength": "A"}),327            call.pop_context(),328            call.pop_context(),329            call.add_summaries({"lowest_ssl_proto": "TLSv1.2", "lowest_ssl_strength": "A"}),330            call.pop_context(),331        ]332        assert posted_cipher_doc == expected333    @resetting_mocks(results_context_constructor)334    @pytest.mark.unit335    def test_parses_cve_info():336        results_parser, mock_mgr, mock_results_context = execute_test_using_results_archive(337            "cve-info-nmap.xml.tar.gz"338        )339        # filter all the calls to those that allow us to inspect the behaviour340        posted_cipher_doc = filter_tested_interactions(341            ["cves"],342            ["push_context", "pop_context"],343            mock_mgr344        )345        assert posted_cipher_doc == [346            call.push_context({347                "port_str": "80",348                "port_id": "80",349                "protocol": "tcp",350            }),351            call.push_context({"cve_code": "CVE-2017-7679"}),352            call.post_results("cves", {"cve_severity": 7.5}),353            call.pop_context(),354            call.push_context({"cve_code": "CVE-2018-1312"}),355            call.post_results("cves", {"cve_severity": 6.8}),356            call.pop_context(),357            call.pop_context(),358        ]359    @resetting_mocks(results_context_constructor)360    @pytest.mark.unit361    def test_parses_multiple_os_cpes_regression_sa_44():362        results_parser, mock_mgr, mock_results_context = execute_test_using_results_archive(363            "multiple-os-cpes-regression-sa-44-nmap.xml.tar.gz"364        )365        # filter all the calls to those that allow us to inspect the behaviour366        posted_cipher_doc = filter_tested_interactions(367            ["os"],368            ["push_context", "pop_context"],369            mock_mgr370        )371        assert posted_cipher_doc == [372            call.push_context({"os_name": "D-Link DWL-624+ or DWL-2000AP, or TRENDnet TEW-432BRP WAP"}),373            call.post_results("os", {374                "os_accuracy": 90,375                "os_classes": [376                    {377                        "os_class_type": "WAP",378                        "os_class_vendor": "D-Link",379                        "os_class_os_family": "embedded",380                        "os_class_os_gen": None,381                        "os_class_accuracy": "90",382                        "os_cpes": ["cpe:/h:dlink:dwl-624%2b", "cpe:/h:dlink:dwl-2000ap"]383                    },384                    {385                        "os_class_type": "WAP",386                        "os_class_vendor": "TRENDnet",387                        "os_class_os_family": "embedded",388                        "os_class_os_gen": None,389                        "os_class_accuracy": "90",390                        "os_cpes": ["cpe:/h:trendnet:tew-432brp"]391                    }392                ]393            }),394            call.pop_context(),395        ]396    @resetting_mocks(results_context_constructor)397    @pytest.mark.unit398    def test_parses_multiple_os_cpes_regression_sa_44():399        results_parser, mock_mgr, mock_results_context = execute_test_using_results_archive(400            "no-timestamps-when-host-down-regression-sa-43-nmap.xml.tar.gz"401        )402        # filter all the calls to those that allow us to inspect the behaviour403        posted_cipher_doc = filter_tested_interactions(404            ["os"],405            ["push_context", "pop_context"],406            mock_mgr407        )408        mock_results_context.publish_results.assert_called_once()409    @resetting_mocks(results_context_constructor)410    @pytest.mark.unit411    def test_parses_os_but_no_osmatch_regression_sa_45():412        results_parser, mock_mgr, mock_results_context = execute_test_using_results_archive(413            "os-but-no-osmatch-regression-sa-45-nmap.xml.tar.gz"414        )415        mock_results_context.publish_results.assert_called_once()416    @resetting_mocks(results_context_constructor)417    @pytest.mark.unit418    def test_parses_http_server_parse_regression_sa_46():419        results_parser, mock_mgr, mock_results_context = execute_test_using_results_archive(420            "http-server-parse-regression-sa-46-nmap.xml.tar.gz"421        )422        # filter all the calls to those that allow us to inspect the behaviour423        posted_cipher_doc = filter_tested_interactions(424            ["ports"],425            ["push_context", "pop_context"],426            mock_mgr427        )428        assert posted_cipher_doc == [429            call.push_context({430                "port_str": "80",431                "port_id": "80",432                "protocol": "tcp",433            }),434            call.post_results("ports", {435                "status": "open",436                "status_reason": "syn-ack",437                "service": "http",438                "product": "Amazon CloudFront httpd",439                "version": None,440                "extra_info": None,441                "os_type": None,442                "http-server-header": ["AmazonS3", "CloudFront"]443            }),444            call.pop_context()445        ]446    @resetting_mocks(results_context_constructor)447    @pytest.mark.unit448    @serialise_mocks()449    @patch("datetime.datetime")450    def test_parses_ssl_certs(datetime):451        datetime.strptime.return_value = datetime_real(2019, 6, 29, 11, 0, 0)452        datetime.now.return_value = datetime_real(2019, 7, 12, 12, 0, 0)453        results_parser, mock_mgr, mock_results_context = execute_test_using_results_archive(454            "test_ssl_cert.xml.tar.gz"455        )456        # filter all the calls to those that allow us to inspect the behaviour457        posted_cipher_doc = filter_tested_interactions(458            ["ssl_cert"],459            ["push_context", "pop_context"],460            mock_mgr461        )462        assert posted_cipher_doc == [463            call.push_context({464                "port_str": "443",465                "port_id": "443",466                "protocol": "tcp",467            }),468            call.post_results("ssl_cert", {469                "extensions": [{"name": "X509v3 Subject Alternative Name", "value": "DNS:scottlogic.com"}],470                "issuer": {471                    "commonName": "Let's Encrypt Authority X3",472                    "countryName": "US",473                    "organizationName": "Let's Encrypt"474                },475                "subject": {"commonName": "scottlogic.com"},476                "validity": {"notAfter": "2019-06-29T06:52:46", "notBefore": "2019-03-31T06:52:46"},477                "expiry_diff_at_scan": -14478            }),479            call.pop_context()480        ]481    @resetting_mocks(results_context_constructor)482    @pytest.mark.unit483    def test_regression_table_format_for_vulns():484        results_parser, mock_mgr, mock_results_context = execute_test_using_results_archive(485            "regression-SA-174-table-format-for-vulns.xml.tar.gz"486        )487        # filter all the calls to those that allow us to inspect the behaviour488        posted_cipher_doc = filter_tested_interactions(489            ["cve_code", "cves"],490            ["push_context", "pop_context"],491            mock_mgr492        )493        assert posted_cipher_doc == [494            call.push_context({495                "port_str": "80",496                "port_id": "80",497                "protocol": "tcp",498            }),499            call.push_context({"cve_code": "CVE-2017-7679"}),500            call.post_results("cves", {"cve_severity": 7.5, "is_exploit": "false", "type": "cve"}),501            call.pop_context(),502            call.push_context({"cve_code": "CVE-2018-1312"}),503            call.post_results("cves", {"cve_severity": 6.8, "is_exploit": "false", "type": "cve"}),504            call.pop_context(),505            call.pop_context(),506        ]507    @serialise_mocks()508    def execute_test_using_results_archive(filename):509        with patch("aioboto3.client"), \510                patch.dict(os.environ, TEST_ENV):511            results_parser = NmapResultsParser()512            results_context_constructor.return_value = mock_results_context = MagicMock()513            mock_mgr = Mock()514            mock_mgr.attach_mock(results_context_constructor, "ResultsContext")515            mock_mgr.attach_mock(mock_results_context.push_context, "push_context")516            mock_mgr.attach_mock(mock_results_context.pop_context, "pop_context")517            mock_mgr.attach_mock(mock_results_context.post_results, "post_results")518            mock_mgr.attach_mock(mock_results_context.publish_results, "publish_results")519            mock_mgr.attach_mock(mock_results_context.add_summaries, "add_summaries")...chess.py
Source:chess.py  
...82	v = VarStack(v, new_context)    # push onto the stack83def function_context(new_context):84	global v85	v = FnStack(v, new_context)86def pop_context():87	global v88	v = v.parent89def pop_function():90	global v91	while isinstance(v, VarStack):92		v = v.parent93	v = v.parent94###############################################################################95def html_output(p_board, p_whose, p_error):96	print "Here's the board: %s\nIt's %s's turn,\nerror is %s" % (p_board, p_whose, p_error)97def html_upgrade(p_board):98	print "Upgrade time: %s" % (p_board, )99def html_hexit():100	print "Hexit"101def schema_row():102	return {103		"a":0,104		"b":0,105		"c":0,106		"d":0,107		"e":0,108		"f":0,109		"g":0,110		"h":0,111	}112def fn_getRow(**kwargs):113	function_context(kwargs)114	push_context({115		"lookup": schema_row(),116	})117	if v["rank"] == 1:118		v["lookup"] = v["row1"]119	if v["rank"] == 2:120		v["lookup"] = v["row2"]121	if v["rank"] == 3:122		v["lookup"] = v["row3"]123	if v["rank"] == 4:124		v["lookup"] = v["row4"]125	if v["rank"] == 5:126		v["lookup"] = v["row5"]127	if v["rank"] == 6:128		v["lookup"] = v["row6"]129	if v["rank"] == 7:130		v["lookup"] = v["row7"]131	if v["rank"] == 8:132		v["lookup"] = v["row8"]133	toR = v["lookup"]134	pop_context()135	pop_context()136	return toR137def fn_setPiece(**kwargs):138	function_context(kwargs)139	push_context({140	})141	if v["rank"] == 1:142		if v["file"] == 1:143			v["row1"]["a"] = v["piece"]144		elif v["file"] == 2:145			v["row1"]["b"] = v["piece"]146		elif v["file"] == 3:147			v["row1"]["c"] = v["piece"]148		elif v["file"] == 4:149			v["row1"]["d"] = v["piece"]150		elif v["file"] == 5:151			v["row1"]["e"] = v["piece"]152		elif v["file"] == 6:153			v["row1"]["f"] = v["piece"]154		elif v["file"] == 7:155			v["row1"]["g"] = v["piece"]156		elif v["file"] == 8:157			v["row1"]["h"] = v["piece"]158	elif v["rank"] == 2:159		if v["file"] == 1:160			v["row2"]["a"] = v["piece"]161		elif v["file"] == 2:162			v["row2"]["b"] = v["piece"]163		elif v["file"] == 3:164			v["row2"]["c"] = v["piece"]165		elif v["file"] == 4:166			v["row2"]["d"] = v["piece"]167		elif v["file"] == 5:168			v["row2"]["e"] = v["piece"]169		elif v["file"] == 6:170			v["row2"]["f"] = v["piece"]171		elif v["file"] == 7:172			v["row2"]["g"] = v["piece"]173		elif v["file"] == 8:174			v["row2"]["h"] = v["piece"]175	elif v["rank"] == 3:176		if v["file"] == 1:177			v["row3"]["a"] = v["piece"]178		elif v["file"] == 2:179			v["row3"]["b"] = v["piece"]180		elif v["file"] == 3:181			v["row3"]["c"] = v["piece"]182		elif v["file"] == 4:183			v["row3"]["d"] = v["piece"]184		elif v["file"] == 5:185			v["row3"]["e"] = v["piece"]186		elif v["file"] == 6:187			v["row3"]["f"] = v["piece"]188		elif v["file"] == 7:189			v["row3"]["g"] = v["piece"]190		elif v["file"] == 8:191			v["row3"]["h"] = v["piece"]192	elif v["rank"] == 4:193		if v["file"] == 1:194			v["row4"]["a"] = v["piece"]195		elif v["file"] == 2:196			v["row4"]["b"] = v["piece"]197		elif v["file"] == 3:198			v["row4"]["c"] = v["piece"]199		elif v["file"] == 4:200			v["row4"]["d"] = v["piece"]201		elif v["file"] == 5:202			v["row4"]["e"] = v["piece"]203		elif v["file"] == 6:204			v["row4"]["f"] = v["piece"]205		elif v["file"] == 7:206			v["row4"]["g"] = v["piece"]207		elif v["file"] == 8:208			v["row4"]["h"] = v["piece"]209	elif v["rank"] == 5:210		if v["file"] == 1:211			v["row5"]["a"] = v["piece"]212		elif v["file"] == 2:213			v["row5"]["b"] = v["piece"]214		elif v["file"] == 3:215			v["row5"]["c"] = v["piece"]216		elif v["file"] == 4:217			v["row5"]["d"] = v["piece"]218		elif v["file"] == 5:219			v["row5"]["e"] = v["piece"]220		elif v["file"] == 6:221			v["row5"]["f"] = v["piece"]222		elif v["file"] == 7:223			v["row5"]["g"] = v["piece"]224		elif v["file"] == 8:225			v["row5"]["h"] = v["piece"]226	elif v["rank"] == 6:227		if v["file"] == 1:228			v["row6"]["a"] = v["piece"]229		elif v["file"] == 2:230			v["row6"]["b"] = v["piece"]231		elif v["file"] == 3:232			v["row6"]["c"] = v["piece"]233		elif v["file"] == 4:234			v["row6"]["d"] = v["piece"]235		elif v["file"] == 5:236			v["row6"]["e"] = v["piece"]237		elif v["file"] == 6:238			v["row6"]["f"] = v["piece"]239		elif v["file"] == 7:240			v["row6"]["g"] = v["piece"]241		elif v["file"] == 8:242			v["row6"]["h"] = v["piece"]243	elif v["rank"] == 7:244		if v["file"] == 1:245			v["row7"]["a"] = v["piece"]246		elif v["file"] == 2:247			v["row7"]["b"] = v["piece"]248		elif v["file"] == 3:249			v["row7"]["c"] = v["piece"]250		elif v["file"] == 4:251			v["row7"]["d"] = v["piece"]252		elif v["file"] == 5:253			v["row7"]["e"] = v["piece"]254		elif v["file"] == 6:255			v["row7"]["f"] = v["piece"]256		elif v["file"] == 7:257			v["row7"]["g"] = v["piece"]258		elif v["file"] == 8:259			v["row7"]["h"] = v["piece"]260	elif v["rank"] == 8:261		if v["file"] == 1:262			v["row8"]["a"] = v["piece"]263		elif v["file"] == 2:264			v["row8"]["b"] = v["piece"]265		elif v["file"] == 3:266			v["row8"]["c"] = v["piece"]267		elif v["file"] == 4:268			v["row8"]["d"] = v["piece"]269		elif v["file"] == 5:270			v["row8"]["e"] = v["piece"]271		elif v["file"] == 6:272			v["row8"]["f"] = v["piece"]273		elif v["file"] == 7:274			v["row8"]["g"] = v["piece"]275		elif v["file"] == 8:276			v["row8"]["h"] = v["piece"]277	pop_context()278	pop_context()279def fn_movePiece(**kwargs):280	function_context(kwargs)281	push_context({282		"piece":0,283		"target_piece":0284		"real_piece":0285		"dx":0,286		"dy":0,287		"lookup":schema_row(),288		"adx":0,289		"ady":0,290		"startx":0,291		"starty":0,292	})293	v["dx"] = v["to_file"] - v["from_file"]294	v["dy"] = v["to_rank"] - v["from_rank"]295	v["lookup"] = fn_getRow(v["from_rank"])296	v["piece"] = fn_getPiece(v["lookup"], v["from_file"])297	v["real_piece"] = v["piece"]298	if v["piece"] == 0:299		toR = "There is no piece at this location."300		pop_context()301		pop_context()302		return toR303	if (v["piece"] <= 6) == turn:304		toR = "You may only move your own pieces."305		pop_context()306		pop_context()307		return toR308	if v["to_rank"] != v["from_rank"]:309		v["lookup"] = fn_getRow(v["to_rank"])310	v["target_piece"] = fn_getPiece(v["lookup"], v["to_file"])311	if v["target_piece"] != 0 and (v["target_piece"] <= 6) != v["turn"]:312		toR = "You may not capture your own piece!"313		pop_context()314		pop_context()315		return toR316	if v["piece"] > 6:317		v["piece"] = v["piece"] - 6318	if v["dx"] < 0:319		v["adx"] = -v["dx"]320		v["startx"] = v["to_file"] + 1321	else:322		v["adx"] = v["dx"]323		v["startx"] = v["from_file"] + 1324	if v["dy"] < 0:325		v["ady"] = -v["dy"]326		v["starty"] = v["to_rank"] + 1327	else:328		v["ady"] = v["dy"]329		v["starty"] = v["from_rank"] + 1330	if v["piece"] == 1 or (v["piece"] == 4 and v["dx"] * v["dy"] == 0):331		push_context({332			"i":0333		})334		if (v["dx"] != 0) and (v["dy"] != 0):335			toR = "Invalid Move: Rooks move along ranks or files."336			pop_context()337			pop_context()338			return toR339		if v["dx"] != 0:340			v["i"] = v["startx"]341			v["adx"] = v["adx"] + v["i"] - 1342			while v["i"] < v["adx"]:343				if fn_getPiece(v["lookup"], v["i"]) != 0:344					toR = "Invalid Move: You may not pass other pieces."345					pop_context()346					pop_context()347					return toR348				v["i"] = v["i"] + 1349		else:350			v["i"] = v["starty"]351			v["ady"] = v["ady"] + v["i"] - 1352			while v["i"] < v["ady"]:353				if fn_getPiece(fn_getRow(v["i"]), v["to_file"]) != 0:354					return "Invalid Move: You may not pass other pieces."355				v["i"] = v["i"] + 1356	# TODO: write dis357def fn_getBoard(**kwargs):358	function_context(kwargs)359	push_context({360		"s":"",361		"i":0,362		"j":0,363		"piece":0,364		"lookup":schema_row(),365	})366	v["s"] = "<table id='game' border=0 cellspacing=0 cellpadding=0>"367	if v["pickable"]:368		v["s"] = v["s"] + "<tr><td class=from>from</td>"369		v["i"] = 1370		while v["i"] <= 8:371			v["s"] = v["s"] + "<td class=from><input onClick='set_from(" + v["i"] + ", 0);' type='radio' name='file_from' value='" + v["i"] + "'></td>"372			v["i"] = v["i"] + 1373		v["s"] = v["s"] + "<td> </td></tr>"374	v["i"] = 1375	while v["i"] <= 8:376		v["lookup"] = fn_getRow(v["i"])377		v["j"] = 1378		v["s"] = v["s"] + "<tr align=center><td class=from><input onClick='set_from(0, " + v["i"] + ");'  type='radio' name='rank_from' value='" + v["i"] + "'></td>"379		while v["j"] <= 8:380			v["piece"] = fn_getPiece(v["lookup"], v["j"])381			v["s"] = v["s"] + "<td id='r" + v["i"] + "f" + v["j"] + "'>"382			if v["piece"] != 0:383				v["s"] = v["s"] + "<img src=chess_ts/p" + v["piece"] + ".png>"384			v["s"] = v["s"] + "</td>"385			v["j"] = v["j"] + 1386		}387		if(v["pickable"])388			v["s"] = v["s"] + "<td class=to><input onClick='set_to(0, " + v["i"] + ");' type='radio' name='rank_to' value='" + v["i"] + "'></td>"389		v["s"] = v["s"] + "</tr>"390		v["i"] = v["i"] + 1391	if v["pickable"]:392		v["i"] = 1393		v["s"] = v["s"] + "<tr><td> </td>"394		while v["i"] <= 8:395			v["s"] = v["s"] + "<td class=to><input onClick='set_to(" + v["i"] + ", 0);' type='radio' name='file_to' value='" + v["i"] + "'></td>"396			v["i"] = v["i"] + 1397		v["s"] = v["s"] + "<td class=to>to</td></tr>"398	toR = v["s"] + "</table>"399	pop_context()400	pop_context()401	return toR402def session_Game():403	global admit_one404	global counter405	global v406	if counter < 1:407		push_context({"board": "", "turn_words": "", "error": "", "upgr": 0, "from_rank": 0, "from_file": 0, "to_rank": 0, "to_file": 0})408		v["error"] = ""409		v["turn"] = True410		v["row1"] = {"a":1, "b":2, "c":3, "d":4, "e":5, "f":3, "g":2, "h":1}411		v["row2"] = {"a":6, "b":6, "c":6, "d":6, "e":6, "f":6, "g":6, "h":6}412		v["row3"] = {"a":0, "b":0, "c":0, "d":0, "e":0, "f":0, "g":0, "h":0}413		v["row4"] = {"a":0, "b":0, "c":0, "d":0, "e":0, "f":0, "g":0, "h":0}414		v["row5"] = {"a":0, "b":0, "c":0, "d":0, "e":0, "f":0, "g":0, "h":0}...markdown.py
Source:markdown.py  
...46                                bg_color = BG_COLOR_MARKDOWN)47        else:48            # markdown background color should span to right edge49            self.buf = self.buf.replace('\n', '\033[K\n')50            self.pop_context()51    def lit(self, s):52        self.buf += s53    def text(self, node, entering=None):54        self.lit(node.literal)55    def stack_context(self, **kwargs):56        curr_state = self.contexts[-1]57        new_state = curr_state.alter(**kwargs)58        self.lit(get_transition_esc_sequence(curr_state, new_state))59        self.contexts.append(new_state)60    def pop_context(self):61        curr_state = self.contexts[-1]62        new_state = self.contexts[-2]63        self.lit(get_transition_esc_sequence(curr_state, new_state))64        self.contexts = self.contexts[:-1]65    def cr(self):66        self.lit('\n')67    def softbreak(self, node=None, entering=None):68        self.cr()69    def linebreak(self, node=None, entering=None):70        self.cr()71    def html_inline(self, node, entering):72        self.lit(node.literal)73    def link(self, node, entering):74        if entering:75            pass76        else:77            if node.destination.endswith('.md'):78                # this is a link for the web browser, ignore here79                return80            self.lit(' (')81            self.stack_context(fg_color = FG_COLOR_URL)82            self.lit(node.destination)83            self.pop_context()84            self.lit(')')85    def paragraph(self, node, entering):86        if entering:87            node.saved_buf = self.buf88            self.buf = ''89        else:90            if detect_table(self.buf):91                table_buf = self.buf92                self.buf = node.saved_buf93                render_table(self, table_buf)94            else:95                self.buf = node.saved_buf + self.wrap_escaped(self.buf)96            self.cr()97            self.cr()98    def block_quote(self, node, entering):99        if entering:100            node.saved_buf = self.buf101            self.target_width -= 2102            self.buf = ''103        else:104            self.buf = node.saved_buf + self.quoted(self.buf)105            self.target_width += 2106            self.cr()107    def justify(self, words, num_spaces):108        num_intervals = len(words) - 1109        if num_intervals == 0:110            # only one word, cannot justify111            return words[0]112        # Fill intervals evenly with appropriate number of spaces113        added_spaces = [ ' ' * (num_spaces//num_intervals)  ] * num_intervals114        num_spaces -= (num_spaces//num_intervals) * num_intervals115        # Because of the integer division, a few remaining spaces should be added116        # (less than the number of intervals).117        # Preferably add one more space after ponctuation marks.118        for signs in ('.!?', ':;', ','):119            for i, word in enumerate(words[:-1]):120                if num_spaces == 0:121                    break122                if word[-1] in signs:123                    added_spaces[i] += ' '124                    num_spaces -= 1125        # For better understanding of what we will do with any space still remaining,126        # let's take an example:127        # if we have 15 intervals and 4 remaining spaces, distribute evenly128        # these 4 spaces at intervals 1*15/5=3, 2*15/5=6, 3*15/5=9 and 4*15/5=12.129        for i in range(1, num_spaces+1):130            added_spaces[i*num_intervals//(num_spaces+1)] += ' '131        # add a fake ending 'interval' for the zip() function below132        added_spaces += [ '' ]133        return ''.join((word + spacing) for word, spacing in zip(words, added_spaces))134    def real_text_len(self, text):135        return len(''.join(RE_ESC_COLOR.split(text)))136    def wrap_escaped(self, text):137        # textwrap.fill does not work well because of the escape sequences138        wrapped_lines = []139        curr_words = []140        curr_words_no_color = []141        for line in text.split('\n'):142            for word in line.split(' '):143                word_no_color = ''.join(RE_ESC_COLOR.split(word))144                min_line_no_color = ' '.join(curr_words_no_color + [ word_no_color ])145                min_len = len(min_line_no_color)146                if 1 + min_len > self.target_width:147                    # cannot include the new word, format previous ones into a line148                    len_no_space = len(''.join(curr_words_no_color))149                    num_spaces = self.target_width - 1 - len_no_space150                    curr_line = self.justify(curr_words, num_spaces)151                    wrapped_lines.append(' ' + curr_line)152                    # the new word will be included into next line153                    curr_words = [ word ]154                    curr_words_no_color = [ word_no_color ]155                else:156                    # ok, include this new word into the current line157                    curr_words.append(word)158                    curr_words_no_color.append(word_no_color)159            wrapped_lines.append(' ' + ' '.join(curr_words))160            curr_words, curr_words_no_color = [], []161        # after wrapping is validated, we can revert non-breaking spaces162        # to regular space.163        return '\n'.join(wrapped_lines).replace('\xa0', ' ')164    def quoted(self, text):165        return '\n'.join((' \u2588' + line) for line in text.rstrip('\n').split('\n')) + '\n'166    def heading(self, node, entering):167        if entering:168            level = 1 if node.level is None else node.level169            self.cr()170            self.stack_context(fg_color = FG_COLOR_HEADING, bold = True)171            self.lit('#'*level + ' ')172            self.underline(None, True)173        else:174            self.underline(None, False)175            self.pop_context()176            self.cr()177            self.cr()178    def underline(self, node, entering):179        if entering:180            self.stack_context(underline = True)181        else:182            self.pop_context()183    def strong(self, node, entering):184        if entering:185            self.stack_context(bold = True)186        else:187            self.pop_context()188    def emph(self, node, entering):189        if entering:190            self.stack_context(dim = True)191        else:192            self.pop_context()193    def code(self, node, entering):194        self.stack_context( fg_color = FG_COLOR_SOURCE_CODE,195                            bg_color = BG_COLOR_SOURCE_CODE)196        # replace spaces with non-breaking space197        # (this should be reverted after the paragraph has been wrapped, see above)198        self.lit(node.literal.replace(' ', '\xa0'))199        self.pop_context()200    def pre_format_code_block(self, text):201        text = textwrap.dedent(text)202        text = '\n'.join(line.rstrip() for line in text.rstrip('\n').split('\n'))203        return text204    # Since pygments output includes escape codes to reset the foreground205    # or background color, we have to make a pass to revert those escape206    # codes and get the default colors we want.207    def fix_pygments_default_colors(self, s, default_fg, default_bg):208        reset_all = "0;%s;%s" % (str(default_fg), str(default_bg))209        mapping = {210                    39: str(default_fg), # default fg color211                    49: str(default_bg), # default bg color212                     0: reset_all213        }214        s2 = ''215        start = 0216        end = 0217        for m in RE_ESC_COLOR.finditer(s):218            start = m.start()219            s2 += s[end:start] + '\x1b['220            codes = (int(c) for c in m.group()[2:-1].split(';'))221            s2 += ';'.join(mapping.get(code, str(code)) for code in codes) + 'm'222            end = m.end()223        s2 += s[end:]224        return s2225    def code_block(self, node, entering):226        code_text = self.pre_format_code_block(node.literal)227        code_width = max(len(line) for line in code_text.split('\n')) + 1228        code_width = max(code_width, self.target_width)229        try:230            lexer = get_lexer_by_name(node.info)231            colored_text = highlight(code_text, lexer, Terminal256Formatter())232            colored_text = self.fix_pygments_default_colors(colored_text,233                                   FG_COLOR_SOURCE_CODE, BG_COLOR_SOURCE_CODE)234        except:235            colored_text = code_text236        for code_line, colored_line in zip(237                    code_text.split('\n'), colored_text.split('\n')):238            self.stack_context( fg_color = FG_COLOR_SOURCE_CODE,239                                bg_color = BG_COLOR_SOURCE_CODE)240            # paste the colored line, then kill ('\e[K') in order to paint the rest241            # with background color of source code, then move to the right ('\e[<N>C')242            # up to the edge of code block243            self.lit(colored_line + '\x1b[K\x1b[%dC' % (code_width-len(code_line)))244            # this will restore markdown background color245            self.pop_context()246            # line feed247            self.cr()248        self.cr()249    def list(self, node, entering):250        if entering:251            if node.list_data['type'] == 'bullet':252                self.list_numbering.append(None)253            else:254                self.list_numbering.append(1)255        else:256            self.list_numbering = self.list_numbering[:-1]257            self.cr()258    def item(self, node, entering):259        if entering:...csharp_interpreter.py
Source:csharp_interpreter.py  
...74        self.currentContext = None75    def push_context(self, context):76        self.contexts.append(context)77        self.currentContext = context78    def pop_context(self):79        if self.contexts:80            self.contexts.pop()81        if self.contexts:82            self.currentContext = self.contexts[-1]83        else:84            self.currentContext = None85    86    def start_class(self, name, ast):87        cl = CSharpClass(name, self.currentContext.currentObject if self.currentContext else None, ast, self.file)88        self.push_context(ClassContext(cl, self.currentContext))89        return cl90      91    def end_class(self):92        self.pop_context()93    94    def start_method(self, name, returnType, accessibility, ast):95        isConstructor = self.currentContext.is_class(name)96        meth = CSharpMethod(name, returnType, accessibility, self.currentContext.currentObject, ast, self.file, isConstructor)97        self.currentContext.add_method(meth)98        self.push_context(MethodContext(meth, self.currentContext))99        return meth100      101    def add_attribute(self, attribute, ast):102        self.currentContext.add_attribute(attribute, ast)103        104    def end_method(self):105        self.pop_context()106    107    def start_block(self, ast):108        block = StatementsBlock(self.currentContext.currentObject if self.currentContext else None, ast)109        self.push_context(BlockContext(block, self.currentContext))110        return block111        112    def end_block(self):113        self.pop_context()114    115    def start_parenthesed_list(self, ast):116        lst = ParenthesedList(self.currentContext.currentObject if self.currentContext else None, ast)117        self.push_context(ParenthesedListContext(lst, self.currentContext))118        return lst119        120    def end_parenthesed_list(self):121        self.pop_context()122    123    def start_expression(self, ast):124        expr = AnyExpression(self.currentContext.currentObject if self.currentContext else None, ast)125        self.push_context(ExpressionContext(expr, self.currentContext))126        return expr127        128    def end_expression(self):129        self.pop_context()130        131    def add_element(self, element):132        if self.currentContext:133            self.currentContext.add_element(element)134        135    def add_any_statement(self, tokens):136        statement = AnyStatement(self.currentContext.currentObject if self.currentContext else None, tokens)137        if self.currentContext:138            self.currentContext.add_statement(statement)139        140    def add_any_expression(self, tokens):141        expr = AnyExpression(self.currentContext.currentObject if self.currentContext else None, tokens)142#         if self.currentContext:143#             self.currentContext.add_statement(statement)144    145    def set_left_operand(self, ast):146        self.currentContext.set_left_operand(ast)147    148    def set_right_operand(self, ast):149        self.currentContext.set_right_operand(ast)150        151    def start_equality_expression(self, ast):152        expr = EqualityExpression(self.currentContext.currentObject if self.currentContext else None, ast)153        self.push_context(BinaryExpressionContext(expr, self.currentContext))154        return expr155    156    def end_equality_expression(self):157        self.pop_context()158    159    def start_assignment_expression(self, ast):160        expr = AssignmentExpression(self.currentContext.currentObject if self.currentContext else None, ast)161        self.push_context(BinaryExpressionContext(expr, self.currentContext))162        return expr163    164    def end_assignment_expression(self):165        self.pop_context()166    167    def start_new_anonymous_expression(self, ast):168        expr = NewAnonymousExpression(self.currentContext.currentObject if self.currentContext else None, ast)169        self.push_context(ParenthesedListContext(expr, self.currentContext))170        return expr171    172    def end_new_anonymous_expression(self):...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!!
