How to use _pattern_matches method in Slash

Best Python code snippet using slash

decrypter.py

Source:decrypter.py Github

copy

Full Screen

1import copy2import logging3from typing import List4from decryptoquote.cypherlettermap import CypherLetterMap5from decryptoquote.helpers import string_to_caps_words6from decryptoquote.wordpatterns import WordPatterns7class Decrypter:8 """9 This class performs Cryptoquote decryption using a version of backtracking10 search.11 This version of backtracking search uses word pattern matches, as described12 in :class:`WordPatterns`. Decrypter determines all matches for each word in13 the coded text. It also maintains a master index value :math:`i` and an14 index value for each word :math:`j_x`. The algorithm works as follows:15 1. Initially, set :math:`i` and all :math:`j_x` to 016 2. Select the "match word" :math:`j_i` for word :math:`i`17 3. Check that this match word is consistent with the current cypher-letter18 map (i.e. any coded letters, if decoded in the map, should decode to the19 same letter in the match word). If it is consistent, complete the "good20 match" steps. If not, complete the "bad match" steps.21 4. "Good match" steps22 a. Update the cypher letter map using the match word.23 b. Increment :math:`i`24 c. If :math:`i` >= number of words in the coded text, decrypting was25 successful; return `True`.26 d. Otherwise, return to step 2 and repeat.27 5. "Bad match" steps28 a. Increment :math:`j_i`29 b. If :math:`j_i` >= number of matches for word :math:`i`, follow the30 "backtrack" steps.31 c. Otherwise, return to step 2 and repeat.32 6. "Backtrack" steps33 a. Remove the match word from the cypher-letter map34 b. Set :math:`j_i` to 035 c. Decrement :math:`i`36 d. Repeat "bad match" steps with new :math:`i`37 e. If :math:`i` < 0, no decoded text can be found; return `False`.38 f. Otherwise, return to step 2 and repeat.39 :param coded_text: the text to decode40 :param cypher_letter_map: CypherLetterMap to use. This map will be cleared41 before use.42 :param word_patterns: WordPatterns to use.43 .. attribute:: cypher_letter_map44 :type: CypherLetterMap45 :value: blank CypherLetterMap46 The mapping from coded cypher letters to decoded letters.47 """48 def __init__(49 self,50 coded_text: str,51 cypher_letter_map: CypherLetterMap,52 word_patterns: WordPatterns,53 ):54 self.cypher_letter_map = cypher_letter_map55 self.cypher_letter_map.clear()56 self._coded_words: List[str] = string_to_caps_words(coded_text)57 self._pattern_matches: List[List[str]] = []58 for coded_word in self._coded_words:59 matches = word_patterns.code_word_to_match_words(coded_word)60 self._pattern_matches.append(matches)61 self._word_index = 062 self._match_indices = [0 for _ in self._coded_words]63 def decrypt(self, continue_decrypting: bool = False) -> bool:64 """65 Decodes the cypher, returning a success value.66 The cypher-letter map can now be used to decode the Cryptoquote text.67 :return: `True` if decoding was successful68 """69 logging.debug("Starting new decryption...")70 word_count: int = len(self._coded_words)71 logging.debug(word_count)72 backtracking: bool = False73 if continue_decrypting:74 logging.debug("Continuing after last solve")75 backtracking = self._bad_match_logic()76 while 0 <= self._word_index < word_count:77 if backtracking:78 backtracking = self._bad_match_logic()79 else:80 current_match_words: List[str] = self._pattern_matches[81 self._word_index]82 if len(current_match_words) == 0:83 return False84 current_match_word: str = current_match_words[85 self._match_indices[self._word_index]]86 current_coded_word: str = self._coded_words[self._word_index]87 if self.cypher_letter_map.does_word_coding_work(88 current_coded_word, current_match_word):89 logging.debug(90 f"Testing word {self._word_index} == "91 f"{current_match_word}, works")92 self._good_match_logic(current_coded_word,93 current_match_word)94 else:95 logging.debug(96 f"Testing word {self._word_index} == "97 f"{current_match_word}, doesn't work")98 backtracking = self._bad_match_logic()99 if self._word_index < 0:100 logging.debug("decrypt failed")101 return False102 logging.debug("decrypt succeeded")103 return True104 def decrypt_all(self) -> List[CypherLetterMap]:105 """106 Finds all valid solutions for the cypher.107 :return: list of cypher-letter maps for all valid solutions.108 """109 logging.debug("Starting new full decryption...")110 solutions: List[CypherLetterMap] = []111 keep_going = self.decrypt()112 while keep_going:113 solution_map = copy.deepcopy(self.cypher_letter_map)114 solutions.append(solution_map)115 self.cypher_letter_map.remove_last_word_from_mapping()116 self._word_index -= 1117 keep_going = self.decrypt(continue_decrypting=True)118 return solutions119 def _is_match_good(120 self,121 current_coded_word: str,122 current_match_word: str123 ) -> bool:124 current_best_decode: str = \125 self.cypher_letter_map.decode(current_coded_word)126 for letter_pair in zip(current_best_decode, current_match_word):127 decode_letter, match_letter = letter_pair128 if decode_letter == '_':129 continue130 if decode_letter != match_letter:131 return False132 return True133 def _good_match_logic(134 self,135 current_coded_word: str,136 current_match_word: str137 ):138 self.cypher_letter_map.add_word_to_mapping(current_coded_word,139 current_match_word)140 self._word_index += 1141 def _bad_match_logic(142 self143 ) -> bool:144 self._match_indices[self._word_index] += 1145 match_count: int = len(self._pattern_matches[self._word_index])146 if self._match_indices[self._word_index] >= match_count:147 self.cypher_letter_map.remove_last_word_from_mapping()148 self._match_indices[self._word_index] = 0149 self._word_index -= 1150 return True...

Full Screen

Full Screen

bot.py

Source:bot.py Github

copy

Full Screen

1import re2from sqlalchemy import create_engine3from sqlalchemy.ext.declarative import declarative_base4from sqlalchemy.orm import scoped_session, sessionmaker5from sqlalchemy.schema import MetaData6from tautbot.base import Base7from tautbot.client import slack8from tautbot.util import database9from tautbot.util.events import Event10class Tautbot(Base):11 def __init__(self, slack_client=None, plugin_registry=None):12 super().__init__()13 self.slack_client = slack_client14 self.plugin_registry = plugin_registry15 self.userlist = []16 # setup db17 db_path = self.conf.get('database', 'sqlite:///tautbot.db')18 self.db_engine = create_engine(db_path)19 self.db_factory = sessionmaker(bind=self.db_engine)20 self.db_session = scoped_session(self.db_factory)21 self.db_metadata = MetaData()22 self.db_base = declarative_base(metadata=self.db_metadata, bind=self.db_engine)23 self.db = self.db_session()24 # set botvars so plugins can access when loading25 database.metadata = self.db_metadata26 database.base = self.db_base27 database.db = self.db28 if slack_client:29 slack.slack_client = slack_client30 self.logger.debug("Database system initialised.")31 def parse_slack_output(self, output_lines):32 """33 Find command or pattern34 The Slack Real Time Messaging API is an events firehose.35 this parsing function returns None unless a message is36 directed at the Bot, based on its ID.37 """38 if output_lines and len(output_lines) > 0:39 for output in output_lines:40 if output and 'text' in output:41 _prefix_matches = re.match('^{}'.format(self.conf['bot_prefix']), output['text'])42 _bot_matches = re.match('^{}'.format(self.conf['at_bot']), output['text'])43 patterns = '(?:({}))'.format('|'.join([p[0] for p in self.plugin_registry.patterns]))44 _pattern_matches = re.match(patterns, output['text'])45 _channel = output['channel']46 Event('pre_parse_slack_output', output, _channel)47 self.logger.debug("{}".format(output))48 if _pattern_matches:49 _pattern = _pattern_matches.group(0)50 Event('channel_pattern_matched', pattern=_pattern, channel=_channel, text=output['text'], output=output)51 if _bot_matches or _prefix_matches:52 if _bot_matches:53 # text after the @ mention, whitespace removed54 _message = output['text'].split(self.conf['at_bot'])[1].strip().lower()55 _command = _message.split(" ")[0]56 elif _prefix_matches:57 # text after the @ mention, whitespace removed58 _message = output['text'].split(self.conf['bot_prefix'])[1].strip().lower()59 _command = _message.split(" ")[0]60 else:61 self.logger.error('The impossible happened')62 raise Warning("I have no idea what happened")63 self.logger.info('command "{}" called by user: {}'.format(_command, output['user']))64 self.route_command(_channel, _command, _message, output)65 def route_command(self, _channel, _command, _message, output):66 """67 Figure out what type of command it is68 """69 if _command in {k for d in self.plugin_registry.commands for k in d}:70 _message_parts = _message.split(" ")71 if len(_message_parts) > 1 and _message_parts[1] in self.plugin_registry.subcommands:72 Event('channel_subcommand', command=_command, channel=_channel, text=_message, output=output)73 else:74 Event('channel_command', command=_command, channel=_channel, text=_message, output=output)75 elif _command in [p[0] for p in self.plugin_registry.aliases]:76 self.logger.info('command "{}" recognized as alias'.format(_command))...

Full Screen

Full Screen

server.py

Source:server.py Github

copy

Full Screen

...11 self.pattern_middlewares = PatternMiddlewares()12 self.request_handlers = RequestHandlers()13 self.server_class = server_class14 self.server = None15 def _pattern_matches(self, pattern: str, path: str) -> bool:16 # TODO: implement a matching function that actually does something17 return pattern == path or pattern == "*"18 def _get_middlewares(self, path: str) -> List[RequestHandler]: 19 middlewares: List[RequestHandler] = []20 for key, value in self.pattern_middlewares.items():21 if self._pattern_matches(key, path):22 middlewares.extend(value)23 return middlewares24 25 def _get_handler(self, path: str, method: HttpMethod) -> Union[None, Tuple[RequestHandler, str]]:26 for key, value in self.request_handlers[method].items():27 if self._pattern_matches(key, path):28 return value, key29 return None30 def _generate_http_request_handler(self):31 class Handler(BaseHTTPRequestHandler):32 def _generate_request(_self, pattern: str) -> Request:33 return Request(pattern, _self)34 def _generate_response(_self) -> Response:35 return Response(_self)36 37 def _handle_method(_self, method: HttpMethod):38 middlewares = self._get_middlewares(_self.path)39 handlerPattern = self._get_handler(_self.path, method)40 if handlerPattern is None:41 _self.close_connection = True...

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 Slash 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