How to use look_like method in Sure

Best Python code snippet using sure_python

_grammar_transformer_spec.py

Source:_grammar_transformer_spec.py Github

copy

Full Screen

...17 '# Example with comments.'18 """)19 assignment = node.body[-1]20 expect(assignment).to(be_a(ast.Expr))21 expect(to_source(assignment)).to(look_like(expected))22 with it('preserves comment indentation'):23 program = """24 with indented:25 # Example is indented.26 """27 node = _grammar_transformer.transform(program)28 expected = goal('''29 with indented:30 """# Example is indented."""31 ''')32 assignment = node.body[-1]33 expect(assignment).to(be_a(ast.With))34 expect(to_source(assignment)).to(look_like(expected))35 with description('visit_Module'):36 with it('prepends header'):37 node = _grammar_transformer.transform('')38 expect(node.body).to(have_len(3))39 with description('dimension definitions'):40 with it('detects dimension = a, b, c'):41 node = _grammar_transformer.transform('name <= {a, b, c}')42 expected = goal("""43 a, b, c = name = dimensions(['name', ['a', 'b', 'c']])44 """)45 assignment = node.body[-1]46 expect(assignment).to(be_a(ast.Assign))47 expect(to_source(assignment)).to(look_like(expected))48 with it('detects dimension = 1, 2, 3'):49 node = _grammar_transformer.transform('name <= {1, 2, 3}')50 expected = goal("""51 _1, _2, _3 = name = dimensions(['name', [1, 2, 3]])52 """)53 assignment = node.body[-1]54 expect(assignment).to(be_a(ast.Assign))55 expect(to_source(assignment)).to(look_like(expected))56 with it('detects dimension = "a", "b c", "d e f"'):57 node = _grammar_transformer.transform('name <= {"a", "b c", "d e f"}')58 expected = goal("""59 a, b_c, d_e_f = name = dimensions(['name', ['a', 'b c', 'd e f']])60 """)61 assignment = node.body[-1]62 expect(assignment).to(be_a(ast.Assign))63 expect(to_source(assignment)).to(look_like(expected))64 with it('detects dimension using "in" keyword'):65 node = _grammar_transformer.transform('name in {a, b, c}')66 expected = goal("""67 a, b, c = name = dimensions(['name', ['a', 'b', 'c']])68 """)69 assignment = node.body[-1]70 expect(assignment).to(be_a(ast.Assign))71 expect(to_source(assignment)).to(look_like(expected))72 with it('supports *N repeats as shorthand'):73 node = _grammar_transformer.transform('name in {a, b, c*3}')74 expected = goal("""75 a, b, c, c, c = name = dimensions(['name', ['a', 'b', 'c', 'c', 'c']])76 """)77 assignment = node.body[-1]78 expect(assignment).to(be_a(ast.Assign))79 expect(to_source(assignment)).to(look_like(expected))80 with it('supports cross-product dimensions'):81 node = _grammar_transformer.transform('(a, b) in ({x, y}, {1, 2, 3})')82 expected = goal("""83 (x1, x2, x3, y1, y2, y3), _ = a, b = a_b = dimensions(84 ['a', ['x', 'y']],85 ['b', [1, 2, 3]],86 )87 """)88 assignment = node.body[-1]89 expect(assignment).to(be_a(ast.Assign))90 expect(to_source(assignment)).to(look_like(expected))91 with it('supports dimensions with counts'):92 node = _grammar_transformer.transform('a in 3*{x, y, z}')93 expected = goal("""94 x, y, z = a = dimensions(95 ['a', 3, ['x', 'y', 'z']],96 )97 """)98 assignment = node.body[-1]99 expect(assignment).to(be_a(ast.Assign))100 expect(to_source(assignment)).to(look_like(expected))101 with it('detects dimension created from networkx graphs'):102 node = _grammar_transformer.transform("""103 import networkx104 position in networkx.icosahedral_graph()105 """)106 expected = goal("""107 position = dimensions(['position', networkx.icosahedral_graph()])108 """)109 assignment = node.body[-1]110 expect(assignment).to(be_a(ast.Assign))111 expect(to_source(assignment)).to(look_like(expected))112 with it('detects dimension created from other calls'):113 node = _grammar_transformer.transform("""114 position in range(26)115 """)116 expected = goal("""117 position = dimensions(['position', range(26)])118 """)119 assignment = node.body[-1]120 expect(assignment).to(be_a(ast.Assign))121 expect(to_source(assignment)).to(look_like(expected))122 with it('compiles dimensions'):123 node = _grammar_transformer.transform('name <= {1, Ex, "Multi Word"}')124 expect(calling(compile, node, '<string>', 'exec')).not_to(raise_error)125 with it('registers dimension references'):126 transformer = _grammar_transformer._GrammarTransformer()127 parsed = ast.parse('name <= {1, Ex, "Multi Word"}')128 transformer.visit(parsed)129 actual = {}130 for reference, node in transformer._references.items():131 expect(node).to(be_a(ast.Name))132 actual[reference] = node.id133 expect(actual).to(equal({134 'name': 'name',135 '_1': '_1',136 'ex': 'ex',137 'multi_word': 'multi_word'138 }))139 with description('variable definitions'):140 with it('creates variables from `bool`'):141 node = _grammar_transformer.transform('foo is bool')142 expected = goal("""143 foo = variable('foo')144 """)145 assignment = node.body[-1]146 expect(assignment).to(be_a(ast.Assign))147 expect(to_source(assignment)).to(look_like(expected))148 with it('creates variables from `range(N)`'):149 node = _grammar_transformer.transform('foo is range(10)')150 expected = goal("""151 foo = variable(10, 'foo')152 """)153 assignment = node.body[-1]154 expect(assignment).to(be_a(ast.Assign))155 expect(to_source(assignment)).to(look_like(expected))156 with it('creates variables from `range(N, M)`'):157 node = _grammar_transformer.transform('foo is range(1, 10)')158 expected = goal("""159 foo = variable(1, 10, 'foo')160 """)161 assignment = node.body[-1]162 expect(assignment).to(be_a(ast.Assign))163 expect(to_source(assignment)).to(look_like(expected))164 with description('rewrite'):165 with it('free tuples into multi-line expressions'):166 node = _grammar_transformer.transform('A, B, C')167 expected = goal("""168 A169 B170 C171 """)172 node.body = node.body[-3:]173 expect(to_source(node)).to(look_like(expected))174 with it('multi-variable comparisons into pairwise comparisons'):175 node = _grammar_transformer.transform('A > B > C')176 expected = goal("""177 model(A > B)178 model(B > C)179 """)180 node.body = node.body[-2:]181 expect(to_source(node)).to(look_like(expected))182 with it('set equality into group equality'):183 node = _grammar_transformer.transform("""184 {A, B, C} == {X, Y, Z}185 """)186 expected = goal("""187 for __x in {A, B, C}:188 model(sum(__x[__y] for __y in {X, Y, Z}) == 1)189 """)190 node = node.body[-1]191 expect(to_source(node)).to(look_like(expected))192 with it('set equality into group equality, different sized lists'):193 node = _grammar_transformer.transform("""194 {A, B, C} == {X}195 """)196 expected = goal("""197 for __x in {X}:198 model(sum(__x[__y] for __y in {A, B, C}) == 1)199 """)200 node = node.body[-1]201 expect(to_source(node)).to(look_like(expected))202 with it('set equality into group inequality, different sized lists'):203 node = _grammar_transformer.transform("""204 {A} != {X, Y, Z}205 """)206 expected = goal("""207 for __x in {A}:208 model(sum(__x[__y] for __y in {X, Y, Z}) != 1)209 """)210 node = node.body[-1]211 expect(to_source(node)).to(look_like(expected))212 with description('model constraints'):213 with it('constrains A == B'):214 node = _grammar_transformer.transform('A == B')215 expected = goal("""216 model(A == B)217 """)218 assignment = node.body[-1]219 expect(assignment).to(be_a(ast.Expr))220 expect(to_source(assignment)).to(look_like(expected))221 with it('constrains A or B or C or D'):222 node = _grammar_transformer.transform('A or B or C or D')223 expected = goal("""224 model(A ^ B ^ C ^ D)225 """)226 assignment = node.body[-1]227 expect(assignment).to(be_a(ast.Expr))228 expect(to_source(assignment)).to(look_like(expected))229 with it('constrains A and B and C and D'):230 node = _grammar_transformer.transform('A and B and C and D')231 expected = goal("""232 model(A & B & C & D)233 """)234 assignment = node.body[-1]235 expect(assignment).to(be_a(ast.Expr))236 expect(to_source(assignment)).to(look_like(expected))237 with it('constrains A & B'):238 node = _grammar_transformer.transform('A & B')239 expected = goal("""240 model(A & B)241 """)242 assignment = node.body[-1]243 expect(assignment).to(be_a(ast.Expr))244 expect(to_source(assignment)).to(look_like(expected))245 with it('constrains simple function calls'):246 node = _grammar_transformer.transform('abs(A - B)')247 expected = goal("""248 model(abs(A - B))249 """)250 assignment = node.body[-1]251 expect(assignment).to(be_a(ast.Expr))252 expect(to_source(assignment)).to(look_like(expected))253 with it('constrains complex function calls'):254 node = _grammar_transformer.transform('any([A, B])')255 expected = goal("""256 model(any([A, B]))257 """)258 assignment = node.body[-1]259 expect(assignment).to(be_a(ast.Expr))260 expect(to_source(assignment)).to(look_like(expected))261 with it('constrains for loop body'):262 node = _grammar_transformer.transform("""263 for a in range(5):264 a < b265 """)266 expected = goal("""267 for a in range(5):268 model(a < b)269 """)270 assignment = node.body[-1]271 expect(assignment).to(be_a(ast.For))272 expect(to_source(assignment)).to(look_like(expected))273 with description('if'):274 with it('converts if->then statements'):275 node = _grammar_transformer.transform('if A: B')276 expected = goal("""277 if "A":278 model(A <= B)279 """)280 assignment = node.body[-1]281 expect(assignment).to(be_a(ast.If))282 expect(to_source(assignment)).to(look_like(expected))283 with it('converts if->then/else statements'):284 node = _grammar_transformer.transform("""285 if A:286 B287 else:288 C289 """)290 expected = goal("""291 if "A":292 model(A <= B)293 model(A + C >= 1)294 """)295 result = node.body[-1]296 expect(result).to(be_a(ast.If))297 expect(to_source(result)).to(look_like(expected))298 with it('converts if->then/else statements with longer bodies'):299 node = _grammar_transformer.transform("""300 if A:301 B1302 B2303 else:304 C1305 C2306 """)307 expected = goal("""308 if "A":309 model(A <= B1 & B2)310 model(A + (C1 & C2) >= 1)311 """)312 assignment = node.body[-1]313 expect(assignment).to(be_a(ast.If))314 expect(to_source(assignment)).to(look_like(expected))315 with it('supports if/else assignments'):316 node = _grammar_transformer.transform("""317 if A:318 x = 1319 else:320 x = 2321 """)322 expected = goal("""323 if "A":324 x = (A == True) * 1 + (A == False) * 2325 """)326 assignment = node.body[-1]327 expect(assignment).to(be_a(ast.If))328 expect(to_source(assignment)).to(look_like(expected))329 with it('supports if/else mixed condition and assignments'):330 node = _grammar_transformer.transform("""331 if A:332 A > B333 x = 1334 else:335 x = 2336 """)337 expected = goal("""338 if "A":339 x = (A == True) * 1 + (A == False) * 2340 model(A <= (A > B))341 """)342 assignment = node.body[-1]343 expect(assignment).to(be_a(ast.If))344 expect(to_source(assignment)).to(look_like(expected))345 with it('supports nested if statements'):346 node = _grammar_transformer.transform("""347 if A:348 if B:349 if C:350 x == 3351 else:352 x == 2353 else:354 x == 1355 else:356 x == 0357 """)358 expected = goal("""359 if 'A':360 model(A <= (B <= (C <= (x == 3)) & (C + (x == 2) >= 1)) & (B + (x == 1) >= 1)361 )362 model(A + (x == 0) >= 1)363 """)364 assignment = node.body[-1]365 expect(assignment).to(be_a(ast.If))366 expect(to_source(assignment)).to(look_like(expected))367 with it('supports if statements in generators'):368 node = _grammar_transformer.transform("""369 all(implication[i] for i in range(10) if condition) 370 """)371 expected = goal("""372 model(all(condition <= implication[i] for i in range(10)))373 """)374 assignment = node.body[-1]375 expect(assignment).to(be_a(ast.Expr))376 expect(to_source(assignment)).to(look_like(expected))377 with description('reference aliases'):378 with it('no-op for well-defined references'):379 node = _grammar_transformer.transform("""380 name <= {andy, bob, cynthia}381 color <= {red, green, blue}382 andy == red383 """)384 expected = goal("""385 model(andy == red)386 """)387 assignment = node.body[-1]388 expect(assignment).to(be_a(ast.Expr))389 expect(to_source(assignment)).to(look_like(expected))390 with it('rewrites string references'):391 node = _grammar_transformer.transform("""392 name <= {andy, bob, cynthia}393 color <= {red, green, 'sky blue'}394 andy == 'sky blue' and bob != sky_blue395 """)396 expected = goal("""397 model((andy == sky_blue) & (bob != sky_blue))398 """)399 assignment = node.body[-1]400 expect(assignment).to(be_a(ast.Expr))401 expect(to_source(assignment)).to(look_like(expected))402 with it('matches alias references'):403 node = _grammar_transformer.transform("""404 key <= {'space case', 'kebab-case', snake_case, CamelCase}405 'space case' != 'kebab-case' != 'snake_case' != 'CamelCase'406 """)407 expected = goal("""408 model(space_case != kebab_case)409 model(kebab_case != snake_case)410 model(snake_case != camelcase)411 """)412 node.body = node.body[-3:]413 expect(to_source(node)).to(look_like(expected))414 with description('visit_With'):415 with it('ignores constraints inside of `with init`: blocks'):416 node = _grammar_transformer.transform("""417 with init:418 a = []419 for a, b in foo:420 local_variable = 'value'421 a.append(name)422 """)423 expected = goal("""424 with init:425 a = []426 for a, b in foo:427 local_variable = 'value'428 a.append(name)429 """)430 assignment = node.body[-1]431 expect(assignment).to(be_a(ast.With))432 expect(to_source(assignment)).to(look_like(expected))433 with it('ignores if statements inside of `with init`: blocks'):434 node = _grammar_transformer.transform("""435 with init:436 if some_condition:437 a = 1438 else:439 a = 2440 """)441 expected = goal("""442 with init:443 if some_condition:444 a = 1445 else:446 a = 2447 """)448 assignment = node.body[-1]449 expect(assignment).to(be_a(ast.With))...

