Best Python code snippet using hypothesis
process_mona_output.py
Source:process_mona_output.py  
...100                ),101            ).group(1)102        )103    @property104    def raw_transitions(self) -> Dict[int, Dict[int, Set[str]]]:105        """106        Get the raw transitions.107        mapping: start state -> end state -> {guard to reach end from start}108        """109        raw_transitions: Dict[int, Dict[int, Set[str]]] = {}110        lines = self.output.splitlines()111        # from the 8th line, the output specifies the transitions.112        transition_strings = lines[7:]113        for t in transition_strings:114            match = cast(115                Match, re.search("State ([0-9]+): ([01X]+|) -> state ([0-9]+)", t)116            )117            if match is None:118                continue...flowbuilder.py
Source:flowbuilder.py  
1from collections import namedtuple2from django.db import transaction3from river.models import State, Workflow4from river.models.factories import TransitionMetaFactory, TransitionApprovalMetaFactory5from river.tests.models.factories import BasicTestModelObjectFactory6RawTransition = namedtuple("RawTransition", ["source_state", "destination_state", "authorization_policies"])7RawState = namedtuple("RawState", ["label"])8AuthorizationPolicy = namedtuple("RawAuthorizationPolicy", ["priority", "permissions", "groups", "user"])9class Flow(object):10    def __init__(self, workflow, states, transitions_metas, transitions_approval_metas, objects):11        self.workflow = workflow12        self.states = states13        self.transitions_metas = transitions_metas14        self.transitions_approval_metas = transitions_approval_metas15        self.objects = objects16    def get_state(self, raw_state):17        return self.states[raw_state.label]18class AuthorizationPolicyBuilder(object):19    def __init__(self):20        self._priority = 021        self._user = None22        self._permissions = []23        self._groups = []24    def with_priority(self, priority):25        self._priority = priority26        return self27    def with_permission(self, permission):28        return self.with_permissions([permission])29    def with_user(self, user):30        self._user = user31        return self32    def with_group(self, group):33        return self.with_groups([group])34    def with_permissions(self, permissions):35        self._permissions.extend(permissions)36        return self37    def with_groups(self, groups):38        self._groups.extend(groups)39        return self40    def build(self):41        return AuthorizationPolicy(self._priority, self._permissions, self._groups, self._user)42class FlowBuilder(object):43    def __init__(self, field_name, content_type):44        self.field_name = field_name45        self.content_type = content_type46        self.raw_transitions = []47        self.additional_raw_states = []48        self.objects_count = 149        self.object_factory = lambda: BasicTestModelObjectFactory().model50    def with_transition(self, source_state, destination_state, authorization_policies=None):51        self.raw_transitions.append(RawTransition(source_state, destination_state, authorization_policies))52        return self53    def with_additional_state(self, state):54        self.additional_raw_states.append(state)55        return self56    def with_objects(self, count):57        self.objects_count = count58        return self59    def with_object_factory(self, factory):60        self.object_factory = factory61        return self62    @transaction.atomic63    def build(self):64        workflow = None65        states = {}66        transition_metas = []67        transitions_approval_metas = []68        workflow_objects = []69        for additional_raw_state in self.additional_raw_states:70            state, _ = State.objects.get_or_create(label=additional_raw_state.label)71            states[state.label] = state72        for raw_transition in self.raw_transitions:73            source_state, _ = State.objects.get_or_create(label=raw_transition.source_state.label)74            if not workflow:75                workflow = Workflow.objects.create(field_name=self.field_name, content_type=self.content_type, initial_state=source_state)76            destination_state, _ = State.objects.get_or_create(label=raw_transition.destination_state.label)77            states[source_state.label] = source_state78            states[destination_state.label] = destination_state79            transition_meta = TransitionMetaFactory.create(80                workflow=workflow,81                source_state=source_state,82                destination_state=destination_state,83            )84            transition_metas.append(transition_meta)85            if raw_transition.authorization_policies:86                for authorization_policy in raw_transition.authorization_policies:87                    transition_approval_meta = TransitionApprovalMetaFactory.create(88                        workflow=workflow,89                        transition_meta=transition_meta,90                        priority=authorization_policy.priority,91                        permissions=authorization_policy.permissions,92                    )93                    transition_approval_meta.groups.set(authorization_policy.groups)94                    transitions_approval_metas.append(transition_approval_meta)95        for i in range(self.objects_count):96            workflow_objects.append(self.object_factory())...MarkovDecisionProcess.py
Source:MarkovDecisionProcess.py  
1import sys2class Action:3    def __init__(self, action_val, transitions, j_value):4        self.action_val = action_val5        self.transitions = transitions6        self.j_value = j_value7class State:8    def __init__(self, state_val, actions, reward):9        self.state_val = state_val10        self.actions = actions11        self.reward = reward12def create_state_from_line(line):13    state_val = int (line [0].replace("s", ""))14    reward = int (line[1])15    raw_transitions = line [2:]16    full_length = len (raw_transitions) 17    transitions = []18    for i in range(0,full_length, 3):19        action = int (raw_transitions[i].replace("(a", ""))20        transition_state = int (raw_transitions[i + 1].replace("s", ""))21        transition_probability = float (raw_transitions[i + 2].replace(")", ""))22        transitions.append([action, transition_state, transition_probability])23    actions = create_actions_from_transitions(transitions)24    return State(state_val, actions, reward)25def create_actions_from_transitions(transitions):26    actions = {}27    # initialize the dic28    for transition in transitions:29        actions[transition[0]] = []30    for transition in transitions:31        curr_transitions = actions[transition[0]]32        curr_transitions.append([transition[1], transition[2]])33        actions[transition[0]] = curr_transitions34    action_objects = []35    for action in actions:36        action_objects.append (Action(action, actions[action], 0))37    return action_objects38def get_optimal_action_and_j_val(state, gamma, prev_j_val):39    actions = state.actions40    max_j = -100000041    maximised_action = None42    for action in actions:43        temp_j = state.reward44        for transition in action.transitions:45            # transition 0 is the state to, and transition 1 is the probability46            temp_j += gamma * (prev_j_val[transition[0]] * transition[1])47        if (temp_j > max_j):48            max_j = temp_j49            maximised_action = action50    return (maximised_action, max_j)51def value_iteration(state_dict, gamma):52    j_one = {}53    for key, state in state_dict.items():54        j_one[state.state_val] = state.reward55    iteration_one_string = ""56    for key, state in state_dict.items():57        iteration_one_string += "(s%s"%state.state_val + " a%s"%state.actions[0].action_val + " %s"%state.reward + ") "58    print("After iteration 1 : ")59    print(iteration_one_string)60    iteration = 0;61    j_value_matrix = [j_one]62    # use delta to stop iteration63    while iteration < 19:64        next_j_row = {}65        current_iteration_as_string = ""66        for key, state in state_dict.items():67            (max_action, max_j) = get_optimal_action_and_j_val(state, gamma, j_value_matrix[iteration])68            current_iteration_as_string += "(s%s"%state.state_val + " a%s"%max_action.action_val + " %s"%round (max_j, 4) + ") "69            next_j_row[state.state_val] = max_j70        print("After iteration %s"%(iteration + 2) + " : ")71        print(current_iteration_as_string)72        j_value_matrix.append(next_j_row)73        iteration += 174            75if len (sys.argv) != 5:76    raise ValueError("Please provide five arguments")77training_set_file_path = sys.argv[3]78gamma = float (sys.argv[4])79raw_states = [i.strip().split() for i in open(training_set_file_path).readlines()]80state_dict = {}81for idx, line in enumerate (raw_states):82    state_dict [idx + 1] = create_state_from_line(line)...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!!
