Ejemplo n.º 1
0
CardDescription = TypedDict(
    'CardDescription',
    {
        # Parts we currently use …
        'all_parts': List[Dict[str, str]],
        'artist': str,
        'card_faces': List[
            Any],  # This should be List[CardDescription] but mypy doesn't support nested types yet.
        'cmc': float,
        'collector_number': str,
        'color_identity': List[str],
        'colors': List[str],
        'flavor_text': str,
        'hand_modifier': str,
        'id': str,
        'layout': str,
        'legalities': Dict[str, str],
        'life_modifier': str,
        'loyalty': str,
        'mana_cost': str,
        'oracle_text': str,
        'power': str,
        'name': str,
        'rarity': str,
        'reserved': bool,
        'set': str,
        'toughness': str,
        'type_line': str,
        'watermark': str,

        # …and parts we don't. Some of these are typed other than str because of the usage in mutliverse_test which uses real data from Scryfall.
        'arena_id': str,
        'artist_ids': List[str],
        'booster': bool,
        'border_color': str,
        'card_back_id': str,
        'color_indicator': str,
        'digital': bool,
        'edhrec_rank': int,
        'foil': bool,
        'frame': str,
        'frame_effects': List[str],
        'full_art': bool,
        'games': List[str],
        'highres_image': bool,
        'illustration_id': str,
        'image_uris': Dict[str, str],
        'lang': str,
        'mtgo_foil_id': int,
        'mtgo_id': int,
        'multiverse_ids': List[int],
        'nonfoil': bool,
        'object': str,
        'oracle_id': str,
        'oversized': bool,
        'printed_name': str,
        'printed_text': str,
        'printed_type_line': str,
        'prints_search_uri': str,
        'promo': bool,
        'promo_types': List[str],
        'related_uris': Dict[str, str],
        'released_at': str,
        'reprint': bool,
        'rulings_uri': str,
        'scryfall_set_uri': str,
        'scryfall_uri': str,
        'set_name': str,
        'set_search_uri': str,
        'set_type': str,
        'set_uri': str,
        'story_spotlight': bool,
        'tcgplayer_id': int,
        'textless': bool,
        'uri': str,
        'variation': bool,
        'variation_of': str,
    },
    total=False)
Ejemplo n.º 2
0
from django.db import models, transaction
from django.core.validators import MinValueValidator
from django.utils.translation import gettext_lazy as _
from django.utils import timezone
from django.core.exceptions import ValidationError
import numpy as np
from mypy_extensions import TypedDict

from server.types import CleanPredictionData
from .match import Match
from .ml_model import MLModel
from .team import Team

MatchingAttributes = TypedDict("MatchingAttributes", {
    "match": Match,
    "ml_model": MLModel
})


class Prediction(models.Model):
    """Model for ML model predictions for each match."""

    created_at = models.DateTimeField(auto_now_add=True,
                                      null=False,
                                      blank=False)
    updated_at = models.DateTimeField(auto_now=True, null=False, blank=False)
    match = models.ForeignKey(Match, on_delete=models.CASCADE)
    ml_model = models.ForeignKey(MLModel, on_delete=models.CASCADE)
    predicted_winner = models.ForeignKey(Team,
                                         on_delete=models.CASCADE,
                                         related_name="predicted_wins")
Ejemplo n.º 3
0
from mypy_extensions import TypedDict
from typing import Callable, Coroutine, Any

from aiohttp import web

Route = TypedDict(
    "Route",
    {
        "method": str,
        "url": str,
        "handler": Callable[[web.Request], Coroutine[Any, Any, web.Response]],
    },
)
Ejemplo n.º 4
0
        elif stream_email_notify:
            notice['trigger'] = 'stream_email_notify'
        else:
            raise AssertionError("Unknown notification trigger!")
        notice['stream_name'] = stream_name
        if not already_notified.get("email_notified"):
            queue_json_publish("missedmessage_emails", notice,
                               lambda notice: None)
            notified['email_notified'] = True

    return notified