Full Screen

Full Screen

main.py

Source:main.py Github

copy

Full Screen

1import docx2import os3import re4import nltk5from fuzzywuzzy import fuzz6from fuzzywuzzy import process7from nltk.corpus import stopwords8nltk.download('punkt')9nltk.download('stopwords')10paths = str(input("Введите путь к файлу\n"))11folder = os.getcwd()12for root, dirs, files in os.walk(folder):13 for file in files:14 if file.endswith('docx') and not file.startswith('~'):15 paths.append(os.path.join(root, file))16for path in paths:17 doc = docx.Document(paths)18 19text = []20for paragraph in doc.paragraphs:21 text.append(paragraph.text)22for table in doc.tables:23 for row in table.rows:24 for cell in row.cells:25 text.append(cell.text)26bad_chars = [';', ':', '!', '*', '№', '$', '%', '^', '&', '?', '*', ')', '(', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' '-', '+', '_', '+', '{', '}', '[', ']', '/', '.', ',', '<', '>']27text = '_'.join(text)28stop_words = set(stopwords.words("russian")) #создание списка на нежелательных слов29keyword = [ #список ключевых слов30 [Интеллект, искуствен, ПО, Нейрон, машин, обучен, развит, подход, алгоритм, интеллектуль, способн, сам, использ, мозг, обработк],31 [технолог,разработк,продукц,процесс,химическ,техник,металл,обработка,средств,строительнств,космическ,практическ,определен,производств,материал,управлен,научн,научно-техническ,деятельн],32 [робототехник,робот,развит,сенсорик,област,субтехнолог,сенсор,цифров,обработк,информац,взаимодейств,человек,просмотр,датчик,по,моделирован,проектирован,механическ,рынок,инновацион,промышл],33 [Средств,интернет, сет,вещ,концеп,устройств,беспроводн,индентификац,физич,уровн,прибор,компан,реальн,будущ,развит,самртфон,деньг,товар,безопасн,товар,дист],34 [5g,3g,4g,сет,связ,технолог, мобильн,скорост,частот,устройств,диапазон,передач,интернет,оператор,задержк,мудл,поколен,сотов,станц,базов,антен,волн,LTE,ГГц],35 [технолог,информац,информацион,коммуникац,протокол,передач,современ,процесс,пользовател,сервер,электрон,социальн,сообщен,ресурс,обеспечива,образован,обучен,информационно,коммуникацион,коммуникативн,сетев,беспроводн],36 [реальност,виртуальн,vr,дополнен,пользовател,реальн,ar,объект,обучен,позволя,сфер,vr/ar,погружен,применен,информац,взаимодейств,пространств,игр,reality,компьютерн,смартфон,дополнительн],37 [блокчейн,реестр,сет,технолог,распределен,транзакц,консенсус,блок,ibm,компан,безопасн,баз,ключ,алгоритм,финансов,крипт,hyperledger,децентрализова,хран,криптовалют,крипт,dlt],38 [квант, криптограф, фотон, коэффициент, поляризац, модул, коммуникац, работ, технолог, шифрован, алгоритм],39 [квант, квадратическ, сенсор, измерен, измерительн, величин, высокоточн, относительн, суперпозиц, технолог],40 [кубит, квант, квантов, суперпозиц, вычислительн, детерминирова, многокубитн, вероятн, экспоненциальн, электрон, фотон],41 42 ]43words = nltk.word_tokenize(text)44without_stop_words = [word for word in words if not word in stop_words]45without_stop_words = '_'.join(without_stop_words)46for i in bad_chars : 47 without_stop_words = without_stop_words.replace(i, ' ')48MainText = f'List of Words ={without_stop_words.split()}'49FileTheame = int(input(Введите тему программы)) #ввод темы для скана50 51look_like_proc = 0 #создание переменной соответствия52 53for i in keyword: #получение процента соответвия54 for j in MainText:55 look_like = fuzz.ratio(keyword[FileTheame[i]], MainText[j])56 if look_like > 40:57 look_like_proc += 100/len(keyword)...

Full Screen

Full Screen

test_validation.py

Source:test_validation.py Github

copy

Full Screen

...41 response = client.describe_scalable_targets(42 ServiceNamespace=DEFAULT_SERVICE_NAMESPACE, ScalableDimension="foo",43 )44 err.response["Error"]["Code"].should.equal("ValidationException")45 err.response["Error"]["Message"].split(":")[0].should.look_like(46 "1 validation error detected"47 )48 err.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(400)49@mock_applicationautoscaling50def test_describe_scalable_targets_with_invalid_service_namespace_should_return_validation_exception():51 client = boto3.client("application-autoscaling", region_name=DEFAULT_REGION)52 with assert_raises(ClientError) as err:53 response = client.describe_scalable_targets(54 ServiceNamespace="foo", ScalableDimension=DEFAULT_SCALABLE_DIMENSION,55 )56 err.response["Error"]["Code"].should.equal("ValidationException")57 err.response["Error"]["Message"].split(":")[0].should.look_like(58 "1 validation error detected"59 )60 err.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(400)61@mock_applicationautoscaling62def test_describe_scalable_targets_with_multiple_invalid_parameters_should_return_validation_exception():63 client = boto3.client("application-autoscaling", region_name=DEFAULT_REGION)64 with assert_raises(ClientError) as err:65 response = client.describe_scalable_targets(66 ServiceNamespace="foo", ScalableDimension="bar",67 )68 err.response["Error"]["Code"].should.equal("ValidationException")69 err.response["Error"]["Message"].split(":")[0].should.look_like(70 "2 validation errors detected"71 )72 err.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(400)73@mock_ecs74@mock_applicationautoscaling75def test_register_scalable_target_ecs_with_non_existent_service_should_return_validation_exception():76 client = boto3.client("application-autoscaling", region_name=DEFAULT_REGION)77 resource_id = "service/{}/foo".format(DEFAULT_ECS_CLUSTER)78 with assert_raises(ClientError) as err:79 register_scalable_target(client, ServiceNamespace="ecs", ResourceId=resource_id)80 err.response["Error"]["Code"].should.equal("ValidationException")81 err.response["Error"]["Message"].should.equal(82 "ECS service doesn't exist: {}".format(resource_id)83 )...

Full Screen

Full Screen

Automation Testing Tutorials

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.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Sure automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful