def test_avg_std(self) -> None: # Use integration to test distribution average and standard deviation. # Only works for distributions which do not consume variates in pairs g = random.Random() N = 5000 x = [i/float(N) for i in range(1,N)] variate = Undefined(Any) for variate, args, mu, sigmasqrd in [ (g.uniform, (1.0,10.0), (10.0+1.0)/2, (10.0-1.0)**2/12), (g.triangular, (0.0, 1.0, 1.0/3.0), 4.0/9.0, 7.0/9.0/18.0), (g.expovariate, (1.5,), 1/1.5, 1/1.5**2), (g.paretovariate, (5.0,), 5.0/(5.0-1), 5.0/((5.0-1)**2*(5.0-2))), (g.weibullvariate, (1.0, 3.0), gamma(1+1/3.0), gamma(1+2/3.0)-gamma(1+1/3.0)**2) ]: setattr(g, 'random', x[:].pop) y = [] # type: List[float] for i in range(len(x)): try: y.append(variate(*args)) except IndexError: pass s1 = s2 = 0.0 for e in y: s1 += e s2 += (e - mu) ** 2 N = len(y) self.assertAlmostEqual(s1/N, mu, places=2) self.assertAlmostEqual(s2/(N-1), sigmasqrd, places=2)
class BaseTestCase(unittest.TestCase): '''Parent class with utility methods for textwrap tests.''' wrapper = Undefined(TextWrapper) def show(self, textin: Sequence[str]) -> str: if isinstance(textin, list): results = [] # type: List[str] for i in range(len(textin)): results.append(" %d: %r" % (i, textin[i])) result = '\n'.join(results) elif isinstance(textin, str): result = " %s\n" % repr(textin) return result def check(self, result: Sequence[str], expect: Sequence[str]) -> None: self.assertEqual( result, expect, 'expected:\n%s\nbut got:\n%s' % (self.show(expect), self.show(result))) def check_wrap(self, text: str, width: int, expect: Sequence[str], **kwargs: Any) -> None: result = wrap(text, width, **kwargs) self.check(result, expect) def check_split(self, text: str, expect: Sequence[str]) -> None: result = self.wrapper._split(text) self.assertEqual(result, expect, "\nexpected %r\n" "but got %r" % (expect, result))
class SMTP_SSL(SMTP): default_port = Undefined(Any) keyfile = Undefined(Any) certfile = Undefined(Any) context = Undefined(Any) def __init__(self, host='', port=0, local_hostname=None, keyfile=None, certfile=None, timeout=Undefined, source_address=None, context=None): pass
class ErrorInfo: """Representation of a single error message.""" # Description of a sequence of imports that refer to the source file # related to this error. Each item is a (path, line number) tuple. import_ctx = Undefined(List[Tuple[str, int]]) # The source file that was the source of this error. file = '' # The name of the type in which this error is located at. type = '' # Unqualified, may be None # The name of the function or member in which this error is located at. function_or_member = '' # Unqualified, may be None # The line number related to this error within file. line = 0 # -1 if unknown # The error message. message = '' def __init__(self, import_ctx: List[Tuple[str, int]], file: str, typ: str, function_or_member: str, line: int, message: str) -> None: self.import_ctx = import_ctx self.file = file self.type = typ self.function_or_member = function_or_member self.line = line self.message = message
class RequestMethods: headers = Undefined(Any) def __init__(self, headers=None): pass def urlopen(self, method, url, body=None, headers=None, encode_multipart=True, multipart_boundary=None, **kw): pass def request(self, method, url, fields=None, headers=None, **urlopen_kw): pass def request_encode_url(self, method, url, fields=None, **urlopen_kw): pass def request_encode_body(self, method, url, fields=None, headers=None, encode_multipart=True, multipart_boundary=None, **urlopen_kw): pass
class QName: text = Undefined(Any) def __init__(self, text_or_uri, tag=None): pass def __hash__(self): pass def __le__(self, other): pass def __lt__(self, other): pass def __ge__(self, other): pass def __gt__(self, other): pass def __eq__(self, other): pass def __ne__(self, other): pass
class Var(SymbolNode): """A variable. It can refer to global/local variable or a data attribute. """ _name = None # type: str # Name without module prefix _fullname = None # type: str # Name with module prefix info = Undefined('TypeInfo') # Defining class (for member variables) type = None # type: mypy.types.Type # Declared or inferred type, or None is_self = False # Is this the first argument to an ordinary method # (usually "self")? is_ready = False # If inferred, is the inferred type available? # Is this initialized explicitly to a non-None value in class body? is_initialized_in_class = False is_staticmethod = False is_classmethod = False is_property = False def __init__(self, name: str, type: 'mypy.types.Type' = None) -> None: self._name = name self.type = type self.is_self = False self.is_ready = True self.is_initialized_in_class = False def name(self) -> str: return self._name def fullname(self) -> str: return self._fullname def accept(self, visitor: NodeVisitor[T]) -> T: return visitor.visit_var(self)
class defaultdict(Dict[_KT, _VT], Generic[_KT, _VT]): default_factory = Undefined(Function[[], _VT]) @overload def __init__(self) -> None: pass @overload def __init__(self, map: Mapping[_KT, _VT]) -> None: pass @overload def __init__(self, iterable: Iterable[Tuple[_KT, _VT]]) -> None: pass @overload def __init__(self, default_factory: Function[[], _VT]) -> None: pass @overload def __init__(self, default_factory: Function[[], _VT], map: Mapping[_KT, _VT]) -> None: pass @overload def __init__(self, default_factory: Function[[], _VT], iterable: Iterable[Tuple[_KT, _VT]]) -> None: pass # TODO __init__ keyword args def __missing__(self, key: _KT) -> _VT: pass
class _TextIOBase(_IOBase): encoding = Undefined(Any) errors = Undefined(Any) newlines = Undefined(Any) def detach(self): pass def read(self, size: int = -1): pass def readline(self, size: int = -1): pass def write(self, b): pass
class TimedRotatingFileHandler(BaseRotatingHandler): when = Undefined(Any) backupCount = Undefined(Any) utc = Undefined(Any) atTime = Undefined(Any) interval = Undefined(Any) suffix = Undefined(Any) extMatch = Undefined(Any) dayOfWeek = Undefined(Any) rolloverAt = Undefined(Any) def __init__(self, filename, when='', interval=1, backupCount=0, encoding=None, delay=False, utc=False, atTime=None): pass def computeRollover(self, currentTime): pass def shouldRollover(self, record): pass def getFilesToDelete(self): pass stream = Undefined(Any) def doRollover(self): pass
class OpExpr(Node): """Binary operation (other than . or [], which have specific nodes).""" op = '' left = Undefined(Node) right = Undefined(Node) # Inferred type for the operator method type (when relevant; None for # 'is'). method_type = None # type: mypy.types.Type def __init__(self, op: str, left: Node, right: Node) -> None: self.op = op self.left = left self.right = right def accept(self, visitor: NodeVisitor[T]) -> T: return visitor.visit_op_expr(self)
class Block(Node): body = Undefined(List[Node]) def __init__(self, body: List[Node]) -> None: self.body = body def accept(self, visitor: NodeVisitor[T]) -> T: return visitor.visit_block(self)
class YieldFromExpr(Node): expr = Undefined(Node) def __init__(self, expr: Node) -> None: self.expr = expr def accept(self, visitor: NodeVisitor[T]) -> T: return visitor.visit_yield_from_expr(self)
class GeneratorExpr(Node): """Generator expression ... for ... in ... [ for ... in ... ] [ if ... ].""" left_expr = Undefined(Node) sequences_expr = Undefined(List[Node]) condlists = Undefined(List[List[Node]]) indices = Undefined(List[Node]) def __init__(self, left_expr: Node, indices: List[Node], sequences: List[Node], condlists: List[List[Node]]) -> None: self.left_expr = left_expr self.sequences = sequences self.condlists = condlists self.indices = indices def accept(self, visitor: NodeVisitor[T]) -> T: return visitor.visit_generator_expr(self)
class PlaceHolder: loggerMap = Undefined(Any) def __init__(self, alogger): pass def append(self, alogger): pass
class RequestError(PoolError): url = Undefined(Any) def __init__(self, pool, url, message): pass def __reduce__(self): pass
class ForStmt(Node): # Index variables index = Undefined(Node) # Expression to iterate expr = Undefined(Node) body = Undefined(Block) else_body = Undefined(Block) def __init__(self, index: Node, expr: Node, body: Block, else_body: Block) -> None: self.index = index self.expr = expr self.body = body self.else_body = else_body def accept(self, visitor: NodeVisitor[T]) -> T: return visitor.visit_for_stmt(self)
class PoolError(HTTPError): pool = Undefined(Any) def __init__(self, pool, message): pass def __reduce__(self): pass
class AssertDyn(MapPremise): i = Undefined(MapExpr) def __init__(self, i: MapExpr) -> None: self.i = i def __str__(self): return str(self.i) + ' = Any'
class _AssertRaisesContext(_AssertRaisesBaseContext): exception = Undefined(Any) # TODO precise type def __enter__(self) -> _AssertRaisesContext: pass def __exit__(self, exc_type, exc_value, tb) -> bool: pass
class MacOSX(BaseBrowser): name = Undefined(Any) def __init__(self, name): pass def open(self, url, new=0, autoraise=True): pass
def expandvars(path: AnyStr) -> AnyStr: """Expand shell variables of form $var and ${var}. Unknown variables are left unchanged.""" global _varprog, _varprogb if isinstance(path, bytes): if b'$' not in path: return path if not _varprogb: import re _varprogb = re.compile(br'\$(\w+|\{[^}]*\})', re.ASCII) search = _varprogb.search start = b'{' end = b'}' else: if '$' not in path: return path if not _varprog: import re _varprog = re.compile(r'\$(\w+|\{[^}]*\})', re.ASCII) search = _varprog.search start = '{' end = '}' i = 0 while True: m = search(path, i) if not m: break i, j = m.span(0) name = Undefined(Union[str, bytes]) name = m.group(1) if name.startswith(start) and name.endswith(end): name = name[1:-1] if isinstance(name, bytes): name = str(name, 'ASCII') if name in os.environ: tail = path[j:] value = Undefined(Union[str, bytes]) value = os.environ[name] if isinstance(path, bytes): value = value.encode('ASCII') path = path[:i] + value i = len(path) path += tail else: i = j return path
class DelStmt(Node): expr = Undefined(Node) def __init__(self, expr: Node) -> None: self.expr = expr def accept(self, visitor: NodeVisitor[T]) -> T: return visitor.visit_del_stmt(self)
class ReturnStmt(Node): expr = Undefined(Node) # Expression or None def __init__(self, expr: Node) -> None: self.expr = expr def accept(self, visitor: NodeVisitor[T]) -> T: return visitor.visit_return_stmt(self)
class LoggerAdapter: logger = Undefined(Any) extra = Undefined(Any) def __init__(self, logger, extra): pass def process(self, msg, kwargs): pass def debug(self, msg, *args, **kwargs): pass def info(self, msg, *args, **kwargs): pass def warning(self, msg, *args, **kwargs): pass def warn(self, msg, *args, **kwargs): pass def error(self, msg, *args, **kwargs): pass def exception(self, msg, *args, **kwargs): pass def critical(self, msg, *args, **kwargs): pass def log(self, level, msg, *args, **kwargs): pass def isEnabledFor(self, level): pass def setLevel(self, level): pass def getEffectiveLevel(self): pass def hasHandlers(self): pass
class ContentManager: get_handlers = Undefined(Any) set_handlers = Undefined(Any) def __init__(self): pass def add_get_handler(self, key, handler): pass def get_content(self, msg, *args, **kw): pass def add_set_handler(self, typekey, handler): pass def set_content(self, msg, obj, *args, **kw): pass
class UnionType(Type): """The union type Union[T1, ..., Tn] (at least one type argument).""" items = Undefined(List[Type]) def __init__(self, items: List[Type], line: int = -1) -> None: self.items = items super().__init__(line) @staticmethod def make_union(items: List[Type], line: int = -1) -> Type: if len(items) > 1: return UnionType(items, line) elif len(items) == 1: return items[0] else: return Void() @staticmethod def make_simplified_union(items: List[Type], line: int = -1) -> Type: while any(isinstance(typ, UnionType) for typ in items): all_items = [] # type: List[Type] for typ in items: if isinstance(typ, UnionType): all_items.extend(typ.items) else: all_items.append(typ) items = all_items from mypy.subtypes import is_subtype removed = set() # type: Set[int] for i in range(len(items)): if any( is_subtype(items[i], items[j]) for j in range(len(items)) if j not in removed and j != i): removed.add(i) simplified_set = [ items[i] for i in range(len(items)) if i not in removed ] return UnionType.make_union(simplified_set) def length(self) -> int: return len(self.items) def accept(self, visitor: 'TypeVisitor[T]') -> T: return visitor.visit_union_type(self) def has_readable_member(self, name): """For a tree of unions of instances, check whether all instances have a given member. This should probably be refactored to go elsewhere.""" return all( isinstance(x, UnionType) and x.has_readable_member(name) or isinstance(x, Instance) and x.type.has_readable_member(name) for x in self.items)
class ContentDispositionHeader(ParameterizedMIMEHeader): value_parser = Undefined(Any) def init(self, *args, **kw): pass @property def content_disposition(self): pass
class ExpressionStmt(Node): """An expression as a statament, such as print(s).""" expr = Undefined(Node) def __init__(self, expr: Node) -> None: self.expr = expr def accept(self, visitor: NodeVisitor[T]) -> T: return visitor.visit_expression_stmt(self)
class SliceExpr(Node): """Slice expression (e.g. 'x:y', 'x:', '::2' or ':'). This is only valid as index in index expressions. """ begin_index = Undefined(Node) # May be None end_index = Undefined(Node) # May be None stride = Undefined(Node) # May be None def __init__(self, begin_index: Node, end_index: Node, stride: Node) -> None: self.begin_index = begin_index self.end_index = end_index self.stride = stride def accept(self, visitor: NodeVisitor[T]) -> T: return visitor.visit_slice_expr(self)
class ComparisonExpr(Node): """Comparison expression (e.g. a < b > c < d).""" operators = Undefined(List[str]) operands = Undefined(List[Node]) # Inferred type for the operator methods (when relevant; None for 'is'). method_types = Undefined(List["mypy.types.Type"]) def __init__(self, operators: List[str], operands: List[Node]) -> None: self.operators = operators self.operands = operands self.method_types = [] self.literal = min(o.literal for o in self.operands) self.literal_hash = ( ('Comparison',) + tuple(operators) + tuple(o.literal_hash for o in operands) ) def accept(self, visitor: NodeVisitor[T]) -> T: return visitor.visit_comparison_expr(self)
def expanduser(path: AnyStr) -> AnyStr: """Expand ~ and ~user constructions. If user or $HOME is unknown, do nothing.""" if isinstance(path, bytes): tilde = b'~' else: tilde = '~' if not path.startswith(tilde): return path sep = _get_sep(path) i = path.find(sep, 1) if i < 0: i = len(path) userhome = Undefined(Union[str, bytes]) if i == 1: if 'HOME' not in os.environ: import pwd userhome = pwd.getpwuid(os.getuid()).pw_dir else: userhome = os.environ['HOME'] else: import pwd name = Undefined(Union[str, bytes]) name = path[1:i] if isinstance(name, bytes): name = str(name, 'ASCII') try: pwent = pwd.getpwnam(name) except KeyError: return path userhome = pwent.pw_dir if isinstance(path, bytes): userhome = os.fsencode(userhome) root = b'/' else: root = '/' userhome = userhome.rstrip(root) return (userhome + path[i:]) or root