ClientInfo = TypedDict(
    'ClientInfo', {
        'client': ClientDescriptor,
        'flags': Optional[Iterable[str]],
        'is_sender': bool,
    })


def get_client_info_for_message_event(
        event_template: Mapping[str, Any],
        users: Iterable[Mapping[str, Any]]) -> Dict[str, ClientInfo]:
    '''
    Return client info for all the clients interested in a message.
    This basically includes clients for users who are recipients
    of the message, with some nuances for bots that auto-subscribe
    to all streams, plus users who may be mentioned, etc.
    '''

    send_to_clients = {}  # type: Dict[str, ClientInfo]
Ejemplo n.º 5
0
from typing import Dict

import aiohttp
from mypy_extensions import TypedDict

from paasta_tools.utils import get_user_agent

HACHECK_CONN_TIMEOUT = 30
HACHECK_READ_TIMEOUT = 10

SpoolInfo = TypedDict(
    'SpoolInfo',
    {
        'service': str,
        'state': str,
        'since': float,
        'until': float,
        'reason': str,
    },
    total=False,
)


async def post_spool(url: str, status: str, data: Dict['str', 'str']) -> None:
    async with aiohttp.ClientSession(
            conn_timeout=HACHECK_CONN_TIMEOUT,
            read_timeout=HACHECK_READ_TIMEOUT,
    ) as session:
        async with session.post(
                url,
                data=data,
Ejemplo n.º 6
0
    from mypy_extensions import TypedDict
    import sublime
    import subprocess
    from .linter import Linter

    Bid = sublime.BufferId
    FileName = str
    LinterName = str
    LintError = TypedDict('LintError', {
        'line': int,
        'start': int,
        'end': int,
        'region': sublime.Region,
        'linter': LinterName,
        'error_type': str,
        'code': str,
        'msg': str,
        'filename': FileName,
        'uid': str,
        'priority': int,
        'panel_line': Tuple[int, int],
        'offending_text': str
    }, total=False)


api_ready = False
kill_switch = True

settings = Settings()

file_errors = defaultdict(list)  # type: DefaultDict[FileName, List[LintError]]
Ejemplo n.º 7
0
import copy
import re
import unicodedata
from typing import Dict, List, Optional, Tuple

from mypy_extensions import TypedDict

# Properties of the various aspects of cards with information about how to store and retrieve them from the database.
ColumnDescription = TypedDict(
    'ColumnDescription', {
        'type': str,
        'nullable': bool,
        'primary_key': bool,
        'query': str,
        'scryfall': bool,
        'foreign_key': Optional[Tuple[str, str]],
        'default': Optional[str],
        'unique': bool,
        'unique_with': Optional[List[str]],
    })
TableDescription = Dict[str, ColumnDescription]

MAX_LEN_TEXT = 21845
MAX_LEN_VARCHAR = 190

BOOLEAN = 'BOOLEAN'
DATE = 'INTEGER'
INTEGER = 'INTEGER'
REAL = 'REAL'
TEXT = 'LONGTEXT'
VARCHAR = 'VARCHAR({n})'.format(n=MAX_LEN_VARCHAR)
Ejemplo n.º 8
0
)

from zerver.models import (get_display_recipient_by_id, get_user_profile_by_id,
                           query_for_ids, Message, Realm, Recipient, Stream,
                           Subscription, UserProfile, UserMessage, Reaction)

from typing import Any, Dict, List, Optional, Set, Tuple, Text, Union
from mypy_extensions import TypedDict

RealmAlertWords = Dict[int, List[Text]]

RawUnreadMessagesResult = TypedDict(
    'RawUnreadMessagesResult', {
        'pm_dict': Dict[int, Any],
        'stream_dict': Dict[int, Any],
        'huddle_dict': Dict[int, Any],
        'mentions': Set[int],
        'muted_stream_ids': List[int],
        'unmuted_stream_msgs': Set[int],
    })

UnreadMessagesResult = TypedDict(
    'UnreadMessagesResult', {
        'pms': List[Dict[str, Any]],
        'streams': List[Dict[str, Any]],
        'huddles': List[Dict[str, Any]],
        'mentions': List[int],
        'count': int,
    })

