'''simple docstring'''





from __future__ import annotations

from collections import deque




class        __A      :



    def __init__(self    :    List[Any]   ,			__a    :    list[str] ):
         UpperCAmelCase_           =   []
         self.adlist.append(
             {"value": "", "next_states": [], "fail_state": 0, "output": []} )

         for keyword in keywords:
              self.add_keyword(__a )
         self.set_fail_transitions()



    def 					_lowercase						(self    :    Union[str, Any]   ,			__a    :    int   ,			__a    :    str ):
         for state in self.adlist[current_state]["next_states"]:
              if char == self.adlist[state]["value"]:
                   return state
         return None



    def 					_lowercase						(self    :    Optional[Any]   ,			__a    :    str ):
         UpperCAmelCase_           =   0
         for character in keyword:
              UpperCAmelCase_           =   self.find_next_state(__a   ,			__a )
              if next_state is None:
                   self.adlist.append(
                       {
                           "value": character,
                           "next_states": [],
                           "fail_state": 0,
                           "output": [],
                       } )
                   self.adlist[current_state]["next_states"].append(len(self.adlist ) - 1 )
                   UpperCAmelCase_           =   len(self.adlist ) - 1
              else:
                   UpperCAmelCase_           =   next_state
         self.adlist[current_state]["output"].append(__a )



    def 					_lowercase						(self    :    int ):
         UpperCAmelCase_           =   deque()
         for node in self.adlist[0]["next_states"]:
              q.append(__a )
              UpperCAmelCase_           =   0
         while q:
              UpperCAmelCase_           =   q.popleft()
              for child in self.adlist[r]["next_states"]:
                   q.append(__a )
                   UpperCAmelCase_           =   self.adlist[r]["fail_state"]
                   while (
                       self.find_next_state(__a   ,			self.adlist[child]["value"] ) is None
                       and state != 0
                   ):
                        UpperCAmelCase_           =   self.adlist[state]["fail_state"]
                   UpperCAmelCase_           =   self.find_next_state(
                       __a   ,			self.adlist[child]["value"] )
                   if self.adlist[child]["fail_state"] is None:
                        UpperCAmelCase_           =   0
                   UpperCAmelCase_           =   (
                       self.adlist[child]["output"]
                       + self.adlist[self.adlist[child]["fail_state"]]["output"]
                   )






    def 					_lowercase						(self    :    Dict   ,			__a    :    str ):
         UpperCAmelCase_           =   {}  # returns a dict with keywords and list of its occurrences
         UpperCAmelCase_           =   0
         for i in range(len(__a ) ):
              while (
                  self.find_next_state(__a   ,			string[i] ) is None
                  and current_state != 0
              ):
                   UpperCAmelCase_           =   self.adlist[current_state]["fail_state"]
              UpperCAmelCase_           =   self.find_next_state(__a   ,			string[i] )
              if next_state is None:
                   UpperCAmelCase_           =   0
              else:
                   UpperCAmelCase_           =   next_state
                   for key in self.adlist[current_state]["output"]:
                        if key not in result:
                             UpperCAmelCase_           =   []
                        result[key].append(i - len(__a ) + 1 )
         return result


if __name__ == "__main__":
    import doctest

    doctest.testmod()





'''simple docstring'''





from typing import Callable, Dict, Optional, Tuple

import torch
from torch import nn
from torch.distributions import (
    AffineTransform,
    Distribution,
    Independent,
    NegativeBinomial,
    Normal,
    StudentT,
    TransformedDistribution,
)




class        __A      ( UpperCamelCase__	):



    def __init__(self    :    int   ,			__a    :    Distribution   ,			__a    :    Dict=None   ,			__a    :    int=None   ,			__a    :    Any=0 ):
         UpperCAmelCase_           =   1.0 if scale is None else scale
         UpperCAmelCase_           =   0.0 if loc is None else loc

         super().__init__(__a   ,			[AffineTransform(loc=self.loc   ,			scale=self.scale   ,			event_dim=__a )] )



    @property
    def 					_lowercase						(self    :    Union[str, Any] ):
         return self.base_dist.mean * self.scale + self.loc



    @property
    def 					_lowercase						(self    :    List[Any] ):
         return self.base_dist.variance * self.scale**2






    @property
    def 					_lowercase						(self    :    List[Any] ):
         return self.variance.sqrt()




class        __A      ( nn.Module	):



    def __init__(self    :    Optional[int]   ,			__a    :    int   ,			__a    :    Dict[str, int]   ,			__a    :    Callable[..., Tuple[torch.Tensor]]   ,			**__a    :    List[str] ):
         super().__init__(**__a )
         UpperCAmelCase_           =   args_dim
         UpperCAmelCase_           =   nn.ModuleList([nn.Linear(__a   ,			__a ) for dim in args_dim.values()] )
         UpperCAmelCase_           =   domain_map






    def 					_lowercase						(self    :    List[str]   ,			__a    :    torch.Tensor ):
         UpperCAmelCase_           =   [proj(__a ) for proj in self.proj]

         return self.domain_map(*__a )