MAX_UNREAD_MESSAGES = 5000
import typing as t

from .exception import LtiException
from .lineitem import LineItem

if t.TYPE_CHECKING:
    from .service_connector import ServiceConnector, _ServiceConnectorResponse
    from .grade import Grade
    from mypy_extensions import TypedDict
    from typing_extensions import Literal

    _AssignmentsGradersData = TypedDict('_AssignmentsGradersData', {
        'scope': t.List[Literal['https://purl.imsglobal.org/spec/lti-ags/scope/score',
                                'https://purl.imsglobal.org/spec/lti-ags/scope/lineitem',
                                'https://purl.imsglobal.org/spec/lti-ags/scope/lineitem.readonly']],
        'lineitems': str,
        'lineitem': str,
    }, total=False)


class AssignmentsGradesService(object):
    _service_connector = None  # type: ServiceConnector
    _service_data = None  # type: _AssignmentsGradersData

    def __init__(self, service_connector, service_data):
        # type: (ServiceConnector, _AssignmentsGradersData) -> None
        self._service_connector = service_connector
        self._service_data = service_data

    def put_grade(self, grade, line_item=None):
        # type: (Grade, t.Optional[LineItem]) -> _ServiceConnectorResponse
Ejemplo n.º 10
0
    CHROME_HEADLESS: bool
    CHROME_SANDBOX: bool

    USE_CURL: bool
    USE_WGET: bool
    USE_SINGLEFILE: bool
    USE_READABILITY: bool
    USE_GIT: bool
    USE_CHROME: bool
    USE_YOUTUBEDL: bool
    CURL_BINARY: str
    GIT_BINARY: str
    WGET_BINARY: str
    SINGLEFILE_BINARY: str
    READABILITY_BINARY: str
    YOUTUBEDL_BINARY: str
    CHROME_BINARY: Optional[str]


ConfigDefaultValueGetter = Callable[[ConfigDict], ConfigValue]
ConfigDefaultValue = Union[ConfigValue, ConfigDefaultValueGetter]

ConfigDefault = TypedDict('ConfigDefault', {
    'default': ConfigDefaultValue,
    'type': Optional[Type],
    'aliases': Optional[Tuple[str, ...]],
},
                          total=False)

ConfigDefaultDict = Dict[str, ConfigDefault]
Ejemplo n.º 11
0
from zulipterminal.helper import (
    asynch,
    classify_unread_counts,
    canonicalize_color,
    index_messages,
    set_count,
    initial_index,
    Message,
    notify,
)
from zulipterminal.ui_tools.utils import create_msg_box_list

GetMessagesArgs = TypedDict('GetMessagesArgs', {
    'num_before': int,
    'num_after': int,
    'anchor': Optional[int]
})

Event = TypedDict(
    'Event',
    {
        'type': str,
        # typing:
        'sender': Dict[str, Any],  # 'email', ...
        # typing & reaction:
        'op': str,
        # reaction:
        'user': Dict[str, Any],  # 'email', 'user_id', 'full_name'
        'reaction_type': str,
        'emoji_code': str,
Ejemplo n.º 12
0
from eth.beacon.types.blocks import BaseBeaconBlock
from eth.beacon.types.attestation_records import AttestationRecord


class Status(Command):
    _cmd_id = 0
    structure = [
        ('protocol_version', sedes.big_endian_int),
        ('network_id', sedes.big_endian_int),
        ('genesis_hash', sedes.binary),
        ('best_hash', sedes.binary),
    ]


GetBeaconBlocksMessage = TypedDict("GetBeaconBlocksMessage", {
    "block_slot_or_hash": Union[int, Hash32],
    "max_blocks": int,
})


class GetBeaconBlocks(Command):
    _cmd_id = 1
    structure = [
        ('block_slot_or_hash', HashOrNumber()),
        ('max_blocks', sedes.big_endian_int),
    ]


class BeaconBlocks(Command):
    _cmd_id = 2
    structure = sedes.CountableList(BaseBeaconBlock)
Ejemplo n.º 13
0
from typing import Tuple

import requests
from mypy_extensions import TypedDict

from paasta_tools import marathon_tools
from paasta_tools import mesos_tools
from paasta_tools.utils import compose_job_id
from paasta_tools.utils import DEFAULT_SOA_DIR
from paasta_tools.utils import get_user_agent


HaproxyBackend = TypedDict(
    'HaproxyBackend',
    {
        'pxname': str,
        'svname': str,
    },
    total=False,
)


def retrieve_haproxy_csv(synapse_host, synapse_port, synapse_haproxy_url_format) -> Iterable[Dict[str, str]]:
    """Retrieves the haproxy csv from the haproxy web interface

    :param synapse_host_port: A string in host:port format that this check
                              should contact for replication information.
    :returns reader: a csv.DictReader object
    """
    synapse_uri = synapse_haproxy_url_format.format(host=synapse_host, port=synapse_port)

    # timeout after 1 second and retry 3 times
Ejemplo n.º 14
0
    )
    parser.add_argument(
        '-d',
        '--soa-dir',
        dest="soa_dir",
        metavar="SOA_DIR",
        default=DEFAULT_SOA_DIR,
        help="define a different soa config directory",
    )
    args = parser.parse_args(argv)
    return args


Marathon_Dashboard_Item = TypedDict('Marathon_Dashboard_Item', {
    'service': str,
    'instance': str,
    'shard_url': str
})
Marathon_Dashboard = Dict[str, List[Marathon_Dashboard_Item]]


def create_marathon_dashboard(
    cluster: str,
    soa_dir: str = DEFAULT_SOA_DIR,
    marathon_clients: MarathonClients = None,
    system_paasta_config: SystemPaastaConfig = None,
) -> Marathon_Dashboard:
    try:
        instances: List = get_services_for_cluster(
            cluster=cluster,
            instance_type='marathon',
Ejemplo n.º 15
0
else:

    def TypedDict(*args, **kwargs):
        pass


_T = TypeVar("_T")
NodeSpans = List[Dict[str, Any]]
SnubaTransaction = TypedDict(
    "SnubaTransaction",
    {
        "id": str,
        "transaction.status": int,
        "transaction.op": str,
        "transaction.duration": int,
        "transaction": str,
        "timestamp": str,
        "trace.span": str,
        "trace.parent_span": str,
        "root": str,
        "project.id": int,
        "project": str,
    },
)
SnubaError = TypedDict(
    "SnubaError",
    {
        "id": str,
        "timestamp": str,
        "trace.span": str,
        "transaction": str,
        "issue.id": int,
Ejemplo n.º 16
0
            # Dynamic key access not yet allowed with TypedDict
            # https://github.com/python/mypy/issues/5359
            transaction_key:
            normalized[transaction_key][indexes[index_key]]  # type: ignore
            for transaction_key, index_key in [
                ("gasLimit", "gas"),
                ("value", "value"),
                ("data", "data"),
            ] if index_key in indexes
        })


FixtureAccountDetails = TypedDict(
    'FixtureAccountDetails', {
        'balance': HexStr,
        'nonce': HexStr,
        'code': HexStr,
        'storage': Dict[HexStr, HexStr]
    })
FixtureAccountState = Dict[Address, FixtureAccountDetails]


def normalize_account_state(
        account_state: FixtureAccountState) -> AccountState:
    return {
        to_canonical_address(address): {
            'balance': to_int(state['balance']),
            'code': decode_hex(state['code']),
            'nonce': to_int(state['nonce']),
            'storage': {
                to_int(slot): big_endian_to_int(decode_hex(value))
Ejemplo n.º 17
0
MACOS = platform.system() == "Darwin"
LINUX = platform.system() == "Linux"
WSL = 'microsoft' in platform.release().lower()

Message = Dict[str, Any]

Index = TypedDict(
    'Index',
    {
        'pointer': Dict[str, Union[int, Set[None]]],  # narrow_str, message_id
        # Various sets of downloaded message ids (all, starred, ...)
        'all_msg_ids': Set[int],
        'starred_msg_ids': Set[int],
        'mentioned_msg_ids': Set[int],
        'private_msg_ids': Set[int],
        'private_msg_ids_by_user_ids': Dict[FrozenSet[int], Set[int]],
        'stream_msg_ids_by_stream_id': Dict[int, Set[int]],
        'topic_msg_ids': Dict[int, Dict[str, Set[int]]],
        # Extra cached information
        'edited_messages': Set[int],  # {message_ids, ...}
        'topics': Dict[int, List[str]],  # {topic names, ...}
        'search': Set[int],  # {message_id, ...}
        # Downloaded message data
        'messages': Dict[int, Message],  # message_id: Message
    })

initial_index = Index(
    pointer=defaultdict(set),
    all_msg_ids=set(),
    starred_msg_ids=set(),
    mentioned_msg_ids=set(),
Ejemplo n.º 18
0
from mypy_extensions import TypedDict

PartialStat = TypedDict(
    'PartialStat',
    {
        'st_size': int,
        'st_atime': float,
        'st_mtime': float,
        'st_ctime': float,
        'st_uid': int,
        'st_gid': int,
    },
    total=True,
)


class FullStat(PartialStat, total=True):
    st_nlink: int
    st_mode: int


__APIHandlerResponse = TypedDict(
    '__APIHandlerResponse',
    {
        'ok': bool,
    },
    total=True,
)


class APIHandlerResponse(__APIHandlerResponse, total=False):
Ejemplo n.º 19
0
import pandas as pd
import numpy as np
from mypy_extensions import TypedDict


MatchResultsData = TypedDict(
    "MatchResultsData",
    {
        "date": str,
        "game": int,
        "season": int,
        "round": str,
        "round_number": int,
        "round_type": str,
        "home_team": str,
        "home_goals": int,
        "home_behinds": int,
        "home_points": int,
        "away_team": str,
        "away_goals": int,
        "away_behinds": int,
        "away_points": int,
        "margin": int,
        "venue": str,
    },
)

FINALS_ROUND_LABELS = ["QF", "EF", "SF", "PF", "GF"]
# Reasonable ranges are two standard deviations plus/minus from the means
# for all recorded AFL matches
REASONABLE_GOAL_RANGE = (2, 23)
Ejemplo n.º 20
0
import textwrap

from .lint import elect, events, persist, util
flatten = chain.from_iterable

MYPY = False
if MYPY:
    from typing import (Any, Collection, Dict, Iterable, List, Optional, Set,
                        Tuple, Union)
    from mypy_extensions import TypedDict
    from .lint.persist import LintError

    Filename = str
    State_ = TypedDict(
        'State_', {
            'active_view': Optional[sublime.View],
            'cursor': int,
            'panel_opened_automatically': Set[sublime.WindowId]
        })
    ErrorsByFile = Dict[Filename, List[LintError]]
    DrawInfo = TypedDict('DrawInfo', {
        'panel': sublime.View,
        'content': str,
        'errors_from_active_view': List[LintError],
        'nearby_lines': Union[int, List[int]]
    },
                         total=False)

PANEL_NAME = "SublimeLinter"
OUTPUT_PANEL = "output." + PANEL_NAME

State = {
Ejemplo n.º 21
0
"""Main entry point to mypy annotation inference utility."""

import json

from typing import List
from mypy_extensions import TypedDict

from pyannotate_tools.annotations.types import ARG_STAR, ARG_STARSTAR
from pyannotate_tools.annotations.infer import infer_annotation
from pyannotate_tools.annotations.parse import parse_json

# Schema of a function signature in the output
Signature = TypedDict('Signature', {
    'arg_types': List[str],
    'return_type': str
})

# Schema of a function in the output
FunctionData = TypedDict(
    'FunctionData', {
        'path': str,
        'line': int,
        'func_name': str,
        'signature': Signature,
        'samples': int
    })


def generate_annotations_json_string(source_path):
    # type: (str) -> List[FunctionData]
    """Produce annotation data JSON file from a JSON file with runtime-collected types.
Ejemplo n.º 22
0
import sublime
import sublime_plugin

import time

from .lint import events, util

MYPY = False
if MYPY:
    from typing import Dict, Optional
    from mypy_extensions import TypedDict

    FileName = str
    LinterName = str
    State_ = TypedDict('State_', {
        'active_view': Optional[sublime.View],
        'running': Dict[FileName, float],
    })

INITIAL_DELAY = 2
CYCLE_TIME = 200
TIMEOUT = 20
STATUS_BUSY_KEY = "sublime_linter_status_busy"

State = {'active_view': None, 'running': {}}  # type: State_


def plugin_loaded():
    active_view = sublime.active_window().active_view()
    if util.is_lintable(active_view):
        State.update({'active_view': active_view})
Ejemplo n.º 23
0
    from mypy_extensions import TypedDict

    from pip._internal.distributions import AbstractDistribution
    from pip._internal.index.package_finder import PackageFinder
    from pip._internal.models.link import Link
    from pip._internal.network.download import Downloader
    from pip._internal.req.req_install import InstallRequirement
    from pip._internal.req.req_tracker import RequirementTracker
    from pip._internal.utils.hashes import Hashes

    if PY2:
        CopytreeKwargs = TypedDict(
            'CopytreeKwargs',
            {
                'ignore': Callable[[str, List[str]], List[str]],
                'symlinks': bool,
            },
            total=False,
        )
    else:
        CopytreeKwargs = TypedDict(
            'CopytreeKwargs',
            {
                'copy_function': Callable[[str, str], None],
                'ignore': Callable[[str, List[str]], List[str]],
                'ignore_dangling_symlinks': bool,
                'symlinks': bool,
            },
            total=False,
        )
Ejemplo n.º 24
0
# All the punctuations in COCO captions, we will remove them.
# fmt: off
PUNCTUATIONS: List[str] = [
    "''", "'", "``", "`", "(", ")", "{", "}", ".", "?", "!", ",", ":", "-",
    "--", "...", ";"
]
# fmt: on

# Special tokens which should be added (all, or a subset) to the vocabulary.
# We use the same token for @@PADDING@@ and @@UNKNOWN@@ -- @@UNKNOWN@@.
SPECIAL_TOKENS: List[str] = ["@@UNKNOWN@@", "@@BOUNDARY@@"]

# Type for each COCO caption example annotation.
CocoCaptionExample = TypedDict("CocoCaptionExample", {
    "id": int,
    "image_id": int,
    "caption": str
})
# ------------------------------------------------------------------------------------------------


def build_caption_vocabulary(caption_json: List[CocoCaptionExample],
                             word_count_threshold: int = 5) -> List[str]:
    r"""
    Given a list of COCO caption examples, return a list of unique captions tokens thresholded
    by minimum occurence.
    """

    word_counts: Dict[str, int] = {}

    # Accumulate unique caption tokens from all caption sequences.
Ejemplo n.º 25
0
logger = logging.getLogger('moveshelf-api')

class TimecodeFramerate(enum.Enum):
    FPS_24 = '24'
    FPS_25 = '25'
    FPS_29_97 = '29.97'
    FPS_30 = '30'
    FPS_50 = '50'
    FPS_59_94 = '59.94'
    FPS_60 = '60'
    FPS_1000 = '1000'


Timecode = TypedDict('Timecode', {
    'timecode': str,
    'framerate': TimecodeFramerate
    })


# set types of input
Metadata = TypedDict('Metadata', {
    'title': str,
    'description': str,
    'previewImageUri': str,
    'allowDownload': bool,
    'allowUnlistedAccess': bool,
    'startTimecode': Timecode
    },
    total=False)

# check api_key 
Ejemplo n.º 26
0
from asgiref.sync import async_to_sync
from channels.layers import get_channel_layer
from django.db.models import Model
from mypy_extensions import TypedDict

from .cache import ChangeIdTooLowError, element_cache, get_element_id
from .projector import get_projector_data
from .timing import Timing
from .utils import get_model_from_collection_string, is_iterable, split_element_id

AutoupdateFormat = TypedDict(
    "AutoupdateFormat",
    {
        "changed": Dict[str, List[Dict[str, Any]]],
        "deleted": Dict[str, List[int]],
        "from_change_id": int,
        "to_change_id": int,
        "all_data": bool,
    },
)


class AutoupdateElementBase(TypedDict):
    id: int
    collection_string: str


class AutoupdateElement(AutoupdateElementBase, total=False):
    """
    Data container to handle one root rest element for the autoupdate, history
    and caching process.
Ejemplo n.º 27
0
from django.db.models import QuerySet
import graphene
import pandas as pd
import numpy as np
from mypy_extensions import TypedDict

from server.models import MLModel
from server.graphql.calculations import calculate_cumulative_metrics
from .models import MLModelType

ModelMetric = TypedDict(
    "ModelMetric",
    {
        "ml_model__name": str,
        "cumulative_correct_count": int,
        "cumulative_accuracy": float,
        "cumulative_mean_absolute_error": float,
        "cumulative_margin_difference": float,
        "cumulative_bits": float,
    },
)

RoundModelMetrics = TypedDict(
    "RoundModelMetrics",
    {
        "match__round_number": int,
        "model_metrics": pd.DataFrame
    },
)

RoundPredictions = TypedDict("RoundPredictions", {
Ejemplo n.º 28
0
GroupByFunction = Callable[[Timestamp], Tuple[Timegroup, Timestamp]]
PeriodInfo = Dict[str, Union[GroupByFunction, int]]
TimeSlices = List[Tuple[Timestamp, Timestamp]]
DataStatValue = Optional[float]
DataStat = List[DataStatValue]
DataStats = List[DataStat]
PredictionParameters = Dict[str, Any]

# TODO: This is somehow related to cmk.utils.prediction.PreditionInfo,
# but using this *instead* of PredicionInfo (==Dict) is not possible.
PredictionData = TypedDict(
    'PredictionData',
    {
        "columns": List[str],
        "points": DataStats,
        "num_points": int,
        "data_twindow": List[Timestamp],
        "step": Seconds,
    },
    total=False,
)


def window_start(timestamp, span):
    # type: (int, int) -> int
    """If time is partitioned in SPAN intervals, how many seconds is TIMESTAMP away from the start

    It works well across time zones, but has an unfair behavior with daylight savings time."""
    return (timestamp - cmk.utils.prediction.timezone_at(timestamp)) % span

Ejemplo n.º 29
0
from mypy_extensions import TypedDict

Movie = TypedDict('Movie', {'name': str, 'year': int}, total=False)
the_rock = Movie(name='The Rock')

the_rock
the_rock['year']
Ejemplo n.º 30
0
    topic_is_muted,
)

from zerver.models import (get_display_recipient_by_id, get_user_profile_by_id,
                           query_for_ids, Message, Realm, Recipient, Stream,
                           Subscription, UserProfile, UserMessage, Reaction)

from typing import Any, Dict, List, Optional, Set, Tuple, Text, Union
from mypy_extensions import TypedDict

RealmAlertWords = Dict[int, List[Text]]

UnreadMessagesResult = TypedDict(
    'UnreadMessagesResult', {
        'pms': List[Dict[str, Any]],
        'streams': List[Dict[str, Any]],
        'huddles': List[Dict[str, Any]],
        'mentions': List[int],
        'count': int,
    })

MAX_UNREAD_MESSAGES = 5000


def sew_messages_and_reactions(messages, reactions):
    # type: (List[Dict[str, Any]], List[Dict[str, Any]]) -> List[Dict[str, Any]]
    """Given a iterable of messages and reactions stitch reactions
    into messages.
    """
    # Add all messages with empty reaction item
    for message in messages:
        message['reactions'] = []