class        __A      ( nn.Module	):



    def __init__(self    :    Union[str, Any]   ,			__a    :    List[str] ):
         super().__init__()
         UpperCAmelCase_           =   function






    def 					_lowercase						(self    :    Optional[int]   ,			__a    :    List[str]   ,			*__a    :    Optional[int] ):
         return self.function(__a   ,			*__a )




class        __A      :
    a__       :						type
    a__       :						int
    a__       :						Dict[str, int]



    def __init__(self    :    List[Any]   ,			__a    :    int = 1 ):
         UpperCAmelCase_           =   dim
         UpperCAmelCase_           =   {k: dim * self.args_dim[k] for k in self.args_dim}



    def 					_lowercase						(self    :    Any   ,			__a    :    Any ):
         if self.dim == 1:
              return self.distribution_class(*__a )
         else:
              return Independent(self.distribution_class(*__a )   ,			1 )



    def 					_lowercase						(self    :    List[str]   ,			__a    :    Union[str, Any]   ,			__a    :    Optional[torch.Tensor] = None   ,			__a    :    Optional[torch.Tensor] = None   ,			):
         UpperCAmelCase_           =   self._base_distribution(__a )
         if loc is None and scale is None:
              return distr
         else:
              return AffineTransformed(__a   ,			loc=__a   ,			scale=__a   ,			event_dim=self.event_dim )



    @property
    def 					_lowercase						(self    :    Any ):
         return () if self.dim == 1 else (self.dim,)



    @property
    def 					_lowercase						(self    :    Dict ):
         return len(self.event_shape )



    @property
    def 					_lowercase						(self    :    Tuple ):
         return 0.0



    def 					_lowercase						(self    :    List[str]   ,			__a    :    int ):
         return ParameterProjection(
             in_features=__a   ,			args_dim=self.args_dim   ,			domain_map=LambdaLayer(self.domain_map )   ,			)



    def 					_lowercase						(self    :    Optional[int]   ,			*__a    :    torch.Tensor ):
         raise NotImplementedError()






    @staticmethod
    def 					_lowercase						(__a    :    torch.Tensor ):
         return (x + torch.sqrt(torch.square(__a ) + 4.0 )) / 2.0




class        __A      ( UpperCamelCase__	):
    a__       :						Dict[str, int]          =  {"df": 1, "loc": 1, "scale": 1}
    a__       :						type          =  StudentT



    @classmethod
    def 					_lowercase						(cls    :    Union[str, Any]   ,			__a    :    torch.Tensor   ,			__a    :    torch.Tensor   ,			__a    :    torch.Tensor ):
         UpperCAmelCase_           =   cls.squareplus(__a ).clamp_min(torch.finfo(scale.dtype ).eps )
         UpperCAmelCase_           =   2.0 + cls.squareplus(__a )
         return df.squeeze(-1 ), loc.squeeze(-1 ), scale.squeeze(-1 )




class        __A      ( UpperCamelCase__	):
    a__       :						Dict[str, int]          =  {"loc": 1, "scale": 1}
    a__       :						type          =  Normal



    @classmethod
    def 					_lowercase						(cls    :    Tuple   ,			__a    :    torch.Tensor   ,			__a    :    torch.Tensor ):
         UpperCAmelCase_           =   cls.squareplus(__a ).clamp_min(torch.finfo(scale.dtype ).eps )
         return loc.squeeze(-1 ), scale.squeeze(-1 )




class        __A      ( UpperCamelCase__	):
    a__       :						Dict[str, int]          =  {"total_count": 1, "logits": 1}
    a__       :						type          =  NegativeBinomial



    @classmethod
    def 					_lowercase						(cls    :    Optional[Any]   ,			__a    :    torch.Tensor   ,			__a    :    torch.Tensor ):
         UpperCAmelCase_           =   cls.squareplus(__a )
         return total_count.squeeze(-1 ), logits.squeeze(-1 )



    def 					_lowercase						(self    :    List[str]   ,			__a    :    str ):
         UpperCAmelCase_    , UpperCAmelCase_           =   distr_args
         if self.dim == 1:
              return self.distribution_class(total_count=__a   ,			logits=__a )
         else:
              return Independent(self.distribution_class(total_count=__a   ,			logits=__a )   ,			1 )






    def 					_lowercase						(self    :    Optional[Any]   ,			__a    :    int   ,			__a    :    Optional[torch.Tensor] = None   ,			__a    :    Optional[torch.Tensor] = None ):
         UpperCAmelCase_    , UpperCAmelCase_           =   distr_args

         if scale is not None:
              # See scaling property of Gamma.
              logits += scale.log()

         return self._base_distribution((total_count, logits) )




